distributed.rs 14.7 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

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

20
use super::utils::GracefulShutdownTracker;
21
use super::{Arc, DistributedRuntime, OK, OnceCell, Result, Runtime, SystemHealth, Weak, error};
22
use std::sync::OnceLock;
Ryan Olson's avatar
Ryan Olson committed
23
24
25

use derive_getters::Dissolve;
use figment::error;
26
27
use std::collections::HashMap;
use tokio::sync::Mutex;
28
use tokio_util::sync::CancellationToken;
Ryan Olson's avatar
Ryan Olson committed
29

30
impl MetricsHierarchy for DistributedRuntime {
31
32
33
34
    fn basename(&self) -> String {
        "".to_string() // drt has no basename. Basename only begins with the Namespace.
    }

35
36
37
38
39
40
    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
41
42
43
    }
}

Ryan Olson's avatar
Ryan Olson committed
44
45
46
47
48
49
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
50
51
impl DistributedRuntime {
    pub async fn new(runtime: Runtime, config: DistributedConfig) -> Result<Self> {
52
        let (selected_kv_store, nats_config, is_static) = config.dissolve();
Ryan Olson's avatar
Ryan Olson committed
53
54
55

        let runtime_clone = runtime.clone();

56
57
58
59
60
61
62
63
64
65
66
67
        let (etcd_client, store) = match (is_static, selected_kv_store) {
            (false, KeyValueStoreSelect::Etcd(etcd_config)) => {
                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)
            }
            (false, KeyValueStoreSelect::File(root)) => (None, KeyValueStoreManager::file(root)),
            (true, _) | (false, KeyValueStoreSelect::Memory) => {
                (None, KeyValueStoreManager::memory())
68
            }
69
        };
Ryan Olson's avatar
Ryan Olson committed
70

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

73
        // Start system status server for health and metrics if enabled in configuration
74
75
76
77
78
79
80
81
        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
        };
82
83
        let starting_health_status = config.starting_health_status.clone();
        let use_endpoint_health_status = config.use_endpoint_health_status.clone();
84
85
        let health_endpoint_path = config.system_health_path.clone();
        let live_endpoint_path = config.system_live_path.clone();
86
        let system_health = Arc::new(parking_lot::Mutex::new(SystemHealth::new(
87
88
            starting_health_status,
            use_endpoint_health_status,
89
90
            health_endpoint_path,
            live_endpoint_path,
91
        )));
92

93
94
        let nats_client_for_metrics = nats_client.clone();

95
        // Initialize discovery backed by KV store
96
        let discovery_client = {
97
98
99
100
101
            use crate::discovery::KVStoreDiscovery;
            Arc::new(KVStoreDiscovery::new(
                store.clone(),
                runtime.primary_token(),
            )) as Arc<dyn Discovery>
102
103
        };

104
        let distributed_runtime = Self {
Ryan Olson's avatar
Ryan Olson committed
105
106
            runtime,
            etcd_client,
107
            store,
Ryan Olson's avatar
Ryan Olson committed
108
109
            nats_client,
            tcp_server: Arc::new(OnceCell::new()),
110
            system_status_server: Arc::new(OnceLock::new()),
111
            discovery_client,
Ryan Olson's avatar
Ryan Olson committed
112
            component_registry: component::Registry::new(),
113
            is_static,
114
            instance_sources: Arc::new(Mutex::new(HashMap::new())),
115
            metrics_registry: crate::MetricsRegistry::new(),
116
            system_health,
117
118
        };

119
120
121
122
123
        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(),
            )?;
124
            // Register a callback to update NATS client metrics on the DRT's metrics registry
125
126
127
128
129
130
131
132
            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
133
134
                .metrics_registry
                .add_update_callback(nats_client_callback);
135
        }
136

137
138
139
140
141
142
        // Initialize the uptime gauge in SystemHealth
        distributed_runtime
            .system_health
            .lock()
            .initialize_uptime_gauge(&distributed_runtime)?;

143
        // Handle system status server initialization
144
        if let Some(cancel_token) = cancel_token {
145
            // System server is enabled - start both the state and HTTP server
146
            let host = config.system_host.clone();
147
            let port = config.system_port as u16;
148

149
            // Start system status server (it creates SystemStatusState internally)
150
            match crate::system_status_server::spawn_system_status_server(
151
152
153
154
                &host,
                port,
                cancel_token,
                Arc::new(distributed_runtime.clone()),
155
156
157
            )
            .await
            {
158
                Ok((addr, handle)) => {
159
                    tracing::info!("System status server started successfully on {}", addr);
160

161
162
163
164
165
166
                    // Store system status server information
                    let system_status_server_info =
                        crate::system_status_server::SystemStatusServerInfo::new(
                            addr,
                            Some(handle),
                        );
167

168
                    // Initialize the system_status_server field
169
                    distributed_runtime
170
171
172
                        .system_status_server
                        .set(Arc::new(system_status_server_info))
                        .expect("System status server info should only be set once");
173
174
                }
                Err(e) => {
175
                    tracing::error!("System status server startup failed: {}", e);
176
                }
177
            }
178
        } else {
179
            // System server HTTP is disabled, but uptime metrics are still being tracked via SystemHealth
180
181
182
            tracing::debug!(
                "System status server HTTP endpoints disabled, but uptime metrics are being tracked"
            );
183
184
        }

185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
        // 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),
            }
        }

210
        Ok(distributed_runtime)
Ryan Olson's avatar
Ryan Olson committed
211
212
213
    }

    pub async fn from_settings(runtime: Runtime) -> Result<Self> {
214
215
216
217
218
219
220
        let config = DistributedConfig::from_settings(false);
        Self::new(runtime, config).await
    }

    // Call this if you are using static workers that do not need etcd-based discovery.
    pub async fn from_settings_without_discovery(runtime: Runtime) -> Result<Self> {
        let config = DistributedConfig::from_settings(true);
Ryan Olson's avatar
Ryan Olson committed
221
222
223
224
225
226
227
        Self::new(runtime, config).await
    }

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

228
229
230
231
    pub fn primary_token(&self) -> CancellationToken {
        self.runtime.primary_token()
    }

232
233
    pub fn connection_id(&self) -> u64 {
        self.store.connection_id()
Ryan Olson's avatar
Ryan Olson committed
234
235
236
237
    }

    pub fn shutdown(&self) {
        self.runtime.shutdown();
238
        self.store.shutdown();
Ryan Olson's avatar
Ryan Olson committed
239
240
241
242
    }

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

246
247
248
    /// Returns the discovery interface for service registration and discovery
    pub fn discovery(&self) -> Arc<dyn Discovery> {
        self.discovery_client.clone()
249
250
    }

251
252
    pub(crate) fn service_client(&self) -> Option<ServiceClient> {
        self.nats_client().map(|nc| ServiceClient::new(nc.clone()))
Ryan Olson's avatar
Ryan Olson committed
253
254
    }

255
    pub async fn tcp_server(&self) -> Result<Arc<tcp::server::TcpStreamServer>> {
Ryan Olson's avatar
Ryan Olson committed
256
257
258
259
260
261
262
263
264
265
266
        Ok(self
            .tcp_server
            .get_or_try_init(async move {
                let options = tcp::server::ServerOptions::default();
                let server = tcp::server::TcpStreamServer::new(options).await?;
                OK(server)
            })
            .await?
            .clone())
    }

267
268
    pub fn nats_client(&self) -> Option<&nats::Client> {
        self.nats_client.as_ref()
Ryan Olson's avatar
Ryan Olson committed
269
270
    }

271
272
273
274
275
    /// 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()
276
277
    }

278
    // todo(ryan): deprecate this as we move to Discovery traits and Component Identifiers
279
280
281
    //
    // 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).
282
    pub fn etcd_client(&self) -> Option<etcd::Client> {
Ryan Olson's avatar
Ryan Olson committed
283
284
        self.etcd_client.clone()
    }
285

286
287
    /// An interface to store things. Will eventually replace `etcd_client`.
    /// Currently does key-value, but will grow to include whatever we need to store.
288
289
    pub fn store(&self) -> &KeyValueStoreManager {
        &self.store
290
291
    }

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

296
297
298
299
    pub(crate) fn graceful_shutdown_tracker(&self) -> Arc<GracefulShutdownTracker> {
        self.runtime.graceful_shutdown_tracker()
    }

300
301
302
    pub fn instance_sources(&self) -> Arc<Mutex<HashMap<Endpoint, Weak<InstanceSource>>>> {
        self.instance_sources.clone()
    }
Ryan Olson's avatar
Ryan Olson committed
303
304
305
306
}

#[derive(Dissolve)]
pub struct DistributedConfig {
307
    pub store_backend: KeyValueStoreSelect,
Ryan Olson's avatar
Ryan Olson committed
308
    pub nats_config: nats::ClientOptions,
309
    pub is_static: bool,
Ryan Olson's avatar
Ryan Olson committed
310
311
312
}

impl DistributedConfig {
313
    pub fn from_settings(is_static: bool) -> DistributedConfig {
Ryan Olson's avatar
Ryan Olson committed
314
        DistributedConfig {
315
            store_backend: KeyValueStoreSelect::Etcd(Box::default()),
Ryan Olson's avatar
Ryan Olson committed
316
            nats_config: nats::ClientOptions::default(),
317
            is_static,
Ryan Olson's avatar
Ryan Olson committed
318
319
        }
    }
Ryan Olson's avatar
Ryan Olson committed
320
321

    pub fn for_cli() -> DistributedConfig {
322
323
324
325
326
327
        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
328
            nats_config: nats::ClientOptions::default(),
329
            is_static: false,
330
        }
Ryan Olson's avatar
Ryan Olson committed
331
    }
Ryan Olson's avatar
Ryan Olson committed
332
}
333

334
pub mod distributed_test_utils {
335
336
337
    //! Common test helper functions for DistributedRuntime tests
    // TODO: Use in-memory DistributedRuntime for tests instead of full runtime when available.

338
    /// Helper function to create a DRT instance for integration-only tests.
339
340
341
342
343
344
345
346
347
348
    /// Uses from_current to leverage existing tokio runtime
    /// Note: Settings are read from environment variables inside DistributedRuntime::from_settings_without_discovery
    #[cfg(feature = "integration")]
    pub async fn create_test_drt_async() -> crate::DistributedRuntime {
        let rt = crate::Runtime::from_current().unwrap();
        crate::DistributedRuntime::from_settings_without_discovery(rt)
            .await
            .unwrap()
    }
}
349

350
#[cfg(all(test, feature = "integration"))]
351
352
353
354
355
356
357
358
359
360
361
362
363
364
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
        temp_env::async_with_vars([("DYN_SYSTEM_ENABLED", Some("false"))], async {
            // 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
365
            let uptime = drt.system_health.lock().uptime();
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
            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
383
        temp_env::async_with_vars([("DYN_SYSTEM_PORT", Some("8081"))], async {
384
385
386
387
388
389
390
            // 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
391
            let uptime = drt.system_health.lock().uptime();
392
393
394
395
396
397
398
399
400
401
402
403
404
405
            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;
    }
}