distributed.rs 20.5 KB
Newer Older
1
2
// SPDX-FileCopyrightText: Copyright (c) 2024-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
Ryan Olson's avatar
Ryan Olson committed
3

4
use crate::component::{Component, Instance};
5
use crate::pipeline::PipelineError;
6
use crate::storage::key_value_store::{
7
8
    EtcdStore, KeyValueStore, KeyValueStoreEnum, KeyValueStoreManager, KeyValueStoreSelect,
    MemoryStore,
9
};
10
use crate::transports::nats::DRTNatsClientPrometheusMetrics;
Ryan Olson's avatar
Ryan Olson committed
11
use crate::{
12
    component::{self, ComponentBuilder, Endpoint, Namespace},
13
    discovery::Discovery,
14
15
    metrics::PrometheusUpdateCallback,
    metrics::{MetricsHierarchy, MetricsRegistry},
Ryan Olson's avatar
Ryan Olson committed
16
17
18
    service::ServiceClient,
    transports::{etcd, nats, tcp},
};
19
use crate::{discovery, system_status_server, transports};
Ryan Olson's avatar
Ryan Olson committed
20

21
use super::utils::GracefulShutdownTracker;
22
23
use crate::SystemHealth;
use crate::runtime::Runtime;
Ryan Olson's avatar
Ryan Olson committed
24

25
26
use async_once_cell::OnceCell;
use std::sync::{Arc, OnceLock, Weak};
27
use tokio::sync::watch::Receiver;
28
29

use anyhow::Result;
Ryan Olson's avatar
Ryan Olson committed
30
31
use derive_getters::Dissolve;
use figment::error;
32
33
use std::collections::HashMap;
use tokio::sync::Mutex;
34
use tokio_util::sync::CancellationToken;
Ryan Olson's avatar
Ryan Olson committed
35

36
37
type InstanceMap = HashMap<Endpoint, Weak<Receiver<Vec<Instance>>>>;

38
39
40
41
42
43
44
/// Distributed [Runtime] which provides access to shared resources across the cluster, this includes
/// communication protocols and transports.
#[derive(Clone)]
pub struct DistributedRuntime {
    // local runtime
    runtime: Runtime,

45
    // Unified transport manager
46
47
48
49
    etcd_client: Option<transports::etcd::Client>,
    nats_client: Option<transports::nats::Client>,
    store: KeyValueStoreManager,
    tcp_server: Arc<OnceCell<Arc<transports::tcp::server::TcpStreamServer>>>,
50
    network_manager: Arc<OnceCell<Arc<crate::pipeline::network::manager::NetworkManager>>>,
51
52
53
54
55
    system_status_server: Arc<OnceLock<Arc<system_status_server::SystemStatusServerInfo>>>,

    // Service discovery client
    discovery_client: Arc<dyn discovery::Discovery>,

56
57
58
59
    // Discovery metadata (only used for Kubernetes backend)
    // Shared with system status server to expose via /metadata endpoint
    discovery_metadata: Option<Arc<tokio::sync::RwLock<discovery::DiscoveryMetadata>>>,

60
61
62
63
64
65
66
    // local registry for components
    // the registry allows us to use share runtime resources across instances of the same component object.
    // take for example two instances of a client to the same remote component. The registry allows us to use
    // a single endpoint watcher for both clients, this keeps the number background tasking watching specific
    // paths in etcd to a minimum.
    component_registry: component::Registry,

67
    instance_sources: Arc<tokio::sync::Mutex<InstanceMap>>,
68
69
70
71
72
73
74
75

    // Health Status
    system_health: Arc<parking_lot::Mutex<SystemHealth>>,

    // This hierarchy's own metrics registry
    metrics_registry: MetricsRegistry,
}

76
impl MetricsHierarchy for DistributedRuntime {
77
78
79
80
    fn basename(&self) -> String {
        "".to_string() // drt has no basename. Basename only begins with the Namespace.
    }

81
82
83
84
85
86
    fn parent_hierarchies(&self) -> Vec<&dyn MetricsHierarchy> {
        vec![] // drt is the root, so no parent hierarchies
    }

    fn get_metrics_registry(&self) -> &MetricsRegistry {
        &self.metrics_registry
87
88
89
    }
}

Ryan Olson's avatar
Ryan Olson committed
90
91
92
93
94
95
impl std::fmt::Debug for DistributedRuntime {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "DistributedRuntime")
    }
}

Ryan Olson's avatar
Ryan Olson committed
96
97
impl DistributedRuntime {
    pub async fn new(runtime: Runtime, config: DistributedConfig) -> Result<Self> {
98
        let (selected_kv_store, nats_config) = config.dissolve();
Ryan Olson's avatar
Ryan Olson committed
99
100
101

        let runtime_clone = runtime.clone();

102
103
        let (etcd_client, store) = match selected_kv_store {
            KeyValueStoreSelect::Etcd(etcd_config) => {
104
105
106
107
108
109
110
                let etcd_client = etcd::Client::new(*etcd_config, runtime_clone).await.inspect_err(|err|
                    // The returned error doesn't show because of a dropped runtime error, so
                    // log it first.
                    tracing::error!(%err, "Could not connect to etcd. Pass `--store-kv ..` to use a different backend or start etcd."))?;
                let store = KeyValueStoreManager::etcd(etcd_client.clone());
                (Some(etcd_client), store)
            }
111
112
            KeyValueStoreSelect::File(root) => (None, KeyValueStoreManager::file(root)),
            KeyValueStoreSelect::Memory => (None, KeyValueStoreManager::memory()),
113
        };
Ryan Olson's avatar
Ryan Olson committed
114

115
        let nats_client = Some(nats_config.clone().connect().await?);
Ryan Olson's avatar
Ryan Olson committed
116

117
        // Start system status server for health and metrics if enabled in configuration
118
119
120
121
122
123
124
125
        let config = crate::config::RuntimeConfig::from_settings().unwrap_or_default();
        // IMPORTANT: We must extract cancel_token from runtime BEFORE moving runtime into the struct below.
        // This is because after moving, runtime is no longer accessible in this scope (ownership rules).
        let cancel_token = if config.system_server_enabled() {
            Some(runtime.clone().child_token())
        } else {
            None
        };
126
127
        let starting_health_status = config.starting_health_status.clone();
        let use_endpoint_health_status = config.use_endpoint_health_status.clone();
128
129
        let health_endpoint_path = config.system_health_path.clone();
        let live_endpoint_path = config.system_live_path.clone();
130
        let system_health = Arc::new(parking_lot::Mutex::new(SystemHealth::new(
131
132
            starting_health_status,
            use_endpoint_health_status,
133
134
            health_endpoint_path,
            live_endpoint_path,
135
        )));
136

137
138
        let nats_client_for_metrics = nats_client.clone();

139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
        // Initialize discovery client based on backend configuration
        let discovery_backend =
            std::env::var("DYN_DISCOVERY_BACKEND").unwrap_or_else(|_| "kv_store".to_string());

        let (discovery_client, discovery_metadata) = match discovery_backend.as_str() {
            "kubernetes" => {
                tracing::info!("Initializing Kubernetes discovery backend");
                let metadata = Arc::new(tokio::sync::RwLock::new(
                    crate::discovery::DiscoveryMetadata::new(),
                ));
                let client = crate::discovery::KubeDiscoveryClient::new(
                    metadata.clone(),
                    runtime.primary_token(),
                )
                .await
                .inspect_err(
                    |err| tracing::error!(%err, "Failed to initialize Kubernetes discovery client"),
                )?;
                (Arc::new(client) as Arc<dyn Discovery>, Some(metadata))
            }
            _ => {
                tracing::info!("Initializing KV store discovery backend");
                use crate::discovery::KVStoreDiscovery;
                (
                    Arc::new(KVStoreDiscovery::new(
                        store.clone(),
                        runtime.primary_token(),
                    )) as Arc<dyn Discovery>,
                    None,
                )
            }
170
171
        };

172
        let distributed_runtime = Self {
Ryan Olson's avatar
Ryan Olson committed
173
174
            runtime,
            etcd_client,
175
            store,
Ryan Olson's avatar
Ryan Olson committed
176
177
            nats_client,
            tcp_server: Arc::new(OnceCell::new()),
178
            network_manager: Arc::new(OnceCell::new()),
179
            system_status_server: Arc::new(OnceLock::new()),
180
            discovery_client,
181
            discovery_metadata,
Ryan Olson's avatar
Ryan Olson committed
182
            component_registry: component::Registry::new(),
183
            instance_sources: Arc::new(Mutex::new(HashMap::new())),
184
            metrics_registry: crate::MetricsRegistry::new(),
185
            system_health,
186
187
        };

188
189
190
191
192
        if let Some(nats_client_for_metrics) = nats_client_for_metrics {
            let nats_client_metrics = DRTNatsClientPrometheusMetrics::new(
                &distributed_runtime,
                nats_client_for_metrics.client().clone(),
            )?;
193
            // Register a callback to update NATS client metrics on the DRT's metrics registry
194
195
196
197
198
199
200
201
            let nats_client_callback = Arc::new({
                let nats_client_clone = nats_client_metrics.clone();
                move || {
                    nats_client_clone.set_from_client_stats();
                    Ok(())
                }
            });
            distributed_runtime
202
203
                .metrics_registry
                .add_update_callback(nats_client_callback);
204
        }
205

206
207
208
209
210
211
        // Initialize the uptime gauge in SystemHealth
        distributed_runtime
            .system_health
            .lock()
            .initialize_uptime_gauge(&distributed_runtime)?;

212
        // Handle system status server initialization
213
        if let Some(cancel_token) = cancel_token {
214
            // System server is enabled - start both the state and HTTP server
215
            let host = config.system_host.clone();
216
            let port = config.system_port as u16;
217

218
            // Start system status server (it creates SystemStatusState internally)
219
            match crate::system_status_server::spawn_system_status_server(
220
221
222
223
                &host,
                port,
                cancel_token,
                Arc::new(distributed_runtime.clone()),
224
                distributed_runtime.discovery_metadata.clone(),
225
226
227
            )
            .await
            {
228
                Ok((addr, handle)) => {
229
                    tracing::info!("System status server started successfully on {}", addr);
230

231
232
233
234
235
236
                    // Store system status server information
                    let system_status_server_info =
                        crate::system_status_server::SystemStatusServerInfo::new(
                            addr,
                            Some(handle),
                        );
237

238
                    // Initialize the system_status_server field
239
                    distributed_runtime
240
241
242
                        .system_status_server
                        .set(Arc::new(system_status_server_info))
                        .expect("System status server info should only be set once");
243
244
                }
                Err(e) => {
245
                    tracing::error!("System status server startup failed: {}", e);
246
                }
247
            }
248
        } else {
249
            // System server HTTP is disabled, but uptime metrics are still being tracked via SystemHealth
250
251
252
            tracing::debug!(
                "System status server HTTP endpoints disabled, but uptime metrics are being tracked"
            );
253
254
        }

255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
        // Start health check manager if enabled
        if config.health_check_enabled {
            let health_check_config = crate::health_check::HealthCheckConfig {
                canary_wait_time: std::time::Duration::from_secs(config.canary_wait_time_secs),
                request_timeout: std::time::Duration::from_secs(
                    config.health_check_request_timeout_secs,
                ),
            };

            // Start the health check manager (spawns per-endpoint monitoring tasks)
            match crate::health_check::start_health_check_manager(
                distributed_runtime.clone(),
                Some(health_check_config),
            )
            .await
            {
                Ok(()) => tracing::info!(
                    "Health check manager started (canary_wait_time: {}s, request_timeout: {}s)",
                    config.canary_wait_time_secs,
                    config.health_check_request_timeout_secs
                ),
                Err(e) => tracing::error!("Health check manager failed to start: {}", e),
            }
        }

280
        Ok(distributed_runtime)
Ryan Olson's avatar
Ryan Olson committed
281
282
283
    }

    pub async fn from_settings(runtime: Runtime) -> Result<Self> {
284
        let config = DistributedConfig::from_settings();
Ryan Olson's avatar
Ryan Olson committed
285
286
287
288
289
290
291
        Self::new(runtime, config).await
    }

    pub fn runtime(&self) -> &Runtime {
        &self.runtime
    }

292
293
294
295
    pub fn primary_token(&self) -> CancellationToken {
        self.runtime.primary_token()
    }

296
297
298
299
300
301
302
303
304
305
306
    // TODO: Don't hand out pointers, instead have methods to use the registry in friendly ways
    // (without being aware of async locks and so on)
    pub fn component_registry(&self) -> &component::Registry {
        &self.component_registry
    }

    // TODO: Don't hand out pointers, instead provide system health related services.
    pub fn system_health(&self) -> Arc<parking_lot::Mutex<SystemHealth>> {
        self.system_health.clone()
    }

307
    pub fn connection_id(&self) -> u64 {
308
        self.discovery_client.instance_id()
Ryan Olson's avatar
Ryan Olson committed
309
310
311
312
    }

    pub fn shutdown(&self) {
        self.runtime.shutdown();
313
        self.store.shutdown();
Ryan Olson's avatar
Ryan Olson committed
314
315
316
317
    }

    /// Create a [`Namespace`]
    pub fn namespace(&self, name: impl Into<String>) -> Result<Namespace> {
318
        Namespace::new(self.clone(), name.into())
Ryan Olson's avatar
Ryan Olson committed
319
320
    }

321
322
323
    /// Returns the discovery interface for service registration and discovery
    pub fn discovery(&self) -> Arc<dyn Discovery> {
        self.discovery_client.clone()
324
325
    }

326
327
    pub(crate) fn service_client(&self) -> Option<ServiceClient> {
        self.nats_client().map(|nc| ServiceClient::new(nc.clone()))
Ryan Olson's avatar
Ryan Olson committed
328
329
    }

330
    pub async fn tcp_server(&self) -> Result<Arc<tcp::server::TcpStreamServer>> {
Ryan Olson's avatar
Ryan Olson committed
331
332
333
334
335
        Ok(self
            .tcp_server
            .get_or_try_init(async move {
                let options = tcp::server::ServerOptions::default();
                let server = tcp::server::TcpStreamServer::new(options).await?;
336
                Ok::<_, PipelineError>(server)
Ryan Olson's avatar
Ryan Olson committed
337
338
339
340
341
            })
            .await?
            .clone())
    }

342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
    /// Get the network manager (lazy initialization)
    ///
    /// The network manager consolidates all network configuration and provides
    /// unified access to request plane servers and clients.
    pub async fn network_manager(
        &self,
    ) -> Result<Arc<crate::pipeline::network::manager::NetworkManager>> {
        use crate::pipeline::network::manager::NetworkManager;

        let manager = self
            .network_manager
            .get_or_try_init(async {
                // Get NATS client if available
                let nats_client = self.nats_client().map(|c| c.client().clone());

                // NetworkManager handles all config reading and mode selection
                anyhow::Ok(NetworkManager::new(
                    self.child_token(),
                    nats_client,
                    self.component_registry.clone(),
                ))
            })
            .await?;

        Ok(manager.clone())
    }

    /// Get the request plane server (convenience method)
    ///
    /// This is a shortcut for `network_manager().await?.server().await`.
    pub async fn request_plane_server(
        &self,
    ) -> Result<Arc<dyn crate::pipeline::network::ingress::unified_server::RequestPlaneServer>>
    {
        let manager = self.network_manager().await?;
        manager.server().await
    }

    /// DEPRECATED: Use network_manager().server() instead
    #[deprecated(note = "Use request_plane_server() or network_manager().server() instead")]
    pub async fn http_server(
        &self,
    ) -> Result<Arc<crate::pipeline::network::ingress::http_endpoint::SharedHttpServer>> {
        // For backward compatibility, try to downcast
        let _server = self.request_plane_server().await?;
        // This will only work if we're actually in HTTP mode
        // For now, just return an error suggesting the new API
        anyhow::bail!(
            "http_server() is deprecated. Use request_plane_server() instead, which returns a trait object that works with all transport types."
        )
    }

    /// DEPRECATED: Use network_manager().server() instead
    #[deprecated(note = "Use request_plane_server() or network_manager().server() instead")]
    pub async fn shared_tcp_server(
        &self,
    ) -> Result<Arc<crate::pipeline::network::ingress::shared_tcp_endpoint::SharedTcpServer>> {
        // For backward compatibility, try to downcast
        let _server = self.request_plane_server().await?;
        // This will only work if we're actually in TCP mode
        // For now, just return an error suggesting the new API
        anyhow::bail!(
            "shared_tcp_server() is deprecated. Use request_plane_server() instead, which returns a trait object that works with all transport types."
        )
    }

408
409
    pub fn nats_client(&self) -> Option<&nats::Client> {
        self.nats_client.as_ref()
Ryan Olson's avatar
Ryan Olson committed
410
411
    }

412
413
414
415
416
    /// Get system status server information if available
    pub fn system_status_server_info(
        &self,
    ) -> Option<Arc<crate::system_status_server::SystemStatusServerInfo>> {
        self.system_status_server.get().cloned()
417
418
    }

419
    // todo(ryan): deprecate this as we move to Discovery traits and Component Identifiers
420
421
422
    //
    // Try to use `store()` instead of this. Only use this if you have not been able to migrate
    // yet, or if you require etcd-specific features like distributed locking (rare).
423
    pub fn etcd_client(&self) -> Option<etcd::Client> {
Ryan Olson's avatar
Ryan Olson committed
424
425
        self.etcd_client.clone()
    }
426

427
428
    /// An interface to store things. Will eventually replace `etcd_client`.
    /// Currently does key-value, but will grow to include whatever we need to store.
429
430
    pub fn store(&self) -> &KeyValueStoreManager {
        &self.store
431
432
    }

433
434
435
    pub fn child_token(&self) -> CancellationToken {
        self.runtime.child_token()
    }
436

437
438
439
440
    pub(crate) fn graceful_shutdown_tracker(&self) -> Arc<GracefulShutdownTracker> {
        self.runtime.graceful_shutdown_tracker()
    }

441
    pub fn instance_sources(&self) -> Arc<Mutex<InstanceMap>> {
442
443
        self.instance_sources.clone()
    }
Ryan Olson's avatar
Ryan Olson committed
444
445
446
447
}

#[derive(Dissolve)]
pub struct DistributedConfig {
448
    pub store_backend: KeyValueStoreSelect,
Ryan Olson's avatar
Ryan Olson committed
449
450
451
452
    pub nats_config: nats::ClientOptions,
}

impl DistributedConfig {
453
    pub fn from_settings() -> DistributedConfig {
Ryan Olson's avatar
Ryan Olson committed
454
        DistributedConfig {
455
            store_backend: KeyValueStoreSelect::Etcd(Box::default()),
Ryan Olson's avatar
Ryan Olson committed
456
457
458
            nats_config: nats::ClientOptions::default(),
        }
    }
Ryan Olson's avatar
Ryan Olson committed
459
460

    pub fn for_cli() -> DistributedConfig {
461
462
463
464
465
466
        let etcd_config = etcd::ClientOptions {
            attach_lease: false,
            ..Default::default()
        };
        DistributedConfig {
            store_backend: KeyValueStoreSelect::Etcd(Box::new(etcd_config)),
Ryan Olson's avatar
Ryan Olson committed
467
            nats_config: nats::ClientOptions::default(),
468
        }
Ryan Olson's avatar
Ryan Olson committed
469
    }
Ryan Olson's avatar
Ryan Olson committed
470
}
471

472
pub mod distributed_test_utils {
473
474
    //! Common test helper functions for DistributedRuntime tests

475
    /// Helper function to create a DRT instance for integration-only tests.
476
    /// Uses from_current to leverage existing tokio runtime
477
    /// Note: Settings are read from environment variables inside DistributedRuntime::from_settings
478
    #[cfg(feature = "integration")]
479
480
481
    pub async fn create_test_drt_async() -> super::DistributedRuntime {
        use crate::{storage::key_value_store::KeyValueStoreSelect, transports::nats};

482
        let rt = crate::Runtime::from_current().unwrap();
483
484
485
486
487
        let config = super::DistributedConfig {
            store_backend: KeyValueStoreSelect::Memory,
            nats_config: nats::ClientOptions::default(),
        };
        super::DistributedRuntime::new(rt, config).await.unwrap()
488
489
    }
}
490

491
#[cfg(all(test, feature = "integration"))]
492
493
494
495
496
497
mod tests {
    use super::distributed_test_utils::create_test_drt_async;

    #[tokio::test]
    async fn test_drt_uptime_after_delay_system_disabled() {
        // Test uptime with system status server disabled
498
        temp_env::async_with_vars([("DYN_SYSTEM_PORT", None::<&str>)], async {
499
500
501
502
503
504
505
            // Start a DRT
            let drt = create_test_drt_async().await;

            // Wait 50ms
            tokio::time::sleep(tokio::time::Duration::from_millis(50)).await;

            // Check that uptime is 50+ ms
506
            let uptime = drt.system_health.lock().uptime();
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
            assert!(
                uptime >= std::time::Duration::from_millis(50),
                "Expected uptime to be at least 50ms, but got {:?}",
                uptime
            );

            println!(
                "✓ DRT uptime test passed (system disabled): uptime = {:?}",
                uptime
            );
        })
        .await;
    }

    #[tokio::test]
    async fn test_drt_uptime_after_delay_system_enabled() {
        // Test uptime with system status server enabled
524
        temp_env::async_with_vars([("DYN_SYSTEM_PORT", Some("8081"))], async {
525
526
527
528
529
530
531
            // Start a DRT
            let drt = create_test_drt_async().await;

            // Wait 50ms
            tokio::time::sleep(tokio::time::Duration::from_millis(50)).await;

            // Check that uptime is 50+ ms
532
            let uptime = drt.system_health.lock().uptime();
533
534
535
536
537
538
539
540
541
542
543
544
545
546
            assert!(
                uptime >= std::time::Duration::from_millis(50),
                "Expected uptime to be at least 50ms, but got {:?}",
                uptime
            );

            println!(
                "✓ DRT uptime test passed (system enabled): uptime = {:?}",
                uptime
            );
        })
        .await;
    }
}