/build/source/nativelink-worker/src/local_worker.rs
Line | Count | Source |
1 | | // Copyright 2024 Trace Machina, Inc. 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::hash::BuildHasher; |
16 | | use core::pin::Pin; |
17 | | use core::str; |
18 | | use core::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering}; |
19 | | use core::time::Duration; |
20 | | use std::borrow::Cow; |
21 | | use std::collections::{HashMap, HashSet}; |
22 | | use std::env; |
23 | | use std::process::Stdio; |
24 | | use std::sync::{Arc, Weak}; |
25 | | use std::time::{SystemTime, UNIX_EPOCH}; |
26 | | |
27 | | use futures::future::BoxFuture; |
28 | | use futures::stream::FuturesUnordered; |
29 | | use futures::{Future, FutureExt, StreamExt, TryFutureExt, select}; |
30 | | use nativelink_config::cas_server::{EnvironmentSource, LocalWorkerConfig}; |
31 | | use nativelink_error::{Code, Error, ErrorContext, ResultExt, make_err, make_input_err}; |
32 | | use nativelink_metric::{MetricsComponent, RootMetricsComponent}; |
33 | | use nativelink_proto::com::github::trace_machina::nativelink::remote_execution::update_for_worker::Update; |
34 | | use nativelink_proto::com::github::trace_machina::nativelink::remote_execution::worker_api_client::WorkerApiClient; |
35 | | use nativelink_proto::com::github::trace_machina::nativelink::remote_execution::{ |
36 | | ActionResourceUsage, ExecuteAccepted, ExecuteComplete, ExecuteDeclined, ExecuteResult, |
37 | | GoingAwayRequest, KeepAliveRequest, OperationMemory, RunningOperations, StartExecute, |
38 | | UpdateForWorker, WorkerLoad, execute_declined, execute_result, |
39 | | }; |
40 | | use nativelink_store::fast_slow_store::FastSlowStore; |
41 | | use nativelink_util::action_messages::{ActionResult, ActionStage, OperationId}; |
42 | | use nativelink_util::common::fs; |
43 | | use nativelink_util::digest_hasher::DigestHasherFunc; |
44 | | use nativelink_util::health_utils::{HealthStatus, HealthStatusIndicator}; |
45 | | use nativelink_util::metrics_utils::{AsyncCounterWrapper, CounterWithTime}; |
46 | | use nativelink_util::shutdown_guard::ShutdownGuard; |
47 | | use nativelink_util::store_trait::Store; |
48 | | use nativelink_util::{background_spawn, spawn, spawn_blocking, tls_utils}; |
49 | | use opentelemetry::context::Context; |
50 | | use parking_lot::Mutex; |
51 | | use tokio::sync::{broadcast, mpsc}; |
52 | | use tokio::{process, time}; |
53 | | use tokio_stream::wrappers::UnboundedReceiverStream; |
54 | | use tonic::{Streaming, async_trait}; |
55 | | use tracing::{Level, debug, error, event, info, info_span, instrument, trace, warn}; |
56 | | |
57 | | use crate::running_actions_manager::{ |
58 | | ExecutionConfiguration, MISSING_INPUT_ERROR_TIP, Metrics as RunningActionManagerMetrics, |
59 | | ResourceEnforcement, RunningAction, RunningActionsManager, RunningActionsManagerArgs, |
60 | | RunningActionsManagerImpl, with_phases, |
61 | | }; |
62 | | use crate::worker_api_client_wrapper::{WorkerApiClientTrait, WorkerApiClientWrapper}; |
63 | | use crate::worker_utils::make_connect_worker_request; |
64 | | |
65 | | /// Amount of time to wait if we have actions in transit before we try to |
66 | | /// consider an error to have occurred. |
67 | | const ACTIONS_IN_TRANSIT_TIMEOUT_S: f32 = 10.; |
68 | | |
69 | | /// Increments `actions_in_transit` on creation and decrements it on drop, so |
70 | | /// the count stays accurate even when the owning action future is aborted by |
71 | | /// a disconnect. A stranded count makes the disconnect handler conclude the |
72 | | /// in-transit actions never drained, turning every disconnect-with-work into |
73 | | /// a fatal error instead of a reconnect. |
74 | | struct ActionsInTransitGuard { |
75 | | actions_in_transit: Arc<AtomicU64>, |
76 | | } |
77 | | |
78 | | impl ActionsInTransitGuard { |
79 | 13.1k | fn new(actions_in_transit: Arc<AtomicU64>) -> Self { |
80 | 13.1k | actions_in_transit.fetch_add(1, Ordering::Release); |
81 | 13.1k | Self { actions_in_transit } |
82 | 13.1k | } |
83 | | } |
84 | | |
85 | | impl Drop for ActionsInTransitGuard { |
86 | 0 | fn drop(&mut self) { |
87 | 0 | self.actions_in_transit.fetch_sub(1, Ordering::Release); |
88 | 0 | } |
89 | | } |
90 | | |
91 | | /// If we lose connection to the worker api server we will wait this many seconds |
92 | | /// before trying to connect, doubling on every failed attempt up to |
93 | | /// `CONNECTION_RETRY_MAX_DELAY_S`, with jitter so a fleet that lost its |
94 | | /// scheduler together does not redial together. |
95 | | const CONNECTION_RETRY_DELAY_S: f32 = 0.5; |
96 | | const CONNECTION_RETRY_MAX_DELAY_S: f32 = 30.0; |
97 | | |
98 | | /// Delay before the `attempt`th consecutive reconnect (0 = first retry), |
99 | | /// between half and one and a half times the exponential figure. `jitter` |
100 | | /// is taken modulo 1000. |
101 | 681 | fn reconnect_delay(attempt: u32, jitter: u32) -> Duration { |
102 | 681 | let exponent = i32::try_from(attempt.min(16)).unwrap_or(16); |
103 | 681 | let base = (CONNECTION_RETRY_DELAY_S * 2f32.powi(exponent)).min(CONNECTION_RETRY_MAX_DELAY_S); |
104 | 681 | let jitter = 0.5 + (jitter % 1_000) as f32 / 1_000.0; |
105 | 681 | Duration::from_secs_f32(base * jitter) |
106 | 681 | } |
107 | | |
108 | | /// The reconnect jitter's default source: the wall clock's nanoseconds. |
109 | 12 | fn wall_clock_jitter() -> u32 { |
110 | 12 | SystemTime::now() |
111 | 12 | .duration_since(UNIX_EPOCH) |
112 | 12 | .map_or(0, |d| d.subsec_nanos()) |
113 | 12 | } |
114 | | |
115 | | type JitterFn = Box<dyn Fn() -> u32 + Send + Sync>; |
116 | | |
117 | | /// Default endpoint timeout. If this value gets modified the documentation in |
118 | | /// `cas_server.rs` must also be updated. |
119 | | const DEFAULT_ENDPOINT_TIMEOUT_S: f32 = 5.; |
120 | | |
121 | | /// Keepalive defaults for the scheduler connection, the same as a store's |
122 | | /// gRPC endpoint (`tls_utils::endpoint`). |
123 | | const DEFAULT_TCP_KEEPALIVE: Duration = Duration::from_secs(30); |
124 | | const DEFAULT_HTTP2_KEEPALIVE_INTERVAL: Duration = Duration::from_secs(30); |
125 | | const DEFAULT_HTTP2_KEEPALIVE_TIMEOUT: Duration = Duration::from_secs(20); |
126 | | |
127 | | /// A configured number of seconds, or the default when unset (0). |
128 | 0 | const fn seconds_or(configured: u64, default: Duration) -> Duration { |
129 | 0 | if configured > 0 { |
130 | 0 | Duration::from_secs(configured) |
131 | | } else { |
132 | 0 | default |
133 | | } |
134 | 0 | } |
135 | | |
136 | | /// Sends `GoingAway` within `deadline`. Logged rather than fatal: the stream |
137 | | /// close that follows is what removes the worker, this only says why. |
138 | 1 | async fn send_going_away<T: WorkerApiClientTrait>( |
139 | 1 | grpc_client: &mut T, |
140 | 1 | drain: bool, |
141 | 1 | deadline: Duration, |
142 | 1 | ) -> Result<(), Error> { |
143 | 1 | match time::timeout(deadline, grpc_client.going_away(GoingAwayRequest { drain })).await { |
144 | 1 | Ok(Ok(())) => Ok(()), |
145 | 0 | Ok(Err(e)) => { |
146 | 0 | error!(?e, drain, "Failed to send GoingAwayRequest"); |
147 | 0 | Err(e.append("Failed to send GoingAwayRequest")) |
148 | | } |
149 | | Err(_) => { |
150 | 0 | error!( |
151 | | drain, |
152 | 0 | deadline_s = deadline.as_secs_f32(), |
153 | | "GoingAwayRequest did not complete; the scheduler connection is stalled" |
154 | | ); |
155 | 0 | Err(make_err!( |
156 | 0 | Code::DeadlineExceeded, |
157 | 0 | "GoingAwayRequest did not complete within {}s", |
158 | 0 | deadline.as_secs_f32() |
159 | 0 | )) |
160 | | } |
161 | | } |
162 | 1 | } |
163 | | |
164 | | /// Default maximum amount of time a task is allowed to run for. |
165 | | /// If this value gets modified the documentation in `cas_server.rs` must also be updated. |
166 | | const DEFAULT_MAX_ACTION_TIMEOUT: Duration = Duration::from_mins(20); |
167 | | const DEFAULT_MAX_UPLOAD_TIMEOUT: Duration = Duration::from_mins(10); |
168 | | /// Default for `max_download_timeout_s`: an input fetch is quick or wedged. |
169 | | const DEFAULT_MAX_DOWNLOAD_TIMEOUT: Duration = Duration::from_mins(10); |
170 | | const DEFAULT_MAX_CLEANUP_WAIT: Duration = Duration::from_secs(30); |
171 | | const DEFAULT_MAX_CLEANUP_BACKOFF: Duration = Duration::from_millis(500); |
172 | | /// If this value gets modified the documentation in `cas_server.rs` must also be updated. |
173 | | const DEFAULT_PRECONDITION_TIMEOUT: Duration = Duration::from_secs(30); |
174 | | /// If this value gets modified the documentation in `cas_server.rs` must also be updated. |
175 | | const DEFAULT_KILL_GRACE: Duration = Duration::from_secs(5); |
176 | | |
177 | | struct FinishedActionResult { |
178 | | action_result: ActionResult, |
179 | | resource_usage: Option<ActionResourceUsage>, |
180 | | do_not_cache: bool, |
181 | | } |
182 | | |
183 | | struct LocalWorkerImpl<'a, T: WorkerApiClientTrait + 'static, U: RunningActionsManager> { |
184 | | config: &'a LocalWorkerConfig, |
185 | | // According to the tonic documentation it is a cheap operation to clone this. |
186 | | grpc_client: T, |
187 | | worker_id: String, |
188 | | running_actions_manager: Arc<U>, |
189 | | // Number of actions that have been received in `Update::StartAction`, but |
190 | | // not yet processed by running_actions_manager's spawn. This number should |
191 | | // always be zero if there are no actions running and no actions being waited |
192 | | // on by the scheduler. |
193 | | actions_in_transit: Arc<AtomicU64>, |
194 | | accepted_action: Arc<AtomicBool>, |
195 | | /// The scheduler said it understands `ExecuteAccepted` and |
196 | | /// `ExecuteDeclined`. Without it the worker runs whatever it is sent, |
197 | | /// as every earlier release did. |
198 | | dispatch_ack: bool, |
199 | | memory: MemoryAdmission, |
200 | | metrics: Arc<Metrics>, |
201 | | } |
202 | | |
203 | | /// What local admission needs to refuse an action for load. |
204 | | struct MemoryAdmission { |
205 | | /// The platform property the scheduler reads an action's memory |
206 | | /// reservation from, as it told us on connection; empty when it does |
207 | | /// not veto on memory. Read from the same property, a refusal for load |
208 | | /// here agrees with what the scheduler would have vetoed. |
209 | | property: String, |
210 | | /// Whether this worker admits any action while it holds nothing else, |
211 | | /// decided once at registration and sent to the scheduler then, so the |
212 | | /// two never disagree. |
213 | | admits_when_idle: bool, |
214 | | } |
215 | | |
216 | | /// Why this worker will not run an action it was just sent. |
217 | | enum Refusal { |
218 | | AtCapacity { in_flight: u64, max: u64 }, |
219 | | Load { needed_kb: u64, free_kb: u64 }, |
220 | | ShuttingDown, |
221 | | } |
222 | | |
223 | | impl Refusal { |
224 | 3 | fn into_declined(self, operation_id: String) -> ExecuteDeclined { |
225 | 3 | let (reason, detail, needed_kb, free_kb) = match self { |
226 | 1 | Self::AtCapacity { in_flight, max } => ( |
227 | 1 | execute_declined::Reason::AtCapacity, |
228 | 1 | format!("{in_flight} of {max} in flight"), |
229 | 1 | 0, |
230 | 1 | 0, |
231 | 1 | ), |
232 | 2 | Self::Load { needed_kb, free_kb } => ( |
233 | 2 | execute_declined::Reason::Load, |
234 | 2 | format!("needs {needed_kb} KiB, {free_kb} KiB free"), |
235 | 2 | needed_kb, |
236 | 2 | free_kb, |
237 | 2 | ), |
238 | 0 | Self::ShuttingDown => ( |
239 | 0 | execute_declined::Reason::ShuttingDown, |
240 | 0 | "worker shutting down".to_string(), |
241 | 0 | 0, |
242 | 0 | 0, |
243 | 0 | ), |
244 | | }; |
245 | 3 | ExecuteDeclined { |
246 | 3 | operation_id, |
247 | 3 | reason: reason as i32, |
248 | 3 | detail, |
249 | 3 | needed_kb, |
250 | 3 | free_kb, |
251 | 3 | } |
252 | 3 | } |
253 | | } |
254 | | |
255 | | /// The memory reservation an action carries under `property`, in KiB, if |
256 | | /// it declares one. An empty property name is a scheduler that does not |
257 | | /// veto on memory, so nothing is ever read. |
258 | 13.1k | fn memory_reservation_kb(start_execute: &StartExecute, property: &str) -> Option<u64> { |
259 | 13.1k | if property.is_empty() { |
260 | 13.1k | return None; |
261 | 3 | } |
262 | 3 | start_execute |
263 | 3 | .platform |
264 | 3 | .as_ref()?0 |
265 | | .properties |
266 | 3 | .iter() |
267 | 3 | .find(|p| p.name == property) |
268 | 3 | .and_then(|p| p.value.parse::<u64>().ok()) |
269 | 3 | .filter(|kb| *kb > 0) |
270 | 13.1k | } |
271 | | |
272 | 13.1k | pub async fn preconditions_met<H: BuildHasher + Sync>( |
273 | 13.1k | precondition_script: Option<String>, |
274 | 13.1k | extra_envs: &HashMap<String, String, H>, |
275 | 13.1k | timeout: Duration, |
276 | 13.1k | ) -> Result<(), Error> { |
277 | 13.1k | let Some(precondition_script3 ) = &precondition_script else { |
278 | | // No script means we are always ok to proceed. |
279 | 13.1k | return Ok(()); |
280 | | }; |
281 | | // TODO: Might want to pass some information about the command to the |
282 | | // script, but at this point it's not even been downloaded yet, |
283 | | // so that's not currently possible. Perhaps we'll move this in |
284 | | // future to pass useful information through? Or perhaps we'll |
285 | | // have a pre-condition and a pre-execute script instead, although |
286 | | // arguably entrypoint already gives us that. |
287 | | |
288 | 3 | let maybe_split_cmd = shlex::split(precondition_script); |
289 | 3 | let (command, args) = match &maybe_split_cmd { |
290 | 3 | Some(split_cmd) => (&split_cmd[0], &split_cmd[1..]), |
291 | | None => { |
292 | 0 | return Err(make_input_err!( |
293 | 0 | "Could not parse the value of precondition_script: '{}'", |
294 | 0 | precondition_script, |
295 | 0 | )); |
296 | | } |
297 | | }; |
298 | | |
299 | 3 | let precondition_process = process::Command::new(command) |
300 | 3 | .args(args) |
301 | 3 | .kill_on_drop(true) |
302 | 3 | .stdin(Stdio::null()) |
303 | 3 | .stdout(Stdio::piped()) |
304 | 3 | .stderr(Stdio::null()) |
305 | 3 | .env_clear() |
306 | 3 | .envs(extra_envs) |
307 | 3 | .spawn() |
308 | 3 | .err_tip(|| format!0 ("Could not execute precondition command {precondition_script:?}"))?0 ; |
309 | 3 | let _owned = crate::reaper::OwnedChild::new(precondition_process.id()); |
310 | | // Bounded: a script that hangs held the action forever, and |
311 | | // `kill_on_drop` ends the script when the timeout drops it. |
312 | 3 | let output2 = match time::timeout(timeout, precondition_process.wait_with_output()).await { |
313 | 2 | Ok(output) => output?0 , |
314 | | Err(_) => { |
315 | 1 | return Err(make_err!( |
316 | 1 | Code::ResourceExhausted, |
317 | 1 | "Preconditions script {precondition_script:?} did not finish within {} ms", |
318 | 1 | timeout.as_millis() |
319 | 1 | )); |
320 | | } |
321 | | }; |
322 | 2 | let stdout = str::from_utf8(&output.stdout).unwrap_or(""); |
323 | 2 | trace!(status = %output.status, %stdout, "Preconditions script returned"); |
324 | 2 | if output.status.code() == Some(0) { |
325 | 1 | Ok(()) |
326 | | } else { |
327 | 1 | Err(make_err!( |
328 | 1 | Code::ResourceExhausted, |
329 | 1 | "Preconditions script returned status {} - {}", |
330 | 1 | output.status, |
331 | 1 | stdout |
332 | 1 | )) |
333 | | } |
334 | 13.1k | } |
335 | | |
336 | | impl<'a, T: WorkerApiClientTrait + 'static, U: RunningActionsManager> LocalWorkerImpl<'a, T, U> { |
337 | 1.77k | fn new( |
338 | 1.77k | config: &'a LocalWorkerConfig, |
339 | 1.77k | grpc_client: T, |
340 | 1.77k | worker_id: String, |
341 | 1.77k | dispatch_ack: bool, |
342 | 1.77k | memory: MemoryAdmission, |
343 | 1.77k | running_actions_manager: Arc<U>, |
344 | 1.77k | metrics: Arc<Metrics>, |
345 | 1.77k | ) -> Self { |
346 | 1.77k | Self { |
347 | 1.77k | config, |
348 | 1.77k | grpc_client, |
349 | 1.77k | worker_id, |
350 | 1.77k | dispatch_ack, |
351 | 1.77k | memory, |
352 | 1.77k | running_actions_manager, |
353 | 1.77k | // Number of actions that have been received in `Update::StartAction`, but |
354 | 1.77k | // not yet processed by running_actions_manager's spawn. This number should |
355 | 1.77k | // always be zero if there are no actions running and no actions being waited |
356 | 1.77k | // on by the scheduler. |
357 | 1.77k | actions_in_transit: Arc::new(AtomicU64::new(0)), |
358 | 1.77k | accepted_action: Arc::new(AtomicBool::new(false)), |
359 | 1.77k | metrics, |
360 | 1.77k | } |
361 | 1.77k | } |
362 | | |
363 | | /// Local admission: the worker's own word on whether it can take this |
364 | | /// action now. The scheduler's ledger says what it believes the worker |
365 | | /// has; this is what the worker has. |
366 | 13.1k | fn admission(&self, start_execute: &StartExecute, in_flight: u64) -> Option<Refusal> { |
367 | 13.1k | let max = self.config.max_inflight_tasks; |
368 | 13.1k | if max > 0 && in_flight >= max13.1k { |
369 | 1 | return Some(Refusal::AtCapacity { in_flight, max }); |
370 | 13.1k | } |
371 | | // The cgroup is read only for an action that reserves memory. |
372 | 13.1k | let needed_kb2 = memory_reservation_kb(start_execute, &self.memory.property)?13.1k ; |
373 | | // With nothing else in flight under a cgroup limit, waiting frees |
374 | | // nothing: what the worker reads free now is the most it will ever |
375 | | // read, since its own process, its hot page cache and the kernel |
376 | | // always count as used. Declining here would have the scheduler |
377 | | // wait for a figure that never comes (the whole-worker escalation |
378 | | // step asks for more than any worker reports free), so the action |
379 | | // runs, and if it truly does not fit, the memory kill escalates or |
380 | | // fails it. Without a limit, free memory is the host's, which other |
381 | | // processes can give back, so waiting can help and the check stands. |
382 | 2 | if in_flight == 0 && self.memory.admits_when_idle { |
383 | 0 | return None; |
384 | 2 | } |
385 | 2 | if let Some(free_kb) = crate::capacity::free_memory_kb() |
386 | 2 | && free_kb < needed_kb |
387 | | { |
388 | 2 | return Some(Refusal::Load { needed_kb, free_kb }); |
389 | 0 | } |
390 | 0 | None |
391 | 13.1k | } |
392 | | |
393 | | /// Tells the scheduler the action is refused; only meaningful when it |
394 | | /// understands the message. |
395 | | /// The one message bounded by the endpoint timeout: `GoingAway` at |
396 | | /// shutdown, so a stalled connection cannot hold a pod past its |
397 | | /// termination grace. Everything else the worker sends rides on the |
398 | | /// `ConnectWorker` stream unbounded, and the scheduler's liveness |
399 | | /// timeout is the clock that evicts a worker it cannot hear. |
400 | 1 | fn going_away_deadline(&self) -> Duration { |
401 | 1 | Duration::from_secs_f32( |
402 | 1 | self.config |
403 | 1 | .worker_api_endpoint |
404 | 1 | .timeout |
405 | 1 | .unwrap_or(DEFAULT_ENDPOINT_TIMEOUT_S), |
406 | | ) |
407 | 1 | } |
408 | | |
409 | | /// A message to the scheduler the run loop does not wait for inline: |
410 | | /// it rides in the loop's future set, so the loop keeps reading its |
411 | | /// stream while the message waits its turn on the one-slot channel |
412 | | /// feeding the `ConnectWorker` stream. No deadline on it: a message |
413 | | /// waits behind whatever the scheduler is still processing, and a |
414 | | /// scheduler that stops hearing this worker closes the stream, which |
415 | | /// the loop now sees. |
416 | 13.1k | fn scheduler_send( |
417 | 13.1k | &self, |
418 | 13.1k | what: &'static str, |
419 | 13.1k | send: impl Future<Output = Result<(), Error>> + Send + 'static, |
420 | 13.1k | ) -> BoxFuture<'static, Result<(), Error>> { |
421 | 13.1k | async move { send.await.err_tip13.1k (|| format!1 ("Could not send {what}")) }13.1k .boxed() |
422 | 13.1k | } |
423 | | |
424 | 3 | fn decline( |
425 | 3 | &self, |
426 | 3 | operation_id: String, |
427 | 3 | refusal: Refusal, |
428 | 3 | ) -> BoxFuture<'static, Result<(), Error>> { |
429 | 3 | self.metrics.actions_declined.inc(); |
430 | 3 | let mut grpc_client = self.grpc_client.clone(); |
431 | 3 | self.scheduler_send("ExecuteDeclined", async move { |
432 | 3 | grpc_client |
433 | 3 | .execute_declined(refusal.into_declined(operation_id)) |
434 | 3 | .await |
435 | 1 | }) |
436 | 3 | } |
437 | | |
438 | | /// Starts a background spawn/thread that will send a message to the server every `timeout / 2`. |
439 | | /// Each keepalive carries `running_operations`, what this worker holds |
440 | | /// from dispatch to published result, so the scheduler can tell an |
441 | | /// operation still running here from one whose result it never saw. |
442 | 1.77k | async fn start_keep_alive( |
443 | 1.77k | &self, |
444 | 1.77k | running_operations: Arc<Mutex<HashSet<String>>>, |
445 | 1.77k | ) -> Result<(), Error> {1.77k |
446 | | // According to tonic's documentation this call should be cheap and is the same stream. |
447 | 1.77k | let mut grpc_client = self.grpc_client.clone(); |
448 | 1.77k | let running_actions_manager = self.running_actions_manager.clone(); |
449 | 1.77k | let timeout = self |
450 | 1.77k | .config |
451 | 1.77k | .worker_api_endpoint |
452 | 1.77k | .timeout |
453 | 1.77k | .unwrap_or(DEFAULT_ENDPOINT_TIMEOUT_S); |
454 | | |
455 | 1.77k | info!(timeout, "Started KeepAlive"); |
456 | | |
457 | | // We always send 2 keep alive requests per timeout. Http2 should manage most of our |
458 | | // timeout issues, this is a secondary check to ensure we can still send data. |
459 | 1.77k | let mut interval = time::interval(Duration::from_secs_f32(timeout) / 2); |
460 | 1.77k | interval.set_missed_tick_behavior(time::MissedTickBehavior::Skip); |
461 | | |
462 | | // Skip the first interval as it happens immediately and we don't need a keep alive until timeout/2 has passed |
463 | 1.77k | interval.tick().await; |
464 | | |
465 | | // Explicitly spawn the keep alive loop so it goes onto a different thread from the execute commands. |
466 | | // Its failure is this worker's failure: a worker whose keepalives |
467 | | // stop reaching the scheduler is evicted `worker_timeout_s` later |
468 | | // with every action it holds requeued, so ending the stream now and |
469 | | // reconnecting is the cheaper outcome. Before, the task died quietly |
470 | | // and the worker ran on without keepalives. |
471 | 1.76k | spawn!("keep alives", async move {1.76k |
472 | | loop { |
473 | 27.4k | interval.tick().await; |
474 | | // What the worker has to spare rides on the keepalive, so a |
475 | | // scheduler with `live_memory_veto` can skip a worker whose |
476 | | // actions declared less than they use. |
477 | 25.6k | let load = crate::capacity::free_memory_kb() |
478 | 25.6k | .map(|free_memory_kb| WorkerLoad { free_memory_kb }); |
479 | 25.6k | let operation_ids = running_operations.lock().iter().cloned().collect(); |
480 | | // Each running action's sampled peak, so a scheduler that |
481 | | // loses this worker can tell which action outgrew its |
482 | | // reservation (RFC-0018). |
483 | 25.6k | let memory = running_actions_manager |
484 | 25.6k | .memory_peaks() |
485 | 25.6k | .into_iter() |
486 | 25.6k | .map(|(operation_id, peak_memory_kb)| OperationMemory { |
487 | 4 | operation_id, |
488 | 4 | peak_memory_kb, |
489 | 4 | }) |
490 | 25.6k | .collect(); |
491 | 25.6k | let request = KeepAliveRequest { |
492 | 25.6k | load, |
493 | 25.6k | running_operations: Some(RunningOperations { |
494 | 25.6k | operation_ids, |
495 | 25.6k | memory, |
496 | 25.6k | }), |
497 | 25.6k | }; |
498 | 25.6k | if let Err(e3 ) = grpc_client.keep_alive(request).await { |
499 | 3 | error!(?e, "Failed to send KeepAlive in LocalWorker"); |
500 | 3 | return Err(e.append("KeepAlive failed; reconnecting to the scheduler")); |
501 | 25.6k | } |
502 | 25.6k | debug!("Sent KeepAlive"); |
503 | | } |
504 | 3 | }) |
505 | 1.76k | .await |
506 | 4 | .map_err(|e| make_err!1 (Code::Internal1 , "KeepAlive task ended: {e:?}"))?1 |
507 | 4 | } |
508 | | |
509 | 1.77k | async fn run( |
510 | 1.77k | &self, |
511 | 1.77k | update_for_worker_stream: Streaming<UpdateForWorker>, |
512 | 1.77k | shutdown_rx: &mut broadcast::Receiver<ShutdownGuard>, |
513 | 1.77k | ) -> Result<(), Error> { |
514 | | // This big block of logic is designed to help simplify upstream components. Upstream |
515 | | // components can write standard futures that return a `Result<(), Error>` and this block |
516 | | // will forward the error up to the client and disconnect from the scheduler. |
517 | | // It is a common use case that an item sent through update_for_worker_stream will always |
518 | | // have a response but the response will be triggered through a callback to the scheduler. |
519 | | // This can be quite tricky to manage, so what we have done here is given access to a |
520 | | // `futures` variable which because this is in a single thread as well as a channel that you |
521 | | // send a future into that makes it into the `futures` variable. |
522 | | // This means that if you want to perform an action based on the result of the future |
523 | | // you use the `.map()` method and the new action will always come to live in this spawn, |
524 | | // giving mutable access to stuff in this struct. |
525 | | // NOTE: If you ever return from this function it will disconnect from the scheduler. |
526 | 1.77k | let mut futures = FuturesUnordered::new(); |
527 | | // What this worker is running, from the dispatch until the result is |
528 | | // published, reported on every keepalive. |
529 | 1.77k | let running_operations = Arc::new(Mutex::new(HashSet::new())); |
530 | 1.77k | futures.push(self.start_keep_alive(running_operations.clone()).boxed()); |
531 | | |
532 | 1.77k | let (add_future_channel, add_future_rx) = mpsc::unbounded_channel(); |
533 | 1.77k | let mut add_future_rx = UnboundedReceiverStream::new(add_future_rx).fuse(); |
534 | | |
535 | 1.77k | let mut update_for_worker_stream = update_for_worker_stream.fuse(); |
536 | | // A notify which is triggered every time actions_in_flight is subtracted. |
537 | 1.77k | let actions_notify = Arc::new(tokio::sync::Notify::new()); |
538 | | // A counter of actions that are in-flight, this is similar to actions_in_transit but |
539 | | // includes the AC upload and notification to the scheduler. |
540 | 1.77k | let actions_in_flight = Arc::new(AtomicU64::new(0)); |
541 | | // Set to true when shutting down, this stops any new StartAction. |
542 | 1.77k | let mut shutting_down = false; |
543 | | |
544 | | loop { |
545 | 52.7k | if self.config.single_use |
546 | 17 | && self.accepted_action.load(Ordering::Acquire) |
547 | 5 | && actions_in_flight.load(Ordering::Acquire) == 0 |
548 | | { |
549 | | // The action, CAS/AC uploads, cleanup, and execution_response |
550 | | // acknowledgment have all completed. This container is spent. |
551 | | // Bounded: a stalled connection must not keep a spent |
552 | | // container from exiting. |
553 | 1 | let mut grpc_client = self.grpc_client.clone(); |
554 | 0 | if let Err(err) = |
555 | 1 | send_going_away(&mut grpc_client, false, self.going_away_deadline()).await |
556 | | { |
557 | 0 | warn!(?err, "Could not unregister completed single-use worker"); |
558 | 1 | } |
559 | 1 | return Ok(()); |
560 | 52.7k | } |
561 | 52.7k | select! { |
562 | 52.7k | maybe_update13.6k = update_for_worker_stream.next() => if !shutting_down13.6k || maybe_update0 .is_some0 () { |
563 | 13.6k | match maybe_update |
564 | 13.6k | .err_tip(|| "UpdateForWorker stream closed early")?512 |
565 | 13.1k | .err_tip(|| "Got error in UpdateForWorker stream")?0 |
566 | | .update |
567 | 13.1k | .err_tip(|| "Expected update to exist in UpdateForWorker")?0 |
568 | | { |
569 | | Update::ConnectionResult(_) => { |
570 | 0 | return Err(make_input_err!( |
571 | 0 | "Got ConnectionResult in LocalWorker::run which should never happen" |
572 | 0 | )); |
573 | | } |
574 | | // TODO(palfrey) We should possibly do something with this notification. |
575 | 2 | Update::Disconnect(()) => { |
576 | 2 | self.metrics.disconnects_received.inc(); |
577 | 2 | } |
578 | 0 | Update::KeepAlive(()) => { |
579 | 0 | self.metrics.keep_alives_received.inc(); |
580 | 0 | } |
581 | | // This worker does not name itself, so the scheduler |
582 | | // does not send this; it has nothing to forget. |
583 | 0 | Update::ExecuteResultAccepted(_) => {} |
584 | 2 | Update::KillOperationRequest(kill_operation_request) => { |
585 | 2 | let operation_id = OperationId::from(kill_operation_request.operation_id); |
586 | 2 | if let Err(err0 ) = self.running_actions_manager.kill_operation(&operation_id).await { |
587 | 0 | error!( |
588 | | %operation_id, |
589 | | ?err, |
590 | | "Failed to send kill request for operation" |
591 | | ); |
592 | 2 | } |
593 | | } |
594 | 13.1k | Update::StartAction(start_execute) => { |
595 | | // Don't accept any new requests if we're shutting down. |
596 | 13.1k | if shutting_down || (self.config.single_use |
597 | 7 | && self.accepted_action.load(Ordering::Acquire)) { |
598 | 1 | if self.dispatch_ack { |
599 | 0 | futures.push(self.decline(start_execute.operation_id, Refusal::ShuttingDown)); |
600 | 1 | } else if let Some(instance_name) = start_execute.execute_request.map(|request| request.instance_name) { |
601 | 1 | let mut grpc_client = self.grpc_client.clone(); |
602 | 1 | let operation_id = start_execute.operation_id; |
603 | 1 | futures.push(self.scheduler_send("ExecutionResponse", async move { |
604 | 1 | grpc_client.execution_response( |
605 | 1 | ExecuteResult{ |
606 | 1 | instance_name, |
607 | 1 | operation_id, |
608 | 1 | result: Some(execute_result::Result::InternalError(make_err!(Code::ResourceExhausted, "Worker shutting down").into())), |
609 | 1 | resource_usage: None, |
610 | 1 | } |
611 | 1 | ).await |
612 | 1 | })); |
613 | 0 | } |
614 | 1 | continue; |
615 | 13.1k | } |
616 | | |
617 | | // Admission, then the acknowledgement: what the |
618 | | // scheduler charged on the send is confirmed or |
619 | | // handed back, and a declined action never runs. |
620 | | // A scheduler that does not speak the |
621 | | // acknowledgement gets the old behaviour, run |
622 | | // whatever arrives. Neither message is awaited |
623 | | // here: this loop is the only reader of the |
624 | | // scheduler's stream, and a send that hangs on a |
625 | | // stalled connection would keep it from ever |
626 | | // seeing that stream close (the worker then sat |
627 | | // evicted and idle until the provisioner retired |
628 | | // it). The action starts once its acknowledgement |
629 | | // has gone out, so the scheduler hears the |
630 | | // acknowledgement before anything the run sends, |
631 | | // and one that fails leaves the action unstarted. |
632 | 13.1k | let acknowledgement13.1k = if self.dispatch_ack { |
633 | 13.1k | if let Some(refusal3 ) = self.admission( |
634 | 13.1k | &start_execute, |
635 | 13.1k | actions_in_flight.load(Ordering::Acquire), |
636 | 13.1k | ) { |
637 | 3 | futures.push(self.decline(start_execute.operation_id, refusal)); |
638 | 3 | continue; |
639 | 13.1k | } |
640 | 13.1k | let mut grpc_client = self.grpc_client.clone(); |
641 | 13.1k | let operation_id = start_execute.operation_id.clone(); |
642 | 13.1k | Some(self.scheduler_send("ExecuteAccepted", async move { |
643 | 13.1k | grpc_client |
644 | 13.1k | .execute_accepted(ExecuteAccepted { operation_id }) |
645 | 13.1k | .await |
646 | 13.1k | })) |
647 | | } else { |
648 | 10 | None |
649 | | }; |
650 | | // Admitted: a single-use worker is spent by this |
651 | | // action once it is acknowledged. A decline above |
652 | | // must not spend it, or every dispatch it turns |
653 | | // away costs a pod. |
654 | 13.1k | let spent_mark = self.config.single_use.then(|| self.accepted_action5 .clone5 ()); |
655 | | |
656 | 13.1k | self.metrics.start_actions_received.inc(); |
657 | | |
658 | 13.1k | let execute_request = start_execute.execute_request.as_ref(); |
659 | 13.1k | let operation_id = start_execute.operation_id.clone(); |
660 | 13.1k | let operation_id_to_log = operation_id.clone(); |
661 | 13.1k | let tracked_operation_id = operation_id.clone(); |
662 | 13.1k | let maybe_instance_name = execute_request.map(|v| v.instance_name.clone()); |
663 | 13.1k | let action_digest = execute_request.and_then(|v| v.action_digest.clone()); |
664 | 13.1k | let digest_hasher = execute_request |
665 | 13.1k | .ok_or_else(|| make_input_err!0 ("Expected execute_request to be set")) |
666 | 13.1k | .and_then(|v| DigestHasherFunc::try_from(v.digest_function)) |
667 | 13.1k | .err_tip(|| "In LocalWorkerImpl::new()")?0 ; |
668 | | |
669 | 13.1k | let start_action_fut = { |
670 | 13.1k | let precondition_script_cfg = self.config.experimental_precondition_script.clone(); |
671 | 13.1k | let precondition_timeout = if self.config.precondition_timeout_ms == 0 { |
672 | 13.1k | DEFAULT_PRECONDITION_TIMEOUT |
673 | | } else { |
674 | 0 | Duration::from_millis(self.config.precondition_timeout_ms) |
675 | | }; |
676 | 13.1k | let mut extra_envs: HashMap<String, String> = HashMap::new(); |
677 | 13.1k | if let Some(ref additional_environment0 ) = self.config.additional_environment { |
678 | 0 | for (name, source) in additional_environment { |
679 | 0 | let value = match source { |
680 | 0 | EnvironmentSource::Property(property) => start_execute |
681 | 0 | .platform.as_ref().and_then(|p|p.properties.iter().find(|pr| &pr.name == property)) |
682 | 0 | .map_or_else(|| Cow::Borrowed(""), |v| Cow::Borrowed(v.value.as_str())), |
683 | 0 | EnvironmentSource::Value(value) => Cow::Borrowed(value.as_str()), |
684 | 0 | EnvironmentSource::FromEnvironment => Cow::Owned(env::var(name).unwrap_or_default()), |
685 | 0 | other => { |
686 | 0 | debug!(?other, "Worker doesn't support this type of additional environment"); |
687 | 0 | continue; |
688 | | } |
689 | | }; |
690 | 0 | extra_envs.insert(name.clone(), value.into_owned()); |
691 | | } |
692 | 13.1k | } |
693 | 13.1k | let actions_in_transit_guard = |
694 | 13.1k | ActionsInTransitGuard::new(self.actions_in_transit.clone()); |
695 | 13.1k | let worker_id = self.worker_id.clone(); |
696 | 13.1k | let running_actions_manager = self.running_actions_manager.clone(); |
697 | 13.1k | let mut grpc_client = self.grpc_client.clone(); |
698 | 13.1k | let complete = ExecuteComplete { |
699 | 13.1k | operation_id: operation_id.clone(), |
700 | 13.1k | }; |
701 | 13.1k | let single_use = self.config.single_use; |
702 | 13.1k | self.metrics.clone().wrap(move |metrics| async move {13.1k |
703 | 13.1k | metrics.preconditions.wrap(preconditions_met(precondition_script_cfg, &extra_envs, precondition_timeout)) |
704 | 13.1k | .and_then(|()| running_actions_manager13.1k .create_and_add_action13.1k (worker_id13.1k , start_execute13.1k )) |
705 | 13.1k | .map(move |r| {13.1k |
706 | | // Now that we either failed or registered our action, we can |
707 | | // consider the action to no longer be in transit. |
708 | 13.1k | drop(actions_in_transit_guard); |
709 | 13.1k | r |
710 | 13.1k | }) |
711 | 13.1k | .and_then(|action| {13.1k |
712 | 13.1k | debug!( |
713 | 243 | operation_id = %action.get_operation_id(), |
714 | | "Received request to run action" |
715 | | ); |
716 | 13.1k | action |
717 | 13.1k | .clone() |
718 | 13.1k | .prepare_action() |
719 | 13.1k | .and_then(RunningAction::execute) |
720 | 13.1k | .and_then(|result| async move {12.3k |
721 | | // Reusable workers release their slot during upload. |
722 | | // A single-use worker must never advertise another slot. |
723 | 12.3k | if !single_use { |
724 | 12.3k | drop(grpc_client.execution_complete(complete).await); |
725 | 1 | } |
726 | 12.3k | Ok(result) |
727 | 24.6k | }) |
728 | 13.1k | .and_then(RunningAction::upload_results) |
729 | 13.1k | .and_then(|action| async move {12.3k |
730 | 12.3k | let resource_usage = action.resource_usage(); |
731 | 12.3k | let do_not_cache = action.do_not_cache(); |
732 | 12.3k | let action_result = action.get_finished_result().await?0 ; |
733 | 12.3k | Ok(FinishedActionResult { |
734 | 12.3k | action_result, |
735 | 12.3k | resource_usage, |
736 | 12.3k | do_not_cache, |
737 | 12.3k | }) |
738 | 24.6k | }) |
739 | | // Note: We need ensure we run cleanup even if one of the other steps fail. |
740 | 13.1k | .then(|result| async move {12.5k |
741 | 12.5k | if let Err(e0 ) = action.cleanup().await { |
742 | 0 | return Result::<FinishedActionResult, Error>::Err(e).merge(result); |
743 | 12.5k | } |
744 | 12.5k | result |
745 | 25.1k | }) |
746 | 13.1k | }13.1k ).await |
747 | 25.7k | }) |
748 | | }; |
749 | | |
750 | 13.1k | let make_publish_future = { |
751 | 13.1k | let mut grpc_client = self.grpc_client.clone(); |
752 | | |
753 | 13.1k | let running_actions_manager = self.running_actions_manager.clone(); |
754 | 13.1k | let worker_id = self.worker_id.clone(); |
755 | 12.5k | move |res: Result<FinishedActionResult, Error>| async move { |
756 | 12.5k | let instance_name = maybe_instance_name |
757 | 12.5k | .err_tip(|| "`instance_name` could not be resolved; this is likely an internal error in local_worker.")?0 ; |
758 | 12.5k | match res { |
759 | 12.3k | Ok(FinishedActionResult { mut action_result, resource_usage, do_not_cache }) => { |
760 | | // Save in the action cache before notifying the scheduler that we've completed. |
761 | 12.3k | if let Some(digest_info) = action_digest.clone().and_then(|action_digest| action_digest.try_into().ok()) && |
762 | 12.3k | let Err(err0 ) = running_actions_manager.cache_action_result(digest_info, &mut action_result, digest_hasher, do_not_cache).await { |
763 | 0 | error!( |
764 | | ?err, |
765 | | ?action_digest, |
766 | | "Error saving action in store", |
767 | | ); |
768 | 12.3k | } |
769 | 12.3k | let resource_usage = resource_usage.map(|mut resource_usage| {0 |
770 | 0 | resource_usage.operation_id.clone_from(&operation_id); |
771 | 0 | resource_usage.worker_id.clone_from(&worker_id); |
772 | 0 | with_phases(&mut resource_usage, &action_result); |
773 | 0 | resource_usage |
774 | 0 | }); |
775 | 12.3k | let action_stage = ActionStage::Completed(action_result); |
776 | 12.3k | grpc_client.execution_response( |
777 | 12.3k | ExecuteResult{ |
778 | 12.3k | instance_name, |
779 | 12.3k | operation_id, |
780 | 12.3k | result: Some(execute_result::Result::ExecuteResponse(action_stage.into())), |
781 | 12.3k | resource_usage, |
782 | 12.3k | } |
783 | 12.3k | ) |
784 | 12.3k | .await |
785 | 12.3k | .err_tip(|| "Error while calling execution_response")?0 ; |
786 | | }, |
787 | 261 | Err(e) => { |
788 | | // The manager tags a NotFound on anything the client |
789 | | // referenced by digest; no store's wording involved. |
790 | 261 | let is_cas_blob_missing = e.code == Code::NotFound |
791 | 2 | && matches!1 (e.context, ErrorContext::MissingDigest { .. }) |
792 | 2 | && e.messages.iter()1 .any1 (|m| m == MISSING_INPUT_ERROR_TIP); |
793 | 261 | if is_cas_blob_missing { |
794 | 1 | warn!( |
795 | | ?e, |
796 | | "Missing CAS inputs during prepare_action, returning FAILED_PRECONDITION" |
797 | | ); |
798 | | // The context names the digest; the |
799 | | // execute response turns it into the |
800 | | // PreconditionFailure detail Bazel |
801 | | // re-uploads and retries on. |
802 | | // Name the action's own digest function |
803 | | // in the context: the store only saw the |
804 | | // task context, which a spawned fetch can |
805 | | // lose. |
806 | 1 | let context = match e.context.clone() { |
807 | 1 | ErrorContext::MissingDigest { hash, size, .. } => { |
808 | 1 | ErrorContext::MissingDigest { |
809 | 1 | hash, |
810 | 1 | size, |
811 | 1 | digest_function: digest_hasher |
812 | 1 | .resource_name_segment() |
813 | 1 | .map(str::to_string), |
814 | 1 | } |
815 | | } |
816 | 0 | other @ ErrorContext::None => other, |
817 | | }; |
818 | 1 | let action_result = ActionResult { |
819 | 1 | error: Some( |
820 | 1 | make_err!( |
821 | 1 | Code::FailedPrecondition, |
822 | 1 | "{}", |
823 | 1 | e.message_string() |
824 | 1 | ) |
825 | 1 | .with_context(context), |
826 | 1 | ), |
827 | 1 | ..ActionResult::default() |
828 | 1 | }; |
829 | 1 | let action_stage = ActionStage::Completed(action_result); |
830 | 1 | grpc_client.execution_response(ExecuteResult{ |
831 | 1 | instance_name, |
832 | 1 | operation_id, |
833 | 1 | result: Some(execute_result::Result::ExecuteResponse(action_stage.into())), |
834 | 1 | resource_usage: None, |
835 | 1 | }).await.err_tip0 (|| "Error calling execution_response with missing inputs")?0 ; |
836 | | } else { |
837 | 260 | grpc_client.execution_response(ExecuteResult{ |
838 | 260 | instance_name, |
839 | 260 | operation_id, |
840 | 260 | result: Some(execute_result::Result::InternalError(e.into())), |
841 | 260 | resource_usage: None, |
842 | 260 | }).await.err_tip258 (|| "Error calling execution_response with error")?0 ; |
843 | | } |
844 | | }, |
845 | | } |
846 | 12.5k | Ok(()) |
847 | 25.1k | } |
848 | | }; |
849 | | |
850 | 13.1k | let add_future_channel = add_future_channel.clone(); |
851 | | |
852 | | // Boxed so the launch closure captures one |
853 | | // erased type, not the whole action future, and |
854 | | // the compiler's Send check does not overflow. |
855 | 13.1k | let start_action_fut: BoxFuture<'static, Result<FinishedActionResult, Error>> = |
856 | 13.1k | start_action_fut.boxed(); |
857 | 13.1k | let launch = { |
858 | 13.1k | let span = info_span!( |
859 | | "worker_start_action_ctx", |
860 | | operation_id = operation_id_to_log, |
861 | 251 | digest_function = %digest_hasher.to_string(), |
862 | | ); |
863 | 13.1k | move || { |
864 | 13.1k | span.in_scope(|| { |
865 | 13.1k | let _guard = Context::current_with_value(digest_hasher) |
866 | 13.1k | .attach(); |
867 | 13.1k | spawn!("worker_start_action", start_action_fut) |
868 | 13.1k | }) |
869 | 13.1k | } |
870 | | }; |
871 | | |
872 | 13.1k | let actions_in_flight = actions_in_flight.clone(); |
873 | 13.1k | let actions_notify = actions_notify.clone(); |
874 | 13.1k | let actions_in_flight_fail = actions_in_flight.clone(); |
875 | 13.1k | let actions_notify_fail = actions_notify.clone(); |
876 | 13.1k | let running_operations_done = running_operations.clone(); |
877 | 13.1k | let running_operations_fail = running_operations.clone(); |
878 | 13.1k | let tracked_done = tracked_operation_id.clone(); |
879 | 13.1k | let tracked_fail = tracked_operation_id.clone(); |
880 | | // Counted from the dispatch, so the next one is |
881 | | // admitted against this slot while the |
882 | | // acknowledgement is still on its way. |
883 | 13.1k | actions_in_flight.fetch_add(1, Ordering::Release); |
884 | 13.1k | running_operations.lock().insert(tracked_operation_id); |
885 | | |
886 | 13.1k | futures.push( |
887 | 13.1k | async move { |
888 | 13.1k | if let Some(acknowledgement13.1k ) = acknowledgement { |
889 | 13.1k | acknowledgement.await?1 ; |
890 | 9 | } |
891 | 13.1k | if let Some(accepted_action4 ) = spent_mark { |
892 | 4 | accepted_action.store(true, Ordering::Release); |
893 | 13.1k | } |
894 | 13.1k | launch().await.err_tip12.5k (|| "Failed to launch spawn") |
895 | 12.5k | } |
896 | 13.1k | .map(move |res| {12.5k |
897 | 12.5k | let res12.5k = res?1 ; |
898 | 12.5k | if let Err(err261 ) = &res { |
899 | 261 | error!(?err, "Error executing action"); |
900 | 12.3k | } |
901 | 12.5k | add_future_channel |
902 | 12.5k | .send(make_publish_future(res).then(move |res| {12.5k |
903 | 12.5k | running_operations_done.lock().remove(&tracked_done); |
904 | 12.5k | actions_in_flight.fetch_sub(1, Ordering::Release); |
905 | 12.5k | actions_notify.notify_one(); |
906 | 12.5k | core::future::ready(res) |
907 | 12.5k | }12.5k ).boxed()) |
908 | 12.5k | .map_err(|err| |
909 | 0 | Error::from_std_err(Code::Internal, &err).append("LocalWorker could not send future") |
910 | 0 | )?; |
911 | 12.5k | Ok(()) |
912 | 12.5k | }) |
913 | 13.1k | .or_else(move |err| {1 |
914 | | // If the make_publish_future is not run we still need to notify. |
915 | 1 | running_operations_fail.lock().remove(&tracked_fail); |
916 | 1 | actions_in_flight_fail.fetch_sub(1, Ordering::Release); |
917 | 1 | actions_notify_fail.notify_one(); |
918 | 1 | core::future::ready(Err(err)) |
919 | 1 | }) |
920 | 13.1k | .boxed() |
921 | | ); |
922 | | } |
923 | | } |
924 | 0 | }, |
925 | 52.7k | res12.5k = add_future_rx.next() => { |
926 | 12.5k | let fut = res.err_tip(|| "New future stream receives should never be closed")?0 ; |
927 | 12.5k | futures.push(fut); |
928 | | }, |
929 | 52.7k | res25.1k = futures.next() => res25.1k .err_tip25.1k (|| "Keep-alive should always pending. Likely unable to send data to scheduler")?0 ?5 , |
930 | 52.7k | complete_msg0 = shutdown_rx.recv().fuse() => { |
931 | 0 | warn!("Worker loop received shutdown signal. Shutting down worker...",); |
932 | 0 | let mut grpc_client = self.grpc_client.clone(); |
933 | 0 | let shutdown_guard = complete_msg.map_err(|e| |
934 | 0 | Error::from_std_err(Code::Internal, &e).append("Failed to receive shutdown message"))?; |
935 | 0 | let actions_in_flight = actions_in_flight.clone(); |
936 | 0 | let actions_notify = actions_notify.clone(); |
937 | 0 | let drain_on_shutdown = self.config.drain_on_shutdown; |
938 | | // The GoingAway messages below are bounded: a stalled |
939 | | // connection must not hold the pod past its grace |
940 | | // period. One that fails or misses is logged and the |
941 | | // shutdown goes on, the in-flight actions still drained; |
942 | | // the scheduler removes this worker when the stream |
943 | | // closes either way. |
944 | 0 | let going_away_deadline = self.going_away_deadline(); |
945 | 0 | let drain_deadline = if self.config.max_action_timeout_s == 0 { |
946 | 0 | DEFAULT_MAX_ACTION_TIMEOUT |
947 | | } else { |
948 | 0 | Duration::from_secs(self.config.max_action_timeout_s as u64) |
949 | | }; |
950 | 0 | let shutdown_future = async move { |
951 | | // Said first on a drain, so nothing new is dispatched |
952 | | // here while the running actions finish; the |
953 | | // scheduler removes this worker when the stream |
954 | | // closes. |
955 | 0 | let mut going_away_result = if drain_on_shutdown { |
956 | 0 | send_going_away(&mut grpc_client, true, going_away_deadline).await |
957 | | } else { |
958 | 0 | Ok(()) |
959 | | }; |
960 | | // Wait for in-flight operations to be fully completed, |
961 | | // for as long as one action is allowed to run. |
962 | 0 | let wait = async { |
963 | 0 | while actions_in_flight.load(Ordering::Acquire) > 0 { |
964 | 0 | actions_notify.notified().await; |
965 | | } |
966 | 0 | }; |
967 | 0 | if time::timeout(drain_deadline, wait).await.is_err() { |
968 | 0 | error!( |
969 | 0 | actions_in_flight = actions_in_flight.load(Ordering::Acquire), |
970 | | "Drain deadline passed with actions still in flight; shutting down anyway" |
971 | | ); |
972 | 0 | } |
973 | 0 | if !drain_on_shutdown { |
974 | | // Sending this message immediately evicts all jobs from |
975 | | // this worker, of which there should be none. |
976 | 0 | going_away_result = send_going_away(&mut grpc_client, false, going_away_deadline).await; |
977 | 0 | } |
978 | | // Allow shutdown to occur now. |
979 | 0 | drop(shutdown_guard); |
980 | 0 | going_away_result |
981 | 0 | }; |
982 | 0 | futures.push(shutdown_future.boxed()); |
983 | 0 | shutting_down = true; |
984 | | }, |
985 | | }; |
986 | | } |
987 | | // Unreachable. |
988 | 518 | } |
989 | | } |
990 | | |
991 | | type ConnectionFactory<T> = Box<dyn Fn() -> BoxFuture<'static, Result<T, Error>> + Send + Sync>; |
992 | | |
993 | | pub struct LocalWorker<T: WorkerApiClientTrait + 'static, U: RunningActionsManager> { |
994 | | config: Arc<LocalWorkerConfig>, |
995 | | running_actions_manager: Arc<U>, |
996 | | connection_factory: ConnectionFactory<T>, |
997 | | sleep_fn: Option<Box<dyn Fn(Duration) -> BoxFuture<'static, ()> + Send + Sync>>, |
998 | | jitter_fn: JitterFn, |
999 | | metrics: Arc<Metrics>, |
1000 | | registration: Arc<WorkerRegistration>, |
1001 | | } |
1002 | | |
1003 | | /// Whether the worker currently holds a registration with its scheduler. |
1004 | | /// A worker that has not registered, or lost its connection and is |
1005 | | /// reconnecting, cannot take work; as a health indicator this is what a |
1006 | | /// readiness probe reads. |
1007 | | #[derive(Debug)] |
1008 | | pub struct WorkerRegistration { |
1009 | | name: String, |
1010 | | registered: AtomicBool, |
1011 | | ever_registered: AtomicBool, |
1012 | | } |
1013 | | |
1014 | | impl WorkerRegistration { |
1015 | 1.28k | pub fn new(name: &str) -> Arc<Self> { |
1016 | 1.28k | Arc::new(Self { |
1017 | 1.28k | name: name.to_string(), |
1018 | 1.28k | registered: AtomicBool::new(false), |
1019 | 1.28k | ever_registered: AtomicBool::new(false), |
1020 | 1.28k | }) |
1021 | 1.28k | } |
1022 | | |
1023 | 6 | pub fn is_registered(&self) -> bool { |
1024 | 6 | self.registered.load(Ordering::Acquire) |
1025 | 6 | } |
1026 | | |
1027 | 2.29k | fn set_registered(&self, registered: bool) { |
1028 | 2.29k | self.registered.store(registered, Ordering::Release); |
1029 | 2.29k | if registered { |
1030 | 1.77k | self.ever_registered.store(true, Ordering::Release); |
1031 | 1.77k | }518 |
1032 | 2.29k | } |
1033 | | } |
1034 | | |
1035 | | #[async_trait] |
1036 | | impl HealthStatusIndicator for WorkerRegistration { |
1037 | 0 | fn get_name(&self) -> &'static str { |
1038 | 0 | "WorkerRegistration" |
1039 | 0 | } |
1040 | | |
1041 | 1 | async fn check_health(&self, _namespace: Cow<'static, str>) -> HealthStatus { |
1042 | | if self.is_registered() { |
1043 | | HealthStatus::Ok { |
1044 | | struct_name: "WorkerRegistration", |
1045 | | message: Cow::Owned(format!( |
1046 | | "worker '{}' registered with the scheduler", |
1047 | | self.name |
1048 | | )), |
1049 | | } |
1050 | | } else if self.ever_registered.load(Ordering::Acquire) { |
1051 | | // Lost after it was there: the worker is reconnecting, and until |
1052 | | // it does it holds no work. Initializing, not Failed: Failed |
1053 | | // turns the plain status check red too, and a liveness probe on |
1054 | | // it would restart every worker during a scheduler roll longer |
1055 | | // than its threshold, and redden a co-hosted CAS on one worker's |
1056 | | // blip. This belongs to readiness alone. |
1057 | | HealthStatus::Initializing { |
1058 | | struct_name: "WorkerRegistration", |
1059 | | message: Cow::Owned(format!( |
1060 | | "worker '{}' lost its scheduler connection, reconnecting", |
1061 | | self.name |
1062 | | )), |
1063 | | } |
1064 | | } else { |
1065 | | HealthStatus::Initializing { |
1066 | | struct_name: "WorkerRegistration", |
1067 | | message: Cow::Owned(format!( |
1068 | | "worker '{}' not yet registered with the scheduler", |
1069 | | self.name |
1070 | | )), |
1071 | | } |
1072 | | } |
1073 | 1 | } |
1074 | | } |
1075 | | |
1076 | | impl< |
1077 | | T: WorkerApiClientTrait + core::fmt::Debug + 'static, |
1078 | | U: RunningActionsManager + core::fmt::Debug, |
1079 | | > core::fmt::Debug for LocalWorker<T, U> |
1080 | | { |
1081 | 0 | fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { |
1082 | 0 | f.debug_struct("LocalWorker") |
1083 | 0 | .field("config", &self.config) |
1084 | 0 | .field("running_actions_manager", &self.running_actions_manager) |
1085 | 0 | .field("metrics", &self.metrics) |
1086 | 0 | .finish_non_exhaustive() |
1087 | 0 | } |
1088 | | } |
1089 | | |
1090 | | /// Creates a new `LocalWorker`. The `cas_store` must be an instance of |
1091 | | /// `FastSlowStore` and will be checked at runtime. |
1092 | 3 | pub async fn new_local_worker( |
1093 | 3 | config: Arc<LocalWorkerConfig>, |
1094 | 3 | cas_store: Store, |
1095 | 3 | ac_store: Option<Store>, |
1096 | 3 | historical_store: Store, |
1097 | 3 | ) -> Result<LocalWorker<WorkerApiClientWrapper, RunningActionsManagerImpl>, Error> { |
1098 | | #[cfg(not(target_os = "linux"))] |
1099 | | if config.experimental_buck2_file_capture.is_some() { |
1100 | | return Err(make_input_err!( |
1101 | | "Buck2 container file capture requires a Linux execution container" |
1102 | | )); |
1103 | | } |
1104 | 3 | let fast_slow_store2 = cas_store |
1105 | 3 | .downcast_ref::<FastSlowStore>(None) |
1106 | 3 | .err_tip(|| "Expected store for LocalWorker's store to be a FastSlowStore")?1 |
1107 | 2 | .get_arc() |
1108 | 2 | .err_tip(|| "FastSlowStore's Arc doesn't exist")?0 ; |
1109 | | |
1110 | | // Log warning about CAS configuration for multi-worker setups |
1111 | 2 | event!( |
1112 | 2 | Level::INFO, |
1113 | 2 | worker_name = %config.name, |
1114 | | "Starting worker '{}'. IMPORTANT: If running multiple workers, all workers \ |
1115 | | must share the same CAS storage path to avoid 'Object not found' errors.", |
1116 | 2 | config.name |
1117 | | ); |
1118 | | |
1119 | 2 | if let Ok(path1 ) = fs::canonicalize(&config.work_directory).await { |
1120 | 1 | fs::remove_dir_all(&path).await.err_tip(|| {0 |
1121 | 0 | format!( |
1122 | | "Could not remove work_directory '{}' in LocalWorker", |
1123 | 0 | path.as_path().to_str().unwrap_or("bad path") |
1124 | | ) |
1125 | 0 | })?; |
1126 | 1 | } |
1127 | | |
1128 | 2 | fs::create_dir_all(&config.work_directory) |
1129 | 2 | .await |
1130 | 2 | .err_tip(|| format!0 ("Could not make work_directory : {}", config.work_directory0 ))?0 ; |
1131 | 2 | let entrypoint = if config.entrypoint.is_empty() { |
1132 | 2 | None |
1133 | | } else { |
1134 | 0 | Some(config.entrypoint.clone()) |
1135 | | }; |
1136 | 2 | let max_action_timeout = if config.max_action_timeout_s == 0 { |
1137 | 2 | DEFAULT_MAX_ACTION_TIMEOUT |
1138 | | } else { |
1139 | 0 | Duration::from_secs(config.max_action_timeout_s as u64) |
1140 | | }; |
1141 | 2 | let max_upload_timeout = if config.max_upload_timeout_s == 0 { |
1142 | 2 | DEFAULT_MAX_UPLOAD_TIMEOUT |
1143 | | } else { |
1144 | 0 | Duration::from_secs(config.max_upload_timeout_s as u64) |
1145 | | }; |
1146 | 2 | let max_download_timeout = if config.max_download_timeout_s == 0 { |
1147 | 2 | DEFAULT_MAX_DOWNLOAD_TIMEOUT |
1148 | | } else { |
1149 | 0 | Duration::from_secs(config.max_download_timeout_s as u64) |
1150 | | }; |
1151 | 2 | let max_cleanup_wait = if config.max_cleanup_wait_s == 0 { |
1152 | 2 | DEFAULT_MAX_CLEANUP_WAIT |
1153 | | } else { |
1154 | 0 | Duration::from_secs(config.max_cleanup_wait_s as u64) |
1155 | | }; |
1156 | 2 | let max_cleanup_backoff = if config.max_cleanup_backoff_ms == 0 { |
1157 | 2 | DEFAULT_MAX_CLEANUP_BACKOFF |
1158 | | } else { |
1159 | 0 | Duration::from_millis(config.max_cleanup_backoff_ms as u64) |
1160 | | }; |
1161 | | |
1162 | | // Initialize directory cache if configured |
1163 | 2 | let directory_cache = if let Some(cache_config0 ) = &config.directory_cache { |
1164 | | use std::path::PathBuf; |
1165 | | |
1166 | | use crate::directory_cache::{ |
1167 | | DirectoryCache, DirectoryCacheConfig as WorkerDirCacheConfig, |
1168 | | }; |
1169 | | |
1170 | 0 | let cache_root = if cache_config.cache_root.is_empty() { |
1171 | 0 | PathBuf::from(&config.work_directory).parent().map_or_else( |
1172 | 0 | || PathBuf::from("/tmp/nativelink_directory_cache"), |
1173 | 0 | |p| p.join("directory_cache"), |
1174 | | ) |
1175 | | } else { |
1176 | 0 | PathBuf::from(&cache_config.cache_root) |
1177 | | }; |
1178 | | |
1179 | 0 | let worker_cache_config = WorkerDirCacheConfig { |
1180 | 0 | max_entries: cache_config.max_entries, |
1181 | 0 | max_size_bytes: cache_config.max_size_bytes, |
1182 | 0 | cache_root, |
1183 | 0 | experimental_subtree_caching: cache_config.experimental_subtree_caching, |
1184 | 0 | max_concurrent_fetches: cache_config.max_concurrent_fetches, |
1185 | 0 | experimental_get_tree_prefetch: cache_config.experimental_get_tree_prefetch, |
1186 | 0 | experimental_clone_executables: cache_config.experimental_clone_executables, |
1187 | 0 | }; |
1188 | | |
1189 | 0 | match DirectoryCache::new(worker_cache_config, fast_slow_store.clone()).await { |
1190 | 0 | Ok(cache) => { |
1191 | 0 | tracing::info!("Directory cache initialized successfully"); |
1192 | 0 | Some(Arc::new(cache)) |
1193 | | } |
1194 | 0 | Err(e) => { |
1195 | 0 | tracing::warn!("Failed to initialize directory cache: {:?}", e); |
1196 | 0 | None |
1197 | | } |
1198 | | } |
1199 | | } else { |
1200 | 2 | None |
1201 | | }; |
1202 | | |
1203 | | #[cfg(target_os = "linux")] |
1204 | 2 | let use_namespaces = { |
1205 | 2 | let use_mount_namespace = config.use_mount_namespace.unwrap_or_default(); |
1206 | | // The mount namespace only exists when `use_namespaces` is on too; |
1207 | | // `isolate_tmp` is judged against that, not against the flag alone, |
1208 | | // or an explicit `true` would be dropped without a word. |
1209 | 2 | let mount_namespace_on = config.use_namespaces == Some(true) && use_mount_namespace0 ; |
1210 | | // A private /tmp is part of the mount isolation unless explicitly |
1211 | | // turned off. A worker without a /tmp, such as a minimal container |
1212 | | // image, has nothing for actions to collide on, so the default is |
1213 | | // off there instead of failing to start. |
1214 | 2 | let isolate_tmp = config.isolate_tmp.unwrap_or_else(|| { |
1215 | 2 | let has_tmp = std::path::Path::new("/tmp").is_dir(); |
1216 | 2 | if mount_namespace_on && !has_tmp0 { |
1217 | 0 | warn!("/tmp does not exist on this worker, so actions will not get a private /tmp"); |
1218 | 2 | } |
1219 | 2 | mount_namespace_on && has_tmp0 |
1220 | 2 | }); |
1221 | 2 | if isolate_tmp && !mount_namespace_on0 { |
1222 | 0 | return Err(make_err!( |
1223 | 0 | Code::InvalidArgument, |
1224 | 0 | "isolate_tmp requires use_namespaces and use_mount_namespace to be true" |
1225 | 0 | )); |
1226 | 2 | } |
1227 | 2 | if let Some(use_namespaces0 ) = &config.use_namespaces { |
1228 | 0 | if *use_namespaces |
1229 | 0 | && !crate::namespace_utils::namespaces_supported(use_mount_namespace, isolate_tmp) |
1230 | | { |
1231 | 0 | return Err(make_err!(Code::Unavailable, "Namespaces not supported")); |
1232 | 0 | } |
1233 | | // Warns when it cannot; the action then sees the host's /proc. |
1234 | 0 | if *use_namespaces { |
1235 | 0 | crate::namespace_utils::fresh_proc_supported(); |
1236 | 0 | } |
1237 | 0 | if !*use_namespaces { |
1238 | 0 | crate::running_actions_manager::UseNamespaces::No |
1239 | 0 | } else if use_mount_namespace { |
1240 | 0 | crate::running_actions_manager::UseNamespaces::YesAndMount { isolate_tmp } |
1241 | | } else { |
1242 | 0 | crate::running_actions_manager::UseNamespaces::Yes |
1243 | | } |
1244 | 2 | } else if use_mount_namespace { |
1245 | 0 | return Err(make_err!( |
1246 | 0 | Code::Unavailable, |
1247 | 0 | "Mount namespaces not supported" |
1248 | 0 | )); |
1249 | | } else { |
1250 | 2 | crate::running_actions_manager::UseNamespaces::No |
1251 | | } |
1252 | | }; |
1253 | | |
1254 | | #[cfg(not(target_os = "linux"))] |
1255 | | if config.use_namespaces.is_some_and(core::convert::identity) { |
1256 | | return Err(make_err!( |
1257 | | Code::Unavailable, |
1258 | | "Namespaces not supported on non-Linux OSes" |
1259 | | )); |
1260 | | } |
1261 | | #[cfg(not(target_os = "linux"))] |
1262 | | if config |
1263 | | .use_mount_namespace |
1264 | | .is_some_and(core::convert::identity) |
1265 | | { |
1266 | | return Err(make_err!( |
1267 | | Code::Unavailable, |
1268 | | "Mount namespaces not supported on non-Linux OSes" |
1269 | | )); |
1270 | | } |
1271 | | #[cfg(not(target_os = "linux"))] |
1272 | | if config.isolate_tmp.is_some_and(core::convert::identity) { |
1273 | | return Err(make_err!( |
1274 | | Code::Unavailable, |
1275 | | "isolate_tmp is not supported on non-Linux OSes" |
1276 | | )); |
1277 | | } |
1278 | | |
1279 | | // A pooled worker process gets the same PID, user, UTS and IPC |
1280 | | // namespaces a one-shot action gets, never the mount namespace. |
1281 | | #[cfg(target_os = "linux")] |
1282 | 2 | let persistent_workers_namespaced = !matches!0 ( |
1283 | 2 | use_namespaces, |
1284 | | crate::running_actions_manager::UseNamespaces::No |
1285 | | ); |
1286 | | #[cfg(not(target_os = "linux"))] |
1287 | | let persistent_workers_namespaced = false; |
1288 | | |
1289 | | #[cfg(not(target_os = "linux"))] |
1290 | | if !config.experimental_readonly_input_mounts.is_empty() { |
1291 | | return Err(make_err!( |
1292 | | Code::Unavailable, |
1293 | | "Read-only input mounts not supported on non-Linux OSes" |
1294 | | )); |
1295 | | } |
1296 | | |
1297 | 2 | let running_actions_manager = |
1298 | 2 | Arc::new(RunningActionsManagerImpl::new(RunningActionsManagerArgs { |
1299 | 2 | root_action_directory: config.work_directory.clone(), |
1300 | | execution_configuration: ExecutionConfiguration { |
1301 | 2 | max_captured_output_bytes: config.max_captured_output_bytes, |
1302 | 2 | kill_grace: if config.kill_grace_ms == 0 { |
1303 | 2 | DEFAULT_KILL_GRACE |
1304 | | } else { |
1305 | 0 | Duration::from_millis(config.kill_grace_ms) |
1306 | | }, |
1307 | 2 | set_tmpdir: config.set_tmpdir, |
1308 | 2 | max_concurrent_input_downloads: config.max_concurrent_input_downloads, |
1309 | 2 | persistent_workers: persistent_worker_settings( |
1310 | 2 | config.persistent_workers.as_ref(), |
1311 | 2 | persistent_workers_namespaced, |
1312 | | ), |
1313 | 2 | buck2_file_capture: config.experimental_buck2_file_capture.clone(), |
1314 | 2 | entrypoint, |
1315 | 2 | additional_environment: config.additional_environment.clone(), |
1316 | 2 | resource_enforcement: config.resource_enforcement.as_ref().and_then( |
1317 | 0 | |enforcement| { |
1318 | 0 | let mut resource_enforcement = |
1319 | 0 | ResourceEnforcement::from_config(enforcement)?; |
1320 | 0 | if let Some(pressure_kill) = &mut resource_enforcement.pressure_kill { |
1321 | | pressure_kill.largest_reservation_kb = |
1322 | 0 | crate::capacity::advertised_memory_kb( |
1323 | 0 | config.capacity.as_ref(), |
1324 | 0 | config.capacity.as_ref().map_or(0, |capacity| { |
1325 | 0 | crate::capacity::memory_headroom_percent( |
1326 | 0 | capacity, |
1327 | 0 | Some(enforcement), |
1328 | | ) |
1329 | 0 | }), |
1330 | 0 | crate::capacity::observe_cgroup(), |
1331 | 0 | &config.platform_properties, |
1332 | 0 | &enforcement.memory_property_name, |
1333 | | ); |
1334 | 0 | } |
1335 | 0 | Some(resource_enforcement) |
1336 | 0 | }, |
1337 | | ), |
1338 | | }, |
1339 | 2 | cas_store: fast_slow_store, |
1340 | 2 | ac_store, |
1341 | 2 | historical_store, |
1342 | 2 | upload_action_result_config: &config.upload_action_result, |
1343 | 2 | max_action_timeout, |
1344 | 2 | max_upload_timeout, |
1345 | 2 | max_download_timeout, |
1346 | 2 | max_cleanup_wait, |
1347 | 2 | max_cleanup_backoff, |
1348 | 2 | timeout_handled_externally: config.timeout_handled_externally, |
1349 | 2 | directory_cache, |
1350 | 2 | active_input_leases: config.experimental_active_input_leases, |
1351 | | #[cfg(target_os = "linux")] |
1352 | 2 | readonly_input_mounts: config.experimental_readonly_input_mounts.clone(), |
1353 | | #[cfg(target_os = "linux")] |
1354 | 2 | use_namespaces, |
1355 | 0 | })?); |
1356 | | // What actions leave behind is reaped here; see `crate::reaper`. |
1357 | 2 | if let Err(err0 ) = crate::reaper::become_subreaper() { |
1358 | 0 | warn!( |
1359 | | ?err, |
1360 | | "Could not become the subreaper; orphans of actions will not be reaped here" |
1361 | | ); |
1362 | 2 | } |
1363 | 2 | drop(background_spawn!("orphan_reaper", async move {1 |
1364 | 1 | let mut seen_last = std::collections::BTreeSet::new(); |
1365 | | loop { |
1366 | 1 | time::sleep(crate::reaper::REAP_INTERVAL).await; |
1367 | | // The sweep reads /proc for every process; off the runtime. |
1368 | 0 | let (reaped, seen) = spawn_blocking!("orphan_reaper_sweep", move || { |
1369 | 0 | crate::reaper::reap_orphaned_zombies(&seen_last) |
1370 | 0 | }) |
1371 | 0 | .await |
1372 | 0 | .unwrap_or_default(); |
1373 | 0 | seen_last = seen; |
1374 | 0 | if reaped > 0 { |
1375 | 0 | info!(reaped, "Reaped zombies that actions left behind"); |
1376 | 0 | } |
1377 | | } |
1378 | | })); |
1379 | 2 | if config.orphan_sweep_interval_s > 0 { |
1380 | 0 | let interval = Duration::from_secs(config.orphan_sweep_interval_s); |
1381 | 0 | let manager = running_actions_manager.clone(); |
1382 | | // Detached on purpose: the guarded spawn aborts its task when the |
1383 | | // handle drops, and this one runs for the worker's whole life. |
1384 | 0 | drop(background_spawn!("orphan_sweep", async move { |
1385 | 0 | info!(interval_s = interval.as_secs(), "Orphan sweep scheduled"); |
1386 | | loop { |
1387 | 0 | time::sleep(interval).await; |
1388 | 0 | match manager.sweep_orphaned_directories().await { |
1389 | 0 | Ok(0) => debug!("Orphan sweep found nothing"), |
1390 | 0 | Ok(removed) => info!(removed, "Orphan sweep finished"), |
1391 | 0 | Err(err) => warn!(?err, "Orphan sweep failed"), |
1392 | | } |
1393 | | } |
1394 | | })); |
1395 | 2 | } |
1396 | 2 | let local_worker = LocalWorker::new_with_connection_factory_and_actions_manager( |
1397 | 2 | config.clone(), |
1398 | 2 | running_actions_manager, |
1399 | 2 | Box::new(move || {0 |
1400 | 0 | let config = config.clone(); |
1401 | 0 | Box::pin(async move { connect_to_scheduler(&config).await }) |
1402 | 0 | }), |
1403 | 2 | Box::new(move |d| Box::pin0 (time::sleep0 (d0 ))), |
1404 | | ); |
1405 | 2 | Ok(local_worker) |
1406 | 3 | } |
1407 | | |
1408 | | /// Connects to the scheduler's worker API the way every worker does: the |
1409 | | /// endpoint, TLS and keepalives from `worker_api_endpoint`. |
1410 | 0 | pub async fn connect_to_scheduler( |
1411 | 0 | config: &LocalWorkerConfig, |
1412 | 0 | ) -> Result<WorkerApiClientWrapper, Error> { |
1413 | 0 | let timeout = config |
1414 | 0 | .worker_api_endpoint |
1415 | 0 | .timeout |
1416 | 0 | .unwrap_or(DEFAULT_ENDPOINT_TIMEOUT_S); |
1417 | 0 | let timeout_duration = Duration::from_secs_f32(timeout); |
1418 | 0 | let tls_config = tls_utils::load_client_config(&config.worker_api_endpoint.tls_config) |
1419 | 0 | .err_tip(|| "Parsing local worker TLS configuration")?; |
1420 | 0 | let endpoint = tls_utils::endpoint_from(&config.worker_api_endpoint.uri, tls_config) |
1421 | 0 | .map_err(|e| { |
1422 | 0 | Error::from_std_err(Code::InvalidArgument, &e).append("Invalid URI for worker endpoint") |
1423 | 0 | })? |
1424 | 0 | .connect_timeout(timeout_duration) |
1425 | 0 | .timeout(timeout_duration) |
1426 | | // Probes under and between the messages, so a |
1427 | | // connection that has gone dead underneath fails |
1428 | | // here instead of hanging every message on it. |
1429 | 0 | .tcp_keepalive(Some(seconds_or( |
1430 | 0 | config.worker_api_endpoint.tcp_keepalive_s, |
1431 | 0 | DEFAULT_TCP_KEEPALIVE, |
1432 | 0 | ))) |
1433 | 0 | .http2_keep_alive_interval(seconds_or( |
1434 | 0 | config.worker_api_endpoint.http2_keepalive_interval_s, |
1435 | | DEFAULT_HTTP2_KEEPALIVE_INTERVAL, |
1436 | | )) |
1437 | 0 | .keep_alive_timeout(seconds_or( |
1438 | 0 | config.worker_api_endpoint.http2_keepalive_timeout_s, |
1439 | | DEFAULT_HTTP2_KEEPALIVE_TIMEOUT, |
1440 | | )) |
1441 | 0 | .keep_alive_while_idle(true); |
1442 | | |
1443 | 0 | let transport = endpoint.connect().await.map_err(|e| { |
1444 | 0 | Error::from_std_err(Code::Internal, &e).append(format!( |
1445 | | "Could not connect to endpoint {}", |
1446 | | config.worker_api_endpoint.uri |
1447 | | )) |
1448 | 0 | })?; |
1449 | 0 | Ok(WorkerApiClient::new(transport).into()) |
1450 | 0 | } |
1451 | | |
1452 | | impl<T: WorkerApiClientTrait + 'static, U: RunningActionsManager> LocalWorker<T, U> { |
1453 | 1.28k | pub fn new_with_connection_factory_and_actions_manager( |
1454 | 1.28k | config: Arc<LocalWorkerConfig>, |
1455 | 1.28k | running_actions_manager: Arc<U>, |
1456 | 1.28k | connection_factory: ConnectionFactory<T>, |
1457 | 1.28k | sleep_fn: Box<dyn Fn(Duration) -> BoxFuture<'static, ()> + Send + Sync>, |
1458 | 1.28k | ) -> Self { |
1459 | 1.28k | let metrics = Arc::new(Metrics::new(Arc::downgrade( |
1460 | 1.28k | running_actions_manager.metrics(), |
1461 | | ))); |
1462 | 1.28k | let registration = WorkerRegistration::new(&config.name); |
1463 | 1.28k | Self { |
1464 | 1.28k | config, |
1465 | 1.28k | running_actions_manager, |
1466 | 1.28k | connection_factory, |
1467 | 1.28k | sleep_fn: Some(sleep_fn), |
1468 | 1.28k | jitter_fn: Box::new(wall_clock_jitter), |
1469 | 1.28k | metrics, |
1470 | 1.28k | registration, |
1471 | 1.28k | } |
1472 | 1.28k | } |
1473 | | |
1474 | | /// Takes the reconnect jitter from `jitter_fn` instead of the wall |
1475 | | /// clock, for tests that need the same backoff every run. |
1476 | | #[must_use] |
1477 | 1.25k | pub fn with_jitter_fn(mut self, jitter_fn: JitterFn) -> Self { |
1478 | 1.25k | self.jitter_fn = jitter_fn; |
1479 | 1.25k | self |
1480 | 1.25k | } |
1481 | | |
1482 | | /// The registration flag this worker flips, for a health registry. |
1483 | 28 | pub fn registration(&self) -> Arc<WorkerRegistration> { |
1484 | 28 | self.registration.clone() |
1485 | 28 | } |
1486 | | |
1487 | | /// Flip a flag that was registered with a health registry before the |
1488 | | /// worker existed, as the server binary has to. |
1489 | | #[must_use] |
1490 | 0 | pub fn with_registration(mut self, registration: Arc<WorkerRegistration>) -> Self { |
1491 | 0 | self.registration = registration; |
1492 | 0 | self |
1493 | 0 | } |
1494 | | |
1495 | | #[allow( |
1496 | | clippy::missing_const_for_fn, |
1497 | | reason = "False positive on stable, but not on nightly" |
1498 | | )] |
1499 | 0 | pub fn name(&self) -> &String { |
1500 | 0 | &self.config.name |
1501 | 0 | } |
1502 | | |
1503 | 1.94k | async fn register_worker( |
1504 | 1.94k | &self, |
1505 | 1.94k | client: &mut T, |
1506 | 1.94k | ) -> Result<(String, bool, MemoryAdmission, Streaming<UpdateForWorker>), Error> { |
1507 | 1.94k | let mut extra_envs: HashMap<String, String> = HashMap::new(); |
1508 | 1.94k | if let Some(ref additional_environment0 ) = self.config.additional_environment { |
1509 | 0 | for (name, source) in additional_environment { |
1510 | 0 | let value = match source { |
1511 | 0 | EnvironmentSource::Value(value) => Cow::Borrowed(value.as_str()), |
1512 | | EnvironmentSource::FromEnvironment => { |
1513 | 0 | Cow::Owned(env::var(name).unwrap_or_default()) |
1514 | | } |
1515 | 0 | other => { |
1516 | 0 | debug!( |
1517 | | ?other, |
1518 | | "Worker registration doesn't support this type of additional environment" |
1519 | | ); |
1520 | 0 | continue; |
1521 | | } |
1522 | | }; |
1523 | 0 | extra_envs.insert(name.clone(), value.into_owned()); |
1524 | | } |
1525 | 1.94k | } |
1526 | | |
1527 | 1.94k | let mut platform_properties = self.config.platform_properties.clone(); |
1528 | 1.94k | if let Some(capacity0 ) = &self.config.capacity { |
1529 | 0 | let memory_headroom_percent = crate::capacity::memory_headroom_percent( |
1530 | 0 | capacity, |
1531 | 0 | self.config.resource_enforcement.as_ref(), |
1532 | | ); |
1533 | 0 | crate::capacity::apply(capacity, memory_headroom_percent, &mut platform_properties) |
1534 | 0 | .err_tip(|| "Advertising capacity from the cgroup")?; |
1535 | 1.94k | } |
1536 | | // Decided once, so what admission does and what the scheduler is |
1537 | | // told always agree. |
1538 | 1.94k | let admits_when_idle = crate::capacity::memory_is_limited(); |
1539 | 1.94k | let connect_worker_request = make_connect_worker_request( |
1540 | 1.94k | self.config.name.clone(), |
1541 | 1.94k | &platform_properties, |
1542 | 1.94k | &extra_envs, |
1543 | 1.94k | if self.config.single_use { |
1544 | 5 | 1 |
1545 | | } else { |
1546 | 1.93k | self.config.max_inflight_tasks |
1547 | | }, |
1548 | 1.94k | admits_when_idle, |
1549 | | ) |
1550 | 1.94k | .await?0 ; |
1551 | 1.94k | let mut update_for_worker_stream1.93k = client |
1552 | 1.94k | .connect_worker(connect_worker_request) |
1553 | 1.94k | .await |
1554 | 1.93k | .err_tip(|| "Could not call connect_worker() in worker")?0 |
1555 | 1.93k | .into_inner(); |
1556 | | |
1557 | 1.93k | let first_msg_update1.77k = update_for_worker_stream |
1558 | 1.93k | .next() |
1559 | 1.93k | .await |
1560 | 1.93k | .err_tip(|| "Got EOF expected UpdateForWorker")?158 |
1561 | 1.77k | .err_tip(|| "Got error when receiving UpdateForWorker")?0 |
1562 | | .update; |
1563 | | |
1564 | 1.77k | let (worker_id, dispatch_ack, memory_property) = match first_msg_update { |
1565 | 1.77k | Some(Update::ConnectionResult(connection_result)) => ( |
1566 | 1.77k | connection_result.worker_id, |
1567 | 1.77k | connection_result.dispatch_ack, |
1568 | 1.77k | connection_result.memory_property, |
1569 | 1.77k | ), |
1570 | 0 | other => { |
1571 | 0 | return Err(make_input_err!( |
1572 | 0 | "Expected first response from scheduler to be a ConnectionResult got : {:?}", |
1573 | 0 | other |
1574 | 0 | )); |
1575 | | } |
1576 | | }; |
1577 | 1.77k | Ok(( |
1578 | 1.77k | worker_id, |
1579 | 1.77k | dispatch_ack, |
1580 | 1.77k | MemoryAdmission { |
1581 | 1.77k | property: memory_property, |
1582 | 1.77k | admits_when_idle, |
1583 | 1.77k | }, |
1584 | 1.77k | update_for_worker_stream, |
1585 | 1.77k | )) |
1586 | 1.93k | } |
1587 | | |
1588 | | #[instrument(skip(self), level = Level::INFO)] |
1589 | 1.28k | pub async fn run( |
1590 | 1.28k | mut self, |
1591 | 1.28k | mut shutdown_rx: broadcast::Receiver<ShutdownGuard>, |
1592 | 1.28k | ) -> Result<(), Error> { |
1593 | | // Belt-and-suspenders QoS bump: the main binary already calls |
1594 | | // this before runtime creation so the tokio worker threads |
1595 | | // inherit P-core preference via pthread QoS inheritance, but |
1596 | | // any thread that reaches this point should also be tagged in |
1597 | | // case it was spawned by a path that bypassed `on_thread_start`. |
1598 | | // No-op on non-macOS. |
1599 | | let _ = crate::qos::set_user_initiated(); |
1600 | | |
1601 | | let sleep_fn = self |
1602 | | .sleep_fn |
1603 | | .take() |
1604 | | .err_tip(|| "Could not unwrap sleep_fn in LocalWorker::run")?; |
1605 | | let sleep_fn_pin = Pin::new(&sleep_fn); |
1606 | | let attempts = AtomicU32::new(0); |
1607 | | let attempts_ref = &attempts; |
1608 | | let jitter_fn = &self.jitter_fn; |
1609 | | let registration = &self.registration; |
1610 | 681 | let error_handler = Box::pin(move |err, failure: &'static str| async move { |
1611 | 681 | let attempt = attempts_ref.fetch_add(1, Ordering::AcqRel); |
1612 | 681 | let delay = reconnect_delay(attempt, jitter_fn()); |
1613 | | // A worker that comes up before its scheduler is reachable is |
1614 | | // normal (e.g. pods starting together in Kubernetes), so those |
1615 | | // startup misses are warnings. Once the worker has registered, |
1616 | | // losing the scheduler is an error. |
1617 | 681 | if registration.ever_registered.load(Ordering::Acquire) { |
1618 | 677 | error!( |
1619 | | ?err, |
1620 | | attempt, |
1621 | 31 | delay_ms = delay.as_millis(), |
1622 | | failure, |
1623 | | "Scheduler connection attempt failed, retrying" |
1624 | | ); |
1625 | | } else { |
1626 | 4 | warn!( |
1627 | | ?err, |
1628 | | attempt, |
1629 | 4 | delay_ms = delay.as_millis(), |
1630 | | failure, |
1631 | | "Scheduler connection attempt failed, retrying" |
1632 | | ); |
1633 | | } |
1634 | 681 | (sleep_fn_pin)(delay).await; |
1635 | 1.35k | }); |
1636 | | |
1637 | | loop { |
1638 | | // First connect to our endpoint. |
1639 | | let mut client = match (self.connection_factory)().await { |
1640 | | Ok(client) => client, |
1641 | | Err(e) => { |
1642 | | (error_handler)(e, "connect").await; |
1643 | | continue; // Try to connect again. |
1644 | | } |
1645 | | }; |
1646 | | |
1647 | | debug!("Connected to endpoint"); |
1648 | | |
1649 | | // Next register our worker with the scheduler. |
1650 | | let (inner, update_for_worker_stream) = match self.register_worker(&mut client).await { |
1651 | | Err(e) => { |
1652 | | (error_handler)(e, "register").await; |
1653 | | continue; // Try to connect again. |
1654 | | } |
1655 | | Ok((worker_id, dispatch_ack, memory, update_for_worker_stream)) => ( |
1656 | | LocalWorkerImpl::new( |
1657 | | &self.config, |
1658 | | client, |
1659 | | worker_id, |
1660 | | dispatch_ack, |
1661 | | memory, |
1662 | | self.running_actions_manager.clone(), |
1663 | | self.metrics.clone(), |
1664 | | ), |
1665 | | update_for_worker_stream, |
1666 | | ), |
1667 | | }; |
1668 | | info!( |
1669 | | worker_id = %inner.worker_id, |
1670 | | "Worker registered with scheduler" |
1671 | | ); |
1672 | | attempts.store(0, Ordering::Release); |
1673 | | self.registration.set_registered(true); |
1674 | | |
1675 | | // Now listen for connections and run all other services. |
1676 | | let run_result = inner.run(update_for_worker_stream, &mut shutdown_rx).await; |
1677 | | self.registration.set_registered(false); |
1678 | | if let Err(err) = run_result { |
1679 | | // Give in-transit actions a chance to settle before we kill |
1680 | | // them, so their results still reach the scheduler. |
1681 | | const ITERATIONS: usize = 1_000; |
1682 | | |
1683 | | let sleep_duration = ACTIONS_IN_TRANSIT_TIMEOUT_S / ITERATIONS as f32; |
1684 | | let mut drained = false; |
1685 | | for _ in 0..ITERATIONS { |
1686 | | if inner.actions_in_transit.load(Ordering::Acquire) == 0 { |
1687 | | drained = true; |
1688 | | break; |
1689 | | } |
1690 | | (sleep_fn_pin)(Duration::from_secs_f32(sleep_duration)).await; |
1691 | | } |
1692 | | if !drained { |
1693 | | // Deliberately not fatal. Returning here propagates out of |
1694 | | // the worker's main loop and aborts the process, so a |
1695 | | // scheduler blip that happened to catch an action in |
1696 | | // transit took the whole worker down — and every action it |
1697 | | // held then had to run again elsewhere. At fleet scale that |
1698 | | // is a restart storm. kill_all() below discards these |
1699 | | // actions anyway, so the wait is a courtesy and overrunning |
1700 | | // it costs nothing beyond the actions we were already |
1701 | | // giving up on. |
1702 | | error!( |
1703 | | actions_in_transit = inner.actions_in_transit.load(Ordering::Acquire), |
1704 | | "Actions in transit did not reach zero before we disconnected from the scheduler" |
1705 | | ); |
1706 | | } |
1707 | | |
1708 | | // Kill off any existing actions because if we re-connect, we'll |
1709 | | // get some more and it might resource lock us. |
1710 | | self.running_actions_manager.kill_all().await; |
1711 | | |
1712 | | if self.config.single_use && inner.accepted_action.load(Ordering::Acquire) { |
1713 | | return Err( |
1714 | | err.append("Single-use worker disconnected after accepting its action") |
1715 | | ); |
1716 | | } |
1717 | | error!(?err, "Worker disconnected from scheduler, reconnecting"); |
1718 | | (error_handler)(err, "disconnect").await; // Try to connect again. |
1719 | | } else if self.config.single_use { |
1720 | | return Ok(()); |
1721 | | } |
1722 | | } |
1723 | | // Unreachable. |
1724 | 2 | } |
1725 | | } |
1726 | | |
1727 | | #[derive(Debug, MetricsComponent)] |
1728 | | pub struct Metrics { |
1729 | | #[metric( |
1730 | | help = "Total number of actions sent to this worker to process. This does not mean it started them, it just means it received a request to execute it." |
1731 | | )] |
1732 | | start_actions_received: CounterWithTime, |
1733 | | #[metric(help = "Total number of disconnects received from the scheduler.")] |
1734 | | disconnects_received: CounterWithTime, |
1735 | | #[metric( |
1736 | | help = "Dispatches this worker declined: at capacity, short of memory, or shutting down." |
1737 | | )] |
1738 | | actions_declined: CounterWithTime, |
1739 | | #[metric(help = "Total number of keep-alives received from the scheduler.")] |
1740 | | keep_alives_received: CounterWithTime, |
1741 | | #[metric( |
1742 | | help = "Stats about the calls to check if an action satisfies the config supplied script." |
1743 | | )] |
1744 | | preconditions: AsyncCounterWrapper, |
1745 | | #[metric] |
1746 | | #[allow( |
1747 | | clippy::struct_field_names, |
1748 | | reason = "TODO Fix this. Triggers on nightly" |
1749 | | )] |
1750 | | running_actions_manager_metrics: Weak<RunningActionManagerMetrics>, |
1751 | | } |
1752 | | |
1753 | | impl RootMetricsComponent for Metrics {} |
1754 | | |
1755 | | impl Metrics { |
1756 | 1.28k | fn new(running_actions_manager_metrics: Weak<RunningActionManagerMetrics>) -> Self { |
1757 | 1.28k | Self { |
1758 | 1.28k | start_actions_received: CounterWithTime::default(), |
1759 | 1.28k | disconnects_received: CounterWithTime::default(), |
1760 | 1.28k | actions_declined: CounterWithTime::default(), |
1761 | 1.28k | keep_alives_received: CounterWithTime::default(), |
1762 | 1.28k | preconditions: AsyncCounterWrapper::default(), |
1763 | 1.28k | running_actions_manager_metrics, |
1764 | 1.28k | } |
1765 | 1.28k | } |
1766 | | } |
1767 | | |
1768 | | impl Metrics { |
1769 | 13.1k | async fn wrap<U, T: Future<Output = U>, F: FnOnce(Arc<Self>) -> T>( |
1770 | 13.1k | self: Arc<Self>, |
1771 | 13.1k | fut: F, |
1772 | 13.1k | ) -> U {13.1k |
1773 | 13.1k | fut(self).await |
1774 | 12.5k | } |
1775 | | } |
1776 | | |
1777 | | /// The pool settings from the worker config, defaults for what it leaves at |
1778 | | /// zero or unset. |
1779 | 2 | fn persistent_worker_settings( |
1780 | 2 | config: Option<&nativelink_config::cas_server::PersistentWorkersConfig>, |
1781 | 2 | namespaced: bool, |
1782 | 2 | ) -> crate::running_actions_manager::PersistentWorkersSettings { |
1783 | | use crate::persistent_worker::PoolConfig; |
1784 | 2 | let defaults = PoolConfig::default(); |
1785 | 2 | let pool = config.map_or(defaults, |c| {0 |
1786 | 0 | let or_default = |value: u64, default: u64| if value == 0 { default } else { value }; |
1787 | | PoolConfig { |
1788 | 0 | max_workers_per_key: if c.max_workers_per_key == 0 { |
1789 | 0 | defaults.max_workers_per_key |
1790 | | } else { |
1791 | 0 | c.max_workers_per_key |
1792 | | }, |
1793 | 0 | idle_timeout: Duration::from_secs(or_default( |
1794 | 0 | c.idle_timeout_s, |
1795 | 0 | defaults.idle_timeout.as_secs(), |
1796 | 0 | )), |
1797 | 0 | max_requests_per_worker: or_default( |
1798 | 0 | c.max_requests_per_worker, |
1799 | 0 | defaults.max_requests_per_worker, |
1800 | 0 | ), |
1801 | 0 | shutdown_grace: Duration::from_millis(or_default( |
1802 | 0 | c.shutdown_grace_ms, |
1803 | 0 | u64::try_from(defaults.shutdown_grace.as_millis()).unwrap_or(5000), |
1804 | 0 | )), |
1805 | 0 | acquire_timeout: Duration::from_secs(or_default( |
1806 | 0 | c.acquire_timeout_s, |
1807 | 0 | defaults.acquire_timeout.as_secs(), |
1808 | 0 | )), |
1809 | 0 | namespaced, |
1810 | | } |
1811 | 0 | }); |
1812 | | crate::running_actions_manager::PersistentWorkersSettings { |
1813 | 2 | enabled: config.is_none_or(|c| c.enabled), |
1814 | 2 | pool: PoolConfig { namespaced, ..pool }, |
1815 | | } |
1816 | 2 | } |