/build/source/nativelink-scheduler/src/worker.rs
Line | Count | Source |
1 | | // Copyright 2024 The NativeLink Authors. All rights reserved. |
2 | | // |
3 | | // Licensed under the Functional Source License, Version 1.1, Apache 2.0 Future License (the "License"); |
4 | | // you may not use this file except in compliance with the License. |
5 | | // You may obtain a copy of the License at |
6 | | // |
7 | | // See LICENSE file for details |
8 | | // |
9 | | // Unless required by applicable law or agreed to in writing, software |
10 | | // distributed under the License is distributed on an "AS IS" BASIS, |
11 | | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
12 | | // See the License for the specific language governing permissions and |
13 | | // limitations under the License. |
14 | | |
15 | | use core::hash::{Hash, Hasher}; |
16 | | use std::collections::{HashMap, HashSet}; |
17 | | use std::sync::Arc; |
18 | | use std::time::{SystemTime, UNIX_EPOCH}; |
19 | | |
20 | | use nativelink_error::{Code, Error, ResultExt, make_err}; |
21 | | use nativelink_metric::MetricsComponent; |
22 | | use nativelink_proto::com::github::trace_machina::nativelink::remote_execution::{ |
23 | | ConnectionResult, StartExecute, UpdateForWorker, update_for_worker, |
24 | | }; |
25 | | use nativelink_util::action_messages::{ActionInfo, OperationId, WorkerId}; |
26 | | use nativelink_util::metrics_utils::{AsyncCounterWrapper, CounterWithTime, FuncCounterWrapper}; |
27 | | use nativelink_util::platform_properties::{PlatformProperties, PlatformPropertyValue}; |
28 | | use tokio::sync::mpsc::UnboundedSender; |
29 | | |
30 | | pub type WorkerTimestamp = u64; |
31 | | |
32 | | /// Represents the action info and the platform properties of the action. |
33 | | /// These platform properties have the type of the properties as well as |
34 | | /// the value of the properties, unlike `ActionInfo`, which only has the |
35 | | /// string value of the properties. |
36 | | #[derive(Clone, Debug, MetricsComponent)] |
37 | | pub struct ActionInfoWithProps { |
38 | | /// The action info of the action. |
39 | | #[metric(group = "action_info")] |
40 | | pub inner: Arc<ActionInfo>, |
41 | | /// The platform properties of the action. |
42 | | #[metric(group = "platform_properties")] |
43 | | pub platform_properties: PlatformProperties, |
44 | | } |
45 | | |
46 | | /// Notifications to send worker about a requested state change. |
47 | | #[derive(Debug)] |
48 | | pub enum WorkerUpdate { |
49 | | /// Requests that the worker begin executing this action. |
50 | | RunAction((OperationId, ActionInfoWithProps)), |
51 | | |
52 | | /// Request that the worker is no longer in the pool and may discard any jobs. |
53 | | Disconnect, |
54 | | } |
55 | | |
56 | | #[derive(Debug, MetricsComponent)] |
57 | | pub struct PendingActionInfoData { |
58 | | #[metric] |
59 | | pub action_info: ActionInfoWithProps, |
60 | | } |
61 | | |
62 | | /// Represents a connection to a worker and used as the medium to |
63 | | /// interact with the worker from the client/scheduler. |
64 | | #[derive(Debug, MetricsComponent)] |
65 | | pub struct Worker { |
66 | | /// Unique identifier of the worker. |
67 | | #[metric(help = "The unique identifier of the worker.")] |
68 | | pub id: WorkerId, |
69 | | |
70 | | /// Properties that describe the capabilities of this worker. |
71 | | #[metric(group = "platform_properties")] |
72 | | pub platform_properties: PlatformProperties, |
73 | | |
74 | | /// Channel to send commands from scheduler to worker. |
75 | | pub tx: UnboundedSender<UpdateForWorker>, |
76 | | |
77 | | /// The action info of the running actions on the worker. |
78 | | #[metric(group = "running_action_infos")] |
79 | | pub running_action_infos: HashMap<OperationId, PendingActionInfoData>, |
80 | | |
81 | | /// If the properties were restored already then it's added to this set. |
82 | | pub restored_platform_properties: HashSet<OperationId>, |
83 | | |
84 | | /// Timestamp of last time this worker had been communicated with. |
85 | | // Warning: Do not update this timestamp without updating the placement of the worker in |
86 | | // the LRUCache in the Workers struct. |
87 | | #[metric(help = "Last time this worker was communicated with.")] |
88 | | pub last_update_timestamp: WorkerTimestamp, |
89 | | |
90 | | /// Whether the worker rejected the last action due to back pressure. |
91 | | #[metric(help = "If the worker is paused.")] |
92 | | pub is_paused: bool, |
93 | | |
94 | | /// Whether the worker is draining. |
95 | | #[metric(help = "If the worker is draining.")] |
96 | | pub is_draining: bool, |
97 | | |
98 | | /// Stats about the worker. |
99 | | #[metric] |
100 | | metrics: Arc<Metrics>, |
101 | | } |
102 | | |
103 | 78 | fn send_msg_to_worker( |
104 | 78 | tx: &UnboundedSender<UpdateForWorker>, |
105 | 78 | msg: update_for_worker::Update, |
106 | 78 | ) -> Result<(), Error> { |
107 | 78 | tx.send(UpdateForWorker { update: Some(msg) }) |
108 | 78 | .map_err(|_| make_err!(Code::Internal7 , "Worker disconnected")) |
109 | 78 | } |
110 | | |
111 | | /// Reduces the platform properties available on the worker based on the platform properties provided. |
112 | | /// This is used because we allow more than 1 job to run on a worker at a time, and this is how the |
113 | | /// scheduler knows if more jobs can run on a given worker. |
114 | 32 | fn reduce_platform_properties( |
115 | 32 | parent_props: &mut PlatformProperties, |
116 | 32 | reduction_props: &PlatformProperties, |
117 | 32 | ) { |
118 | 32 | debug_assert!(reduction_props0 .is_satisfied_by0 (parent_props0 )); |
119 | 36 | for (property4 , prop_value4 ) in &reduction_props.properties { |
120 | 4 | if let PlatformPropertyValue::Minimum(value3 ) = prop_value { Branch (120:16): [True: 3, False: 1]
Branch (120:16): [Folded - Ignored]
|
121 | 3 | let worker_props = &mut parent_props.properties; |
122 | 3 | if let &mut PlatformPropertyValue::Minimum(worker_value) = Branch (122:20): [True: 3, False: 0]
Branch (122:20): [Folded - Ignored]
|
123 | 3 | &mut worker_props.get_mut(property).unwrap() |
124 | 3 | { |
125 | 3 | *worker_value -= value; |
126 | 3 | }0 |
127 | 1 | } |
128 | | } |
129 | 32 | } |
130 | | |
131 | | impl Worker { |
132 | 35 | pub fn new( |
133 | 35 | id: WorkerId, |
134 | 35 | platform_properties: PlatformProperties, |
135 | 35 | tx: UnboundedSender<UpdateForWorker>, |
136 | 35 | timestamp: WorkerTimestamp, |
137 | 35 | ) -> Self { |
138 | 35 | Self { |
139 | 35 | id, |
140 | 35 | platform_properties, |
141 | 35 | tx, |
142 | 35 | running_action_infos: HashMap::new(), |
143 | 35 | restored_platform_properties: HashSet::new(), |
144 | 35 | last_update_timestamp: timestamp, |
145 | 35 | is_paused: false, |
146 | 35 | is_draining: false, |
147 | 35 | metrics: Arc::new(Metrics { |
148 | 35 | connected_timestamp: SystemTime::now() |
149 | 35 | .duration_since(UNIX_EPOCH) |
150 | 35 | .unwrap() |
151 | 35 | .as_secs(), |
152 | 35 | actions_completed: CounterWithTime::default(), |
153 | 35 | run_action: AsyncCounterWrapper::default(), |
154 | 35 | keep_alive: FuncCounterWrapper::default(), |
155 | 35 | notify_disconnect: CounterWithTime::default(), |
156 | 35 | }), |
157 | 35 | } |
158 | 35 | } |
159 | | |
160 | | /// Sends the initial connection information to the worker. This generally is just meta info. |
161 | | /// This should only be sent once and should always be the first item in the stream. |
162 | 35 | pub fn send_initial_connection_result(&mut self) -> Result<(), Error> { |
163 | 35 | send_msg_to_worker( |
164 | 35 | &self.tx, |
165 | 35 | update_for_worker::Update::ConnectionResult(ConnectionResult { |
166 | 35 | worker_id: self.id.clone().into(), |
167 | 35 | }), |
168 | | ) |
169 | 35 | .err_tip(|| format!("Failed to send ConnectionResult to worker : {}"0 , self.id)) |
170 | 35 | } |
171 | | |
172 | | /// Notifies the worker of a requested state change. |
173 | 42 | pub async fn notify_update(&mut self, worker_update: WorkerUpdate) -> Result<(), Error> { |
174 | 42 | match worker_update { |
175 | 32 | WorkerUpdate::RunAction((operation_id, action_info)) => { |
176 | 32 | self.run_action(operation_id, action_info).await |
177 | | } |
178 | | WorkerUpdate::Disconnect => { |
179 | 10 | self.metrics.notify_disconnect.inc(); |
180 | 10 | send_msg_to_worker(&self.tx, update_for_worker::Update::Disconnect(())) |
181 | | } |
182 | | } |
183 | 42 | } |
184 | | |
185 | 1 | pub fn keep_alive(&mut self) -> Result<(), Error> { |
186 | 1 | let tx = &mut self.tx; |
187 | 1 | let id = &self.id; |
188 | 1 | self.metrics.keep_alive.wrap(move || { |
189 | 1 | send_msg_to_worker(tx, update_for_worker::Update::KeepAlive(())) |
190 | 1 | .err_tip(|| format!("Failed to send KeepAlive to worker : {id}"0 )) |
191 | 1 | }) |
192 | 1 | } |
193 | | |
194 | 32 | async fn run_action( |
195 | 32 | &mut self, |
196 | 32 | operation_id: OperationId, |
197 | 32 | action_info: ActionInfoWithProps, |
198 | 32 | ) -> Result<(), Error> { |
199 | 32 | let tx = &mut self.tx; |
200 | 32 | let worker_platform_properties = &mut self.platform_properties; |
201 | 32 | let running_action_infos = &mut self.running_action_infos; |
202 | 32 | let worker_id = self.id.clone().into(); |
203 | 32 | self.metrics |
204 | 32 | .run_action |
205 | 32 | .wrap(async move { |
206 | 32 | let action_info_clone = action_info.clone(); |
207 | 32 | let operation_id_string = operation_id.to_string(); |
208 | 32 | let start_execute = StartExecute { |
209 | 32 | execute_request: Some(action_info_clone.inner.as_ref().into()), |
210 | 32 | operation_id: operation_id_string, |
211 | 32 | queued_timestamp: Some(action_info.inner.insert_timestamp.into()), |
212 | 32 | platform: Some((&action_info.platform_properties).into()), |
213 | 32 | worker_id, |
214 | 32 | }; |
215 | 32 | reduce_platform_properties( |
216 | 32 | worker_platform_properties, |
217 | 32 | &action_info.platform_properties, |
218 | | ); |
219 | 32 | running_action_infos.insert(operation_id, PendingActionInfoData { action_info }); |
220 | | |
221 | 32 | send_msg_to_worker(tx, update_for_worker::Update::StartAction(start_execute)) |
222 | 32 | }) |
223 | 32 | .await |
224 | 32 | } |
225 | | |
226 | 0 | pub(crate) fn execution_complete(&mut self, operation_id: &OperationId) { |
227 | 0 | if let Some((operation_id, pending_action_info)) = Branch (227:16): [True: 0, False: 0]
Branch (227:16): [Folded - Ignored]
|
228 | 0 | self.running_action_infos.remove_entry(operation_id) |
229 | 0 | { |
230 | 0 | self.restored_platform_properties |
231 | 0 | .insert(operation_id.clone()); |
232 | 0 | self.restore_platform_properties(&pending_action_info.action_info.platform_properties); |
233 | 0 | self.running_action_infos |
234 | 0 | .insert(operation_id, pending_action_info); |
235 | 0 | } |
236 | 0 | } |
237 | | |
238 | 8 | pub(crate) async fn complete_action( |
239 | 8 | &mut self, |
240 | 8 | operation_id: &OperationId, |
241 | 8 | ) -> Result<(), Error> { |
242 | 8 | let pending_action_info = self.running_action_infos.remove(operation_id).err_tip(|| {0 |
243 | 0 | format!( |
244 | 0 | "Worker {} tried to complete operation {} that was not running", |
245 | | self.id, operation_id |
246 | | ) |
247 | 0 | })?; |
248 | 8 | if !self.restored_platform_properties.remove(operation_id) { Branch (248:12): [True: 8, False: 0]
Branch (248:12): [Folded - Ignored]
|
249 | 8 | self.restore_platform_properties(&pending_action_info.action_info.platform_properties); |
250 | 8 | }0 |
251 | 8 | self.is_paused = false; |
252 | 8 | self.metrics.actions_completed.inc(); |
253 | 8 | Ok(()) |
254 | 8 | } |
255 | | |
256 | 0 | pub fn has_actions(&self) -> bool { |
257 | 0 | !self.running_action_infos.is_empty() |
258 | 0 | } |
259 | | |
260 | 8 | fn restore_platform_properties(&mut self, props: &PlatformProperties) { |
261 | 10 | for (property2 , prop_value2 ) in &props.properties { |
262 | 2 | if let PlatformPropertyValue::Minimum(value) = prop_value { Branch (262:20): [True: 2, False: 0]
Branch (262:20): [Folded - Ignored]
|
263 | 2 | let worker_props = &mut self.platform_properties.properties; |
264 | 2 | if let PlatformPropertyValue::Minimum(worker_value) = Branch (264:24): [True: 2, False: 0]
Branch (264:24): [Folded - Ignored]
|
265 | 2 | worker_props.get_mut(property).unwrap() |
266 | 2 | { |
267 | 2 | *worker_value += value; |
268 | 2 | }0 |
269 | 0 | } |
270 | | } |
271 | 8 | } |
272 | | |
273 | 46 | pub const fn can_accept_work(&self) -> bool { |
274 | 46 | !self.is_paused && !self.is_draining Branch (274:9): [True: 46, False: 0]
Branch (274:9): [Folded - Ignored]
|
275 | 46 | } |
276 | | } |
277 | | |
278 | | impl PartialEq for Worker { |
279 | 0 | fn eq(&self, other: &Self) -> bool { |
280 | 0 | self.id == other.id |
281 | 0 | } |
282 | | } |
283 | | |
284 | | impl Eq for Worker {} |
285 | | |
286 | | impl Hash for Worker { |
287 | 0 | fn hash<H: Hasher>(&self, state: &mut H) { |
288 | 0 | self.id.hash(state); |
289 | 0 | } |
290 | | } |
291 | | |
292 | | #[derive(Debug, Default, MetricsComponent)] |
293 | | struct Metrics { |
294 | | #[metric(help = "The timestamp of when this worker connected.")] |
295 | | connected_timestamp: u64, |
296 | | #[metric(help = "The number of actions completed for this worker.")] |
297 | | actions_completed: CounterWithTime, |
298 | | #[metric(help = "The number of actions started for this worker.")] |
299 | | run_action: AsyncCounterWrapper, |
300 | | #[metric(help = "The number of keep_alive sent to this worker.")] |
301 | | keep_alive: FuncCounterWrapper, |
302 | | #[metric(help = "The number of notify_disconnect sent to this worker.")] |
303 | | notify_disconnect: CounterWithTime, |
304 | | } |