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