/build/source/nativelink-scheduler/src/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::{Hash, Hasher}; |
16 | | use std::collections::{HashMap, HashSet, VecDeque}; |
17 | | use std::sync::Arc; |
18 | | use std::time::{SystemTime, UNIX_EPOCH}; |
19 | | |
20 | | use nativelink_error::{Code, Error, ResultExt}; |
21 | | use nativelink_metric::MetricsComponent; |
22 | | use nativelink_proto::com::github::trace_machina::nativelink::remote_execution::{ |
23 | | ActionResourceUsage, ConnectionResult, ExecuteResultAccepted, KillOperationRequest, |
24 | | StartExecute, UpdateForWorker, WorkerLoad, update_for_worker, |
25 | | }; |
26 | | use nativelink_util::action_messages::{ActionInfo, OperationId, WorkerId}; |
27 | | use nativelink_util::metrics_utils::{AsyncCounterWrapper, CounterWithTime, FuncCounterWrapper}; |
28 | | use nativelink_util::origin_event::OriginMetadata; |
29 | | use nativelink_util::platform_properties::{PlatformProperties, PlatformPropertyValue}; |
30 | | use tokio::sync::mpsc::Sender; |
31 | | use tokio::sync::mpsc::error::TrySendError; |
32 | | |
33 | | pub type WorkerTimestamp = u64; |
34 | | |
35 | | /// Represents the action info and the platform properties of the action. |
36 | | /// These platform properties have the type of the properties as well as |
37 | | /// the value of the properties, unlike `ActionInfo`, which only has the |
38 | | /// string value of the properties. |
39 | | #[derive(Clone, Debug, MetricsComponent)] |
40 | | pub struct ActionInfoWithProps { |
41 | | /// The action info of the action. |
42 | | #[metric(group = "action_info")] |
43 | | pub inner: Arc<ActionInfo>, |
44 | | /// The platform properties of the action. |
45 | | #[metric(group = "platform_properties")] |
46 | | pub platform_properties: PlatformProperties, |
47 | | /// Origin metadata used when publishing scheduler-side telemetry for this action. |
48 | | pub origin_metadata: OriginMetadata, |
49 | | /// `OriginEvent` id for the `scheduler_start_execute` request. |
50 | | pub scheduler_start_execute_event_id: Option<String>, |
51 | | } |
52 | | |
53 | | /// Notifications to send worker about a requested state change. |
54 | | #[derive(Debug)] |
55 | | pub enum WorkerUpdate { |
56 | | /// Requests that the worker begin executing this action, dispatched at |
57 | | /// this scheduler time. |
58 | | RunAction(Box<(OperationId, ActionInfoWithProps, WorkerTimestamp)>), |
59 | | |
60 | | /// Request that the worker is no longer in the pool and may discard any jobs. |
61 | | Disconnect, |
62 | | |
63 | | /// Requests that the worker stop executing this operation. |
64 | | KillOperation(OperationId), |
65 | | |
66 | | /// Tells the worker its result for this operation is settled. |
67 | | ResultAccepted(OperationId), |
68 | | } |
69 | | |
70 | | /// Who chose a worker's id. |
71 | | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
72 | | pub enum WorkerIdChosenBy { |
73 | | /// The scheduler, on each connection: an older worker. |
74 | | Scheduler, |
75 | | /// The worker, once for its process. It knows `ExecuteResultAccepted`. |
76 | | Worker, |
77 | | } |
78 | | |
79 | | #[derive(Debug, MetricsComponent)] |
80 | | pub struct PendingActionInfoData { |
81 | | #[metric] |
82 | | pub action_info: ActionInfoWithProps, |
83 | | /// When the worker was told to kill this operation, recorded as the |
84 | | /// worker's last-seen timestamp at send time; keepalives keep that |
85 | | /// within the worker timeout of now, so a deadline computed from it |
86 | | /// fires at most one worker timeout late, never early. `None` until a |
87 | | /// kill is sent. The operation's later report then only settles the |
88 | | /// worker's own bookkeeping. |
89 | | #[metric(help = "When the worker was asked to kill this operation.")] |
90 | | pub kill_requested_at: Option<WorkerTimestamp>, |
91 | | /// The worker's last-seen timestamp when the dispatch was sent. |
92 | | #[metric(help = "When this operation was dispatched to the worker.")] |
93 | | pub dispatched_at: WorkerTimestamp, |
94 | | /// The worker said it took the action. A worker that does not speak |
95 | | /// the acknowledgement never sets this, which is why the |
96 | | /// unacknowledged sweep is opt-in. |
97 | | #[metric(help = "Whether the worker acknowledged the dispatch.")] |
98 | | pub accepted: bool, |
99 | | /// The last resource usage the worker reported for this operation; it |
100 | | /// arrives just before the result and says whether the result is a kill. |
101 | | pub last_usage: Option<ActionResourceUsage>, |
102 | | /// Keepalive reports in a row that left this operation out. Counted only |
103 | | /// once the worker acknowledged the dispatch; a report that names the |
104 | | /// operation resets it. |
105 | | #[metric(help = "Consecutive keepalive reports that left this operation out.")] |
106 | | pub missed_reports: u32, |
107 | | /// The most memory the worker's keepalives have reported for this |
108 | | /// operation, in KiB; 0 until one does. Read when the worker is lost, |
109 | | /// to tell which of its actions grew past its reservation (RFC-0018). |
110 | | #[metric(help = "The highest memory the worker reported for this operation, in KiB.")] |
111 | | pub reported_peak_memory_kb: u64, |
112 | | } |
113 | | |
114 | | /// How many keepalive reports in a row may leave an acknowledged operation |
115 | | /// out before the worker is taken to have dropped it. One miss is a report |
116 | | /// sent while the dispatch was still landing; two is a worker that ran the |
117 | | /// action and whose result never arrived. |
118 | | pub const LOST_AFTER_MISSED_REPORTS: u32 = 2; |
119 | | |
120 | | /// What the outcome tripwire has done with a worker. |
121 | | #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] |
122 | | pub enum TripwireState { |
123 | | /// Nothing, or an operator lifted its drain since. |
124 | | #[default] |
125 | | Clear, |
126 | | /// It would have drained the worker, but as many workers were already |
127 | | /// drained as it may drain at once; logged once. |
128 | | Held, |
129 | | /// It drained the worker. |
130 | | Tripped, |
131 | | } |
132 | | |
133 | | /// Represents a connection to a worker and used as the medium to |
134 | | /// interact with the worker from the client/scheduler. |
135 | | #[derive(Debug, MetricsComponent)] |
136 | | pub struct Worker { |
137 | | /// Unique identifier of the worker. |
138 | | #[metric(help = "The unique identifier of the worker.")] |
139 | | pub id: WorkerId, |
140 | | |
141 | | /// Properties that describe the capabilities of this worker. |
142 | | #[metric(group = "platform_properties")] |
143 | | pub platform_properties: PlatformProperties, |
144 | | |
145 | | /// The properties the worker registered with. `platform_properties` is |
146 | | /// reduced while actions run; this is what the worker offers when idle. |
147 | | pub total_platform_properties: PlatformProperties, |
148 | | |
149 | | /// Channel to send commands from scheduler to worker. |
150 | | pub tx: Sender<UpdateForWorker>, |
151 | | |
152 | | /// The action info of the running actions on the worker. |
153 | | #[metric(group = "running_action_infos")] |
154 | | pub running_action_infos: HashMap<OperationId, PendingActionInfoData>, |
155 | | |
156 | | /// Timestamp of last time this worker had been communicated with. |
157 | | // Warning: Do not update this timestamp without updating the placement of the worker in |
158 | | // the LRUCache in the Workers struct. |
159 | | #[metric(help = "Last time this worker was communicated with.")] |
160 | | pub last_update_timestamp: WorkerTimestamp, |
161 | | |
162 | | /// Whether the worker rejected the last action due to back pressure. |
163 | | #[metric(help = "If the worker is paused.")] |
164 | | pub is_paused: bool, |
165 | | |
166 | | /// Set when the pause came from a decline for load: it lifts only on a |
167 | | /// keepalive whose free memory covers this much, not on any keepalive. |
168 | | #[metric(help = "Free memory in KiB the worker must report before it is unpaused.")] |
169 | | pub pause_needs_kb: Option<u64>, |
170 | | |
171 | | /// The worker said on connection that it admits any action while it |
172 | | /// holds nothing else, so a decline for load from it comes from a busy |
173 | | /// worker even when this scheduler thinks it idle. |
174 | | pub admits_when_idle: bool, |
175 | | |
176 | | /// Which of this worker id's connections the entry belongs to. A worker |
177 | | /// that names itself keeps its id across reconnects, so the end of an |
178 | | /// earlier connection must not remove the entry a later one made. |
179 | | pub connection: u64, |
180 | | |
181 | | /// Who chose the worker's id, which tells what the worker understands. |
182 | | pub id_chosen_by: WorkerIdChosenBy, |
183 | | |
184 | | /// The smallest reservation this worker declined for load while it held |
185 | | /// nothing else, from a worker that does not admit when idle (an older |
186 | | /// one, or one with no cgroup limit). It is not offered that much or |
187 | | /// more until a keepalive reports that much free. |
188 | | #[metric(help = "Smallest reservation in KiB the worker declined while idle.")] |
189 | | pub idle_declined_kb: Option<u64>, |
190 | | |
191 | | /// Whether the worker is draining. |
192 | | #[metric(help = "If the worker is draining.")] |
193 | | pub is_draining: bool, |
194 | | |
195 | | /// How the worker's recent attempts ended, oldest first, `true` for a |
196 | | /// failure (a command or input fetch timeout, a worker error); a result |
197 | | /// of any exit code is a success. Bounded by the outcome tripwire's |
198 | | /// window; empty when there is no tripwire. |
199 | | pub recent_outcomes: VecDeque<bool>, |
200 | | |
201 | | /// What the outcome tripwire has done with this worker. |
202 | | pub tripwire: TripwireState, |
203 | | |
204 | | /// Maximum inflight tasks for this worker (or 0 for unlimited) |
205 | | #[metric(help = "Maximum inflight tasks for this worker (or 0 for unlimited)")] |
206 | | pub max_inflight_tasks: u64, |
207 | | |
208 | | /// What the worker last reported having to spare, from its keepalive; |
209 | | /// `None` until it reports, and for workers that never do. |
210 | | pub last_load: Option<WorkerLoad>, |
211 | | |
212 | | /// Stats about the worker. |
213 | | #[metric] |
214 | | metrics: Arc<Metrics>, |
215 | | } |
216 | | |
217 | | /// Messages the channel holds beyond the worker's own concurrency: kills, |
218 | | /// keepalives and the disconnect, which arrive alongside the dispatches. |
219 | | const CHANNEL_HEADROOM: usize = 16; |
220 | | /// A worker that set no `max_inflight_tasks` gets this much queue. |
221 | | const DEFAULT_CHANNEL_DISPATCHES: usize = 256; |
222 | | |
223 | | /// How many messages the worker's channel holds: what its concurrency |
224 | | /// allows in flight plus the headroom. Bounded so that a worker that has |
225 | | /// stopped reading cannot be handed work without limit; a full channel is |
226 | | /// `ResourceExhausted` on the send, and the caller requeues. |
227 | 0 | pub fn channel_capacity(max_inflight_tasks: u64) -> usize { |
228 | 0 | let ceiling = DEFAULT_CHANNEL_DISPATCHES * 4; |
229 | 0 | let dispatches = match usize::try_from(max_inflight_tasks) { |
230 | 0 | Ok(0) => DEFAULT_CHANNEL_DISPATCHES, |
231 | 0 | Ok(n) if n <= ceiling => n, |
232 | 0 | _ => ceiling, |
233 | | }; |
234 | 0 | dispatches + CHANNEL_HEADROOM |
235 | 0 | } |
236 | | |
237 | 18.9k | fn send_msg_to_worker( |
238 | 18.9k | tx: &Sender<UpdateForWorker>, |
239 | 18.9k | msg: update_for_worker::Update, |
240 | 18.9k | ) -> Result<(), Error> { |
241 | 18.9k | match tx.try_send(UpdateForWorker { update: Some(msg) }) { |
242 | 17.7k | Ok(()) => Ok(()), |
243 | 2 | Err(TrySendError::Full(_)) => Err(Error::new( |
244 | 2 | Code::ResourceExhausted, |
245 | 2 | "Worker channel full".to_string(), |
246 | 2 | )), |
247 | 1.18k | Err(err @ TrySendError::Closed(_)) => { |
248 | 1.18k | Err(Error::from_std_err(Code::Internal, &err).append("Worker disconnected")) |
249 | | } |
250 | | } |
251 | 18.9k | } |
252 | | |
253 | | /// Reduces the platform properties available on the worker based on the platform properties provided. |
254 | | /// This is used because we allow more than 1 job to run on a worker at a time, and this is how the |
255 | | /// scheduler knows if more jobs can run on a given worker. |
256 | 15.1k | fn reduce_platform_properties( |
257 | 15.1k | parent_props: &mut PlatformProperties, |
258 | 15.1k | reduction_props: &PlatformProperties, |
259 | 15.1k | ) { |
260 | 15.1k | debug_assert!(reduction_props0 .is_satisfied_by0 (parent_props0 , false)); |
261 | 15.1k | for (property446 , prop_value446 ) in &reduction_props.properties { |
262 | 446 | if let PlatformPropertyValue::Minimum(value420 ) = prop_value { |
263 | 420 | let worker_props = &mut parent_props.properties; |
264 | 420 | if let PlatformPropertyValue::Minimum(worker_value) = |
265 | 420 | worker_props.get_mut(property).unwrap() |
266 | 420 | { |
267 | 420 | *worker_value -= value; |
268 | 420 | }0 |
269 | 26 | } |
270 | | } |
271 | 15.1k | } |
272 | | |
273 | | impl Worker { |
274 | 2.36k | pub fn new( |
275 | 2.36k | id: WorkerId, |
276 | 2.36k | platform_properties: PlatformProperties, |
277 | 2.36k | tx: Sender<UpdateForWorker>, |
278 | 2.36k | timestamp: WorkerTimestamp, |
279 | 2.36k | max_inflight_tasks: u64, |
280 | 2.36k | ) -> Self { |
281 | 2.36k | Self { |
282 | 2.36k | id, |
283 | 2.36k | total_platform_properties: platform_properties.clone(), |
284 | 2.36k | platform_properties, |
285 | 2.36k | tx, |
286 | 2.36k | running_action_infos: HashMap::new(), |
287 | 2.36k | last_update_timestamp: timestamp, |
288 | 2.36k | is_paused: false, |
289 | 2.36k | pause_needs_kb: None, |
290 | 2.36k | admits_when_idle: false, |
291 | 2.36k | connection: 0, |
292 | 2.36k | id_chosen_by: WorkerIdChosenBy::Scheduler, |
293 | 2.36k | idle_declined_kb: None, |
294 | 2.36k | is_draining: false, |
295 | 2.36k | recent_outcomes: VecDeque::new(), |
296 | 2.36k | tripwire: TripwireState::Clear, |
297 | 2.36k | max_inflight_tasks, |
298 | 2.36k | last_load: None, |
299 | 2.36k | metrics: Arc::new(Metrics { |
300 | 2.36k | connected_timestamp: SystemTime::now() |
301 | 2.36k | .duration_since(UNIX_EPOCH) |
302 | 2.36k | .unwrap() |
303 | 2.36k | .as_secs(), |
304 | 2.36k | actions_completed: CounterWithTime::default(), |
305 | 2.36k | run_action: AsyncCounterWrapper::default(), |
306 | 2.36k | keep_alive: FuncCounterWrapper::default(), |
307 | 2.36k | notify_disconnect: CounterWithTime::default(), |
308 | 2.36k | kill_operation: CounterWithTime::default(), |
309 | 2.36k | keep_alives_dropped: CounterWithTime::default(), |
310 | 2.36k | }), |
311 | 2.36k | } |
312 | 2.36k | } |
313 | | |
314 | | /// Sends the initial connection information to the worker. This generally is just meta info. |
315 | | /// This should only be sent once and should always be the first item in the stream. |
316 | | /// `memory_property` is the platform property the scheduler vetoes |
317 | | /// placement on; the worker declines for load against the same one, so |
318 | | /// the two sides cannot disagree. None means the worker never declines |
319 | | /// for load. |
320 | 2.36k | pub fn send_initial_connection_result( |
321 | 2.36k | &mut self, |
322 | 2.36k | memory_property: Option<&str>, |
323 | 2.36k | ) -> Result<(), Error> { |
324 | 2.36k | send_msg_to_worker( |
325 | 2.36k | &self.tx, |
326 | 2.36k | update_for_worker::Update::ConnectionResult(ConnectionResult { |
327 | 2.36k | worker_id: self.id.clone().into(), |
328 | 2.36k | dispatch_ack: true, |
329 | 2.36k | memory_property: memory_property.unwrap_or_default().to_string(), |
330 | 2.36k | }), |
331 | | ) |
332 | 2.36k | .err_tip(|| format!0 ("Failed to send ConnectionResult to worker : {}", self.id)) |
333 | 2.36k | } |
334 | | |
335 | | /// Notifies the worker of a requested state change. |
336 | 16.6k | pub async fn notify_update(&mut self, worker_update: WorkerUpdate) -> Result<(), Error> { |
337 | 16.6k | match worker_update { |
338 | 15.2k | WorkerUpdate::RunAction(action) => { |
339 | 15.2k | let (operation_id, action_info, dispatched_at) = *action; |
340 | 15.2k | self.run_action(operation_id, action_info, dispatched_at) |
341 | 15.2k | .await |
342 | | } |
343 | | WorkerUpdate::Disconnect => { |
344 | 1.36k | self.metrics.notify_disconnect.inc(); |
345 | 1.36k | send_msg_to_worker(&self.tx, update_for_worker::Update::Disconnect(())) |
346 | | } |
347 | 8 | WorkerUpdate::KillOperation(operation_id) => { |
348 | 8 | let last_seen = self.last_update_timestamp; |
349 | 8 | let pending_action_info = self |
350 | 8 | .running_action_infos |
351 | 8 | .get_mut(&operation_id) |
352 | 8 | .err_tip(|| {0 |
353 | 0 | format!( |
354 | | "Worker {} asked to kill operation {operation_id} that is not running on it", |
355 | | self.id |
356 | | ) |
357 | 0 | })?; |
358 | | // Set before the send so a racing update_action cannot slip |
359 | | // through in between. |
360 | 8 | pending_action_info.kill_requested_at = Some(last_seen); |
361 | 8 | self.metrics.kill_operation.inc(); |
362 | 8 | send_msg_to_worker( |
363 | 8 | &self.tx, |
364 | 8 | update_for_worker::Update::KillOperationRequest(KillOperationRequest { |
365 | 8 | operation_id: operation_id.to_string(), |
366 | 8 | }), |
367 | | ) |
368 | | } |
369 | 2 | WorkerUpdate::ResultAccepted(operation_id) => send_msg_to_worker( |
370 | 2 | &self.tx, |
371 | 2 | update_for_worker::Update::ExecuteResultAccepted(ExecuteResultAccepted { |
372 | 2 | operation_id: operation_id.to_string(), |
373 | 2 | }), |
374 | | ), |
375 | | } |
376 | 16.6k | } |
377 | | |
378 | | /// Tells the worker to stop an operation this scheduler no longer holds |
379 | | /// for it: a late acknowledgement of a dispatch the sweep already took |
380 | | /// back means the worker is about to run an action that now belongs |
381 | | /// elsewhere. Nothing to book, since the operation is not on the ledger. |
382 | 1 | pub(crate) fn kill_unknown_operation(&self, operation_id: &OperationId) -> Result<(), Error> { |
383 | 1 | self.metrics.kill_operation.inc(); |
384 | 1 | send_msg_to_worker( |
385 | 1 | &self.tx, |
386 | 1 | update_for_worker::Update::KillOperationRequest(KillOperationRequest { |
387 | 1 | operation_id: operation_id.to_string(), |
388 | 1 | }), |
389 | | ) |
390 | 1 | } |
391 | | |
392 | | /// Forgets a kill request whose message never reached the worker, so |
393 | | /// the next revoked-operation sweep sends it again. |
394 | 1 | pub(crate) fn clear_kill_request(&mut self, operation_id: &OperationId) { |
395 | 1 | if let Some(pending_action_info) = self.running_action_infos.get_mut(operation_id) { |
396 | 1 | pending_action_info.kill_requested_at = None; |
397 | 1 | }0 |
398 | 1 | } |
399 | | |
400 | | /// Whether the worker has been told to kill this operation. |
401 | 51.7k | pub(crate) fn is_kill_requested(&self, operation_id: &OperationId) -> bool { |
402 | 51.7k | self.running_action_infos |
403 | 51.7k | .get(operation_id) |
404 | 51.7k | .is_some_and(|pending_action_info| pending_action_info.kill_requested_at.is_some()) |
405 | 51.7k | } |
406 | | |
407 | 1 | pub fn keep_alive(&mut self) -> Result<(), Error> { |
408 | 1 | let tx = &mut self.tx; |
409 | 1 | let id = &self.id; |
410 | 1 | let dropped = &self.metrics.keep_alives_dropped; |
411 | 1 | self.metrics.keep_alive.wrap(move || { |
412 | 1 | match send_msg_to_worker(tx, update_for_worker::Update::KeepAlive(())) { |
413 | | // A worker that is not reading has a full queue of work |
414 | | // ahead of the keepalive; skipping one costs nothing. |
415 | 0 | Err(err) if err.code == Code::ResourceExhausted => { |
416 | 0 | dropped.inc(); |
417 | 0 | Ok(()) |
418 | | } |
419 | 1 | other => other.err_tip(|| format!0 ("Failed to send KeepAlive to worker : {id}")), |
420 | | } |
421 | 1 | }) |
422 | 1 | } |
423 | | |
424 | | /// The worker said it took this operation. False when the operation is |
425 | | /// not on this worker, which a late acknowledgement can cause. |
426 | 14.3k | pub fn mark_accepted(&mut self, operation_id: &OperationId) -> bool { |
427 | 14.3k | match self.running_action_infos.get_mut(operation_id) { |
428 | 14.3k | Some(pending) => { |
429 | 14.3k | pending.accepted = true; |
430 | 14.3k | true |
431 | | } |
432 | 1 | None => false, |
433 | | } |
434 | 14.3k | } |
435 | | |
436 | | /// Takes a keepalive's report of what the worker is running and returns |
437 | | /// the acknowledged operations it has left out of |
438 | | /// [`LOST_AFTER_MISSED_REPORTS`] reports in a row. An operation the |
439 | | /// worker was told to kill is on its way off and not counted; one it has |
440 | | /// not acknowledged may still be in transit, which the acknowledgement |
441 | | /// sweep covers. |
442 | 25.5k | pub fn unreported_operations(&mut self, reported: &HashSet<OperationId>) -> Vec<OperationId> { |
443 | 25.5k | let mut lost = Vec::new(); |
444 | 25.5k | for (operation_id19.0k , pending19.0k ) in &mut self.running_action_infos { |
445 | 19.0k | if reported.contains(operation_id) { |
446 | 18.9k | pending.missed_reports = 0; |
447 | 18.9k | continue; |
448 | 70 | } |
449 | 70 | if !pending.accepted || pending.kill_requested_at7 .is_some7 () { |
450 | 67 | continue; |
451 | 3 | } |
452 | 3 | pending.missed_reports += 1; |
453 | 3 | if pending.missed_reports >= LOST_AFTER_MISSED_REPORTS { |
454 | 1 | lost.push(operation_id.clone()); |
455 | 2 | } |
456 | | } |
457 | 25.5k | lost |
458 | 25.5k | } |
459 | | |
460 | | /// Operations dispatched at or before `cutoff` that the worker never |
461 | | /// acknowledged. |
462 | 22 | pub fn unacknowledged(&self, cutoff: WorkerTimestamp) -> Vec<OperationId> { |
463 | 22 | self.running_action_infos |
464 | 22 | .iter() |
465 | 22 | .filter(|(_, pending)| !pending.accepted17 && pending.dispatched_at <= cutoff8 ) |
466 | 22 | .map(|(operation_id, _)| operation_id2 .clone2 ()) |
467 | 22 | .collect() |
468 | 22 | } |
469 | | |
470 | 15.2k | async fn run_action( |
471 | 15.2k | &mut self, |
472 | 15.2k | operation_id: OperationId, |
473 | 15.2k | action_info: ActionInfoWithProps, |
474 | 15.2k | dispatched_at: WorkerTimestamp, |
475 | 15.2k | ) -> Result<(), Error> { |
476 | 15.2k | let tx = &mut self.tx; |
477 | 15.2k | let worker_platform_properties = &mut self.platform_properties; |
478 | 15.2k | let running_action_infos = &mut self.running_action_infos; |
479 | 15.2k | let worker_id = self.id.clone().into(); |
480 | 15.2k | self.metrics |
481 | 15.2k | .run_action |
482 | 15.2k | .wrap(async move { |
483 | 15.2k | let action_info_clone = action_info.clone(); |
484 | 15.2k | let operation_id_string = operation_id.to_string(); |
485 | 15.2k | let start_execute = StartExecute { |
486 | 15.2k | execute_request: Some(action_info_clone.inner.as_ref().into()), |
487 | 15.2k | operation_id: operation_id_string, |
488 | 15.2k | queued_timestamp: Some(action_info.inner.insert_timestamp.into()), |
489 | 15.2k | platform: Some((&action_info.platform_properties).into()), |
490 | 15.2k | worker_id, |
491 | 15.2k | request_metadata: action_info.origin_metadata.bazel_metadata.clone(), |
492 | 15.2k | }; |
493 | | // Send first: a channel that will not take the message |
494 | | // leaves the ledger untouched, and the caller requeues. |
495 | 15.2k | send_msg_to_worker(tx, update_for_worker::Update::StartAction(start_execute))?69 ; |
496 | 15.1k | reduce_platform_properties( |
497 | 15.1k | worker_platform_properties, |
498 | 15.1k | &action_info.platform_properties, |
499 | | ); |
500 | 15.1k | running_action_infos.insert( |
501 | 15.1k | operation_id, |
502 | 15.1k | PendingActionInfoData { |
503 | 15.1k | action_info, |
504 | 15.1k | kill_requested_at: None, |
505 | 15.1k | missed_reports: 0, |
506 | 15.1k | dispatched_at, |
507 | 15.1k | accepted: false, |
508 | 15.1k | last_usage: None, |
509 | 15.1k | reported_peak_memory_kb: 0, |
510 | 15.1k | }, |
511 | | ); |
512 | 15.1k | Ok(()) |
513 | 15.2k | }) |
514 | 15.2k | .await |
515 | 15.2k | } |
516 | | |
517 | | /// Releases everything the action reserved. This is the only place the |
518 | | /// `Minimum` budget comes back: the worker's `ExecuteComplete` used to |
519 | | /// restore it when the process exited, but the action is still resident |
520 | | /// through output upload, which is where its memory peaks (output buffers, |
521 | | /// the upload fan-out), so handing the budget back then admitted new work |
522 | | /// onto a worker at its fullest. |
523 | 13.1k | pub(crate) fn complete_action(&mut self, operation_id: &OperationId) -> Result<(), Error> { |
524 | 13.1k | let pending_action_info = self.running_action_infos.remove(operation_id).err_tip(|| {0 |
525 | 0 | format!( |
526 | | "Worker {} tried to complete operation {} that was not running", |
527 | | self.id, operation_id |
528 | | ) |
529 | 0 | })?; |
530 | 13.1k | self.restore_platform_properties(&pending_action_info.action_info.platform_properties); |
531 | 13.1k | self.is_paused = false; |
532 | 13.1k | self.pause_needs_kb = None; |
533 | 13.1k | self.metrics.actions_completed.inc(); |
534 | 13.1k | Ok(()) |
535 | 13.1k | } |
536 | | |
537 | 0 | pub fn has_actions(&self) -> bool { |
538 | 0 | !self.running_action_infos.is_empty() |
539 | 0 | } |
540 | | |
541 | 13.1k | fn restore_platform_properties(&mut self, props: &PlatformProperties) { |
542 | 13.1k | for (property244 , prop_value244 ) in &props.properties { |
543 | 244 | if let PlatformPropertyValue::Minimum(value) = prop_value { |
544 | 244 | let worker_props = &mut self.platform_properties.properties; |
545 | 244 | if let PlatformPropertyValue::Minimum(worker_value) = |
546 | 244 | worker_props.get_mut(property).unwrap() |
547 | 244 | { |
548 | 244 | *worker_value += value; |
549 | 244 | }0 |
550 | 0 | } |
551 | | } |
552 | 13.1k | } |
553 | | |
554 | 201M | pub fn can_accept_work(&self) -> bool { |
555 | 201M | !self.is_paused |
556 | 201M | && !self.is_draining |
557 | 201M | && (self.max_inflight_tasks == 0 |
558 | 201M | || u64::try_from(self.running_action_infos.len()).unwrap_or(u64::MAX) |
559 | 201M | < self.max_inflight_tasks) |
560 | 201M | } |
561 | | } |
562 | | |
563 | | impl PartialEq for Worker { |
564 | 0 | fn eq(&self, other: &Self) -> bool { |
565 | 0 | self.id == other.id |
566 | 0 | } |
567 | | } |
568 | | |
569 | | impl Eq for Worker {} |
570 | | |
571 | | impl Hash for Worker { |
572 | 0 | fn hash<H: Hasher>(&self, state: &mut H) { |
573 | 0 | self.id.hash(state); |
574 | 0 | } |
575 | | } |
576 | | |
577 | | #[derive(Debug, Default, MetricsComponent)] |
578 | | struct Metrics { |
579 | | #[metric(help = "The timestamp of when this worker connected.")] |
580 | | connected_timestamp: u64, |
581 | | #[metric(help = "The number of actions completed for this worker.")] |
582 | | actions_completed: CounterWithTime, |
583 | | #[metric(help = "The number of actions started for this worker.")] |
584 | | run_action: AsyncCounterWrapper, |
585 | | #[metric(help = "The number of keep_alive sent to this worker.")] |
586 | | keep_alive: FuncCounterWrapper, |
587 | | #[metric(help = "The number of notify_disconnect sent to this worker.")] |
588 | | notify_disconnect: CounterWithTime, |
589 | | #[metric(help = "The number of kill_operation sent to this worker.")] |
590 | | kill_operation: CounterWithTime, |
591 | | #[metric(help = "Keepalives not sent because the worker's channel was full.")] |
592 | | keep_alives_dropped: CounterWithTime, |
593 | | } |