/build/source/src/bin/nativelink.rs
Line  | Count  | Source  | 
1  |  | // Copyright 2024 The NativeLink Authors. All rights reserved.  | 
2  |  | //  | 
3  |  | // Licensed under the Functional Source License, Version 1.1, Apache 2.0 Future License (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  |  | //    See LICENSE file for details  | 
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 core::net::SocketAddr;  | 
16  |  | use core::time::Duration;  | 
17  |  | use std::collections::{HashMap, HashSet}; | 
18  |  | use std::sync::Arc;  | 
19  |  |  | 
20  |  | use async_lock::Mutex as AsyncMutex;  | 
21  |  | use axum::Router;  | 
22  |  | use axum::http::Uri;  | 
23  |  | use clap::Parser;  | 
24  |  | use futures::FutureExt;  | 
25  |  | use futures::future::{BoxFuture, Either, OptionFuture, TryFutureExt, try_join_all}; | 
26  |  | use hyper::StatusCode;  | 
27  |  | use hyper_util::rt::tokio::TokioIo;  | 
28  |  | use hyper_util::server::conn::auto;  | 
29  |  | use hyper_util::service::TowerToHyperService;  | 
30  |  | use mimalloc::MiMalloc;  | 
31  |  | use nativelink_config::cas_server::{ | 
32  |  |     CasConfig, GlobalConfig, HttpCompressionAlgorithm, ListenerConfig, SchedulerConfig,  | 
33  |  |     ServerConfig, StoreConfig, WorkerConfig,  | 
34  |  | };  | 
35  |  | use nativelink_config::stores::ConfigDigestHashFunction;  | 
36  |  | use nativelink_error::{Code, Error, ResultExt, make_err, make_input_err}; | 
37  |  | use nativelink_scheduler::default_scheduler_factory::scheduler_factory;  | 
38  |  | use nativelink_service::ac_server::AcServer;  | 
39  |  | use nativelink_service::bep_server::BepServer;  | 
40  |  | use nativelink_service::bytestream_server::ByteStreamServer;  | 
41  |  | use nativelink_service::capabilities_server::CapabilitiesServer;  | 
42  |  | use nativelink_service::cas_server::CasServer;  | 
43  |  | use nativelink_service::execution_server::ExecutionServer;  | 
44  |  | use nativelink_service::fetch_server::FetchServer;  | 
45  |  | use nativelink_service::health_server::HealthServer;  | 
46  |  | use nativelink_service::push_server::PushServer;  | 
47  |  | use nativelink_service::worker_api_server::WorkerApiServer;  | 
48  |  | use nativelink_store::default_store_factory::store_factory;  | 
49  |  | use nativelink_store::store_manager::StoreManager;  | 
50  |  | use nativelink_util::common::fs::set_open_file_limit;  | 
51  |  | use nativelink_util::digest_hasher::{DigestHasherFunc, set_default_digest_hasher_func}; | 
52  |  | use nativelink_util::health_utils::HealthRegistryBuilder;  | 
53  |  | use nativelink_util::origin_event_publisher::OriginEventPublisher;  | 
54  |  | #[cfg(target_family = "unix")]  | 
55  |  | use nativelink_util::shutdown_guard::Priority;  | 
56  |  | use nativelink_util::shutdown_guard::ShutdownGuard;  | 
57  |  | use nativelink_util::store_trait::{ | 
58  |  |     DEFAULT_DIGEST_SIZE_HEALTH_CHECK_CFG, set_default_digest_size_health_check,  | 
59  |  | };  | 
60  |  | use nativelink_util::task::TaskExecutor;  | 
61  |  | use nativelink_util::telemetry::init_tracing;  | 
62  |  | use nativelink_util::{background_spawn, fs, spawn}; | 
63  |  | use nativelink_worker::local_worker::new_local_worker;  | 
64  |  | use rustls_pemfile::{certs as extract_certs, crls as extract_crls}; | 
65  |  | use tokio::net::TcpListener;  | 
66  |  | use tokio::select;  | 
67  |  | #[cfg(target_family = "unix")]  | 
68  |  | use tokio::signal::unix::{SignalKind, signal}; | 
69  |  | use tokio::sync::oneshot::Sender;  | 
70  |  | use tokio::sync::{broadcast, mpsc, oneshot}; | 
71  |  | use tokio_rustls::TlsAcceptor;  | 
72  |  | use tokio_rustls::rustls::pki_types::CertificateDer;  | 
73  |  | use tokio_rustls::rustls::server::WebPkiClientVerifier;  | 
74  |  | use tokio_rustls::rustls::{RootCertStore, ServerConfig as TlsServerConfig}; | 
75  |  | use tonic::codec::CompressionEncoding;  | 
76  |  | use tonic::service::Routes;  | 
77  |  | use tracing::{error, error_span, info, trace_span, warn}; | 
78  |  |  | 
79  |  | #[global_allocator]  | 
80  |  | static GLOBAL: MiMalloc = MiMalloc;  | 
81  |  |  | 
82  |  | /// Note: This must be kept in sync with the documentation in `AdminConfig::path`.  | 
83  |  | const DEFAULT_ADMIN_API_PATH: &str = "/admin";  | 
84  |  |  | 
85  |  | // Note: This must be kept in sync with the documentation in `HealthConfig::path`.  | 
86  |  | const DEFAULT_HEALTH_STATUS_CHECK_PATH: &str = "/status";  | 
87  |  |  | 
88  |  | // Note: This must be kept in sync with the documentation in  | 
89  |  | // `OriginEventsConfig::max_event_queue_size`.  | 
90  |  | const DEFAULT_MAX_QUEUE_EVENTS: usize = 0x0001_0000;  | 
91  |  |  | 
92  |  | /// Broadcast Channel Capacity  | 
93  |  | /// Note: The actual capacity may be greater than the provided capacity.  | 
94  |  | const BROADCAST_CAPACITY: usize = 1;  | 
95  |  |  | 
96  |  | /// Backend for bazel remote execution / cache API.  | 
97  |  | #[derive(Parser, Debug)]  | 
98  |  | #[clap(  | 
99  |  |     author = "Trace Machina, Inc. <nativelink@tracemachina.com>",  | 
100  |  |     version,  | 
101  |  |     about,  | 
102  |  |     long_about = None  | 
103  |  | )]  | 
104  |  | struct Args { | 
105  |  |     /// Config file to use.  | 
106  |  |     #[clap(value_parser)]  | 
107  |  |     config_file: String,  | 
108  |  | }  | 
109  |  |  | 
110  |  | trait RoutesExt { | 
111  |  |     fn add_optional_service<S>(self, svc: Option<S>) -> Self  | 
112  |  |     where  | 
113  |  |         S: tower::Service<  | 
114  |  |                 axum::http::Request<tonic::body::Body>,  | 
115  |  |                 Error = core::convert::Infallible,  | 
116  |  |             > + tonic::server::NamedService  | 
117  |  |             + Clone  | 
118  |  |             + Send  | 
119  |  |             + Sync  | 
120  |  |             + 'static,  | 
121  |  |         S::Response: axum::response::IntoResponse,  | 
122  |  |         S::Future: Send + 'static;  | 
123  |  | }  | 
124  |  |  | 
125  |  | impl RoutesExt for Routes { | 
126  | 0  |     fn add_optional_service<S>(mut self, svc: Option<S>) -> Self  | 
127  | 0  |     where  | 
128  | 0  |         S: tower::Service<  | 
129  | 0  |                 axum::http::Request<tonic::body::Body>,  | 
130  | 0  |                 Error = core::convert::Infallible,  | 
131  | 0  |             > + tonic::server::NamedService  | 
132  | 0  |             + Clone  | 
133  | 0  |             + Send  | 
134  | 0  |             + Sync  | 
135  | 0  |             + 'static,  | 
136  | 0  |         S::Response: axum::response::IntoResponse,  | 
137  | 0  |         S::Future: Send + 'static,  | 
138  |  |     { | 
139  | 0  |         if let Some(svc) = svc {  Branch (139:16): [Folded - Ignored]
  | 
140  | 0  |             self = self.add_service(svc);  | 
141  | 0  |         }  | 
142  | 0  |         self  | 
143  | 0  |     }  | 
144  |  | }  | 
145  |  |  | 
146  |  | /// If this value changes update the documentation in the config definition.  | 
147  |  | const DEFAULT_MAX_DECODING_MESSAGE_SIZE: usize = 4 * 1024 * 1024;  | 
148  |  |  | 
149  |  | macro_rules! service_setup { | 
150  |  |     ($v: tt, $http_config: tt) => {{ | 
151  |  |         let mut service = $v.into_service();  | 
152  |  |         let max_decoding_message_size = if $http_config.max_decoding_message_size == 0 { | 
153  |  |             DEFAULT_MAX_DECODING_MESSAGE_SIZE  | 
154  |  |         } else { | 
155  |  |             $http_config.max_decoding_message_size  | 
156  |  |         };  | 
157  |  |         service = service.max_decoding_message_size(max_decoding_message_size);  | 
158  |  |         let send_algo = &$http_config.compression.send_compression_algorithm;  | 
159  |  |         if let Some(encoding) = into_encoding(send_algo.unwrap_or(HttpCompressionAlgorithm::None)) { | 
160  |  |             service = service.send_compressed(encoding);  | 
161  |  |         }  | 
162  |  |         for encoding in $http_config  | 
163  |  |             .compression  | 
164  |  |             .accepted_compression_algorithms  | 
165  |  |             .iter()  | 
166  |  |             // Filter None values.  | 
167  | 0  |             .filter_map(|from: &HttpCompressionAlgorithm| into_encoding(*from))  | 
168  |  |         { | 
169  |  |             service = service.accept_compressed(encoding);  | 
170  |  |         }  | 
171  |  |         service  | 
172  |  |     }};  | 
173  |  | }  | 
174  |  |  | 
175  | 0  | async fn inner_main(  | 
176  | 0  |     cfg: CasConfig,  | 
177  | 0  |     shutdown_tx: broadcast::Sender<ShutdownGuard>,  | 
178  | 0  |     scheduler_shutdown_tx: Sender<()>,  | 
179  | 0  | ) -> Result<(), Error> { | 
180  | 0  |     const 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  |  |  | 
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 root_futures: Vec<BoxFuture<Result<(), Error>>> = Vec::new();  | 
206  |  |  | 
207  | 0  |     let maybe_origin_event_tx = cfg  | 
208  | 0  |         .experimental_origin_events  | 
209  | 0  |         .as_ref()  | 
210  | 0  |         .map(|origin_events_cfg| { | 
211  | 0  |             let mut max_queued_events = origin_events_cfg.max_event_queue_size;  | 
212  | 0  |             if max_queued_events == 0 {  Branch (212:16): [Folded - Ignored]
  | 
213  | 0  |                 max_queued_events = DEFAULT_MAX_QUEUE_EVENTS;  | 
214  | 0  |             }  | 
215  | 0  |             let (tx, rx) = mpsc::channel(max_queued_events);  | 
216  | 0  |             let store_name = origin_events_cfg.publisher.store.as_str();  | 
217  | 0  |             let store = store_manager.get_store(store_name).err_tip(|| { | 
218  | 0  |                 format!("Could not get store {store_name} for origin event publisher") | 
219  | 0  |             })?;  | 
220  |  |  | 
221  | 0  |             root_futures.push(Box::pin(  | 
222  | 0  |                 OriginEventPublisher::new(store, rx, shutdown_tx.clone())  | 
223  | 0  |                     .run()  | 
224  | 0  |                     .map(Ok),  | 
225  | 0  |             ));  | 
226  |  |  | 
227  | 0  |             Ok::<_, Error>(tx)  | 
228  | 0  |         })  | 
229  | 0  |         .transpose()?;  | 
230  |  |  | 
231  | 0  |     let mut action_schedulers = HashMap::new();  | 
232  | 0  |     let mut worker_schedulers = HashMap::new();  | 
233  | 0  |     for SchedulerConfig { name, spec } in cfg.schedulers.iter().flatten() { | 
234  | 0  |         let (maybe_action_scheduler, maybe_worker_scheduler) =  | 
235  | 0  |             scheduler_factory(spec, &store_manager, maybe_origin_event_tx.as_ref())  | 
236  | 0  |                 .err_tip(|| format!("Failed to create scheduler '{name}'"))?; | 
237  | 0  |         if let Some(action_scheduler) = maybe_action_scheduler {  Branch (237:16): [Folded - Ignored]
  | 
238  | 0  |             action_schedulers.insert(name.clone(), action_scheduler.clone());  | 
239  | 0  |         }  | 
240  | 0  |         if let Some(worker_scheduler) = maybe_worker_scheduler {  Branch (240:16): [Folded - Ignored]
  | 
241  | 0  |             worker_schedulers.insert(name.clone(), worker_scheduler.clone());  | 
242  | 0  |         }  | 
243  |  |     }  | 
244  |  |  | 
245  | 0  |     let server_cfgs: Vec<ServerConfig> = cfg.servers.into_iter().collect();  | 
246  |  |  | 
247  | 0  |     for server_cfg in server_cfgs { | 
248  | 0  |         let services = server_cfg  | 
249  | 0  |             .services  | 
250  | 0  |             .err_tip(|| "'services' must be configured")?;  | 
251  |  |  | 
252  |  |         // Currently we only support http as our socket type.  | 
253  | 0  |         let ListenerConfig::Http(http_config) = server_cfg.listener;  | 
254  |  |  | 
255  | 0  |         let tonic_services = Routes::builder()  | 
256  | 0  |             .routes()  | 
257  | 0  |             .add_optional_service(  | 
258  | 0  |                 services  | 
259  | 0  |                     .ac  | 
260  | 0  |                     .map_or(Ok(None), |cfg| { | 
261  | 0  |                         AcServer::new(&cfg, &store_manager)  | 
262  | 0  |                             .map(|v| Some(service_setup!(v, http_config)))  | 
263  | 0  |                     })  | 
264  | 0  |                     .err_tip(|| "Could not create AC service")?,  | 
265  |  |             )  | 
266  | 0  |             .add_optional_service(  | 
267  | 0  |                 services  | 
268  | 0  |                     .cas  | 
269  | 0  |                     .map_or(Ok(None), |cfg| { | 
270  | 0  |                         CasServer::new(&cfg, &store_manager)  | 
271  | 0  |                             .map(|v| Some(service_setup!(v, http_config)))  | 
272  | 0  |                     })  | 
273  | 0  |                     .err_tip(|| "Could not create CAS service")?,  | 
274  |  |             )  | 
275  | 0  |             .add_optional_service(  | 
276  | 0  |                 services  | 
277  | 0  |                     .execution  | 
278  | 0  |                     .map_or(Ok(None), |cfg| { | 
279  | 0  |                         ExecutionServer::new(&cfg, &action_schedulers, &store_manager)  | 
280  | 0  |                             .map(|v| Some(service_setup!(v, http_config)))  | 
281  | 0  |                     })  | 
282  | 0  |                     .err_tip(|| "Could not create Execution service")?,  | 
283  |  |             )  | 
284  | 0  |             .add_optional_service(  | 
285  | 0  |                 services  | 
286  | 0  |                     .fetch  | 
287  | 0  |                     .map_or(Ok(None), |cfg| { | 
288  | 0  |                         FetchServer::new(&cfg, &store_manager)  | 
289  | 0  |                             .map(|v| Some(service_setup!(v, http_config)))  | 
290  | 0  |                     })  | 
291  | 0  |                     .err_tip(|| "Could not create Fetch service")?,  | 
292  |  |             )  | 
293  | 0  |             .add_optional_service(  | 
294  | 0  |                 services  | 
295  | 0  |                     .push  | 
296  | 0  |                     .map_or(Ok(None), |cfg| { | 
297  | 0  |                         PushServer::new(&cfg, &store_manager)  | 
298  | 0  |                             .map(|v| Some(service_setup!(v, http_config)))  | 
299  | 0  |                     })  | 
300  | 0  |                     .err_tip(|| "Could not create Push service")?,  | 
301  |  |             )  | 
302  | 0  |             .add_optional_service(  | 
303  | 0  |                 services  | 
304  | 0  |                     .bytestream  | 
305  | 0  |                     .map_or(Ok(None), |cfg| { | 
306  | 0  |                         ByteStreamServer::new(&cfg, &store_manager)  | 
307  | 0  |                             .map(|v| Some(service_setup!(v, http_config)))  | 
308  | 0  |                     })  | 
309  | 0  |                     .err_tip(|| "Could not create ByteStream service")?,  | 
310  |  |             )  | 
311  | 0  |             .add_optional_service(  | 
312  | 0  |                 OptionFuture::from(  | 
313  | 0  |                     services  | 
314  | 0  |                         .capabilities  | 
315  | 0  |                         .as_ref()  | 
316  | 0  |                         .map(|cfg| CapabilitiesServer::new(cfg, &action_schedulers)),  | 
317  |  |                 )  | 
318  | 0  |                 .await  | 
319  | 0  |                 .map_or(Ok::<Option<CapabilitiesServer>, Error>(None), |server| { | 
320  | 0  |                     Ok(Some(server?))  | 
321  | 0  |                 })  | 
322  | 0  |                 .err_tip(|| "Could not create Capabilities service")?  | 
323  | 0  |                 .map(|v| service_setup!(v, http_config)),  | 
324  |  |             )  | 
325  | 0  |             .add_optional_service(  | 
326  | 0  |                 services  | 
327  | 0  |                     .worker_api  | 
328  | 0  |                     .map_or(Ok(None), |cfg| { | 
329  | 0  |                         WorkerApiServer::new(&cfg, &worker_schedulers)  | 
330  | 0  |                             .map(|v| Some(service_setup!(v, http_config)))  | 
331  | 0  |                     })  | 
332  | 0  |                     .err_tip(|| "Could not create WorkerApi service")?,  | 
333  |  |             )  | 
334  | 0  |             .add_optional_service(  | 
335  | 0  |                 services  | 
336  | 0  |                     .experimental_bep  | 
337  | 0  |                     .map_or(Ok(None), |cfg| { | 
338  | 0  |                         BepServer::new(&cfg, &store_manager)  | 
339  | 0  |                             .map(|v| Some(service_setup!(v, http_config)))  | 
340  | 0  |                     })  | 
341  | 0  |                     .err_tip(|| "Could not create BEP service")?,  | 
342  |  |             );  | 
343  |  |  | 
344  | 0  |         let health_registry = health_registry_builder.lock().await.build();  | 
345  |  |  | 
346  | 0  |         let mut svc =  | 
347  | 0  |             tonic_services  | 
348  | 0  |                 .into_axum_router()  | 
349  | 0  |                 .layer(nativelink_util::telemetry::OtlpLayer::new(  | 
350  | 0  |                     server_cfg.experimental_identity_header.required,  | 
351  |  |                 ));  | 
352  |  |  | 
353  | 0  |         if let Some(health_cfg) = services.health {  Branch (353:16): [Folded - Ignored]
  | 
354  | 0  |             let path = if health_cfg.path.is_empty() {  Branch (354:27): [Folded - Ignored]
  | 
355  | 0  |                 DEFAULT_HEALTH_STATUS_CHECK_PATH  | 
356  |  |             } else { | 
357  | 0  |                 &health_cfg.path  | 
358  |  |             };  | 
359  | 0  |             svc = svc.route_service(path, HealthServer::new(health_registry, &health_cfg));  | 
360  | 0  |         }  | 
361  |  |  | 
362  | 0  |         if let Some(admin_config) = services.admin {  Branch (362:16): [Folded - Ignored]
  | 
363  | 0  |             let path = if admin_config.path.is_empty() {  Branch (363:27): [Folded - Ignored]
  | 
364  | 0  |                 DEFAULT_ADMIN_API_PATH  | 
365  |  |             } else { | 
366  | 0  |                 &admin_config.path  | 
367  |  |             };  | 
368  | 0  |             let worker_schedulers = Arc::new(worker_schedulers.clone());  | 
369  | 0  |             svc = svc.nest_service(  | 
370  | 0  |                 path,  | 
371  | 0  |                 Router::new().route(  | 
372  | 0  |                     "/scheduler/{instance_name}/set_drain_worker/{worker_id}/{is_draining}", | 
373  | 0  |                     axum::routing::post(  | 
374  | 0  |                         move |params: axum::extract::Path<(String, String, String)>| async move { | 
375  | 0  |                             let (instance_name, worker_id, is_draining) = params.0;  | 
376  | 0  |                             (async move { | 
377  | 0  |                                 let is_draining = match is_draining.as_str() { | 
378  | 0  |                                     "0" => false,  | 
379  | 0  |                                     "1" => true,  | 
380  |  |                                     _ => { | 
381  | 0  |                                         return Err(make_err!(  | 
382  | 0  |                                             Code::Internal,  | 
383  | 0  |                                             "{} is neither 0 nor 1", | 
384  | 0  |                                             is_draining  | 
385  | 0  |                                         ));  | 
386  |  |                                     }  | 
387  |  |                                 };  | 
388  | 0  |                                 worker_schedulers  | 
389  | 0  |                                     .get(&instance_name)  | 
390  | 0  |                                     .err_tip(|| { | 
391  | 0  |                                         format!(  | 
392  | 0  |                                             "Can not get an instance with the name of '{}'", | 
393  | 0  |                                             &instance_name  | 
394  |  |                                         )  | 
395  | 0  |                                     })?  | 
396  | 0  |                                     .clone()  | 
397  | 0  |                                     .set_drain_worker(&worker_id.clone().into(), is_draining)  | 
398  | 0  |                                     .await?;  | 
399  | 0  |                                 Ok::<_, Error>(format!("Draining worker {worker_id}")) | 
400  |  |                             })  | 
401  | 0  |                             .await  | 
402  | 0  |                             .map_err(|e| { | 
403  | 0  |                                 Err::<String, _>((  | 
404  | 0  |                                     StatusCode::INTERNAL_SERVER_ERROR,  | 
405  | 0  |                                     format!("Error: {e:?}"), | 
406  | 0  |                                 ))  | 
407  | 0  |                             })  | 
408  | 0  |                         },  | 
409  |  |                     ),  | 
410  |  |                 ),  | 
411  |  |             );  | 
412  | 0  |         }  | 
413  |  |  | 
414  |  |         // This is the default service that executes if no other endpoint matches.  | 
415  | 0  |         svc = svc.fallback(|uri: Uri| async move { | 
416  | 0  |             warn!("No route for {uri}"); | 
417  | 0  |             (StatusCode::NOT_FOUND, format!("No route for {uri}")) | 
418  | 0  |         });  | 
419  |  |  | 
420  |  |         // Configure our TLS acceptor if we have TLS configured.  | 
421  | 0  |         let maybe_tls_acceptor = http_config.tls.map_or(Ok(None), |tls_config| { | 
422  | 0  |             fn read_cert(cert_file: &str) -> Result<Vec<CertificateDer<'static>>, Error> { | 
423  | 0  |                 let mut cert_reader = std::io::BufReader::new(  | 
424  | 0  |                     std::fs::File::open(cert_file)  | 
425  | 0  |                         .err_tip(|| format!("Could not open cert file {cert_file}"))?, | 
426  |  |                 );  | 
427  | 0  |                 let certs = extract_certs(&mut cert_reader)  | 
428  | 0  |                     .collect::<Result<Vec<CertificateDer<'_>>, _>>()  | 
429  | 0  |                     .err_tip(|| format!("Could not extract certs from file {cert_file}"))?; | 
430  | 0  |                 Ok(certs)  | 
431  | 0  |             }  | 
432  | 0  |             let certs = read_cert(&tls_config.cert_file)?;  | 
433  | 0  |             let mut key_reader = std::io::BufReader::new(  | 
434  | 0  |                 std::fs::File::open(&tls_config.key_file)  | 
435  | 0  |                     .err_tip(|| format!("Could not open key file {}", tls_config.key_file))?, | 
436  |  |             );  | 
437  | 0  |             let key = match rustls_pemfile::read_one(&mut key_reader)  | 
438  | 0  |                 .err_tip(|| format!("Could not extract key(s) from file {}", tls_config.key_file))? | 
439  |  |             { | 
440  | 0  |                 Some(rustls_pemfile::Item::Pkcs8Key(key)) => key.into(),  | 
441  | 0  |                 Some(rustls_pemfile::Item::Sec1Key(key)) => key.into(),  | 
442  | 0  |                 Some(rustls_pemfile::Item::Pkcs1Key(key)) => key.into(),  | 
443  |  |                 _ => { | 
444  | 0  |                     return Err(make_err!(  | 
445  | 0  |                         Code::Internal,  | 
446  | 0  |                         "No keys found in file {}", | 
447  | 0  |                         tls_config.key_file  | 
448  | 0  |                     ));  | 
449  |  |                 }  | 
450  |  |             };  | 
451  | 0  |             if let Ok(Some(_)) = rustls_pemfile::read_one(&mut key_reader) {  Branch (451:20): [Folded - Ignored]
  | 
452  | 0  |                 return Err(make_err!(  | 
453  | 0  |                     Code::InvalidArgument,  | 
454  | 0  |                     "Expected 1 key in file {}", | 
455  | 0  |                     tls_config.key_file  | 
456  | 0  |                 ));  | 
457  | 0  |             }  | 
458  | 0  |             let verifier = if let Some(client_ca_file) = &tls_config.client_ca_file {  Branch (458:35): [Folded - Ignored]
  | 
459  | 0  |                 let mut client_auth_roots = RootCertStore::empty();  | 
460  | 0  |                 for cert in read_cert(client_ca_file)? { | 
461  | 0  |                     client_auth_roots.add(cert).map_err(|e| { | 
462  | 0  |                         make_err!(Code::Internal, "Could not read client CA: {e:?}") | 
463  | 0  |                     })?;  | 
464  |  |                 }  | 
465  | 0  |                 let crls = if let Some(client_crl_file) = &tls_config.client_crl_file {  Branch (465:35): [Folded - Ignored]
  | 
466  | 0  |                     let mut crl_reader = std::io::BufReader::new(  | 
467  | 0  |                         std::fs::File::open(client_crl_file)  | 
468  | 0  |                             .err_tip(|| format!("Could not open CRL file {client_crl_file}"))?, | 
469  |  |                     );  | 
470  | 0  |                     extract_crls(&mut crl_reader)  | 
471  | 0  |                         .collect::<Result<_, _>>()  | 
472  | 0  |                         .err_tip(|| format!("Could not extract CRLs from file {client_crl_file}"))? | 
473  |  |                 } else { | 
474  | 0  |                     Vec::new()  | 
475  |  |                 };  | 
476  | 0  |                 WebPkiClientVerifier::builder(Arc::new(client_auth_roots))  | 
477  | 0  |                     .with_crls(crls)  | 
478  | 0  |                     .build()  | 
479  | 0  |                     .map_err(|e| { | 
480  | 0  |                         make_err!(  | 
481  | 0  |                             Code::Internal,  | 
482  |  |                             "Could not create WebPkiClientVerifier: {e:?}" | 
483  |  |                         )  | 
484  | 0  |                     })?  | 
485  |  |             } else { | 
486  | 0  |                 WebPkiClientVerifier::no_client_auth()  | 
487  |  |             };  | 
488  | 0  |             let mut config = TlsServerConfig::builder()  | 
489  | 0  |                 .with_client_cert_verifier(verifier)  | 
490  | 0  |                 .with_single_cert(certs, key)  | 
491  | 0  |                 .map_err(|e| { | 
492  | 0  |                     make_err!(Code::Internal, "Could not create TlsServerConfig : {e:?}") | 
493  | 0  |                 })?;  | 
494  |  |  | 
495  | 0  |             config.alpn_protocols.push("h2".into()); | 
496  | 0  |             Ok(Some(TlsAcceptor::from(Arc::new(config))))  | 
497  | 0  |         })?;  | 
498  |  |  | 
499  | 0  |         let socket_addr = http_config  | 
500  | 0  |             .socket_address  | 
501  | 0  |             .parse::<SocketAddr>()  | 
502  | 0  |             .map_err(|e| { | 
503  | 0  |                 make_input_err!("Invalid address '{}' - {e:?}", http_config.socket_address) | 
504  | 0  |             })?;  | 
505  | 0  |         let tcp_listener = TcpListener::bind(&socket_addr).await?;  | 
506  | 0  |         let mut http = auto::Builder::new(TaskExecutor::default());  | 
507  |  |  | 
508  | 0  |         let http_config = &http_config.advanced_http;  | 
509  | 0  |         if let Some(value) = http_config.http2_keep_alive_interval {  Branch (509:16): [Folded - Ignored]
  | 
510  | 0  |             http.http2()  | 
511  | 0  |                 .keep_alive_interval(Duration::from_secs(u64::from(value)));  | 
512  | 0  |         }  | 
513  |  |  | 
514  | 0  |         if let Some(value) = http_config.experimental_http2_max_pending_accept_reset_streams {  Branch (514:16): [Folded - Ignored]
  | 
515  | 0  |             http.http2()  | 
516  | 0  |                 .max_pending_accept_reset_streams(usize::try_from(value).err_tip(  | 
517  |  |                     || "Could not convert experimental_http2_max_pending_accept_reset_streams",  | 
518  | 0  |                 )?);  | 
519  | 0  |         }  | 
520  | 0  |         if let Some(value) = http_config.experimental_http2_initial_stream_window_size {  Branch (520:16): [Folded - Ignored]
  | 
521  | 0  |             http.http2().initial_stream_window_size(value);  | 
522  | 0  |         }  | 
523  | 0  |         if let Some(value) = http_config.experimental_http2_initial_connection_window_size {  Branch (523:16): [Folded - Ignored]
  | 
524  | 0  |             http.http2().initial_connection_window_size(value);  | 
525  | 0  |         }  | 
526  | 0  |         if let Some(value) = http_config.experimental_http2_adaptive_window {  Branch (526:16): [Folded - Ignored]
  | 
527  | 0  |             http.http2().adaptive_window(value);  | 
528  | 0  |         }  | 
529  | 0  |         if let Some(value) = http_config.experimental_http2_max_frame_size {  Branch (529:16): [Folded - Ignored]
  | 
530  | 0  |             http.http2().max_frame_size(value);  | 
531  | 0  |         }  | 
532  | 0  |         if let Some(value) = http_config.experimental_http2_max_concurrent_streams {  Branch (532:16): [Folded - Ignored]
  | 
533  | 0  |             http.http2().max_concurrent_streams(value);  | 
534  | 0  |         }  | 
535  | 0  |         if let Some(value) = http_config.experimental_http2_keep_alive_timeout {  Branch (535:16): [Folded - Ignored]
  | 
536  | 0  |             http.http2()  | 
537  | 0  |                 .keep_alive_timeout(Duration::from_secs(u64::from(value)));  | 
538  | 0  |         }  | 
539  | 0  |         if let Some(value) = http_config.experimental_http2_max_send_buf_size {  Branch (539:16): [Folded - Ignored]
  | 
540  | 0  |             http.http2().max_send_buf_size(  | 
541  | 0  |                 usize::try_from(value).err_tip(|| "Could not convert http2_max_send_buf_size")?,  | 
542  |  |             );  | 
543  | 0  |         }  | 
544  | 0  |         if http_config.experimental_http2_enable_connect_protocol == Some(true) {  Branch (544:12): [Folded - Ignored]
  | 
545  | 0  |             http.http2().enable_connect_protocol();  | 
546  | 0  |         }  | 
547  | 0  |         if let Some(value) = http_config.experimental_http2_max_header_list_size {  Branch (547:16): [Folded - Ignored]
  | 
548  | 0  |             http.http2().max_header_list_size(value);  | 
549  | 0  |         }  | 
550  | 0  |         info!("Ready, listening on {socket_addr}",); | 
551  | 0  |         root_futures.push(Box::pin(async move { | 
552  |  |             loop { | 
553  | 0  |                 select! { | 
554  | 0  |                     accept_result = tcp_listener.accept() => { | 
555  | 0  |                         match accept_result { | 
556  | 0  |                             Ok((tcp_stream, remote_addr)) => { | 
557  | 0  |                                 info!(  | 
558  |  |                                     target: "nativelink::services",  | 
559  |  |                                     ?remote_addr,  | 
560  |  |                                     ?socket_addr,  | 
561  | 0  |                                     "Client connected"  | 
562  |  |                                 );  | 
563  |  |  | 
564  | 0  |                                 let (http, svc, maybe_tls_acceptor) =  | 
565  | 0  |                                     (http.clone(), svc.clone(), maybe_tls_acceptor.clone());  | 
566  |  |  | 
567  | 0  |                                 background_spawn!(  | 
568  |  |                                     name: "http_connection",  | 
569  | 0  |                                     fut: error_span!(  | 
570  |  |                                         "http_connection",  | 
571  |  |                                         remote_addr = %remote_addr,  | 
572  |  |                                         socket_addr = %socket_addr,  | 
573  | 0  |                                     ).in_scope(|| async move { | 
574  | 0  |                                         let serve_connection = if let Some(tls_acceptor) = maybe_tls_acceptor {  Branch (574:71): [Folded - Ignored]
  | 
575  | 0  |                                             match tls_acceptor.accept(tcp_stream).await { | 
576  | 0  |                                                 Ok(tls_stream) => Either::Left(http.serve_connection(  | 
577  | 0  |                                                     TokioIo::new(tls_stream),  | 
578  | 0  |                                                     TowerToHyperService::new(svc),  | 
579  | 0  |                                                 )),  | 
580  | 0  |                                                 Err(err) => { | 
581  | 0  |                                                     error!(?err, "Failed to accept tls stream");  | 
582  | 0  |                                                     return;  | 
583  |  |                                                 }  | 
584  |  |                                             }  | 
585  |  |                                         } else { | 
586  | 0  |                                             Either::Right(http.serve_connection(  | 
587  | 0  |                                                 TokioIo::new(tcp_stream),  | 
588  | 0  |                                                 TowerToHyperService::new(svc),  | 
589  | 0  |                                             ))  | 
590  |  |                                         };  | 
591  |  |  | 
592  | 0  |                                         if let Err(err) = serve_connection.await {  Branch (592:48): [Folded - Ignored]
  | 
593  | 0  |                                             error!(  | 
594  |  |                                                 target: "nativelink::services",  | 
595  |  |                                                 ?err,  | 
596  | 0  |                                                 "Failed running service"  | 
597  |  |                                             );  | 
598  | 0  |                                         }  | 
599  | 0  |                                     }),  | 
600  |  |                                     target: "nativelink::services",  | 
601  |  |                                     ?remote_addr,  | 
602  |  |                                     ?socket_addr,  | 
603  |  |                                 );  | 
604  |  |                             },  | 
605  | 0  |                             Err(err) => { | 
606  | 0  |                                 error!(?err, "Failed to accept tcp connection");  | 
607  |  |                             }  | 
608  |  |                         }  | 
609  |  |                     },  | 
610  |  |                 }  | 
611  |  |             }  | 
612  |  |             // Unreachable  | 
613  |  |         }));  | 
614  |  |     }  | 
615  |  |  | 
616  |  |     { | 
617  |  |         // We start workers after our TcpListener is setup so if our worker connects to one  | 
618  |  |         // of these services it will be able to connect.  | 
619  | 0  |         let worker_cfgs = cfg.workers.unwrap_or_default();  | 
620  | 0  |         let mut worker_names = HashSet::with_capacity(worker_cfgs.len());  | 
621  | 0  |         for (i, worker_cfg) in worker_cfgs.into_iter().enumerate() { | 
622  | 0  |             let spawn_fut = match worker_cfg { | 
623  | 0  |                 WorkerConfig::Local(local_worker_cfg) => { | 
624  | 0  |                     let fast_slow_store = store_manager  | 
625  | 0  |                         .get_store(&local_worker_cfg.cas_fast_slow_store)  | 
626  | 0  |                         .err_tip(|| { | 
627  | 0  |                             format!(  | 
628  | 0  |                                 "Failed to find store for cas_store_ref in worker config : {}", | 
629  |  |                                 local_worker_cfg.cas_fast_slow_store  | 
630  |  |                             )  | 
631  | 0  |                         })?;  | 
632  |  |  | 
633  | 0  |                     let maybe_ac_store = if let Some(ac_store_ref) =   Branch (633:49): [Folded - Ignored]
  | 
634  | 0  |                         &local_worker_cfg.upload_action_result.ac_store  | 
635  |  |                     { | 
636  | 0  |                         Some(store_manager.get_store(ac_store_ref).err_tip(|| { | 
637  | 0  |                             format!("Failed to find store for ac_store in worker config : {ac_store_ref}") | 
638  | 0  |                         })?)  | 
639  |  |                     } else { | 
640  | 0  |                         None  | 
641  |  |                     };  | 
642  |  |                     // Note: Defaults to fast_slow_store if not specified. If this ever changes it must  | 
643  |  |                     // be updated in config documentation for the `historical_results_store` the field.  | 
644  | 0  |                     let historical_store = if let Some(cas_store_ref) = &local_worker_cfg   Branch (644:51): [Folded - Ignored]
  | 
645  | 0  |                         .upload_action_result  | 
646  | 0  |                         .historical_results_store  | 
647  |  |                     { | 
648  | 0  |                         store_manager.get_store(cas_store_ref).err_tip(|| { | 
649  | 0  |                                 format!(  | 
650  | 0  |                                 "Failed to find store for historical_results_store in worker config : {cas_store_ref}" | 
651  |  |                             )  | 
652  | 0  |                             })?  | 
653  |  |                     } else { | 
654  | 0  |                         fast_slow_store.clone()  | 
655  |  |                     };  | 
656  | 0  |                     let local_worker = new_local_worker(  | 
657  | 0  |                         Arc::new(local_worker_cfg),  | 
658  | 0  |                         fast_slow_store,  | 
659  | 0  |                         maybe_ac_store,  | 
660  | 0  |                         historical_store,  | 
661  | 0  |                     )  | 
662  | 0  |                     .await  | 
663  | 0  |                     .err_tip(|| "Could not make LocalWorker")?;  | 
664  |  |  | 
665  | 0  |                     let name = if local_worker.name().is_empty() {  Branch (665:35): [Folded - Ignored]
  | 
666  | 0  |                         format!("worker_{i}") | 
667  |  |                     } else { | 
668  | 0  |                         local_worker.name().clone()  | 
669  |  |                     };  | 
670  |  |  | 
671  | 0  |                     if worker_names.contains(&name) {  Branch (671:24): [Folded - Ignored]
  | 
672  | 0  |                         Err(make_input_err!(  | 
673  | 0  |                             "Duplicate worker name '{}' found in config", | 
674  | 0  |                             name  | 
675  | 0  |                         ))?;  | 
676  | 0  |                     }  | 
677  | 0  |                     worker_names.insert(name.clone());  | 
678  | 0  |                     let shutdown_rx = shutdown_tx.subscribe();  | 
679  | 0  |                     let fut = trace_span!("worker_ctx", worker_name = %name) | 
680  | 0  |                         .in_scope(|| local_worker.run(shutdown_rx));  | 
681  | 0  |                     spawn!("worker", fut, ?name) | 
682  |  |                 }  | 
683  |  |             };  | 
684  | 0  |             root_futures.push(Box::pin(spawn_fut.map_ok_or_else(|e| Err(e.into()), |v| v)));  | 
685  |  |         }  | 
686  |  |     }  | 
687  |  |  | 
688  |  |     // Set up a shutdown handler for the worker schedulers.  | 
689  | 0  |     let mut shutdown_rx = shutdown_tx.subscribe();  | 
690  | 0  |     root_futures.push(Box::pin(async move { | 
691  | 0  |         if let Ok(shutdown_guard) = shutdown_rx.recv().await {  Branch (691:16): [Folded - Ignored]
  | 
692  | 0  |             let _ = scheduler_shutdown_tx.send(());  | 
693  | 0  |             for (_name, scheduler) in worker_schedulers { | 
694  | 0  |                 scheduler.shutdown(shutdown_guard.clone()).await;  | 
695  |  |             }  | 
696  | 0  |         }  | 
697  | 0  |         Ok(())  | 
698  | 0  |     }));  | 
699  |  |  | 
700  | 0  |     if let Err(e) = try_join_all(root_futures).await {  Branch (700:12): [Folded - Ignored]
  | 
701  | 0  |         panic!("{e:?}"); | 
702  | 0  |     }  | 
703  |  |  | 
704  | 0  |     Ok(())  | 
705  | 0  | }  | 
706  |  |  | 
707  | 0  | fn get_config() -> Result<CasConfig, Error> { | 
708  | 0  |     let args = Args::parse();  | 
709  | 0  |     CasConfig::try_from_json5_file(&args.config_file)  | 
710  | 0  | }  | 
711  |  |  | 
712  | 0  | fn main() -> Result<(), Box<dyn core::error::Error>> { | 
713  |  |     #[expect(clippy::disallowed_methods, reason = "starting main runtime")]  | 
714  | 0  |     let runtime = tokio::runtime::Builder::new_multi_thread()  | 
715  | 0  |         .enable_all()  | 
716  | 0  |         .build()?;  | 
717  |  |  | 
718  |  |     // The OTLP exporters need to run in a Tokio context  | 
719  |  |     // Do this first so all the other logging works  | 
720  |  |     #[expect(clippy::disallowed_methods, reason = "tracing init on main runtime")]  | 
721  | 0  |     runtime.block_on(async { tokio::spawn(async { init_tracing() }).await? })?; | 
722  |  |  | 
723  | 0  |     if cfg!(feature = "worker_find_logging") { | 
724  | 0  |         info!("worker_find_logging enabled"); | 
725  | 0  |     }  | 
726  |  |  | 
727  | 0  |     let mut cfg = get_config()?;  | 
728  |  |  | 
729  | 0  |     let global_cfg = if let Some(global_cfg) = &mut cfg.global {  Branch (729:29): [Folded - Ignored]
  | 
730  | 0  |         if global_cfg.max_open_files == 0 {  Branch (730:12): [Folded - Ignored]
  | 
731  | 0  |             global_cfg.max_open_files = fs::DEFAULT_OPEN_FILE_LIMIT;  | 
732  | 0  |         }  | 
733  | 0  |         if global_cfg.default_digest_size_health_check == 0 {  Branch (733:12): [Folded - Ignored]
  | 
734  | 0  |             global_cfg.default_digest_size_health_check = DEFAULT_DIGEST_SIZE_HEALTH_CHECK_CFG;  | 
735  | 0  |         }  | 
736  |  |  | 
737  | 0  |         *global_cfg  | 
738  |  |     } else { | 
739  | 0  |         GlobalConfig { | 
740  | 0  |             max_open_files: fs::DEFAULT_OPEN_FILE_LIMIT,  | 
741  | 0  |             default_digest_hash_function: None,  | 
742  | 0  |             default_digest_size_health_check: DEFAULT_DIGEST_SIZE_HEALTH_CHECK_CFG,  | 
743  | 0  |         }  | 
744  |  |     };  | 
745  | 0  |     set_open_file_limit(global_cfg.max_open_files);  | 
746  | 0  |     set_default_digest_hasher_func(DigestHasherFunc::from(  | 
747  | 0  |         global_cfg  | 
748  | 0  |             .default_digest_hash_function  | 
749  | 0  |             .unwrap_or(ConfigDigestHashFunction::Sha256),  | 
750  | 0  |     ))?;  | 
751  | 0  |     set_default_digest_size_health_check(global_cfg.default_digest_size_health_check)?;  | 
752  |  |  | 
753  |  |     // Initiates the shutdown process by broadcasting the shutdown signal via the `oneshot::Sender` to all listeners.  | 
754  |  |     // Each listener will perform its cleanup and then drop its `oneshot::Sender`, signaling completion.  | 
755  |  |     // Once all `oneshot::Sender` instances are dropped, the worker knows it can safely terminate.  | 
756  | 0  |     let (shutdown_tx, _) = broadcast::channel::<ShutdownGuard>(BROADCAST_CAPACITY);  | 
757  |  |     #[cfg(target_family = "unix")]  | 
758  | 0  |     let shutdown_tx_clone = shutdown_tx.clone();  | 
759  |  |     #[cfg(target_family = "unix")]  | 
760  | 0  |     let mut shutdown_guard = ShutdownGuard::default();  | 
761  |  |  | 
762  |  |     #[expect(clippy::disallowed_methods, reason = "signal handler on main runtime")]  | 
763  | 0  |     runtime.spawn(async move { | 
764  | 0  |         tokio::signal::ctrl_c()  | 
765  | 0  |             .await  | 
766  | 0  |             .expect("Failed to listen to SIGINT"); | 
767  | 0  |         eprintln!("User terminated process via SIGINT"); | 
768  | 0  |         std::process::exit(130);  | 
769  |  |     });  | 
770  |  |  | 
771  |  |     #[allow(unused_variables)]  | 
772  | 0  |     let (scheduler_shutdown_tx, scheduler_shutdown_rx) = oneshot::channel();  | 
773  |  |  | 
774  |  |     #[cfg(target_family = "unix")]  | 
775  |  |     #[expect(clippy::disallowed_methods, reason = "signal handler on main runtime")]  | 
776  | 0  |     runtime.spawn(async move { | 
777  | 0  |         signal(SignalKind::terminate())  | 
778  | 0  |             .expect("Failed to listen to SIGTERM") | 
779  | 0  |             .recv()  | 
780  | 0  |             .await;  | 
781  | 0  |         warn!("Process terminated via SIGTERM",); | 
782  | 0  |         drop(shutdown_tx_clone.send(shutdown_guard.clone()));  | 
783  | 0  |         scheduler_shutdown_rx  | 
784  | 0  |             .await  | 
785  | 0  |             .expect("Failed to receive scheduler shutdown"); | 
786  | 0  |         let () = shutdown_guard.wait_for(Priority::P0).await;  | 
787  | 0  |         warn!("Successfully shut down nativelink.",); | 
788  | 0  |         std::process::exit(143);  | 
789  |  |     });  | 
790  |  |  | 
791  |  |     #[expect(clippy::disallowed_methods, reason = "waiting on everything to finish")]  | 
792  | 0  |     runtime  | 
793  | 0  |         .block_on(async { | 
794  | 0  |             trace_span!("main") | 
795  | 0  |                 .in_scope(|| async { inner_main(cfg, shutdown_tx, scheduler_shutdown_tx).await }) | 
796  | 0  |                 .await  | 
797  | 0  |         })  | 
798  | 0  |         .err_tip(|| "main() function failed")?;  | 
799  | 0  |     Ok(())  | 
800  | 0  | }  |