/build/source/src/bin/nativelink.rs
Line | Count | Source |
1 | | // Copyright 2024 The NativeLink Authors. All rights reserved. |
2 | | // |
3 | | // Licensed under the Apache License, Version 2.0 (the "License"); |
4 | | // you may not use this file except in compliance with the License. |
5 | | // You may obtain a copy of the License at |
6 | | // |
7 | | // http://www.apache.org/licenses/LICENSE-2.0 |
8 | | // |
9 | | // Unless required by applicable law or agreed to in writing, software |
10 | | // distributed under the License is distributed on an "AS IS" BASIS, |
11 | | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
12 | | // See the License for the specific language governing permissions and |
13 | | // limitations under the License. |
14 | | |
15 | | use std::collections::{HashMap, HashSet}; |
16 | | use std::net::SocketAddr; |
17 | | use std::sync::Arc; |
18 | | use std::time::{Duration, SystemTime, UNIX_EPOCH}; |
19 | | |
20 | | use async_lock::Mutex as AsyncMutex; |
21 | | use axum::Router; |
22 | | use clap::Parser; |
23 | | use futures::future::{try_join_all, BoxFuture, Either, OptionFuture, TryFutureExt}; |
24 | | use futures::FutureExt; |
25 | | use hyper::{Response, StatusCode}; |
26 | | use hyper_util::rt::tokio::TokioIo; |
27 | | use hyper_util::server::conn::auto; |
28 | | use hyper_util::service::TowerToHyperService; |
29 | | use mimalloc::MiMalloc; |
30 | | use nativelink_config::cas_server::{ |
31 | | CasConfig, GlobalConfig, HttpCompressionAlgorithm, ListenerConfig, ServerConfig, WorkerConfig, |
32 | | }; |
33 | | use nativelink_config::stores::ConfigDigestHashFunction; |
34 | | use nativelink_config::{SchedulerConfig, StoreConfig}; |
35 | | use nativelink_error::{make_err, make_input_err, Code, Error, ResultExt}; |
36 | | use nativelink_metric::{ |
37 | | MetricFieldData, MetricKind, MetricPublishKnownKindData, MetricsComponent, RootMetricsComponent, |
38 | | }; |
39 | | use nativelink_metric_collector::{otel_export, MetricsCollectorLayer}; |
40 | | use nativelink_scheduler::default_scheduler_factory::scheduler_factory; |
41 | | use nativelink_service::ac_server::AcServer; |
42 | | use nativelink_service::bep_server::BepServer; |
43 | | use nativelink_service::bytestream_server::ByteStreamServer; |
44 | | use nativelink_service::capabilities_server::CapabilitiesServer; |
45 | | use nativelink_service::cas_server::CasServer; |
46 | | use nativelink_service::execution_server::ExecutionServer; |
47 | | use nativelink_service::health_server::HealthServer; |
48 | | use nativelink_service::worker_api_server::WorkerApiServer; |
49 | | use nativelink_store::default_store_factory::store_factory; |
50 | | use nativelink_store::store_manager::StoreManager; |
51 | | use nativelink_util::common::fs::set_open_file_limit; |
52 | | use nativelink_util::digest_hasher::{set_default_digest_hasher_func, DigestHasherFunc}; |
53 | | use nativelink_util::health_utils::HealthRegistryBuilder; |
54 | | use nativelink_util::metrics_utils::{set_metrics_enabled_for_this_thread, Counter}; |
55 | | use nativelink_util::operation_state_manager::ClientStateManager; |
56 | | use nativelink_util::origin_context::{ActiveOriginContext, OriginContext}; |
57 | | use nativelink_util::origin_event_middleware::OriginEventMiddlewareLayer; |
58 | | use nativelink_util::origin_event_publisher::OriginEventPublisher; |
59 | | use nativelink_util::shutdown_guard::{Priority, ShutdownGuard}; |
60 | | use nativelink_util::store_trait::{ |
61 | | set_default_digest_size_health_check, DEFAULT_DIGEST_SIZE_HEALTH_CHECK_CFG, |
62 | | }; |
63 | | use nativelink_util::task::TaskExecutor; |
64 | | use nativelink_util::{background_spawn, fs, init_tracing, spawn, spawn_blocking}; |
65 | | use nativelink_worker::local_worker::new_local_worker; |
66 | | use opentelemetry::metrics::MeterProvider; |
67 | | use opentelemetry_sdk::metrics::SdkMeterProvider; |
68 | | use parking_lot::{Mutex, RwLock}; |
69 | | use prometheus::{Encoder, TextEncoder}; |
70 | | use rustls_pemfile::{certs as extract_certs, crls as extract_crls}; |
71 | | use scopeguard::guard; |
72 | | use tokio::net::TcpListener; |
73 | | use tokio::select; |
74 | | #[cfg(target_family = "unix")] |
75 | | use tokio::signal::unix::{signal, SignalKind}; |
76 | | use tokio::sync::{broadcast, mpsc}; |
77 | | use tokio_rustls::rustls::pki_types::CertificateDer; |
78 | | use tokio_rustls::rustls::server::WebPkiClientVerifier; |
79 | | use tokio_rustls::rustls::{RootCertStore, ServerConfig as TlsServerConfig}; |
80 | | use tokio_rustls::TlsAcceptor; |
81 | | use tonic::codec::CompressionEncoding; |
82 | | use tonic::transport::Server as TonicServer; |
83 | | use tracing::{error_span, event, trace_span, Level}; |
84 | | use tracing_subscriber::layer::SubscriberExt; |
85 | | |
86 | | #[global_allocator] |
87 | | static GLOBAL: MiMalloc = MiMalloc; |
88 | | |
89 | | /// Note: This must be kept in sync with the documentation in `PrometheusConfig::path`. |
90 | | const DEFAULT_PROMETHEUS_METRICS_PATH: &str = "/metrics"; |
91 | | |
92 | | /// Note: This must be kept in sync with the documentation in `AdminConfig::path`. |
93 | | const DEFAULT_ADMIN_API_PATH: &str = "/admin"; |
94 | | |
95 | | // Note: This must be kept in sync with the documentation in `HealthConfig::path`. |
96 | | const DEFAULT_HEALTH_STATUS_CHECK_PATH: &str = "/status"; |
97 | | |
98 | | /// Name of environment variable to disable metrics. |
99 | | const METRICS_DISABLE_ENV: &str = "NATIVELINK_DISABLE_METRICS"; |
100 | | |
101 | | // Note: This must be kept in sync with the documentation in |
102 | | // `OriginEventsConfig::max_event_queue_size`. |
103 | | const DEFAULT_MAX_QUEUE_EVENTS: usize = 65536; |
104 | | |
105 | | /// Broadcast Channel Capacity |
106 | | /// Note: The actual capacity may be greater than the provided capacity. |
107 | | const BROADCAST_CAPACITY: usize = 1; |
108 | | |
109 | | /// Backend for bazel remote execution / cache API. |
110 | | #[derive(Parser, Debug)] |
111 | | #[clap( |
112 | | author = "Trace Machina, Inc. <nativelink@tracemachina.com>", |
113 | | version, |
114 | | about, |
115 | | long_about = None |
116 | | )] |
117 | | struct Args { |
118 | | /// Config file to use. |
119 | | #[clap(value_parser)] |
120 | 0 | config_file: String, |
121 | | } |
122 | | |
123 | | /// The root metrics collector struct. All metrics will be |
124 | | /// collected from this struct traversing down each child |
125 | | /// component. |
126 | | #[derive(MetricsComponent)] |
127 | | struct RootMetrics { |
128 | | #[metric(group = "stores")] |
129 | | stores: Arc<dyn RootMetricsComponent>, |
130 | | #[metric(group = "servers")] |
131 | | servers: HashMap<String, Arc<dyn RootMetricsComponent>>, |
132 | | #[metric(group = "workers")] |
133 | | workers: HashMap<String, Arc<dyn RootMetricsComponent>>, |
134 | | // TODO(allada) We cannot upcast these to RootMetricsComponent because |
135 | | // of https://github.com/rust-lang/rust/issues/65991. |
136 | | // TODO(allada) To prevent output from being too verbose we only |
137 | | // print the action_schedulers. |
138 | | #[metric(group = "action_schedulers")] |
139 | | schedulers: HashMap<String, Arc<dyn ClientStateManager>>, |
140 | | } |
141 | | |
142 | | impl RootMetricsComponent for RootMetrics {} |
143 | | |
144 | | /// Wrapper to allow us to hash `SocketAddr` for metrics. |
145 | | #[derive(Hash, PartialEq, Eq)] |
146 | | struct SocketAddrWrapper(SocketAddr); |
147 | | |
148 | | impl MetricsComponent for SocketAddrWrapper { |
149 | 0 | fn publish( |
150 | 0 | &self, |
151 | 0 | _kind: MetricKind, |
152 | 0 | _field_metadata: MetricFieldData, |
153 | 0 | ) -> Result<MetricPublishKnownKindData, nativelink_metric::Error> { |
154 | 0 | Ok(MetricPublishKnownKindData::String(self.0.to_string())) |
155 | 0 | } |
156 | | } |
157 | | |
158 | | impl RootMetricsComponent for SocketAddrWrapper {} |
159 | | |
160 | | /// Simple wrapper to enable us to register the Hashmap so it can |
161 | | /// report metrics about what clients are connected. |
162 | | #[derive(MetricsComponent)] |
163 | | struct ConnectedClientsMetrics { |
164 | | #[metric(group = "currently_connected_clients")] |
165 | | inner: Mutex<HashSet<SocketAddrWrapper>>, |
166 | | #[metric(help = "Total client connections since server started")] |
167 | | counter: Counter, |
168 | | #[metric(help = "Timestamp when the server started")] |
169 | | server_start_ts: u64, |
170 | | } |
171 | | |
172 | | impl RootMetricsComponent for ConnectedClientsMetrics {} |
173 | | |
174 | 0 | async fn inner_main( |
175 | 0 | cfg: CasConfig, |
176 | 0 | server_start_timestamp: u64, |
177 | 0 | shutdown_tx: broadcast::Sender<ShutdownGuard>, |
178 | 0 | ) -> Result<(), Error> { |
179 | 0 | const fn into_encoding(from: HttpCompressionAlgorithm) -> Option<CompressionEncoding> { |
180 | 0 | match from { |
181 | 0 | HttpCompressionAlgorithm::gzip => Some(CompressionEncoding::Gzip), |
182 | 0 | HttpCompressionAlgorithm::none => None, |
183 | | } |
184 | 0 | } |
185 | | |
186 | 0 | let health_registry_builder = |
187 | 0 | Arc::new(AsyncMutex::new(HealthRegistryBuilder::new("nativelink"))); |
188 | 0 |
|
189 | 0 | let store_manager = Arc::new(StoreManager::new()); |
190 | | { |
191 | 0 | let mut health_registry_lock = health_registry_builder.lock().await; |
192 | | |
193 | 0 | for StoreConfig { name, spec } in cfg.stores { |
194 | 0 | let health_component_name = format!("stores/{name}"); |
195 | 0 | let mut health_register_store = |
196 | 0 | health_registry_lock.sub_builder(&health_component_name); |
197 | 0 | let store = store_factory(&spec, &store_manager, Some(&mut health_register_store)) |
198 | 0 | .await |
199 | 0 | .err_tip(|| format!("Failed to create store '{name}'"))?; |
200 | 0 | store_manager.add_store(&name, store); |
201 | | } |
202 | | } |
203 | | |
204 | 0 | let mut root_futures: Vec<BoxFuture<Result<(), Error>>> = Vec::new(); |
205 | | |
206 | 0 | let maybe_origin_event_tx = cfg |
207 | 0 | .experimental_origin_events |
208 | 0 | .as_ref() |
209 | 0 | .map(|origin_events_cfg| { |
210 | 0 | let mut max_queued_events = origin_events_cfg.max_event_queue_size; |
211 | 0 | if max_queued_events == 0 { Branch (211:16): [Folded - Ignored]
|
212 | 0 | max_queued_events = DEFAULT_MAX_QUEUE_EVENTS; |
213 | 0 | } |
214 | 0 | let (tx, rx) = mpsc::channel(max_queued_events); |
215 | 0 | let store_name = origin_events_cfg.publisher.store.as_str(); |
216 | 0 | let store = store_manager.get_store(store_name).err_tip(|| { |
217 | 0 | format!("Could not get store {store_name} for origin event publisher") |
218 | 0 | })?; |
219 | | |
220 | 0 | root_futures.push(Box::pin( |
221 | 0 | OriginEventPublisher::new(store, rx, shutdown_tx.clone()) |
222 | 0 | .run() |
223 | 0 | .map(Ok), |
224 | 0 | )); |
225 | 0 |
|
226 | 0 | Ok::<_, Error>(tx) |
227 | 0 | }) |
228 | 0 | .transpose()?; |
229 | | |
230 | 0 | let mut action_schedulers = HashMap::new(); |
231 | 0 | let mut worker_schedulers = HashMap::new(); |
232 | 0 | for SchedulerConfig { name, spec } in cfg.schedulers.iter().flatten() { |
233 | 0 | let (maybe_action_scheduler, maybe_worker_scheduler) = |
234 | 0 | scheduler_factory(spec, &store_manager, maybe_origin_event_tx.as_ref()) |
235 | 0 | .err_tip(|| format!("Failed to create scheduler '{name}'"))?; |
236 | 0 | if let Some(action_scheduler) = maybe_action_scheduler { Branch (236:16): [Folded - Ignored]
|
237 | 0 | action_schedulers.insert(name.clone(), action_scheduler.clone()); |
238 | 0 | } |
239 | 0 | if let Some(worker_scheduler) = maybe_worker_scheduler { Branch (239:16): [Folded - Ignored]
|
240 | 0 | worker_schedulers.insert(name.clone(), worker_scheduler.clone()); |
241 | 0 | } |
242 | | } |
243 | | |
244 | 0 | let mut server_metrics: HashMap<String, Arc<dyn RootMetricsComponent>> = HashMap::new(); |
245 | 0 | // Registers all the ConnectedClientsMetrics to the registries |
246 | 0 | // and zips them in. It is done this way to get around the need |
247 | 0 | // for `root_metrics_registry` to become immutable in the loop. |
248 | 0 | let servers_and_clients: Vec<(ServerConfig, _)> = cfg |
249 | 0 | .servers |
250 | 0 | .into_iter() |
251 | 0 | .enumerate() |
252 | 0 | .map(|(i, server_cfg)| { |
253 | 0 | let name = if server_cfg.name.is_empty() { Branch (253:27): [Folded - Ignored]
|
254 | 0 | format!("{i}") |
255 | | } else { |
256 | 0 | server_cfg.name.clone() |
257 | | }; |
258 | 0 | let connected_clients_mux = Arc::new(ConnectedClientsMetrics { |
259 | 0 | inner: Mutex::new(HashSet::new()), |
260 | 0 | counter: Counter::default(), |
261 | 0 | server_start_ts: server_start_timestamp, |
262 | 0 | }); |
263 | 0 | server_metrics.insert(name.clone(), connected_clients_mux.clone()); |
264 | 0 |
|
265 | 0 | (server_cfg, connected_clients_mux) |
266 | 0 | }) |
267 | 0 | .collect(); |
268 | 0 |
|
269 | 0 | let root_metrics = Arc::new(RwLock::new(RootMetrics { |
270 | 0 | stores: store_manager.clone(), |
271 | 0 | servers: server_metrics, |
272 | 0 | workers: HashMap::new(), // Will be filled in later. |
273 | 0 | schedulers: action_schedulers.clone(), |
274 | 0 | })); |
275 | | |
276 | 0 | for (server_cfg, connected_clients_mux) in servers_and_clients { |
277 | 0 | let services = server_cfg |
278 | 0 | .services |
279 | 0 | .err_tip(|| "'services' must be configured")?; |
280 | | |
281 | | // Currently we only support http as our socket type. |
282 | 0 | let ListenerConfig::http(http_config) = server_cfg.listener; |
283 | | |
284 | 0 | let tonic_services = TonicServer::builder() |
285 | 0 | .add_optional_service( |
286 | 0 | services |
287 | 0 | .ac |
288 | 0 | .map_or(Ok(None), |cfg| { |
289 | 0 | AcServer::new(&cfg, &store_manager).map(|v| { |
290 | 0 | let mut service = v.into_service(); |
291 | 0 | let send_algo = &http_config.compression.send_compression_algorithm; |
292 | 0 | if let Some(encoding) = Branch (292:36): [Folded - Ignored]
|
293 | 0 | into_encoding(send_algo.unwrap_or(HttpCompressionAlgorithm::none)) |
294 | 0 | { |
295 | 0 | service = service.send_compressed(encoding); |
296 | 0 | } |
297 | 0 | for encoding in http_config |
298 | 0 | .compression |
299 | 0 | .accepted_compression_algorithms |
300 | 0 | .iter() |
301 | 0 | // Filter None values. |
302 | 0 | .filter_map(|from: &HttpCompressionAlgorithm| into_encoding(*from)) |
303 | 0 | { |
304 | 0 | service = service.accept_compressed(encoding); |
305 | 0 | } |
306 | 0 | Some(service) |
307 | 0 | }) |
308 | 0 | }) |
309 | 0 | .err_tip(|| "Could not create AC service")?, |
310 | | ) |
311 | | .add_optional_service( |
312 | 0 | services |
313 | 0 | .cas |
314 | 0 | .map_or(Ok(None), |cfg| { |
315 | 0 | CasServer::new(&cfg, &store_manager).map(|v| { |
316 | 0 | let mut service = v.into_service(); |
317 | 0 | let send_algo = &http_config.compression.send_compression_algorithm; |
318 | 0 | if let Some(encoding) = Branch (318:36): [Folded - Ignored]
|
319 | 0 | into_encoding(send_algo.unwrap_or(HttpCompressionAlgorithm::none)) |
320 | 0 | { |
321 | 0 | service = service.send_compressed(encoding); |
322 | 0 | } |
323 | 0 | for encoding in http_config |
324 | 0 | .compression |
325 | 0 | .accepted_compression_algorithms |
326 | 0 | .iter() |
327 | 0 | // Filter None values. |
328 | 0 | .filter_map(|from: &HttpCompressionAlgorithm| into_encoding(*from)) |
329 | 0 | { |
330 | 0 | service = service.accept_compressed(encoding); |
331 | 0 | } |
332 | 0 | Some(service) |
333 | 0 | }) |
334 | 0 | }) |
335 | 0 | .err_tip(|| "Could not create CAS service")?, |
336 | | ) |
337 | | .add_optional_service( |
338 | 0 | services |
339 | 0 | .execution |
340 | 0 | .map_or(Ok(None), |cfg| { |
341 | 0 | ExecutionServer::new(&cfg, &action_schedulers, &store_manager).map(|v| { |
342 | 0 | let mut service = v.into_service(); |
343 | 0 | let send_algo = &http_config.compression.send_compression_algorithm; |
344 | 0 | if let Some(encoding) = Branch (344:36): [Folded - Ignored]
|
345 | 0 | into_encoding(send_algo.unwrap_or(HttpCompressionAlgorithm::none)) |
346 | 0 | { |
347 | 0 | service = service.send_compressed(encoding); |
348 | 0 | } |
349 | 0 | for encoding in http_config |
350 | 0 | .compression |
351 | 0 | .accepted_compression_algorithms |
352 | 0 | .iter() |
353 | 0 | // Filter None values. |
354 | 0 | .filter_map(|from: &HttpCompressionAlgorithm| into_encoding(*from)) |
355 | 0 | { |
356 | 0 | service = service.accept_compressed(encoding); |
357 | 0 | } |
358 | 0 | Some(service) |
359 | 0 | }) |
360 | 0 | }) |
361 | 0 | .err_tip(|| "Could not create Execution service")?, |
362 | | ) |
363 | | .add_optional_service( |
364 | 0 | services |
365 | 0 | .bytestream |
366 | 0 | .map_or(Ok(None), |cfg| { |
367 | 0 | ByteStreamServer::new(&cfg, &store_manager).map(|v| { |
368 | 0 | let mut service = v.into_service(); |
369 | 0 | let send_algo = &http_config.compression.send_compression_algorithm; |
370 | 0 | if let Some(encoding) = Branch (370:36): [Folded - Ignored]
|
371 | 0 | into_encoding(send_algo.unwrap_or(HttpCompressionAlgorithm::none)) |
372 | 0 | { |
373 | 0 | service = service.send_compressed(encoding); |
374 | 0 | } |
375 | 0 | for encoding in http_config |
376 | 0 | .compression |
377 | 0 | .accepted_compression_algorithms |
378 | 0 | .iter() |
379 | 0 | // Filter None values. |
380 | 0 | .filter_map(|from: &HttpCompressionAlgorithm| into_encoding(*from)) |
381 | 0 | { |
382 | 0 | service = service.accept_compressed(encoding); |
383 | 0 | } |
384 | 0 | Some(service) |
385 | 0 | }) |
386 | 0 | }) |
387 | 0 | .err_tip(|| "Could not create ByteStream service")?, |
388 | | ) |
389 | | .add_optional_service( |
390 | 0 | OptionFuture::from( |
391 | 0 | services |
392 | 0 | .capabilities |
393 | 0 | .as_ref() |
394 | 0 | // Borrow checker fighting here... |
395 | 0 | .map(|_| { |
396 | 0 | CapabilitiesServer::new( |
397 | 0 | services.capabilities.as_ref().unwrap(), |
398 | 0 | &action_schedulers, |
399 | 0 | ) |
400 | 0 | }), |
401 | 0 | ) |
402 | 0 | .await |
403 | 0 | .map_or(Ok::<Option<CapabilitiesServer>, Error>(None), |server| { |
404 | 0 | Ok(Some(server?)) |
405 | 0 | }) |
406 | 0 | .err_tip(|| "Could not create Capabilities service")? |
407 | 0 | .map(|v| { |
408 | 0 | let mut service = v.into_service(); |
409 | 0 | let send_algo = &http_config.compression.send_compression_algorithm; |
410 | 0 | if let Some(encoding) = Branch (410:28): [Folded - Ignored]
|
411 | 0 | into_encoding(send_algo.unwrap_or(HttpCompressionAlgorithm::none)) |
412 | 0 | { |
413 | 0 | service = service.send_compressed(encoding); |
414 | 0 | } |
415 | 0 | for encoding in http_config |
416 | 0 | .compression |
417 | 0 | .accepted_compression_algorithms |
418 | 0 | .iter() |
419 | 0 | // Filter None values. |
420 | 0 | .filter_map(|from: &HttpCompressionAlgorithm| into_encoding(*from)) |
421 | 0 | { |
422 | 0 | service = service.accept_compressed(encoding); |
423 | 0 | } |
424 | 0 | service |
425 | 0 | }), |
426 | 0 | ) |
427 | 0 | .add_optional_service( |
428 | 0 | services |
429 | 0 | .worker_api |
430 | 0 | .map_or(Ok(None), |cfg| { |
431 | 0 | WorkerApiServer::new(&cfg, &worker_schedulers).map(|v| { |
432 | 0 | let mut service = v.into_service(); |
433 | 0 | let send_algo = &http_config.compression.send_compression_algorithm; |
434 | 0 | if let Some(encoding) = Branch (434:36): [Folded - Ignored]
|
435 | 0 | into_encoding(send_algo.unwrap_or(HttpCompressionAlgorithm::none)) |
436 | 0 | { |
437 | 0 | service = service.send_compressed(encoding); |
438 | 0 | } |
439 | 0 | for encoding in http_config |
440 | 0 | .compression |
441 | 0 | .accepted_compression_algorithms |
442 | 0 | .iter() |
443 | 0 | // Filter None values. |
444 | 0 | .filter_map(|from: &HttpCompressionAlgorithm| into_encoding(*from)) |
445 | 0 | { |
446 | 0 | service = service.accept_compressed(encoding); |
447 | 0 | } |
448 | 0 | Some(service) |
449 | 0 | }) |
450 | 0 | }) |
451 | 0 | .err_tip(|| "Could not create WorkerApi service")?, |
452 | | ) |
453 | | .add_optional_service( |
454 | 0 | services |
455 | 0 | .experimental_bep |
456 | 0 | .map_or(Ok(None), |cfg| { |
457 | 0 | BepServer::new(&cfg, &store_manager).map(|v| { |
458 | 0 | let mut service = v.into_service(); |
459 | 0 | let send_algo = &http_config.compression.send_compression_algorithm; |
460 | 0 | if let Some(encoding) = Branch (460:36): [Folded - Ignored]
|
461 | 0 | into_encoding(send_algo.unwrap_or(HttpCompressionAlgorithm::none)) |
462 | 0 | { |
463 | 0 | service = service.send_compressed(encoding); |
464 | 0 | } |
465 | 0 | for encoding in http_config |
466 | 0 | .compression |
467 | 0 | .accepted_compression_algorithms |
468 | 0 | .iter() |
469 | 0 | // Filter None values. |
470 | 0 | .filter_map(|from: &HttpCompressionAlgorithm| into_encoding(*from)) |
471 | 0 | { |
472 | 0 | service = service.accept_compressed(encoding); |
473 | 0 | } |
474 | 0 | Some(service) |
475 | 0 | }) |
476 | 0 | }) |
477 | 0 | .err_tip(|| "Could not create BEP service")?, |
478 | | ); |
479 | | |
480 | 0 | let health_registry = health_registry_builder.lock().await.build(); |
481 | 0 |
|
482 | 0 | let mut svc = Router::new().merge(tonic_services.into_service().into_axum_router().layer( |
483 | 0 | OriginEventMiddlewareLayer::new( |
484 | 0 | maybe_origin_event_tx.clone(), |
485 | 0 | server_cfg.experimental_identity_header.clone(), |
486 | 0 | ), |
487 | 0 | )); |
488 | | |
489 | 0 | if let Some(health_cfg) = services.health { Branch (489:16): [Folded - Ignored]
|
490 | 0 | let path = if health_cfg.path.is_empty() { Branch (490:27): [Folded - Ignored]
|
491 | 0 | DEFAULT_HEALTH_STATUS_CHECK_PATH |
492 | | } else { |
493 | 0 | &health_cfg.path |
494 | | }; |
495 | 0 | svc = svc.route_service(path, HealthServer::new(health_registry)); |
496 | 0 | } |
497 | | |
498 | 0 | if let Some(prometheus_cfg) = services.experimental_prometheus { Branch (498:16): [Folded - Ignored]
|
499 | 0 | fn error_to_response<E: std::error::Error>(e: E) -> Response<axum::body::Body> { |
500 | 0 | let mut response = Response::new(format!("Error: {e:?}").into()); |
501 | 0 | *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; |
502 | 0 | response |
503 | 0 | } |
504 | 0 | let path = if prometheus_cfg.path.is_empty() { Branch (504:27): [Folded - Ignored]
|
505 | 0 | DEFAULT_PROMETHEUS_METRICS_PATH |
506 | | } else { |
507 | 0 | &prometheus_cfg.path |
508 | | }; |
509 | | |
510 | 0 | let root_metrics_clone = root_metrics.clone(); |
511 | 0 |
|
512 | 0 | svc = svc.route_service( |
513 | 0 | path, |
514 | 0 | axum::routing::get(move |request: hyper::Request<axum::body::Body>| { |
515 | 0 | ActiveOriginContext::get() |
516 | 0 | .expect("OriginContext should be set here") |
517 | 0 | .wrap_async(trace_span!("prometheus_ctx"), async move { |
518 | 0 | // We spawn on a thread that can block to give more freedom to our metrics |
519 | 0 | // collection. This allows it to call functions like `tokio::block_in_place` |
520 | 0 | // if it needs to wait on a future. |
521 | 0 | spawn_blocking!("prometheus_metrics", move || { |
522 | 0 | let (layer, output_metrics) = MetricsCollectorLayer::new(); |
523 | 0 |
|
524 | 0 | // Traverse all the MetricsComponent's. The `MetricsCollectorLayer` will |
525 | 0 | // collect all the metrics and store them in `output_metrics`. |
526 | 0 | tracing::subscriber::with_default( |
527 | 0 | tracing_subscriber::registry().with(layer), |
528 | 0 | || { |
529 | 0 | let metrics_component = root_metrics_clone.read(); |
530 | 0 | MetricsComponent::publish( |
531 | 0 | &*metrics_component, |
532 | 0 | MetricKind::Component, |
533 | 0 | MetricFieldData::default(), |
534 | 0 | ) |
535 | 0 | }, |
536 | 0 | ) |
537 | 0 | .map_err(|e| make_err!(Code::Internal, "{e}")) |
538 | 0 | .err_tip(|| "While processing prometheus metrics")?; |
539 | | |
540 | | // Convert the collected metrics into OpenTelemetry metrics then |
541 | | // encode them into Prometheus format and populate them into a |
542 | | // hyper::Response. |
543 | 0 | let response = { |
544 | 0 | let registry = prometheus::Registry::new(); |
545 | 0 | let exporter = opentelemetry_prometheus::exporter() |
546 | 0 | .with_registry(registry.clone()) |
547 | 0 | .without_counter_suffixes() |
548 | 0 | .without_scope_info() |
549 | 0 | .build() |
550 | 0 | .map_err(|e| make_err!(Code::Internal, "{e}")) |
551 | 0 | .err_tip(|| { |
552 | 0 | "While creating OpenTelemetry Prometheus exporter" |
553 | 0 | })?; |
554 | | |
555 | | // Prepare our OpenTelemetry collector/exporter. |
556 | 0 | let provider = |
557 | 0 | SdkMeterProvider::builder().with_reader(exporter).build(); |
558 | 0 | let meter = provider.meter("nativelink"); |
559 | | |
560 | | // TODO(allada) We should put this as part of the config instead of a magic |
561 | | // request header. |
562 | 0 | if let Some(json_type) = Branch (562:44): [Folded - Ignored]
|
563 | 0 | request.headers().get("x-nativelink-json") |
564 | | { |
565 | 0 | let json_data = if json_type == "pretty" { Branch (565:60): [Folded - Ignored]
|
566 | 0 | serde_json::to_string_pretty(&*output_metrics.lock()) |
567 | 0 | .map_err(|e| { |
568 | 0 | make_err!( |
569 | 0 | Code::Internal, |
570 | 0 | "Could not convert to json {e:?}" |
571 | 0 | ) |
572 | 0 | })? |
573 | | } else { |
574 | 0 | serde_json::to_string(&*output_metrics.lock()).map_err( |
575 | 0 | |e| { |
576 | 0 | make_err!( |
577 | 0 | Code::Internal, |
578 | 0 | "Could not convert to json {e:?}" |
579 | 0 | ) |
580 | 0 | }, |
581 | 0 | )? |
582 | | }; |
583 | 0 | let mut response = |
584 | 0 | Response::new(axum::body::Body::from(json_data)); |
585 | 0 | response.headers_mut().insert( |
586 | 0 | hyper::header::CONTENT_TYPE, |
587 | 0 | hyper::header::HeaderValue::from_static( |
588 | 0 | "application/json", |
589 | 0 | ), |
590 | 0 | ); |
591 | 0 | return Ok(response); |
592 | 0 | } |
593 | 0 |
|
594 | 0 | // Export the metrics to OpenTelemetry. |
595 | 0 | otel_export( |
596 | 0 | "nativelink".to_string(), |
597 | 0 | &meter, |
598 | 0 | &output_metrics.lock(), |
599 | 0 | ); |
600 | 0 |
|
601 | 0 | // Translate the OpenTelemetry metrics to Prometheus format and encode |
602 | 0 | // them into a hyper::Response. |
603 | 0 | let mut result = vec![]; |
604 | 0 | TextEncoder::new() |
605 | 0 | .encode(®istry.gather(), &mut result) |
606 | 0 | .unwrap(); |
607 | 0 | let mut response = |
608 | 0 | Response::new(axum::body::Body::from(result)); |
609 | 0 | // Per spec we should probably use `application/openmetrics-text; version=1.0.0; charset=utf-8` |
610 | 0 | // https://github.com/OpenObservability/OpenMetrics/blob/1386544931307dff279688f332890c31b6c5de36/specification/OpenMetrics.md#overall-structure |
611 | 0 | // However, this makes debugging more difficult, so we use the old text/plain instead. |
612 | 0 | response.headers_mut().insert( |
613 | 0 | hyper::header::CONTENT_TYPE, |
614 | 0 | hyper::header::HeaderValue::from_static( |
615 | 0 | "text/plain; version=0.0.4; charset=utf-8", |
616 | 0 | ), |
617 | 0 | ); |
618 | 0 | Result::<_, Error>::Ok(response) |
619 | 0 | }; |
620 | 0 | response |
621 | 0 | }) |
622 | 0 | .await |
623 | 0 | .unwrap_or_else(|e| Ok(error_to_response(e))) |
624 | 0 | .unwrap_or_else(error_to_response) |
625 | 0 | }) |
626 | 0 | }), |
627 | 0 | ); |
628 | 0 | } |
629 | | |
630 | 0 | if let Some(admin_config) = services.admin { Branch (630:16): [Folded - Ignored]
|
631 | 0 | let path = if admin_config.path.is_empty() { Branch (631:27): [Folded - Ignored]
|
632 | 0 | DEFAULT_ADMIN_API_PATH |
633 | | } else { |
634 | 0 | &admin_config.path |
635 | | }; |
636 | 0 | let worker_schedulers = Arc::new(worker_schedulers.clone()); |
637 | 0 | svc = svc.nest_service( |
638 | 0 | path, |
639 | 0 | Router::new().route( |
640 | 0 | "/scheduler/:instance_name/set_drain_worker/:worker_id/:is_draining", |
641 | 0 | axum::routing::post( |
642 | 0 | move |params: axum::extract::Path<(String, String, String)>| async move { |
643 | 0 | let (instance_name, worker_id, is_draining) = params.0; |
644 | 0 | (async move { |
645 | 0 | let is_draining = match is_draining.as_str() { |
646 | 0 | "0" => false, |
647 | 0 | "1" => true, |
648 | | _ => { |
649 | 0 | return Err(make_err!( |
650 | 0 | Code::Internal, |
651 | 0 | "{} is neither 0 nor 1", |
652 | 0 | is_draining |
653 | 0 | )); |
654 | | } |
655 | | }; |
656 | 0 | worker_schedulers |
657 | 0 | .get(&instance_name) |
658 | 0 | .err_tip(|| { |
659 | 0 | format!( |
660 | 0 | "Can not get an instance with the name of '{}'", |
661 | 0 | &instance_name |
662 | 0 | ) |
663 | 0 | })? |
664 | 0 | .clone() |
665 | 0 | .set_drain_worker(&worker_id.clone().into(), is_draining) |
666 | 0 | .await?; |
667 | 0 | Ok::<_, Error>(format!("Draining worker {worker_id}")) |
668 | 0 | }) |
669 | 0 | .await |
670 | 0 | .map_err(|e| { |
671 | 0 | Err::<String, _>(( |
672 | 0 | axum::http::StatusCode::INTERNAL_SERVER_ERROR, |
673 | 0 | format!("Error: {e:?}"), |
674 | 0 | )) |
675 | 0 | }) |
676 | 0 | }, |
677 | 0 | ), |
678 | 0 | ), |
679 | 0 | ); |
680 | 0 | } |
681 | | |
682 | 0 | svc = svc |
683 | 0 | // This is the default service that executes if no other endpoint matches. |
684 | 0 | .fallback((StatusCode::NOT_FOUND, "Not Found")); |
685 | | |
686 | | // Configure our TLS acceptor if we have TLS configured. |
687 | 0 | let maybe_tls_acceptor = http_config.tls.map_or(Ok(None), |tls_config| { |
688 | 0 | fn read_cert(cert_file: &str) -> Result<Vec<CertificateDer<'static>>, Error> { |
689 | 0 | let mut cert_reader = std::io::BufReader::new( |
690 | 0 | std::fs::File::open(cert_file) |
691 | 0 | .err_tip(|| format!("Could not open cert file {cert_file}"))?, |
692 | | ); |
693 | 0 | let certs = extract_certs(&mut cert_reader) |
694 | 0 | .collect::<Result<Vec<CertificateDer<'_>>, _>>() |
695 | 0 | .err_tip(|| format!("Could not extract certs from file {cert_file}"))?; |
696 | 0 | Ok(certs) |
697 | 0 | } |
698 | 0 | let certs = read_cert(&tls_config.cert_file)?; |
699 | 0 | let mut key_reader = std::io::BufReader::new( |
700 | 0 | std::fs::File::open(&tls_config.key_file) |
701 | 0 | .err_tip(|| format!("Could not open key file {}", tls_config.key_file))?, |
702 | | ); |
703 | 0 | let key = match rustls_pemfile::read_one(&mut key_reader) |
704 | 0 | .err_tip(|| format!("Could not extract key(s) from file {}", tls_config.key_file))? |
705 | | { |
706 | 0 | Some(rustls_pemfile::Item::Pkcs8Key(key)) => key.into(), |
707 | 0 | Some(rustls_pemfile::Item::Sec1Key(key)) => key.into(), |
708 | 0 | Some(rustls_pemfile::Item::Pkcs1Key(key)) => key.into(), |
709 | | _ => { |
710 | 0 | return Err(make_err!( |
711 | 0 | Code::Internal, |
712 | 0 | "No keys found in file {}", |
713 | 0 | tls_config.key_file |
714 | 0 | )); |
715 | | } |
716 | | }; |
717 | 0 | if let Ok(Some(_)) = rustls_pemfile::read_one(&mut key_reader) { Branch (717:20): [Folded - Ignored]
|
718 | 0 | return Err(make_err!( |
719 | 0 | Code::InvalidArgument, |
720 | 0 | "Expected 1 key in file {}", |
721 | 0 | tls_config.key_file |
722 | 0 | )); |
723 | 0 | } |
724 | 0 | let verifier = if let Some(client_ca_file) = &tls_config.client_ca_file { Branch (724:35): [Folded - Ignored]
|
725 | 0 | let mut client_auth_roots = RootCertStore::empty(); |
726 | 0 | for cert in read_cert(client_ca_file)? { |
727 | 0 | client_auth_roots.add(cert).map_err(|e| { |
728 | 0 | make_err!(Code::Internal, "Could not read client CA: {e:?}") |
729 | 0 | })?; |
730 | | } |
731 | 0 | let crls = if let Some(client_crl_file) = &tls_config.client_crl_file { Branch (731:35): [Folded - Ignored]
|
732 | 0 | let mut crl_reader = std::io::BufReader::new( |
733 | 0 | std::fs::File::open(client_crl_file) |
734 | 0 | .err_tip(|| format!("Could not open CRL file {client_crl_file}"))?, |
735 | | ); |
736 | 0 | extract_crls(&mut crl_reader) |
737 | 0 | .collect::<Result<_, _>>() |
738 | 0 | .err_tip(|| format!("Could not extract CRLs from file {client_crl_file}"))? |
739 | | } else { |
740 | 0 | Vec::new() |
741 | | }; |
742 | 0 | WebPkiClientVerifier::builder(Arc::new(client_auth_roots)) |
743 | 0 | .with_crls(crls) |
744 | 0 | .build() |
745 | 0 | .map_err(|e| { |
746 | 0 | make_err!( |
747 | 0 | Code::Internal, |
748 | 0 | "Could not create WebPkiClientVerifier: {e:?}" |
749 | 0 | ) |
750 | 0 | })? |
751 | | } else { |
752 | 0 | WebPkiClientVerifier::no_client_auth() |
753 | | }; |
754 | 0 | let mut config = TlsServerConfig::builder() |
755 | 0 | .with_client_cert_verifier(verifier) |
756 | 0 | .with_single_cert(certs, key) |
757 | 0 | .map_err(|e| { |
758 | 0 | make_err!(Code::Internal, "Could not create TlsServerConfig : {e:?}") |
759 | 0 | })?; |
760 | | |
761 | 0 | config.alpn_protocols.push("h2".into()); |
762 | 0 | Ok(Some(TlsAcceptor::from(Arc::new(config)))) |
763 | 0 | })?; |
764 | | |
765 | 0 | let socket_addr = http_config |
766 | 0 | .socket_address |
767 | 0 | .parse::<SocketAddr>() |
768 | 0 | .map_err(|e| { |
769 | 0 | make_input_err!("Invalid address '{}' - {e:?}", http_config.socket_address) |
770 | 0 | })?; |
771 | 0 | let tcp_listener = TcpListener::bind(&socket_addr).await?; |
772 | 0 | let mut http = auto::Builder::new(TaskExecutor::default()); |
773 | 0 |
|
774 | 0 | let http_config = &http_config.advanced_http; |
775 | 0 | if let Some(value) = http_config.http2_keep_alive_interval { Branch (775:16): [Folded - Ignored]
|
776 | 0 | http.http2() |
777 | 0 | .keep_alive_interval(Duration::from_secs(u64::from(value))); |
778 | 0 | } |
779 | | |
780 | 0 | if let Some(value) = http_config.experimental_http2_max_pending_accept_reset_streams { Branch (780:16): [Folded - Ignored]
|
781 | 0 | http.http2() |
782 | 0 | .max_pending_accept_reset_streams(usize::try_from(value).err_tip(|| { |
783 | 0 | "Could not convert experimental_http2_max_pending_accept_reset_streams" |
784 | 0 | })?); |
785 | 0 | } |
786 | 0 | if let Some(value) = http_config.experimental_http2_initial_stream_window_size { Branch (786:16): [Folded - Ignored]
|
787 | 0 | http.http2().initial_stream_window_size(value); |
788 | 0 | } |
789 | 0 | if let Some(value) = http_config.experimental_http2_initial_connection_window_size { Branch (789:16): [Folded - Ignored]
|
790 | 0 | http.http2().initial_connection_window_size(value); |
791 | 0 | } |
792 | 0 | if let Some(value) = http_config.experimental_http2_adaptive_window { Branch (792:16): [Folded - Ignored]
|
793 | 0 | http.http2().adaptive_window(value); |
794 | 0 | } |
795 | 0 | if let Some(value) = http_config.experimental_http2_max_frame_size { Branch (795:16): [Folded - Ignored]
|
796 | 0 | http.http2().max_frame_size(value); |
797 | 0 | } |
798 | 0 | if let Some(value) = http_config.experimental_http2_max_concurrent_streams { Branch (798:16): [Folded - Ignored]
|
799 | 0 | http.http2().max_concurrent_streams(value); |
800 | 0 | } |
801 | 0 | if let Some(value) = http_config.experimental_http2_keep_alive_timeout { Branch (801:16): [Folded - Ignored]
|
802 | 0 | http.http2() |
803 | 0 | .keep_alive_timeout(Duration::from_secs(u64::from(value))); |
804 | 0 | } |
805 | 0 | if let Some(value) = http_config.experimental_http2_max_send_buf_size { Branch (805:16): [Folded - Ignored]
|
806 | 0 | http.http2().max_send_buf_size( |
807 | 0 | usize::try_from(value).err_tip(|| "Could not convert http2_max_send_buf_size")?, |
808 | | ); |
809 | 0 | } |
810 | 0 | if let Some(true) = http_config.experimental_http2_enable_connect_protocol { Branch (810:16): [Folded - Ignored]
|
811 | 0 | http.http2().enable_connect_protocol(); |
812 | 0 | } |
813 | 0 | if let Some(value) = http_config.experimental_http2_max_header_list_size { Branch (813:16): [Folded - Ignored]
|
814 | 0 | http.http2().max_header_list_size(value); |
815 | 0 | } |
816 | 0 | event!(Level::WARN, "Ready, listening on {socket_addr}",); |
817 | 0 | root_futures.push(Box::pin(async move { |
818 | | loop { |
819 | 0 | select! { |
820 | 0 | accept_result = tcp_listener.accept() => { |
821 | 0 | match accept_result { |
822 | 0 | Ok((tcp_stream, remote_addr)) => { |
823 | 0 | event!( |
824 | | target: "nativelink::services", |
825 | 0 | Level::INFO, |
826 | | ?remote_addr, |
827 | | ?socket_addr, |
828 | 0 | "Client connected" |
829 | | ); |
830 | 0 | connected_clients_mux |
831 | 0 | .inner |
832 | 0 | .lock() |
833 | 0 | .insert(SocketAddrWrapper(remote_addr)); |
834 | 0 | connected_clients_mux.counter.inc(); |
835 | 0 |
|
836 | 0 | // This is the safest way to guarantee that if our future |
837 | 0 | // is ever dropped we will cleanup our data. |
838 | 0 | let scope_guard = guard( |
839 | 0 | Arc::downgrade(&connected_clients_mux), |
840 | 0 | move |weak_connected_clients_mux| { |
841 | 0 | event!( |
842 | | target: "nativelink::services", |
843 | 0 | Level::INFO, |
844 | | ?remote_addr, |
845 | | ?socket_addr, |
846 | 0 | "Client disconnected" |
847 | | ); |
848 | 0 | if let Some(connected_clients_mux) = weak_connected_clients_mux.upgrade() { Branch (848:48): [Folded - Ignored]
|
849 | 0 | connected_clients_mux |
850 | 0 | .inner |
851 | 0 | .lock() |
852 | 0 | .remove(&SocketAddrWrapper(remote_addr)); |
853 | 0 | } |
854 | 0 | }, |
855 | 0 | ); |
856 | 0 |
|
857 | 0 | let (http, svc, maybe_tls_acceptor) = |
858 | 0 | (http.clone(), svc.clone(), maybe_tls_acceptor.clone()); |
859 | 0 | Arc::new(OriginContext::new()).background_spawn( |
860 | 0 | error_span!( |
861 | 0 | target: "nativelink::services", |
862 | 0 | "http_connection", |
863 | 0 | ?remote_addr, |
864 | 0 | ?socket_addr |
865 | 0 | ), |
866 | 0 | async move {}, |
867 | 0 | ); |
868 | 0 | background_spawn!( |
869 | 0 | name: "http_connection", |
870 | 0 | fut: async move { |
871 | 0 | // Move it into our spawn, so if our spawn dies the cleanup happens. |
872 | 0 | let _guard = scope_guard; |
873 | 0 | let serve_connection = if let Some(tls_acceptor) = maybe_tls_acceptor { Branch (873:71): [Folded - Ignored]
|
874 | 0 | match tls_acceptor.accept(tcp_stream).await { |
875 | 0 | Ok(tls_stream) => Either::Left(http.serve_connection( |
876 | 0 | TokioIo::new(tls_stream), |
877 | 0 | TowerToHyperService::new(svc), |
878 | 0 | )), |
879 | 0 | Err(err) => { |
880 | 0 | event!(Level::ERROR, ?err, "Failed to accept tls stream"); |
881 | 0 | return; |
882 | | } |
883 | | } |
884 | | } else { |
885 | 0 | Either::Right(http.serve_connection( |
886 | 0 | TokioIo::new(tcp_stream), |
887 | 0 | TowerToHyperService::new(svc), |
888 | 0 | )) |
889 | | }; |
890 | | |
891 | 0 | if let Err(err) = serve_connection.await { Branch (891:48): [Folded - Ignored]
|
892 | 0 | event!( |
893 | | target: "nativelink::services", |
894 | 0 | Level::ERROR, |
895 | | ?err, |
896 | 0 | "Failed running service" |
897 | | ); |
898 | 0 | } |
899 | 0 | }, |
900 | 0 | target: "nativelink::services", |
901 | 0 | ?remote_addr, |
902 | 0 | ?socket_addr, |
903 | 0 | ); |
904 | | }, |
905 | 0 | Err(err) => { |
906 | 0 | event!(Level::ERROR, ?err, "Failed to accept tcp connection"); |
907 | | } |
908 | | } |
909 | | }, |
910 | | } |
911 | | } |
912 | | // Unreachable |
913 | 0 | })); |
914 | 0 | } |
915 | | |
916 | | { |
917 | | // We start workers after our TcpListener is setup so if our worker connects to one |
918 | | // of these services it will be able to connect. |
919 | 0 | let worker_cfgs = cfg.workers.unwrap_or_default(); |
920 | 0 | let mut worker_names = HashSet::with_capacity(worker_cfgs.len()); |
921 | 0 | let mut worker_metrics: HashMap<String, Arc<dyn RootMetricsComponent>> = HashMap::new(); |
922 | 0 | for (i, worker_cfg) in worker_cfgs.into_iter().enumerate() { |
923 | 0 | let spawn_fut = match worker_cfg { |
924 | 0 | WorkerConfig::local(local_worker_cfg) => { |
925 | 0 | let fast_slow_store = store_manager |
926 | 0 | .get_store(&local_worker_cfg.cas_fast_slow_store) |
927 | 0 | .err_tip(|| { |
928 | 0 | format!( |
929 | 0 | "Failed to find store for cas_store_ref in worker config : {}", |
930 | 0 | local_worker_cfg.cas_fast_slow_store |
931 | 0 | ) |
932 | 0 | })?; |
933 | | |
934 | 0 | let maybe_ac_store = if let Some(ac_store_ref) = Branch (934:49): [Folded - Ignored]
|
935 | 0 | &local_worker_cfg.upload_action_result.ac_store |
936 | | { |
937 | 0 | Some(store_manager.get_store(ac_store_ref).err_tip(|| { |
938 | 0 | format!("Failed to find store for ac_store in worker config : {ac_store_ref}") |
939 | 0 | })?) |
940 | | } else { |
941 | 0 | None |
942 | | }; |
943 | | // Note: Defaults to fast_slow_store if not specified. If this ever changes it must |
944 | | // be updated in config documentation for the `historical_results_store` the field. |
945 | 0 | let historical_store = if let Some(cas_store_ref) = &local_worker_cfg Branch (945:51): [Folded - Ignored]
|
946 | 0 | .upload_action_result |
947 | 0 | .historical_results_store |
948 | | { |
949 | 0 | store_manager.get_store(cas_store_ref).err_tip(|| { |
950 | 0 | format!( |
951 | 0 | "Failed to find store for historical_results_store in worker config : {cas_store_ref}" |
952 | 0 | ) |
953 | 0 | })? |
954 | | } else { |
955 | 0 | fast_slow_store.clone() |
956 | | }; |
957 | 0 | let (local_worker, metrics) = new_local_worker( |
958 | 0 | Arc::new(local_worker_cfg), |
959 | 0 | fast_slow_store, |
960 | 0 | maybe_ac_store, |
961 | 0 | historical_store, |
962 | 0 | ) |
963 | 0 | .await |
964 | 0 | .err_tip(|| "Could not make LocalWorker")?; |
965 | | |
966 | 0 | let name = if local_worker.name().is_empty() { Branch (966:35): [Folded - Ignored]
|
967 | 0 | format!("worker_{i}") |
968 | | } else { |
969 | 0 | local_worker.name().clone() |
970 | | }; |
971 | | |
972 | 0 | if worker_names.contains(&name) { Branch (972:24): [Folded - Ignored]
|
973 | 0 | Err(make_input_err!( |
974 | 0 | "Duplicate worker name '{}' found in config", |
975 | 0 | name |
976 | 0 | ))?; |
977 | 0 | } |
978 | 0 | worker_names.insert(name.clone()); |
979 | 0 | worker_metrics.insert(name.clone(), metrics); |
980 | 0 | let shutdown_rx = shutdown_tx.subscribe(); |
981 | 0 | let fut = Arc::new(OriginContext::new()) |
982 | 0 | .wrap_async(trace_span!("worker_ctx"), local_worker.run(shutdown_rx)); |
983 | 0 | spawn!("worker", fut, ?name) |
984 | | } |
985 | | }; |
986 | 0 | root_futures.push(Box::pin(spawn_fut.map_ok_or_else(|e| Err(e.into()), |v| v))); |
987 | 0 | } |
988 | 0 | root_metrics.write().workers = worker_metrics; |
989 | | } |
990 | | |
991 | 0 | if let Err(e) = try_join_all(root_futures).await { Branch (991:12): [Folded - Ignored]
|
992 | 0 | panic!("{e:?}"); |
993 | 0 | }; |
994 | 0 |
|
995 | 0 | Ok(()) |
996 | 0 | } |
997 | | |
998 | 0 | async fn get_config() -> Result<CasConfig, Box<dyn std::error::Error>> { |
999 | 0 | let args = Args::parse(); |
1000 | 0 | let json_contents = String::from_utf8( |
1001 | 0 | std::fs::read(&args.config_file) |
1002 | 0 | .err_tip(|| format!("Could not open config file {}", args.config_file))?, |
1003 | 0 | )?; |
1004 | 0 | Ok(serde_json5::from_str(&json_contents)?) |
1005 | 0 | } |
1006 | | |
1007 | 0 | fn main() -> Result<(), Box<dyn std::error::Error>> { |
1008 | 0 | init_tracing()?; |
1009 | | |
1010 | 0 | let mut cfg = futures::executor::block_on(get_config())?; |
1011 | | |
1012 | 0 | let mut metrics_enabled = { |
1013 | 0 | let global_cfg = if let Some(global_cfg) = &mut cfg.global { Branch (1013:33): [Folded - Ignored]
|
1014 | 0 | if global_cfg.max_open_files == 0 { Branch (1014:16): [Folded - Ignored]
|
1015 | 0 | global_cfg.max_open_files = fs::DEFAULT_OPEN_FILE_PERMITS; |
1016 | 0 | } |
1017 | 0 | if global_cfg.default_digest_size_health_check == 0 { Branch (1017:16): [Folded - Ignored]
|
1018 | 0 | global_cfg.default_digest_size_health_check = DEFAULT_DIGEST_SIZE_HEALTH_CHECK_CFG; |
1019 | 0 | } |
1020 | | |
1021 | 0 | *global_cfg |
1022 | | } else { |
1023 | 0 | GlobalConfig { |
1024 | 0 | max_open_files: fs::DEFAULT_OPEN_FILE_PERMITS, |
1025 | 0 | disable_metrics: cfg.servers.iter().all(|v| { |
1026 | 0 | let Some(service) = &v.services else { Branch (1026:25): [Folded - Ignored]
|
1027 | 0 | return true; |
1028 | | }; |
1029 | 0 | service.experimental_prometheus.is_none() |
1030 | 0 | }), |
1031 | 0 | default_digest_hash_function: None, |
1032 | 0 | default_digest_size_health_check: DEFAULT_DIGEST_SIZE_HEALTH_CHECK_CFG, |
1033 | 0 | } |
1034 | | }; |
1035 | 0 | set_open_file_limit(global_cfg.max_open_files); |
1036 | 0 | set_default_digest_hasher_func(DigestHasherFunc::from( |
1037 | 0 | global_cfg |
1038 | 0 | .default_digest_hash_function |
1039 | 0 | .unwrap_or(ConfigDigestHashFunction::sha256), |
1040 | 0 | ))?; |
1041 | 0 | set_default_digest_size_health_check(global_cfg.default_digest_size_health_check)?; |
1042 | 0 | !global_cfg.disable_metrics |
1043 | 0 | }; |
1044 | 0 | // Override metrics enabled if the environment variable is set. |
1045 | 0 | if std::env::var(METRICS_DISABLE_ENV).is_ok() { Branch (1045:8): [Folded - Ignored]
|
1046 | 0 | metrics_enabled = false; |
1047 | 0 | } |
1048 | 0 | let server_start_time = SystemTime::now() |
1049 | 0 | .duration_since(UNIX_EPOCH) |
1050 | 0 | .unwrap() |
1051 | 0 | .as_secs(); |
1052 | | #[allow(clippy::disallowed_methods)] |
1053 | | { |
1054 | 0 | let runtime = tokio::runtime::Builder::new_multi_thread() |
1055 | 0 | .enable_all() |
1056 | 0 | .on_thread_start(move || set_metrics_enabled_for_this_thread(metrics_enabled)) |
1057 | 0 | .build()?; |
1058 | | |
1059 | | // Initiates the shutdown process by broadcasting the shutdown signal via the `oneshot::Sender` to all listeners. |
1060 | | // Each listener will perform its cleanup and then drop its `oneshot::Sender`, signaling completion. |
1061 | | // Once all `oneshot::Sender` instances are dropped, the worker knows it can safely terminate. |
1062 | 0 | let (shutdown_tx, _) = broadcast::channel::<ShutdownGuard>(BROADCAST_CAPACITY); |
1063 | 0 | let shutdown_tx_clone = shutdown_tx.clone(); |
1064 | 0 | let mut shutdown_guard = ShutdownGuard::default(); |
1065 | 0 |
|
1066 | 0 | runtime.spawn(async move { |
1067 | 0 | tokio::signal::ctrl_c() |
1068 | 0 | .await |
1069 | 0 | .expect("Failed to listen to SIGINT"); |
1070 | 0 | eprintln!("User terminated process via SIGINT"); |
1071 | 0 | std::process::exit(130); |
1072 | 0 | }); |
1073 | 0 |
|
1074 | 0 | #[cfg(target_family = "unix")] |
1075 | 0 | { |
1076 | 0 | runtime.spawn(async move { |
1077 | 0 | signal(SignalKind::terminate()) |
1078 | 0 | .expect("Failed to listen to SIGTERM") |
1079 | 0 | .recv() |
1080 | 0 | .await; |
1081 | 0 | event!(Level::WARN, "Process terminated via SIGTERM",); |
1082 | 0 | let _ = shutdown_tx_clone.send(shutdown_guard.clone()); |
1083 | 0 | let () = shutdown_guard.wait_for(Priority::P0).await; |
1084 | 0 | event!(Level::WARN, "Successfully shut down nativelink.",); |
1085 | 0 | std::process::exit(143); |
1086 | 0 | }); |
1087 | 0 | } |
1088 | 0 |
|
1089 | 0 | runtime |
1090 | 0 | .block_on(Arc::new(OriginContext::new()).wrap_async( |
1091 | 0 | trace_span!("main"), |
1092 | 0 | inner_main(cfg, server_start_time, shutdown_tx), |
1093 | 0 | )) |
1094 | 0 | .err_tip(|| "main() function failed")?; |
1095 | | } |
1096 | 0 | Ok(()) |
1097 | 0 | } |