"deploy/cloud/vscode:/vscode.git/clone" did not exist on "043c80c4b3413fc0ed7d3692d328a83ed5a5c89f"
distributed.rs 8.41 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// SPDX-FileCopyrightText: Copyright (c) 2024-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Ryan Olson's avatar
Ryan Olson committed
15
16
17

pub use crate::component::Component;
use crate::{
18
    component::{self, ComponentBuilder, Endpoint, InstanceSource, Namespace},
Ryan Olson's avatar
Ryan Olson committed
19
    discovery::DiscoveryClient,
20
    metrics::MetricsRegistry,
Ryan Olson's avatar
Ryan Olson committed
21
22
23
24
25
    service::ServiceClient,
    transports::{etcd, nats, tcp},
    ErrorContext,
};

26
use super::{error, Arc, DistributedRuntime, OnceCell, Result, Runtime, SystemHealth, Weak, OK};
Ryan Olson's avatar
Ryan Olson committed
27
28
29

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

34
35
36
37
38
39
40
41
42
43
impl MetricsRegistry for DistributedRuntime {
    fn basename(&self) -> String {
        "".to_string() // drt has no basename. Basename only begins with the Namespace.
    }

    fn parent_hierarchy(&self) -> Vec<String> {
        vec![] // drt is the root, so no parent hierarchy
    }
}

Ryan Olson's avatar
Ryan Olson committed
44
45
46
impl DistributedRuntime {
    pub async fn new(runtime: Runtime, config: DistributedConfig) -> Result<Self> {
        let secondary = runtime.secondary();
47
        let (etcd_config, nats_config, is_static) = config.dissolve();
Ryan Olson's avatar
Ryan Olson committed
48
49
50

        let runtime_clone = runtime.clone();

51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
        let etcd_client = if is_static {
            None
        } else {
            Some(
                secondary
                    .spawn(async move {
                        let client = etcd::Client::new(etcd_config.clone(), runtime_clone)
                            .await
                            .context(format!(
                                "Failed to connect to etcd server with config {:?}",
                                etcd_config
                            ))?;
                        OK(client)
                    })
                    .await??,
            )
        };
Ryan Olson's avatar
Ryan Olson committed
68
69
70
71
72
73
74
75
76
77
78

        let nats_client = secondary
            .spawn(async move {
                let client = nats_config.clone().connect().await.context(format!(
                    "Failed to connect to NATS server with config {:?}",
                    nats_config
                ))?;
                anyhow::Ok(client)
            })
            .await??;

79
80
81
82
83
84
85
86
87
        // Start HTTP server for health and metrics if enabled in configuration
        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
        };
88
89
90
91
92
93
        let starting_health_status = config.starting_health_status.clone();
        let use_endpoint_health_status = config.use_endpoint_health_status.clone();
        let system_health = Arc::new(Mutex::new(SystemHealth::new(
            starting_health_status,
            use_endpoint_health_status,
        )));
94

95
        let distributed_runtime = Self {
Ryan Olson's avatar
Ryan Olson committed
96
97
98
99
100
            runtime,
            etcd_client,
            nats_client,
            tcp_server: Arc::new(OnceCell::new()),
            component_registry: component::Registry::new(),
101
            is_static,
102
            instance_sources: Arc::new(Mutex::new(HashMap::new())),
103
104
105
106
            prometheus_registries_by_prefix: Arc::new(std::sync::Mutex::new(HashMap::<
                String,
                prometheus::Registry,
            >::new())),
107
            system_health,
108
109
        };

110
111
112
113
114
115
        // Start HTTP server if enabled
        if let Some(cancel_token) = cancel_token {
            let host = config.system_host.clone();
            let port = config.system_port;

            // Start HTTP server (it spawns its own task internally)
116
            match crate::http_server::spawn_http_server(
117
118
119
120
                &host,
                port,
                cancel_token,
                Arc::new(distributed_runtime.clone()),
121
122
123
            )
            .await
            {
124
                Ok((addr, _)) => {
125
126
127
                    tracing::info!("HTTP server started successfully on {}", addr);
                }
                Err(e) => {
128
129
                    tracing::error!("HTTP server startup failed: {}", e);
                }
130
            }
131
        } else {
132
            tracing::debug!("Health and metrics HTTP server is disabled via DYN_SYSTEM_ENABLED");
133
134
135
        }

        Ok(distributed_runtime)
Ryan Olson's avatar
Ryan Olson committed
136
137
138
    }

    pub async fn from_settings(runtime: Runtime) -> Result<Self> {
139
140
141
142
143
144
145
        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
146
147
148
149
150
151
152
        Self::new(runtime, config).await
    }

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

153
154
155
156
    pub fn primary_token(&self) -> CancellationToken {
        self.runtime.primary_token()
    }

157
158
159
160
    /// The etcd lease all our components will be attached to.
    /// Not available for static workers.
    pub fn primary_lease(&self) -> Option<etcd::Lease> {
        self.etcd_client.as_ref().map(|c| c.primary_lease())
Ryan Olson's avatar
Ryan Olson committed
161
162
163
164
165
166
167
168
    }

    pub fn shutdown(&self) {
        self.runtime.shutdown();
    }

    /// Create a [`Namespace`]
    pub fn namespace(&self, name: impl Into<String>) -> Result<Namespace> {
169
        Namespace::new(self.clone(), name.into(), self.is_static)
Ryan Olson's avatar
Ryan Olson committed
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
    }

    // /// Create a [`Component`]
    // pub fn component(
    //     &self,
    //     name: impl Into<String>,
    //     namespace: impl Into<String>,
    // ) -> Result<Component> {
    //     Ok(ComponentBuilder::from_runtime(self.clone())
    //         .name(name.into())
    //         .namespace(namespace.into())
    //         .build()?)
    // }

    pub(crate) fn discovery_client(&self, namespace: impl Into<String>) -> DiscoveryClient {
185
186
187
188
189
190
        DiscoveryClient::new(
            namespace.into(),
            self.etcd_client
                .clone()
                .expect("Attempt to get discovery_client on static DistributedRuntime"),
        )
Ryan Olson's avatar
Ryan Olson committed
191
192
193
194
195
196
    }

    pub(crate) fn service_client(&self) -> ServiceClient {
        ServiceClient::new(self.nats_client.clone())
    }

197
    pub async fn tcp_server(&self) -> Result<Arc<tcp::server::TcpStreamServer>> {
Ryan Olson's avatar
Ryan Olson committed
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
        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())
    }

    pub fn nats_client(&self) -> nats::Client {
        self.nats_client.clone()
    }

213
    // todo(ryan): deprecate this as we move to Discovery traits and Component Identifiers
214
    pub fn etcd_client(&self) -> Option<etcd::Client> {
Ryan Olson's avatar
Ryan Olson committed
215
216
        self.etcd_client.clone()
    }
217
218
219
220

    pub fn child_token(&self) -> CancellationToken {
        self.runtime.child_token()
    }
221
222
223
224

    pub fn instance_sources(&self) -> Arc<Mutex<HashMap<Endpoint, Weak<InstanceSource>>>> {
        self.instance_sources.clone()
    }
Ryan Olson's avatar
Ryan Olson committed
225
226
227
228
229
230
}

#[derive(Dissolve)]
pub struct DistributedConfig {
    pub etcd_config: etcd::ClientOptions,
    pub nats_config: nats::ClientOptions,
231
    pub is_static: bool,
Ryan Olson's avatar
Ryan Olson committed
232
233
234
}

impl DistributedConfig {
235
    pub fn from_settings(is_static: bool) -> DistributedConfig {
Ryan Olson's avatar
Ryan Olson committed
236
237
238
        DistributedConfig {
            etcd_config: etcd::ClientOptions::default(),
            nats_config: nats::ClientOptions::default(),
239
            is_static,
Ryan Olson's avatar
Ryan Olson committed
240
241
        }
    }
Ryan Olson's avatar
Ryan Olson committed
242
243
244
245
246

    pub fn for_cli() -> DistributedConfig {
        let mut config = DistributedConfig {
            etcd_config: etcd::ClientOptions::default(),
            nats_config: nats::ClientOptions::default(),
247
            is_static: false,
Ryan Olson's avatar
Ryan Olson committed
248
249
250
251
252
253
        };

        config.etcd_config.attach_lease = false;

        config
    }
Ryan Olson's avatar
Ryan Olson committed
254
}