kube.rs 18.3 KB
Newer Older
1
// SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
3
// SPDX-License-Identifier: Apache-2.0

4
mod crd;
5
6
7
mod daemon;
mod utils;

8
pub use crd::{DynamoWorkerMetadata, DynamoWorkerMetadataSpec};
9
// hash_pod_name is used by C bindings (EPP) for pod-level worker ID mapping.
10
11
pub use utils::hash_pod_name;

12
use crd::{apply_cr, build_cr};
13
use daemon::DiscoveryDaemon;
14
use utils::{KubeDiscoveryMode, PodInfo};
15
16
17

use crate::CancellationToken;
use crate::discovery::{
18
19
    Discovery, DiscoveryEvent, DiscoveryInstance, DiscoveryInstanceId, DiscoveryMetadata,
    DiscoveryQuery, DiscoverySpec, DiscoveryStream, MetadataSnapshot,
20
21
22
};
use anyhow::Result;
use async_trait::async_trait;
23
use kube::{Api, Client as KubeClient, api::DeleteParams};
24
25
26
27
28
29
30
31
32
33
use std::collections::HashSet;
use std::sync::Arc;
use tokio::sync::RwLock;

/// Kubernetes-based discovery client
#[derive(Clone)]
pub struct KubeDiscoveryClient {
    instance_id: u64,
    metadata: Arc<RwLock<DiscoveryMetadata>>,
    metadata_watch: tokio::sync::watch::Receiver<Arc<MetadataSnapshot>>,
34
35
    kube_client: KubeClient,
    pod_info: PodInfo,
36
37
38
39
40
41
42
43
44
45
46
47
48
}

impl KubeDiscoveryClient {
    /// Create a new Kubernetes discovery client
    ///
    /// # Arguments
    /// * `metadata` - Shared metadata store (also used by system server)
    /// * `cancel_token` - Cancellation token for shutdown
    pub async fn new(
        metadata: Arc<RwLock<DiscoveryMetadata>>,
        cancel_token: CancellationToken,
    ) -> Result<Self> {
        let pod_info = PodInfo::from_env()?;
49
50
        let instance_id = pod_info.target.instance_id();
        let cr_name = pod_info.target.cr_name();
51
52

        tracing::info!(
53
54
55
56
            "Initializing KubeDiscoveryClient: mode={:?}, target={:?}, cr_name={}, instance_id={:x}, namespace={}, pod_uid={}",
            pod_info.mode,
            pod_info.target,
            cr_name,
57
            instance_id,
58
59
            pod_info.pod_namespace,
            pod_info.pod_uid
60
61
62
63
64
65
        );

        let kube_client = KubeClient::try_default()
            .await
            .map_err(|e| anyhow::anyhow!("Failed to create Kubernetes client: {}", e))?;

66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
        // In container mode, delete any stale CR from a previous incarnation of this container.
        // In failover pods, the pod stays alive when a container crashes and restarts,
        // so the old CR persists. Deleting it ensures the daemon doesn't see stale data.
        // In pod mode this is unnecessary — pod restart creates a new pod (and new CR name).
        if pod_info.mode == KubeDiscoveryMode::Container {
            let cr_api: Api<DynamoWorkerMetadata> =
                Api::namespaced(kube_client.clone(), &pod_info.pod_namespace);
            match cr_api.delete(&cr_name, &DeleteParams::default()).await {
                Ok(_) => tracing::info!("Deleted stale CR: {}", cr_name),
                Err(kube::Error::Api(err_resp)) if err_resp.code == 404 => {
                    tracing::debug!("No stale CR to delete: {}", cr_name);
                }
                Err(e) => {
                    panic!(
                        "Failed to clear stale CR '{}': {} — cannot start with stale discovery state",
                        cr_name, e
                    );
                }
            }
        }

87
88
89
90
        // Create watch channel with initial empty snapshot
        let (watch_tx, watch_rx) = tokio::sync::watch::channel(Arc::new(MetadataSnapshot::empty()));

        // Create and spawn daemon
91
        let daemon = DiscoveryDaemon::new(kube_client.clone(), pod_info.clone(), cancel_token)?;
92
93
94

        tokio::spawn(async move {
            if let Err(e) = daemon.run(watch_tx).await {
95
                tracing::error!("Discovery daemon failed: {e}");
96
97
98
99
100
101
102
103
104
            }
        });

        tracing::info!("Discovery daemon started");

        Ok(Self {
            instance_id,
            metadata,
            metadata_watch: watch_rx,
105
106
            kube_client,
            pod_info,
107
108
109
110
111
112
113
114
115
116
        })
    }
}

#[async_trait]
impl Discovery for KubeDiscoveryClient {
    fn instance_id(&self) -> u64 {
        self.instance_id
    }

117
    async fn register_internal(&self, spec: DiscoverySpec) -> Result<DiscoveryInstance> {
118
119
120
121
122
123
124
125
126
        let instance_id = self.instance_id();
        let instance = spec.with_instance_id(instance_id);

        tracing::debug!(
            "Registering instance: {:?} with instance_id={:x}",
            instance,
            instance_id
        );

127
128
        // Write to local metadata and persist to CR
        // IMPORTANT: Hold the write lock across the CR write to prevent race conditions
129
        let mut metadata = self.metadata.write().await;
130
131
132
133

        // Clone state for rollback in case CR persistence fails
        let original_state = metadata.clone();

134
135
136
        match &instance {
            DiscoveryInstance::Endpoint(inst) => {
                tracing::info!(
137
                    "Registering endpoint: namespace={}, component={}, endpoint={}, instance_id={:x}",
138
139
140
141
142
143
144
145
146
147
148
149
150
151
                    inst.namespace,
                    inst.component,
                    inst.endpoint,
                    instance_id
                );
                metadata.register_endpoint(instance.clone())?;
            }
            DiscoveryInstance::Model {
                namespace,
                component,
                endpoint,
                ..
            } => {
                tracing::info!(
152
                    "Registering model card: namespace={}, component={}, endpoint={}, instance_id={:x}",
153
154
155
156
157
158
159
                    namespace,
                    component,
                    endpoint,
                    instance_id
                );
                metadata.register_model_card(instance.clone())?;
            }
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
            DiscoveryInstance::EventChannel {
                namespace,
                component,
                topic,
                ..
            } => {
                tracing::info!(
                    "Registering event channel: namespace={}, component={}, topic={}, instance_id={:x}",
                    namespace,
                    component,
                    topic,
                    instance_id
                );
                metadata.register_event_channel(instance.clone())?;
            }
175
176
        }

177
178
        // Build and apply the CR with the updated metadata
        // This persists the metadata to Kubernetes for other pods to discover
179
180
181
182
183
184
185
        let cr_name = self.pod_info.target.cr_name();
        let cr = build_cr(
            &cr_name,
            &self.pod_info.pod_name,
            &self.pod_info.pod_uid,
            &metadata,
        )?;
186
187
188
189
190
191
192
193
194
195
196
197
198

        if let Err(e) = apply_cr(&self.kube_client, &self.pod_info.pod_namespace, &cr).await {
            // Rollback local state on CR persistence failure
            tracing::warn!(
                "Failed to persist metadata to CR, rolling back local state: {}",
                e
            );
            *metadata = original_state;
            return Err(e);
        }

        tracing::debug!("Persisted metadata to DynamoWorkerMetadata CR");

199
200
201
        Ok(instance)
    }

202
    async fn unregister(&self, instance: DiscoveryInstance) -> Result<()> {
203
204
205
206
        let instance_id = self.instance_id();

        // Write to local metadata and persist to CR
        // IMPORTANT: Hold the write lock across the CR write to prevent race conditions
207
        let mut metadata = self.metadata.write().await;
208
209
210
211

        // Clone state for rollback in case CR persistence fails
        let original_state = metadata.clone();

212
        match &instance {
213
214
215
216
217
218
219
220
            DiscoveryInstance::Endpoint(inst) => {
                tracing::info!(
                    "Unregistering endpoint: namespace={}, component={}, endpoint={}, instance_id={:x}",
                    inst.namespace,
                    inst.component,
                    inst.endpoint,
                    instance_id
                );
221
222
                metadata.unregister_endpoint(&instance)?;
            }
223
224
225
226
227
228
229
230
231
232
233
234
235
            DiscoveryInstance::Model {
                namespace,
                component,
                endpoint,
                ..
            } => {
                tracing::info!(
                    "Unregistering model card: namespace={}, component={}, endpoint={}, instance_id={:x}",
                    namespace,
                    component,
                    endpoint,
                    instance_id
                );
236
237
                metadata.unregister_model_card(&instance)?;
            }
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
            DiscoveryInstance::EventChannel {
                namespace,
                component,
                topic,
                ..
            } => {
                tracing::info!(
                    "Unregistering event channel: namespace={}, component={}, topic={}, instance_id={:x}",
                    namespace,
                    component,
                    topic,
                    instance_id
                );
                metadata.unregister_event_channel(&instance)?;
            }
253
254
        }

255
256
        // Build and apply the CR with the updated metadata
        // This persists the removal to Kubernetes for other pods to see
257
258
259
260
261
262
263
        let cr_name = self.pod_info.target.cr_name();
        let cr = build_cr(
            &cr_name,
            &self.pod_info.pod_name,
            &self.pod_info.pod_uid,
            &metadata,
        )?;
264
265
266
267
268
269
270
271
272
273
274
275
276

        if let Err(e) = apply_cr(&self.kube_client, &self.pod_info.pod_namespace, &cr).await {
            // Rollback local state on CR persistence failure
            tracing::warn!(
                "Failed to persist metadata removal to CR, rolling back local state: {}",
                e
            );
            *metadata = original_state;
            return Err(e);
        }

        tracing::debug!("Persisted metadata removal to DynamoWorkerMetadata CR");

277
278
279
        Ok(())
    }

280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
    async fn list(&self, query: DiscoveryQuery) -> Result<Vec<DiscoveryInstance>> {
        tracing::debug!("KubeDiscoveryClient::list called with query={:?}", query);

        // Get current snapshot (may be empty if daemon hasn't fetched yet)
        let snapshot = self.metadata_watch.borrow().clone();

        tracing::debug!(
            "List using snapshot seq={} with {} instances",
            snapshot.sequence,
            snapshot.instances.len()
        );

        // Filter snapshot by query
        let instances = snapshot.filter(&query);

        tracing::info!(
            "KubeDiscoveryClient::list returning {} instances for query={:?}",
            instances.len(),
            query
        );

        Ok(instances)
    }

    async fn list_and_watch(
        &self,
        query: DiscoveryQuery,
        cancel_token: Option<CancellationToken>,
    ) -> Result<DiscoveryStream> {
        use tokio::sync::mpsc;

        tracing::info!(
            "KubeDiscoveryClient::list_and_watch started for query={:?}",
            query
        );

        // Clone the watch receiver
        let mut watch_rx = self.metadata_watch.clone();

        // Create output stream
        let (event_tx, event_rx) = mpsc::unbounded_channel();

        // Generate unique stream identifier for tracing
        let stream_id = uuid::Uuid::new_v4();

        // Spawn task to process snapshots
        tokio::spawn(async move {
327
            // Initialize from current snapshot state
328
329
330
331
            // This is critical: watch_rx.changed() only fires on FUTURE changes,
            // so we must capture the current state first to detect removals correctly
            let initial_snapshot = watch_rx.borrow_and_update().clone();

332
333
334
335
336
337
338
339
            // Build initial map: DiscoveryInstanceId -> DiscoveryInstance
            let initial: std::collections::HashMap<DiscoveryInstanceId, DiscoveryInstance> =
                initial_snapshot
                    .instances
                    .values()
                    .flat_map(|metadata| metadata.filter(&query))
                    .map(|instance| (instance.id(), instance))
                    .collect();
340
341
342

            tracing::debug!(
                stream_id = %stream_id,
343
                initial_count = initial.len(),
344
345
346
347
                "Watch started for query={:?}",
                query
            );

348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
            // Emit initial Added events (the "list" part of list_and_watch)
            for instance in initial.values() {
                tracing::info!(
                    stream_id = %stream_id,
                    instance_id = format!("{:x}", instance.instance_id()),
                    "Emitting initial Added event"
                );
                if event_tx
                    .send(Ok(DiscoveryEvent::Added(instance.clone())))
                    .is_err()
                {
                    tracing::debug!(
                        stream_id = %stream_id,
                        "Watch receiver dropped during initial sync"
                    );
                    return;
364
365
366
                }
            }

367
368
369
            // Track known instances by their unique ID
            let mut known: HashSet<DiscoveryInstanceId> = initial.into_keys().collect();

370
            loop {
371
372
                tracing::trace!(
                    stream_id = %stream_id,
373
                    known_count = known.len(),
374
375
376
                    "Watch loop waiting for changes"
                );

377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
                // Wait for next snapshot or cancellation
                let watch_result = if let Some(ref token) = cancel_token {
                    tokio::select! {
                        result = watch_rx.changed() => result,
                        _ = token.cancelled() => {
                            tracing::info!(
                                stream_id = %stream_id,
                                "Watch cancelled via cancel token"
                            );
                            break;
                        }
                    }
                } else {
                    watch_rx.changed().await
                };

                match watch_result {
                    Ok(()) => {
                        // Get latest snapshot
                        let snapshot = watch_rx.borrow_and_update().clone();

398
399
400
401
402
403
404
405
406
407
408
                        // Build current map: DiscoveryInstanceId -> DiscoveryInstance
                        let current: std::collections::HashMap<
                            DiscoveryInstanceId,
                            DiscoveryInstance,
                        > = snapshot
                            .instances
                            .values()
                            .flat_map(|metadata| metadata.filter(&query))
                            .map(|instance| (instance.id(), instance))
                            .collect();

409
410
411
                        tracing::debug!(
                            stream_id = %stream_id,
                            seq = snapshot.sequence,
412
413
                            current_count = current.len(),
                            known_count = known.len(),
414
415
416
                            "Watch received snapshot update"
                        );

417
418
419
                        // Compute diff using keys
                        let current_keys: HashSet<&DiscoveryInstanceId> = current.keys().collect();
                        let known_keys: HashSet<&DiscoveryInstanceId> = known.iter().collect();
420

421
422
                        let added: Vec<&DiscoveryInstanceId> =
                            current_keys.difference(&known_keys).copied().collect();
423

424
425
426
                        let removed: Vec<DiscoveryInstanceId> = known_keys
                            .difference(&current_keys)
                            .map(|&id| id.clone())
427
428
                            .collect();

429
430
431
432
433
434
435
436
                        // Log diff results (even if empty, for debugging)
                        if added.is_empty() && removed.is_empty() {
                            tracing::debug!(
                                stream_id = %stream_id,
                                seq = snapshot.sequence,
                                "Watch snapshot received but no diff detected"
                            );
                        } else {
437
438
439
440
441
                            tracing::debug!(
                                stream_id = %stream_id,
                                seq = snapshot.sequence,
                                added = added.len(),
                                removed = removed.len(),
442
                                total = current.len(),
443
444
445
446
447
                                "Watch detected changes"
                            );
                        }

                        // Emit Added events
448
449
450
451
452
453
454
455
456
457
458
459
                        for id in added {
                            if let Some(instance) = current.get(id) {
                                tracing::info!(
                                    stream_id = %stream_id,
                                    instance_id = format!("{:x}", instance.instance_id()),
                                    "Emitting Added event"
                                );
                                if event_tx
                                    .send(Ok(DiscoveryEvent::Added(instance.clone())))
                                    .is_err()
                                {
                                    tracing::debug!(
460
                                        stream_id = %stream_id,
461
                                        "Watch receiver dropped"
462
                                    );
463
                                    return;
464
465
466
467
468
                                }
                            }
                        }

                        // Emit Removed events
469
                        for id in removed {
470
471
                            tracing::info!(
                                stream_id = %stream_id,
472
                                id = ?id,
473
474
                                "Emitting Removed event"
                            );
475
                            if event_tx.send(Ok(DiscoveryEvent::Removed(id))).is_err() {
476
477
478
479
480
481
                                tracing::debug!(stream_id = %stream_id, "Watch receiver dropped");
                                return;
                            }
                        }

                        // Update known set
482
                        known = current.into_keys().collect();
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
                    }
                    Err(_) => {
                        tracing::info!(
                            stream_id = %stream_id,
                            "Watch channel closed (daemon stopped)"
                        );
                        break;
                    }
                }
            }
        });

        // Convert receiver to stream
        let stream = tokio_stream::wrappers::UnboundedReceiverStream::new(event_rx);
        Ok(Box::pin(stream))
    }
}