/build/source/nativelink-worker/src/running_actions_manager.rs
Line | Count | Source |
1 | | // Copyright 2024 The NativeLink Authors. All rights reserved. |
2 | | // |
3 | | // Licensed under the Apache License, Version 2.0 (the "License"); |
4 | | // you may not use this file except in compliance with the License. |
5 | | // You may obtain a copy of the License at |
6 | | // |
7 | | // http://www.apache.org/licenses/LICENSE-2.0 |
8 | | // |
9 | | // Unless required by applicable law or agreed to in writing, software |
10 | | // distributed under the License is distributed on an "AS IS" BASIS, |
11 | | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
12 | | // See the License for the specific language governing permissions and |
13 | | // limitations under the License. |
14 | | |
15 | | use std::borrow::Cow; |
16 | | use std::cmp::min; |
17 | | use std::collections::vec_deque::VecDeque; |
18 | | use std::collections::HashMap; |
19 | | use std::convert::Into; |
20 | | use std::ffi::{OsStr, OsString}; |
21 | | use std::fmt::Debug; |
22 | | #[cfg(target_family = "unix")] |
23 | | use std::fs::Permissions; |
24 | | #[cfg(target_family = "unix")] |
25 | | use std::os::unix::fs::{MetadataExt, PermissionsExt}; |
26 | | use std::path::Path; |
27 | | use std::pin::Pin; |
28 | | use std::process::Stdio; |
29 | | use std::sync::atomic::{AtomicBool, Ordering}; |
30 | | use std::sync::{Arc, Weak}; |
31 | | use std::time::{Duration, SystemTime}; |
32 | | |
33 | | use bytes::{Bytes, BytesMut}; |
34 | | use filetime::{set_file_mtime, FileTime}; |
35 | | use formatx::Template; |
36 | | use futures::future::{ |
37 | | try_join, try_join3, try_join_all, BoxFuture, Future, FutureExt, TryFutureExt, |
38 | | }; |
39 | | use futures::stream::{FuturesUnordered, StreamExt, TryStreamExt}; |
40 | | use nativelink_config::cas_server::{ |
41 | | EnvironmentSource, UploadActionResultConfig, UploadCacheResultsStrategy, |
42 | | }; |
43 | | use nativelink_error::{make_err, make_input_err, Code, Error, ResultExt}; |
44 | | use nativelink_metric::MetricsComponent; |
45 | | use nativelink_proto::build::bazel::remote::execution::v2::{ |
46 | | Action, ActionResult as ProtoActionResult, Command as ProtoCommand, |
47 | | Directory as ProtoDirectory, Directory, DirectoryNode, ExecuteResponse, FileNode, SymlinkNode, |
48 | | Tree as ProtoTree, UpdateActionResultRequest, |
49 | | }; |
50 | | use nativelink_proto::com::github::trace_machina::nativelink::remote_execution::{ |
51 | | HistoricalExecuteResponse, StartExecute, |
52 | | }; |
53 | | use nativelink_store::ac_utils::{ |
54 | | compute_buf_digest, get_and_decode_digest, serialize_and_upload_message, ESTIMATED_DIGEST_SIZE, |
55 | | }; |
56 | | use nativelink_store::fast_slow_store::FastSlowStore; |
57 | | use nativelink_store::filesystem_store::{FileEntry, FilesystemStore}; |
58 | | use nativelink_store::grpc_store::GrpcStore; |
59 | | use nativelink_util::action_messages::{ |
60 | | to_execute_response, ActionInfo, ActionResult, DirectoryInfo, ExecutionMetadata, FileInfo, |
61 | | NameOrPath, OperationId, SymlinkInfo, |
62 | | }; |
63 | | use nativelink_util::common::{fs, DigestInfo}; |
64 | | use nativelink_util::digest_hasher::{DigestHasher, DigestHasherFunc}; |
65 | | use nativelink_util::metrics_utils::{AsyncCounterWrapper, CounterWithTime}; |
66 | | use nativelink_util::shutdown_guard::ShutdownGuard; |
67 | | use nativelink_util::store_trait::{Store, StoreLike, UploadSizeInfo}; |
68 | | use nativelink_util::{background_spawn, spawn, spawn_blocking}; |
69 | | use parking_lot::Mutex; |
70 | | use prost::Message; |
71 | | use relative_path::RelativePath; |
72 | | use scopeguard::{guard, ScopeGuard}; |
73 | | use serde::Deserialize; |
74 | | use tokio::io::{AsyncReadExt, AsyncSeekExt}; |
75 | | use tokio::process; |
76 | | use tokio::sync::{oneshot, watch}; |
77 | | use tokio_stream::wrappers::ReadDirStream; |
78 | | use tonic::Request; |
79 | | use tracing::{enabled, event, Level}; |
80 | | use uuid::Uuid; |
81 | | |
82 | | /// For simplicity we use a fixed exit code for cases when our program is terminated |
83 | | /// due to a signal. |
84 | | const EXIT_CODE_FOR_SIGNAL: i32 = 9; |
85 | | |
86 | | /// Default strategy for uploading historical results. |
87 | | /// Note: If this value changes the config documentation |
88 | | /// should reflect it. |
89 | | const DEFAULT_HISTORICAL_RESULTS_STRATEGY: UploadCacheResultsStrategy = |
90 | | UploadCacheResultsStrategy::failures_only; |
91 | | |
92 | | /// Valid string reasons for a failure. |
93 | | /// Note: If these change, the documentation should be updated. |
94 | | #[allow(non_camel_case_types)] |
95 | | #[derive(Debug, Deserialize)] |
96 | | enum SideChannelFailureReason { |
97 | | /// Task should be considered timed out. |
98 | | timeout, |
99 | | } |
100 | | |
101 | | /// This represents the json data that can be passed from the running process |
102 | | /// to the parent via the `SideChannelFile`. See: |
103 | | /// `config::EnvironmentSource::sidechannelfile` for more details. |
104 | | /// Note: Any fields added here must be added to the documentation. |
105 | | #[derive(Debug, Deserialize, Default)] |
106 | | struct SideChannelInfo { |
107 | | /// If the task should be considered a failure and why. |
108 | | failure: Option<SideChannelFailureReason>, |
109 | | } |
110 | | |
111 | | /// Aggressively download the digests of files and make a local folder from it. This function |
112 | | /// will spawn unbounded number of futures to try and get these downloaded. The store itself |
113 | | /// should be rate limited if spawning too many requests at once is an issue. |
114 | | /// We require the `FilesystemStore` to be the `fast` store of `FastSlowStore`. This is for |
115 | | /// efficiency reasons. We will request the `FastSlowStore` to populate the entry then we will |
116 | | /// assume the `FilesystemStore` has the file available immediately after and hardlink the file |
117 | | /// to a new location. |
118 | | // Sadly we cannot use `async fn` here because the rust compiler cannot determine the auto traits |
119 | | // of the future. So we need to force this function to return a dynamic future instead. |
120 | | // see: https://github.com/rust-lang/rust/issues/78649 |
121 | 16 | pub fn download_to_directory<'a>( |
122 | 16 | cas_store: &'a FastSlowStore, |
123 | 16 | filesystem_store: Pin<&'a FilesystemStore>, |
124 | 16 | digest: &'a DigestInfo, |
125 | 16 | current_directory: &'a str, |
126 | 16 | ) -> BoxFuture<'a, Result<(), Error>> { |
127 | 16 | async move { |
128 | 16 | let directory = get_and_decode_digest::<ProtoDirectory>(cas_store, digest.into()) |
129 | 16 | .await |
130 | 16 | .err_tip(|| "Converting digest to Directory"0 )?0 ; |
131 | 16 | let mut futures = FuturesUnordered::new(); |
132 | | |
133 | 20 | for file4 in directory.files { |
134 | 4 | let digest: DigestInfo = file |
135 | 4 | .digest |
136 | 4 | .err_tip(|| "Expected Digest to exist in Directory::file::digest"0 )?0 |
137 | 4 | .try_into() |
138 | 4 | .err_tip(|| "In Directory::file::digest"0 )?0 ; |
139 | 4 | let dest = format!("{}/{}", current_directory, file.name); |
140 | 4 | let (mtime, mut unix_mode) = match file.node_properties { |
141 | 1 | Some(properties) => (properties.mtime, properties.unix_mode), |
142 | 3 | None => (None, None), |
143 | | }; |
144 | | #[cfg_attr(target_family = "windows", allow(unused_assignments))] |
145 | 4 | if file.is_executable { Branch (145:16): [True: 1, False: 3]
Branch (145:16): [Folded - Ignored]
|
146 | 1 | unix_mode = Some(unix_mode.unwrap_or(0o444) | 0o111); |
147 | 3 | } |
148 | 4 | futures.push( |
149 | 4 | cas_store |
150 | 4 | .populate_fast_store(digest.into()) |
151 | 4 | .and_then(move |()| async move { |
152 | 4 | let file_entry = filesystem_store |
153 | 4 | .get_file_entry_for_digest(&digest) |
154 | 4 | .await |
155 | 4 | .err_tip(|| "During hard link"0 )?0 ; |
156 | 4 | file_entry |
157 | 4 | .get_file_path_locked(|src| fs::hard_link(src, &dest)) |
158 | 4 | .await |
159 | 4 | .map_err(|e| { |
160 | 0 | make_err!(Code::Internal, "Could not make hardlink, {e:?} : {dest}") |
161 | 4 | })?0 ; |
162 | | #[cfg(target_family = "unix")] |
163 | 4 | if let Some(unix_mode1 ) = unix_mode { Branch (163:32): [True: 1, False: 3]
Branch (163:32): [Folded - Ignored]
|
164 | 1 | fs::set_permissions(&dest, Permissions::from_mode(unix_mode)) |
165 | 1 | .await |
166 | 1 | .err_tip(|| { |
167 | 0 | format!( |
168 | 0 | "Could not set unix mode in download_to_directory {dest}" |
169 | 0 | ) |
170 | 1 | })?0 ; |
171 | 3 | } |
172 | 4 | if let Some(mtime1 ) = mtime { Branch (172:32): [True: 1, False: 3]
Branch (172:32): [Folded - Ignored]
|
173 | 1 | spawn_blocking!("download_to_directory_set_mtime", move || { |
174 | 1 | set_file_mtime( |
175 | 1 | &dest, |
176 | 1 | FileTime::from_unix_time(mtime.seconds, mtime.nanos as u32), |
177 | 1 | ) |
178 | 1 | .err_tip(|| { |
179 | 0 | format!("Failed to set mtime in download_to_directory {dest}") |
180 | 1 | }) |
181 | 1 | }) |
182 | 1 | .await |
183 | 1 | .err_tip(|| { |
184 | 0 | "Failed to launch spawn_blocking in download_to_directory" |
185 | 1 | })?0 ?0 ; |
186 | 3 | } |
187 | 4 | Ok(()) |
188 | 8 | }) |
189 | 4 | .map_err(move |e| e.append(format!("for digest {digest}"))0 ) |
190 | 4 | .boxed(), |
191 | 4 | ); |
192 | 4 | } |
193 | | |
194 | 22 | for directory6 in directory.directories { |
195 | 6 | let digest: DigestInfo = directory |
196 | 6 | .digest |
197 | 6 | .err_tip(|| "Expected Digest to exist in Directory::directories::digest"0 )?0 |
198 | 6 | .try_into() |
199 | 6 | .err_tip(|| "In Directory::file::digest"0 )?0 ; |
200 | 6 | let new_directory_path = format!("{}/{}", current_directory, directory.name); |
201 | 6 | futures.push( |
202 | 6 | async move { |
203 | 6 | fs::create_dir(&new_directory_path) |
204 | 6 | .await |
205 | 6 | .err_tip(|| format!("Could not create directory {new_directory_path}")0 )?0 ; |
206 | 6 | download_to_directory( |
207 | 6 | cas_store, |
208 | 6 | filesystem_store, |
209 | 6 | &digest, |
210 | 6 | &new_directory_path, |
211 | 6 | ) |
212 | 6 | .await |
213 | 6 | .err_tip(|| format!("in download_to_directory : {new_directory_path}")0 )?0 ; |
214 | 6 | Ok(()) |
215 | 6 | } |
216 | 6 | .boxed(), |
217 | 6 | ); |
218 | 6 | } |
219 | | |
220 | | #[cfg(target_family = "unix")] |
221 | 17 | for symlink_node1 in directory.symlinks { |
222 | 1 | let dest = format!("{}/{}", current_directory, symlink_node.name); |
223 | 1 | futures.push( |
224 | 1 | async move { |
225 | 1 | fs::symlink(&symlink_node.target, &dest).await.err_tip(|| { |
226 | 0 | format!( |
227 | 0 | "Could not create symlink {} -> {}", |
228 | 0 | symlink_node.target, dest |
229 | 0 | ) |
230 | 1 | })?0 ; |
231 | 1 | Ok(()) |
232 | 1 | } |
233 | 1 | .boxed(), |
234 | 1 | ); |
235 | 1 | } |
236 | | |
237 | 27 | while futures.try_next().await?0 .is_some() {}11 Branch (237:15): [True: 11, False: 16]
Branch (237:15): [Folded - Ignored]
|
238 | 16 | Ok(()) |
239 | 16 | } |
240 | 16 | .boxed() |
241 | 16 | } |
242 | | |
243 | | #[cfg(target_family = "windows")] |
244 | | fn is_executable(_metadata: &std::fs::Metadata, full_path: &impl AsRef<Path>) -> bool { |
245 | | static EXECUTABLE_EXTENSIONS: &[&str] = &["exe", "bat", "com"]; |
246 | | EXECUTABLE_EXTENSIONS |
247 | | .iter() |
248 | | .any(|ext| full_path.as_ref().extension().map_or(false, |v| v == *ext)) |
249 | | } |
250 | | |
251 | | #[cfg(target_family = "unix")] |
252 | 2 | fn is_executable(metadata: &std::fs::Metadata, _full_path: &impl AsRef<Path>) -> bool { |
253 | 2 | (metadata.mode() & 0o111) != 0 |
254 | 2 | } |
255 | | |
256 | 2 | async fn upload_file( |
257 | 2 | cas_store: Pin<&impl StoreLike>, |
258 | 2 | full_path: impl AsRef<Path> + Debug, |
259 | 2 | hasher: DigestHasherFunc, |
260 | 2 | metadata: std::fs::Metadata, |
261 | 2 | ) -> Result<FileInfo, Error> { |
262 | 2 | let is_executable = is_executable(&metadata, &full_path); |
263 | 2 | let file_size = metadata.len(); |
264 | 2 | let resumeable_file = fs::open_file(&full_path, u64::MAX) |
265 | 2 | .await |
266 | 2 | .err_tip(|| format!("Could not open file {full_path:?}")0 )?0 ; |
267 | | |
268 | 2 | let (digest, mut resumeable_file) = hasher |
269 | 2 | .hasher() |
270 | 2 | .digest_for_file(resumeable_file, Some(file_size)) |
271 | 2 | .await |
272 | 2 | .err_tip(|| format!("Failed to hash file in digest_for_file failed for {full_path:?}")0 )?0 ; |
273 | | |
274 | 2 | resumeable_file |
275 | 2 | .as_reader() |
276 | 2 | .await |
277 | 2 | .err_tip(|| "Could not get reader from file slot in RunningActionsManager::upload_file()"0 )?0 |
278 | 2 | .get_mut() |
279 | 2 | .rewind() |
280 | 2 | .await |
281 | 2 | .err_tip(|| "Could not rewind file"0 )?0 ; |
282 | | |
283 | | // Note: For unknown reasons we appear to be hitting: |
284 | | // https://github.com/rust-lang/rust/issues/92096 |
285 | | // or a smiliar issue if we try to use the non-store driver function, so we |
286 | | // are using the store driver function here. |
287 | 2 | cas_store |
288 | 2 | .as_store_driver_pin() |
289 | 2 | .update_with_whole_file( |
290 | 2 | digest.into(), |
291 | 2 | resumeable_file, |
292 | 2 | UploadSizeInfo::ExactSize(digest.size_bytes()), |
293 | 2 | ) |
294 | 2 | .await |
295 | 2 | .err_tip(|| format!("for {full_path:?}")0 )?0 ; |
296 | | |
297 | 2 | let name = full_path |
298 | 2 | .as_ref() |
299 | 2 | .file_name() |
300 | 2 | .err_tip(|| format!("Expected file_name to exist on {full_path:?}")0 )?0 |
301 | 2 | .to_str() |
302 | 2 | .err_tip(|| { |
303 | 0 | make_err!( |
304 | 0 | Code::Internal, |
305 | 0 | "Could not convert {:?} to string", |
306 | 0 | full_path |
307 | 0 | ) |
308 | 2 | })?0 |
309 | 2 | .to_string(); |
310 | 2 | |
311 | 2 | Ok(FileInfo { |
312 | 2 | name_or_path: NameOrPath::Name(name), |
313 | 2 | digest, |
314 | 2 | is_executable, |
315 | 2 | }) |
316 | 2 | } |
317 | | |
318 | 0 | async fn upload_symlink( |
319 | 0 | full_path: impl AsRef<Path> + Debug, |
320 | 0 | full_work_directory_path: impl AsRef<Path>, |
321 | 0 | ) -> Result<SymlinkInfo, Error> { |
322 | 0 | let full_target_path = fs::read_link(full_path.as_ref()) |
323 | 0 | .await |
324 | 0 | .err_tip(|| format!("Could not get read_link path of {full_path:?}"))?; |
325 | | |
326 | | // Detect if our symlink is inside our work directory, if it is find the |
327 | | // relative path otherwise use the absolute path. |
328 | 0 | let target = if full_target_path.starts_with(full_work_directory_path.as_ref()) { Branch (328:21): [Folded - Ignored]
Branch (328:21): [Folded - Ignored]
Branch (328:21): [True: 0, False: 0]
Branch (328:21): [True: 0, False: 0]
|
329 | 0 | let full_target_path = RelativePath::from_path(&full_target_path) |
330 | 0 | .map_err(|v| make_err!(Code::Internal, "Could not convert {} to RelativePath", v))?; |
331 | 0 | RelativePath::from_path(full_work_directory_path.as_ref()) |
332 | 0 | .map_err(|v| make_err!(Code::Internal, "Could not convert {} to RelativePath", v))? |
333 | 0 | .relative(full_target_path) |
334 | 0 | .normalize() |
335 | 0 | .into_string() |
336 | | } else { |
337 | 0 | full_target_path |
338 | 0 | .to_str() |
339 | 0 | .err_tip(|| { |
340 | 0 | make_err!( |
341 | 0 | Code::Internal, |
342 | 0 | "Could not convert '{:?}' to string", |
343 | 0 | full_target_path |
344 | 0 | ) |
345 | 0 | })? |
346 | 0 | .to_string() |
347 | | }; |
348 | | |
349 | 0 | let name = full_path |
350 | 0 | .as_ref() |
351 | 0 | .file_name() |
352 | 0 | .err_tip(|| format!("Expected file_name to exist on {full_path:?}"))? |
353 | 0 | .to_str() |
354 | 0 | .err_tip(|| { |
355 | 0 | make_err!( |
356 | 0 | Code::Internal, |
357 | 0 | "Could not convert {:?} to string", |
358 | 0 | full_path |
359 | 0 | ) |
360 | 0 | })? |
361 | 0 | .to_string(); |
362 | 0 |
|
363 | 0 | Ok(SymlinkInfo { |
364 | 0 | name_or_path: NameOrPath::Name(name), |
365 | 0 | target, |
366 | 0 | }) |
367 | 0 | } |
368 | | |
369 | 0 | fn upload_directory<'a, P: AsRef<Path> + Debug + Send + Sync + Clone + 'a>( |
370 | 0 | cas_store: Pin<&'a impl StoreLike>, |
371 | 0 | full_dir_path: P, |
372 | 0 | full_work_directory: &'a str, |
373 | 0 | hasher: DigestHasherFunc, |
374 | 0 | ) -> BoxFuture<'a, Result<(Directory, VecDeque<ProtoDirectory>), Error>> { |
375 | 0 | Box::pin(async move { |
376 | 0 | let file_futures = FuturesUnordered::new(); |
377 | 0 | let dir_futures = FuturesUnordered::new(); |
378 | 0 | let symlink_futures = FuturesUnordered::new(); |
379 | | { |
380 | 0 | let (_permit, dir_handle) = fs::read_dir(&full_dir_path) |
381 | 0 | .await |
382 | 0 | .err_tip(|| format!("Error reading dir for reading {full_dir_path:?}"))? |
383 | 0 | .into_inner(); |
384 | 0 | let mut dir_stream = ReadDirStream::new(dir_handle); |
385 | | // Note: Try very hard to not leave file descriptors open. Try to keep them as short |
386 | | // lived as possible. This is why we iterate the directory and then build a bunch of |
387 | | // futures with all the work we are wanting to do then execute it. It allows us to |
388 | | // close the directory iterator file descriptor, then open the child files/folders. |
389 | 0 | while let Some(entry_result) = dir_stream.next().await { Branch (389:23): [Folded - Ignored]
Branch (389:23): [Folded - Ignored]
Branch (389:23): [True: 0, False: 0]
Branch (389:23): [True: 0, False: 0]
|
390 | 0 | let entry = entry_result.err_tip(|| "Error while iterating directory")?; |
391 | 0 | let file_type = entry |
392 | 0 | .file_type() |
393 | 0 | .await |
394 | 0 | .err_tip(|| format!("Error running file_type() on {entry:?}"))?; |
395 | 0 | let full_path = full_dir_path.as_ref().join(entry.path()); |
396 | 0 | if file_type.is_dir() { Branch (396:20): [Folded - Ignored]
Branch (396:20): [Folded - Ignored]
Branch (396:20): [True: 0, False: 0]
Branch (396:20): [True: 0, False: 0]
|
397 | 0 | let full_dir_path = full_dir_path.clone(); |
398 | 0 | dir_futures.push( |
399 | 0 | upload_directory(cas_store, full_path.clone(), full_work_directory, hasher) |
400 | 0 | .and_then(|(dir, all_dirs)| async move { |
401 | 0 | let directory_name = full_path |
402 | 0 | .file_name() |
403 | 0 | .err_tip(|| { |
404 | 0 | format!("Expected file_name to exist on {full_dir_path:?}") |
405 | 0 | })? |
406 | 0 | .to_str() |
407 | 0 | .err_tip(|| { |
408 | 0 | make_err!( |
409 | 0 | Code::Internal, |
410 | 0 | "Could not convert {:?} to string", |
411 | 0 | full_dir_path |
412 | 0 | ) |
413 | 0 | })? |
414 | 0 | .to_string(); |
415 | | |
416 | 0 | let digest = serialize_and_upload_message( |
417 | 0 | &dir, |
418 | 0 | cas_store, |
419 | 0 | &mut hasher.hasher(), |
420 | 0 | ) |
421 | 0 | .await |
422 | 0 | .err_tip(|| format!("for {full_path:?}"))?; |
423 | | |
424 | 0 | Result::<(DirectoryNode, VecDeque<Directory>), Error>::Ok(( |
425 | 0 | DirectoryNode { |
426 | 0 | name: directory_name, |
427 | 0 | digest: Some(digest.into()), |
428 | 0 | }, |
429 | 0 | all_dirs, |
430 | 0 | )) |
431 | 0 | }) |
432 | 0 | .boxed(), |
433 | 0 | ); |
434 | 0 | } else if file_type.is_file() { Branch (434:27): [Folded - Ignored]
Branch (434:27): [Folded - Ignored]
Branch (434:27): [True: 0, False: 0]
Branch (434:27): [True: 0, False: 0]
|
435 | 0 | file_futures.push(async move { |
436 | 0 | let metadata = fs::metadata(&full_path) |
437 | 0 | .await |
438 | 0 | .err_tip(|| format!("Could not open file {full_path:?}"))?; |
439 | 0 | upload_file(cas_store, &full_path, hasher, metadata) |
440 | 0 | .map_ok(Into::into) |
441 | 0 | .await |
442 | 0 | }); |
443 | 0 | } else if file_type.is_symlink() { Branch (443:27): [Folded - Ignored]
Branch (443:27): [Folded - Ignored]
Branch (443:27): [True: 0, False: 0]
Branch (443:27): [True: 0, False: 0]
|
444 | 0 | symlink_futures |
445 | 0 | .push(upload_symlink(full_path, &full_work_directory).map_ok(Into::into)); |
446 | 0 | } |
447 | | } |
448 | | } |
449 | | |
450 | 0 | let (mut file_nodes, dir_entries, mut symlinks) = try_join3( |
451 | 0 | file_futures.try_collect::<Vec<FileNode>>(), |
452 | 0 | dir_futures.try_collect::<Vec<(DirectoryNode, VecDeque<Directory>)>>(), |
453 | 0 | symlink_futures.try_collect::<Vec<SymlinkNode>>(), |
454 | 0 | ) |
455 | 0 | .await?; |
456 | | |
457 | 0 | let mut directory_nodes = Vec::with_capacity(dir_entries.len()); |
458 | 0 | // For efficiency we use a deque because it allows cheap concat of Vecs. |
459 | 0 | // We make the assumption here that when performance is important it is because |
460 | 0 | // our directory is quite large. This allows us to cheaply merge large amounts of |
461 | 0 | // directories into one VecDeque. Then after we are done we need to collapse it |
462 | 0 | // down into a single Vec. |
463 | 0 | let mut all_child_directories = VecDeque::with_capacity(dir_entries.len()); |
464 | 0 | for (directory_node, mut recursive_child_directories) in dir_entries { |
465 | 0 | directory_nodes.push(directory_node); |
466 | 0 | all_child_directories.append(&mut recursive_child_directories); |
467 | 0 | } |
468 | | |
469 | 0 | file_nodes.sort_unstable_by(|a, b| a.name.cmp(&b.name)); |
470 | 0 | directory_nodes.sort_unstable_by(|a, b| a.name.cmp(&b.name)); |
471 | 0 | symlinks.sort_unstable_by(|a, b| a.name.cmp(&b.name)); |
472 | 0 |
|
473 | 0 | let directory = Directory { |
474 | 0 | files: file_nodes, |
475 | 0 | directories: directory_nodes, |
476 | 0 | symlinks, |
477 | 0 | node_properties: None, // We don't support file properties. |
478 | 0 | }; |
479 | 0 | all_child_directories.push_back(directory.clone()); |
480 | 0 |
|
481 | 0 | Ok((directory, all_child_directories)) |
482 | 0 | }) |
483 | 0 | } |
484 | | |
485 | 0 | async fn process_side_channel_file( |
486 | 0 | side_channel_file: Cow<'_, OsStr>, |
487 | 0 | args: &[&OsStr], |
488 | 0 | timeout: Duration, |
489 | 0 | ) -> Result<Option<Error>, Error> { |
490 | 0 | let mut json_contents = String::new(); |
491 | | { |
492 | | // Note: Scoping `file_slot` allows the file_slot semaphore to be released faster. |
493 | 0 | let mut file_slot = match fs::open_file(side_channel_file, u64::MAX).await { |
494 | 0 | Ok(file_slot) => file_slot, |
495 | 0 | Err(e) => { |
496 | 0 | if e.code != Code::NotFound { Branch (496:20): [Folded - Ignored]
Branch (496:20): [Folded - Ignored]
Branch (496:20): [True: 0, False: 0]
|
497 | 0 | return Err(e).err_tip(|| "Error opening side channel file"); |
498 | 0 | } |
499 | 0 | // Note: If file does not exist, it's ok. Users are not required to create this file. |
500 | 0 | return Ok(None); |
501 | | } |
502 | | }; |
503 | 0 | let reader = file_slot |
504 | 0 | .as_reader() |
505 | 0 | .await |
506 | 0 | .err_tip(|| "Error getting reader from side channel file (maybe permissions?)")?; |
507 | 0 | reader |
508 | 0 | .read_to_string(&mut json_contents) |
509 | 0 | .await |
510 | 0 | .err_tip(|| "Error reading side channel file")?; |
511 | | } |
512 | | |
513 | 0 | let side_channel_info: SideChannelInfo = |
514 | 0 | serde_json5::from_str(&json_contents).map_err(|e| { |
515 | 0 | make_input_err!( |
516 | 0 | "Could not convert contents of side channel file (json) to SideChannelInfo : {e:?}" |
517 | 0 | ) |
518 | 0 | })?; |
519 | 0 | Ok(side_channel_info.failure.map(|failure| match failure { |
520 | 0 | SideChannelFailureReason::timeout => Error::new( |
521 | 0 | Code::DeadlineExceeded, |
522 | 0 | format!( |
523 | 0 | "Command '{}' timed out after {} seconds", |
524 | 0 | args.join(OsStr::new(" ")).to_string_lossy(), |
525 | 0 | timeout.as_secs_f32() |
526 | 0 | ), |
527 | 0 | ), |
528 | 0 | })) |
529 | 0 | } |
530 | | |
531 | 7 | async fn do_cleanup( |
532 | 7 | running_actions_manager: &RunningActionsManagerImpl, |
533 | 7 | operation_id: &OperationId, |
534 | 7 | action_directory: &str, |
535 | 7 | ) -> Result<(), Error> { |
536 | 7 | event!(Level::INFO, "Worker cleaning up"0 ); |
537 | | // Note: We need to be careful to keep trying to cleanup even if one of the steps fails. |
538 | 7 | let remove_dir_result = fs::remove_dir_all(action_directory) |
539 | 7 | .await |
540 | 7 | .err_tip(|| format!("Could not remove working directory {action_directory}")0 ); |
541 | 7 | if let Err(err0 ) = running_actions_manager.cleanup_action(operation_id) { Branch (541:12): [True: 0, False: 0]
Branch (541:12): [Folded - Ignored]
Branch (541:12): [True: 0, False: 7]
|
542 | 0 | event!( |
543 | 0 | Level::ERROR, |
544 | | ?operation_id, |
545 | | ?err, |
546 | 0 | "Error cleaning up action" |
547 | | ); |
548 | 0 | return Result::<(), Error>::Err(err).merge(remove_dir_result); |
549 | 7 | } |
550 | 7 | if let Err(err0 ) = remove_dir_result { Branch (550:12): [True: 0, False: 0]
Branch (550:12): [Folded - Ignored]
Branch (550:12): [True: 0, False: 7]
|
551 | 0 | event!( |
552 | 0 | Level::ERROR, |
553 | | ?operation_id, |
554 | | ?err, |
555 | 0 | "Error removing working directory" |
556 | | ); |
557 | 0 | return Err(err); |
558 | 7 | } |
559 | 7 | Ok(()) |
560 | 7 | } |
561 | | |
562 | | pub trait RunningAction: Sync + Send + Sized + Unpin + 'static { |
563 | | /// Returns the action id of the action. |
564 | | fn get_operation_id(&self) -> &OperationId; |
565 | | |
566 | | /// Anything that needs to execute before the actions is actually executed should happen here. |
567 | | fn prepare_action(self: Arc<Self>) -> impl Future<Output = Result<Arc<Self>, Error>> + Send; |
568 | | |
569 | | /// Actually perform the execution of the action. |
570 | | fn execute(self: Arc<Self>) -> impl Future<Output = Result<Arc<Self>, Error>> + Send; |
571 | | |
572 | | /// Any uploading, processing or analyzing of the results should happen here. |
573 | | fn upload_results(self: Arc<Self>) -> impl Future<Output = Result<Arc<Self>, Error>> + Send; |
574 | | |
575 | | /// Cleanup any residual files, handles or other junk resulting from running the action. |
576 | | fn cleanup(self: Arc<Self>) -> impl Future<Output = Result<Arc<Self>, Error>> + Send; |
577 | | |
578 | | /// Returns the final result. As a general rule this action should be thought of as |
579 | | /// a consumption of `self`, meaning once a return happens here the lifetime of `Self` |
580 | | /// is over and any action performed on it after this call is undefined behavior. |
581 | | fn get_finished_result( |
582 | | self: Arc<Self>, |
583 | | ) -> impl Future<Output = Result<ActionResult, Error>> + Send; |
584 | | |
585 | | /// Returns the work directory of the action. |
586 | | fn get_work_directory(&self) -> &String; |
587 | | } |
588 | | |
589 | | struct RunningActionImplExecutionResult { |
590 | | stdout: Bytes, |
591 | | stderr: Bytes, |
592 | | exit_code: i32, |
593 | | } |
594 | | |
595 | | struct RunningActionImplState { |
596 | | command_proto: Option<ProtoCommand>, |
597 | | // TODO(allada) Kill is not implemented yet, but is instrumented. |
598 | | // However, it is used if the worker disconnects to destroy current jobs. |
599 | | kill_channel_tx: Option<oneshot::Sender<()>>, |
600 | | kill_channel_rx: Option<oneshot::Receiver<()>>, |
601 | | execution_result: Option<RunningActionImplExecutionResult>, |
602 | | action_result: Option<ActionResult>, |
603 | | execution_metadata: ExecutionMetadata, |
604 | | // If there was an internal error, this will be set. |
605 | | // This should NOT be set if everything was fine, but the process had a |
606 | | // non-zero exit code. Instead this should be used for internal errors |
607 | | // that prevented the action from running, upload failures, timeouts, exc... |
608 | | // but we have (or could have) the action results (like stderr/stdout). |
609 | | error: Option<Error>, |
610 | | } |
611 | | |
612 | | pub struct RunningActionImpl { |
613 | | operation_id: OperationId, |
614 | | action_directory: String, |
615 | | work_directory: String, |
616 | | action_info: ActionInfo, |
617 | | timeout: Duration, |
618 | | running_actions_manager: Arc<RunningActionsManagerImpl>, |
619 | | state: Mutex<RunningActionImplState>, |
620 | | did_cleanup: AtomicBool, |
621 | | } |
622 | | |
623 | | impl RunningActionImpl { |
624 | 7 | fn new( |
625 | 7 | execution_metadata: ExecutionMetadata, |
626 | 7 | operation_id: OperationId, |
627 | 7 | action_directory: String, |
628 | 7 | action_info: ActionInfo, |
629 | 7 | timeout: Duration, |
630 | 7 | running_actions_manager: Arc<RunningActionsManagerImpl>, |
631 | 7 | ) -> Self { |
632 | 7 | let work_directory = format!("{}/{}", action_directory, "work"); |
633 | 7 | let (kill_channel_tx, kill_channel_rx) = oneshot::channel(); |
634 | 7 | Self { |
635 | 7 | operation_id, |
636 | 7 | action_directory, |
637 | 7 | work_directory, |
638 | 7 | action_info, |
639 | 7 | timeout, |
640 | 7 | running_actions_manager, |
641 | 7 | state: Mutex::new(RunningActionImplState { |
642 | 7 | command_proto: None, |
643 | 7 | kill_channel_rx: Some(kill_channel_rx), |
644 | 7 | kill_channel_tx: Some(kill_channel_tx), |
645 | 7 | execution_result: None, |
646 | 7 | action_result: None, |
647 | 7 | execution_metadata, |
648 | 7 | error: None, |
649 | 7 | }), |
650 | 7 | did_cleanup: AtomicBool::new(false), |
651 | 7 | } |
652 | 7 | } |
653 | | |
654 | 0 | fn metrics(&self) -> &Arc<Metrics> { |
655 | 0 | &self.running_actions_manager.metrics |
656 | 0 | } |
657 | | |
658 | | /// Prepares any actions needed to execution this action. This action will do the following: |
659 | | /// |
660 | | /// * Download any files needed to execute the action |
661 | | /// * Build a folder with all files needed to execute the action. |
662 | | /// |
663 | | /// This function will aggressively download and spawn potentially thousands of futures. It is |
664 | | /// up to the stores to rate limit if needed. |
665 | 7 | async fn inner_prepare_action(self: Arc<Self>) -> Result<Arc<Self>, Error> { |
666 | 7 | { |
667 | 7 | let mut state = self.state.lock(); |
668 | 7 | state.execution_metadata.input_fetch_start_timestamp = |
669 | 7 | (self.running_actions_manager.callbacks.now_fn)(); |
670 | 7 | } |
671 | 7 | let command = { |
672 | | // Download and build out our input files/folders. Also fetch and decode our Command. |
673 | 7 | let command_fut = self.metrics().get_proto_command_from_store.wrap(async { |
674 | 7 | get_and_decode_digest::<ProtoCommand>( |
675 | 7 | self.running_actions_manager.cas_store.as_ref(), |
676 | 7 | self.action_info.command_digest.into(), |
677 | 7 | ) |
678 | 7 | .await |
679 | 7 | .err_tip(|| "Converting command_digest to Command"0 ) |
680 | 7 | }); |
681 | 7 | let filesystem_store_pin = |
682 | 7 | Pin::new(self.running_actions_manager.filesystem_store.as_ref()); |
683 | 7 | let (command, ()) = try_join(command_fut, async { |
684 | 7 | fs::create_dir(&self.work_directory) |
685 | 7 | .await |
686 | 7 | .err_tip(|| format!("Error creating work directory {}", self.work_directory)0 )?0 ; |
687 | | // Download the input files/folder and place them into the temp directory. |
688 | 7 | self.metrics() |
689 | 7 | .download_to_directory |
690 | 7 | .wrap(download_to_directory( |
691 | 7 | &self.running_actions_manager.cas_store, |
692 | 7 | filesystem_store_pin, |
693 | 7 | &self.action_info.input_root_digest, |
694 | 7 | &self.work_directory, |
695 | 7 | )) |
696 | 7 | .await |
697 | 7 | }) |
698 | 7 | .await?0 ; |
699 | 7 | command |
700 | 7 | }; |
701 | 7 | { |
702 | 7 | // Create all directories needed for our output paths. This is required by the bazel spec. |
703 | 7 | let prepare_output_directories = |output_file| {4 |
704 | 4 | let full_output_path = if command.working_directory.is_empty() { Branch (704:43): [Folded - Ignored]
Branch (704:43): [Folded - Ignored]
Branch (704:43): [True: 1, False: 3]
|
705 | 1 | format!("{}/{}", self.work_directory, output_file) |
706 | | } else { |
707 | 3 | format!( |
708 | 3 | "{}/{}/{}", |
709 | 3 | self.work_directory, command.working_directory, output_file |
710 | 3 | ) |
711 | | }; |
712 | 4 | async move { |
713 | 4 | let full_parent_path = Path::new(&full_output_path) |
714 | 4 | .parent() |
715 | 4 | .err_tip(|| format!("Parent path for {full_output_path} has no parent")0 )?0 ; |
716 | 4 | fs::create_dir_all(full_parent_path).await.err_tip(|| { |
717 | 0 | format!( |
718 | 0 | "Error creating output directory {} (file)", |
719 | 0 | full_parent_path.display() |
720 | 0 | ) |
721 | 4 | })?0 ; |
722 | 4 | Result::<(), Error>::Ok(()) |
723 | 4 | } |
724 | 4 | }; |
725 | 7 | self.metrics() |
726 | 7 | .prepare_output_files |
727 | 7 | .wrap(try_join_all( |
728 | 7 | command.output_files.iter().map(prepare_output_directories), |
729 | 7 | )) |
730 | 7 | .await?0 ; |
731 | 7 | self.metrics() |
732 | 7 | .prepare_output_paths |
733 | 7 | .wrap(try_join_all( |
734 | 7 | command.output_paths.iter().map(prepare_output_directories), |
735 | 7 | )) |
736 | 7 | .await?0 ; |
737 | | } |
738 | 7 | event!(Level::INFO, ?command, "Worker received command"0 ,); |
739 | 7 | { |
740 | 7 | let mut state = self.state.lock(); |
741 | 7 | state.command_proto = Some(command); |
742 | 7 | state.execution_metadata.input_fetch_completed_timestamp = |
743 | 7 | (self.running_actions_manager.callbacks.now_fn)(); |
744 | 7 | } |
745 | 7 | Ok(self) |
746 | 7 | } |
747 | | |
748 | 5 | async fn inner_execute(self: Arc<Self>) -> Result<Arc<Self>, Error> 0 { |
749 | 5 | let (command_proto, mut kill_channel_rx) = { |
750 | 5 | let mut state = self.state.lock(); |
751 | 5 | state.execution_metadata.execution_start_timestamp = |
752 | 5 | (self.running_actions_manager.callbacks.now_fn)(); |
753 | 5 | ( |
754 | 5 | state |
755 | 5 | .command_proto |
756 | 5 | .take() |
757 | 5 | .err_tip(|| "Expected state to have command_proto in execute()"0 )?0 , |
758 | 5 | state |
759 | 5 | .kill_channel_rx |
760 | 5 | .take() |
761 | 5 | .err_tip(|| "Expected state to have kill_channel_rx in execute()"0 )?0 |
762 | | // This is important as we may be killed at any point. |
763 | 5 | .fuse(), |
764 | 5 | ) |
765 | 5 | }; |
766 | 5 | if command_proto.arguments.is_empty() { Branch (766:12): [Folded - Ignored]
Branch (766:12): [Folded - Ignored]
Branch (766:12): [True: 0, False: 5]
|
767 | 0 | return Err(make_input_err!("No arguments provided in Command proto")); |
768 | 5 | } |
769 | 5 | let args: Vec<&OsStr> = if let Some(entrypoint0 ) = &self Branch (769:40): [Folded - Ignored]
Branch (769:40): [Folded - Ignored]
Branch (769:40): [True: 0, False: 5]
|
770 | 5 | .running_actions_manager |
771 | 5 | .execution_configuration |
772 | 5 | .entrypoint |
773 | | { |
774 | 0 | std::iter::once(entrypoint.as_ref()) |
775 | 0 | .chain(command_proto.arguments.iter().map(AsRef::as_ref)) |
776 | 0 | .collect() |
777 | | } else { |
778 | 5 | command_proto.arguments.iter().map(AsRef::as_ref).collect() |
779 | | }; |
780 | 5 | event!(Level::INFO, ?args, "Executing command"0 ,); |
781 | 5 | let mut command_builder = process::Command::new(args[0]); |
782 | 5 | command_builder |
783 | 5 | .args(&args[1..]) |
784 | 5 | .kill_on_drop(true) |
785 | 5 | .stdin(Stdio::null()) |
786 | 5 | .stdout(Stdio::piped()) |
787 | 5 | .stderr(Stdio::piped()) |
788 | 5 | .current_dir(format!( |
789 | 5 | "{}/{}", |
790 | 5 | self.work_directory, command_proto.working_directory |
791 | 5 | )) |
792 | 5 | .env_clear(); |
793 | | |
794 | 5 | let requested_timeout = if self.action_info.timeout.is_zero() { Branch (794:36): [Folded - Ignored]
Branch (794:36): [Folded - Ignored]
Branch (794:36): [True: 5, False: 0]
|
795 | 5 | self.running_actions_manager.max_action_timeout |
796 | | } else { |
797 | 0 | self.action_info.timeout |
798 | | }; |
799 | | |
800 | 5 | let mut maybe_side_channel_file: Option<Cow<'_, OsStr>> = None; |
801 | 5 | if let Some(additional_environment0 ) = &self Branch (801:16): [Folded - Ignored]
Branch (801:16): [Folded - Ignored]
Branch (801:16): [True: 0, False: 5]
|
802 | 5 | .running_actions_manager |
803 | 5 | .execution_configuration |
804 | 5 | .additional_environment |
805 | | { |
806 | 0 | for (name, source) in additional_environment { |
807 | 0 | let value = match source { |
808 | 0 | EnvironmentSource::property(property) => self |
809 | 0 | .action_info |
810 | 0 | .platform_properties |
811 | 0 | .get(property) |
812 | 0 | .map_or_else(|| Cow::Borrowed(""), |v| Cow::Borrowed(v.as_str())), |
813 | 0 | EnvironmentSource::value(value) => Cow::Borrowed(value.as_str()), |
814 | | EnvironmentSource::timeout_millis => { |
815 | 0 | Cow::Owned(requested_timeout.as_millis().to_string()) |
816 | | } |
817 | | EnvironmentSource::side_channel_file => { |
818 | 0 | let file_cow = |
819 | 0 | format!("{}/{}", self.action_directory, Uuid::new_v4().simple()); |
820 | 0 | maybe_side_channel_file = Some(Cow::Owned(file_cow.clone().into())); |
821 | 0 | Cow::Owned(file_cow) |
822 | | } |
823 | | EnvironmentSource::action_directory => { |
824 | 0 | Cow::Borrowed(self.action_directory.as_str()) |
825 | | } |
826 | | }; |
827 | 0 | command_builder.env(name, value.as_ref()); |
828 | | } |
829 | 5 | } |
830 | | |
831 | | #[cfg(target_family = "unix")] |
832 | 5 | let envs = &command_proto.environment_variables; |
833 | | // If SystemRoot is not set on windows we set it to default. Failing to do |
834 | | // this causes all commands to fail. |
835 | | #[cfg(target_family = "windows")] |
836 | | let envs = { |
837 | | let mut envs = command_proto.environment_variables.clone(); |
838 | | if !envs.iter().any(|v| v.name.to_uppercase() == "SYSTEMROOT") { |
839 | | envs.push( |
840 | | nativelink_proto::build::bazel::remote::execution::v2::command::EnvironmentVariable { |
841 | | name: "SystemRoot".to_string(), |
842 | | value: "C:\\Windows".to_string(), |
843 | | }, |
844 | | ); |
845 | | } |
846 | | if !envs.iter().any(|v| v.name.to_uppercase() == "PATH") { |
847 | | envs.push( |
848 | | nativelink_proto::build::bazel::remote::execution::v2::command::EnvironmentVariable { |
849 | | name: "PATH".to_string(), |
850 | | value: "C:\\Windows\\System32".to_string(), |
851 | | }, |
852 | | ); |
853 | | } |
854 | | envs |
855 | | }; |
856 | 6 | for environment_variable1 in envs { |
857 | 1 | command_builder.env(&environment_variable.name, &environment_variable.value); |
858 | 1 | } |
859 | | |
860 | 5 | let mut child_process = command_builder |
861 | 5 | .spawn() |
862 | 5 | .err_tip(|| format!("Could not execute command {args:?}")0 )?0 ; |
863 | 5 | let mut stdout_reader = child_process |
864 | 5 | .stdout |
865 | 5 | .take() |
866 | 5 | .err_tip(|| "Expected stdout to exist on command this should never happen"0 )?0 ; |
867 | 5 | let mut stderr_reader = child_process |
868 | 5 | .stderr |
869 | 5 | .take() |
870 | 5 | .err_tip(|| "Expected stderr to exist on command this should never happen"0 )?0 ; |
871 | | |
872 | 5 | let mut child_process_guard = guard(child_process, |mut child_process| { |
873 | 0 | event!( |
874 | 0 | Level::ERROR, |
875 | 0 | "Child process was not cleaned up before dropping the call to execute(), killing in background spawn." |
876 | | ); |
877 | 0 | background_spawn!("running_actions_manager_kill_child_process", async move { |
878 | 0 | child_process.kill().await |
879 | 0 | }); |
880 | 5 | }0 ); |
881 | | |
882 | 5 | let all_stdout_fut = spawn!("stdout_reader", async move { |
883 | 5 | let mut all_stdout = BytesMut::new(); |
884 | | loop { |
885 | 7 | let sz6 = stdout_reader |
886 | 7 | .read_buf(&mut all_stdout) |
887 | 7 | .await |
888 | 6 | .err_tip(|| "Error reading stdout stream"0 )?0 ; |
889 | 6 | if sz == 0 { Branch (889:20): [Folded - Ignored]
Branch (889:20): [Folded - Ignored]
Branch (889:20): [True: 4, False: 2]
|
890 | 4 | break; // EOF. |
891 | 2 | } |
892 | | } |
893 | 4 | Result::<Bytes, Error>::Ok(all_stdout.freeze()) |
894 | 5 | }4 ); |
895 | 5 | let all_stderr_fut = spawn!("stderr_reader", async move { |
896 | 5 | let mut all_stderr = BytesMut::new(); |
897 | | loop { |
898 | 7 | let sz6 = stderr_reader |
899 | 7 | .read_buf(&mut all_stderr) |
900 | 7 | .await |
901 | 6 | .err_tip(|| "Error reading stderr stream"0 )?0 ; |
902 | 6 | if sz == 0 { Branch (902:20): [Folded - Ignored]
Branch (902:20): [Folded - Ignored]
Branch (902:20): [True: 4, False: 2]
|
903 | 4 | break; // EOF. |
904 | 2 | } |
905 | | } |
906 | 4 | Result::<Bytes, Error>::Ok(all_stderr.freeze()) |
907 | 5 | }4 ); |
908 | 5 | let mut killed_action = false; |
909 | 5 | |
910 | 5 | let timer = self.metrics().child_process.begin_timer(); |
911 | 5 | let mut sleep_fut = (self.running_actions_manager.callbacks.sleep_fn)(self.timeout).fuse(); |
912 | | loop { |
913 | 6 | tokio::select! { |
914 | 6 | () = &mut sleep_fut => { |
915 | 1 | self.running_actions_manager.metrics.task_timeouts.inc(); |
916 | 1 | killed_action = true; |
917 | 1 | if let Err(err0 ) = child_process_guard.start_kill() { Branch (917:28): [Folded - Ignored]
Branch (917:28): [Folded - Ignored]
Branch (917:28): [True: 0, False: 1]
|
918 | 0 | event!( |
919 | 0 | Level::ERROR, |
920 | | ?err, |
921 | 0 | "Could not kill process in RunningActionsManager for action timeout", |
922 | | ); |
923 | 1 | } |
924 | 1 | { |
925 | 1 | let mut state = self.state.lock(); |
926 | 1 | state.error = Error::merge_option(state.error.take(), Some(Error::new( |
927 | 1 | Code::DeadlineExceeded, |
928 | 1 | format!( |
929 | 1 | "Command '{}' timed out after {} seconds", |
930 | 1 | args.join(OsStr::new(" ")).to_string_lossy(), |
931 | 1 | self.action_info.timeout.as_secs_f32() |
932 | 1 | ) |
933 | 1 | ))); |
934 | 1 | } |
935 | | }, |
936 | 6 | maybe_exit_status5 = child_process_guard.wait() => { |
937 | | // Defuse our guard so it does not try to cleanup and make nessless logs. |
938 | 5 | drop(ScopeGuard::<_, _>::into_inner(child_process_guard)); |
939 | 5 | let exit_status = maybe_exit_status.err_tip(|| "Failed to collect exit code of process"0 )?0 ; |
940 | | // TODO(allada) We should implement stderr/stdout streaming to client here. |
941 | | // If we get killed before the stream is started, then these will lock up. |
942 | | // TODO(allada) There is a significant bug here. If we kill the action and the action creates |
943 | | // child processes, it can create zombies. See: https://github.com/tracemachina/nativelink/issues/225 |
944 | 5 | let (stdout, stderr) = if killed_action { Branch (944:47): [Folded - Ignored]
Branch (944:47): [Folded - Ignored]
Branch (944:47): [True: 1, False: 4]
|
945 | 1 | drop(timer); |
946 | 1 | (Bytes::new(), Bytes::new()) |
947 | | } else { |
948 | 4 | timer.measure(); |
949 | 4 | let (maybe_all_stdout, maybe_all_stderr) = tokio::join!(all_stdout_fut, all_stderr_fut); |
950 | | ( |
951 | 4 | maybe_all_stdout.err_tip(|| "Internal error reading from stdout of worker task"0 )?0 ?0 , |
952 | 4 | maybe_all_stderr.err_tip(|| "Internal error reading from stderr of worker task"0 )?0 ?0 |
953 | | ) |
954 | | }; |
955 | 5 | let exit_code = if let Some(exit_code4 ) = exit_status.code() { Branch (955:44): [Folded - Ignored]
Branch (955:44): [Folded - Ignored]
Branch (955:44): [True: 4, False: 1]
|
956 | 4 | if exit_code == 0 { Branch (956:28): [Folded - Ignored]
Branch (956:28): [Folded - Ignored]
Branch (956:28): [True: 3, False: 1]
|
957 | 3 | self.metrics().child_process_success_error_code.inc(); |
958 | 3 | } else { |
959 | 1 | self.metrics().child_process_failure_error_code.inc(); |
960 | 1 | } |
961 | 4 | exit_code |
962 | | } else { |
963 | 1 | EXIT_CODE_FOR_SIGNAL |
964 | | }; |
965 | | |
966 | 5 | let maybe_error_override = if let Some(side_channel_file0 ) = maybe_side_channel_file { Branch (966:55): [Folded - Ignored]
Branch (966:55): [Folded - Ignored]
Branch (966:55): [True: 0, False: 5]
|
967 | 0 | process_side_channel_file(side_channel_file.clone(), &args, requested_timeout).await |
968 | 0 | .err_tip(|| format!("Error processing side channel file: {side_channel_file:?}"))? |
969 | | } else { |
970 | 5 | None |
971 | | }; |
972 | 5 | { |
973 | 5 | let mut state = self.state.lock(); |
974 | 5 | state.error = Error::merge_option(state.error.take(), maybe_error_override); |
975 | 5 | |
976 | 5 | state.command_proto = Some(command_proto); |
977 | 5 | state.execution_result = Some(RunningActionImplExecutionResult{ |
978 | 5 | stdout, |
979 | 5 | stderr, |
980 | 5 | exit_code, |
981 | 5 | }); |
982 | 5 | state.execution_metadata.execution_completed_timestamp = (self.running_actions_manager.callbacks.now_fn)(); |
983 | 5 | } |
984 | 5 | return Ok(self); |
985 | | }, |
986 | 6 | _ = &mut kill_channel_rx => { |
987 | 0 | killed_action = true; |
988 | 0 | if let Err(err) = child_process_guard.start_kill() { Branch (988:28): [Folded - Ignored]
Branch (988:28): [Folded - Ignored]
Branch (988:28): [True: 0, False: 0]
|
989 | 0 | event!( |
990 | 0 | Level::ERROR, |
991 | 0 | operation_id = ?self.operation_id, |
992 | 0 | ?err, |
993 | 0 | "Could not kill process", |
994 | | ); |
995 | | } else { |
996 | 0 | event!( |
997 | 0 | Level::ERROR, |
998 | 0 | operation_id = ?self.operation_id, |
999 | 0 | "Could not get child process id, maybe already dead?", |
1000 | | ); |
1001 | | } |
1002 | 0 | { |
1003 | 0 | let mut state = self.state.lock(); |
1004 | 0 | state.error = Error::merge_option(state.error.take(), Some(Error::new( |
1005 | 0 | Code::Aborted, |
1006 | 0 | format!( |
1007 | 0 | "Command '{}' was killed by scheduler", |
1008 | 0 | args.join(OsStr::new(" ")).to_string_lossy() |
1009 | 0 | ) |
1010 | 0 | ))); |
1011 | 0 | } |
1012 | | }, |
1013 | | } |
1014 | | } |
1015 | | // Unreachable. |
1016 | 5 | } |
1017 | | |
1018 | 5 | async fn inner_upload_results(self: Arc<Self>) -> Result<Arc<Self>, Error> { |
1019 | | enum OutputType { |
1020 | | None, |
1021 | | File(FileInfo), |
1022 | | Directory(DirectoryInfo), |
1023 | | FileSymlink(SymlinkInfo), |
1024 | | DirectorySymlink(SymlinkInfo), |
1025 | | } |
1026 | | |
1027 | 5 | event!(Level::INFO, "Worker uploading results"0 ,); |
1028 | 5 | let (mut command_proto, execution_result, mut execution_metadata) = { |
1029 | 5 | let mut state = self.state.lock(); |
1030 | 5 | state.execution_metadata.output_upload_start_timestamp = |
1031 | 5 | (self.running_actions_manager.callbacks.now_fn)(); |
1032 | 5 | ( |
1033 | 5 | state |
1034 | 5 | .command_proto |
1035 | 5 | .take() |
1036 | 5 | .err_tip(|| "Expected state to have command_proto in execute()"0 )?0 , |
1037 | 5 | state |
1038 | 5 | .execution_result |
1039 | 5 | .take() |
1040 | 5 | .err_tip(|| "Execution result does not exist at upload_results stage"0 )?0 , |
1041 | 5 | state.execution_metadata.clone(), |
1042 | 5 | ) |
1043 | 5 | }; |
1044 | 5 | let cas_store = self.running_actions_manager.cas_store.as_ref(); |
1045 | 5 | let hasher = self.action_info.unique_qualifier.digest_function(); |
1046 | 5 | |
1047 | 5 | let mut output_path_futures = FuturesUnordered::new(); |
1048 | 5 | let mut output_paths = command_proto.output_paths; |
1049 | 5 | if output_paths.is_empty() { Branch (1049:12): [Folded - Ignored]
Branch (1049:12): [Folded - Ignored]
Branch (1049:12): [True: 3, False: 2]
|
1050 | 3 | output_paths |
1051 | 3 | .reserve(command_proto.output_files.len() + command_proto.output_directories.len()); |
1052 | 3 | output_paths.append(&mut command_proto.output_files); |
1053 | 3 | output_paths.append(&mut command_proto.output_directories); |
1054 | 3 | }2 |
1055 | 7 | for entry2 in output_paths { |
1056 | 2 | let full_path = OsString::from(if command_proto.working_directory.is_empty() { Branch (1056:47): [Folded - Ignored]
Branch (1056:47): [Folded - Ignored]
Branch (1056:47): [True: 0, False: 2]
|
1057 | 0 | format!("{}/{}", self.work_directory, entry) |
1058 | | } else { |
1059 | 2 | format!( |
1060 | 2 | "{}/{}/{}", |
1061 | 2 | self.work_directory, command_proto.working_directory, entry |
1062 | 2 | ) |
1063 | | }); |
1064 | 2 | let work_directory = &self.work_directory; |
1065 | 2 | output_path_futures.push(async move { |
1066 | 0 | let metadata = { |
1067 | 2 | let metadata = match fs::symlink_metadata(&full_path).await { |
1068 | 2 | Ok(file) => file, |
1069 | 0 | Err(e) => { |
1070 | 0 | if e.code == Code::NotFound { Branch (1070:32): [Folded - Ignored]
Branch (1070:32): [Folded - Ignored]
Branch (1070:32): [True: 0, False: 0]
|
1071 | | // In the event our output does not exist, according to the bazel remote |
1072 | | // execution spec, we simply ignore it continue. |
1073 | 0 | return Result::<OutputType, Error>::Ok(OutputType::None); |
1074 | 0 | } |
1075 | 0 | return Err(e).err_tip(|| format!("Could not open file {full_path:?}")); |
1076 | | } |
1077 | | }; |
1078 | | |
1079 | 2 | if metadata.is_file() { Branch (1079:24): [Folded - Ignored]
Branch (1079:24): [Folded - Ignored]
Branch (1079:24): [True: 2, False: 0]
|
1080 | | return Ok(OutputType::File( |
1081 | 2 | upload_file(cas_store.as_pin(), &full_path, hasher, metadata) |
1082 | 2 | .await |
1083 | 2 | .map(|mut file_info| { |
1084 | 2 | file_info.name_or_path = NameOrPath::Path(entry); |
1085 | 2 | file_info |
1086 | 2 | }) |
1087 | 2 | .err_tip(|| format!("Uploading file {full_path:?}")0 )?0 , |
1088 | | )); |
1089 | 0 | } |
1090 | 0 | metadata |
1091 | 0 | }; |
1092 | 0 | if metadata.is_dir() { Branch (1092:20): [Folded - Ignored]
Branch (1092:20): [Folded - Ignored]
Branch (1092:20): [True: 0, False: 0]
|
1093 | | Ok(OutputType::Directory( |
1094 | 0 | upload_directory(cas_store.as_pin(), &full_path, work_directory, hasher) |
1095 | 0 | .and_then(|(root_dir, children)| async move { |
1096 | 0 | let tree = ProtoTree { |
1097 | 0 | root: Some(root_dir), |
1098 | 0 | children: children.into(), |
1099 | 0 | }; |
1100 | 0 | let tree_digest = serialize_and_upload_message( |
1101 | 0 | &tree, |
1102 | 0 | cas_store.as_pin(), |
1103 | 0 | &mut hasher.hasher(), |
1104 | 0 | ) |
1105 | 0 | .await |
1106 | 0 | .err_tip(|| format!("While processing {entry}"))?; |
1107 | 0 | Ok(DirectoryInfo { |
1108 | 0 | path: entry, |
1109 | 0 | tree_digest, |
1110 | 0 | }) |
1111 | 0 | }) |
1112 | 0 | .await |
1113 | 0 | .err_tip(|| format!("Uploading directory {full_path:?}"))?, |
1114 | | )) |
1115 | 0 | } else if metadata.is_symlink() { Branch (1115:27): [Folded - Ignored]
Branch (1115:27): [Folded - Ignored]
Branch (1115:27): [True: 0, False: 0]
|
1116 | 0 | let output_symlink = upload_symlink(&full_path, work_directory) |
1117 | 0 | .await |
1118 | 0 | .map(|mut symlink_info| { |
1119 | 0 | symlink_info.name_or_path = NameOrPath::Path(entry); |
1120 | 0 | symlink_info |
1121 | 0 | }) |
1122 | 0 | .err_tip(|| format!("Uploading symlink {full_path:?}"))?; |
1123 | 0 | match fs::metadata(&full_path).await { |
1124 | 0 | Ok(metadata) => { |
1125 | 0 | if metadata.is_dir() { Branch (1125:32): [Folded - Ignored]
Branch (1125:32): [Folded - Ignored]
Branch (1125:32): [True: 0, False: 0]
|
1126 | 0 | return Ok(OutputType::DirectorySymlink(output_symlink)); |
1127 | 0 | } |
1128 | 0 | // Note: If it's anything but directory we put it as a file symlink. |
1129 | 0 | return Ok(OutputType::FileSymlink(output_symlink)); |
1130 | | } |
1131 | 0 | Err(e) => { |
1132 | 0 | if e.code != Code::NotFound { Branch (1132:32): [Folded - Ignored]
Branch (1132:32): [Folded - Ignored]
Branch (1132:32): [True: 0, False: 0]
|
1133 | 0 | return Err(e).err_tip(|| { |
1134 | 0 | format!( |
1135 | 0 | "While querying target symlink metadata for {full_path:?}" |
1136 | 0 | ) |
1137 | 0 | }); |
1138 | 0 | } |
1139 | 0 | // If the file doesn't exist, we consider it a file. Even though the |
1140 | 0 | // file doesn't exist we still need to populate an entry. |
1141 | 0 | return Ok(OutputType::FileSymlink(output_symlink)); |
1142 | | } |
1143 | | } |
1144 | | } else { |
1145 | 0 | Err(make_err!( |
1146 | 0 | Code::Internal, |
1147 | 0 | "{full_path:?} was not a file, folder or symlink. Must be one.", |
1148 | 0 | )) |
1149 | | } |
1150 | 2 | }); |
1151 | 2 | } |
1152 | 5 | let mut output_files = vec![]; |
1153 | 5 | let mut output_folders = vec![]; |
1154 | 5 | let mut output_directory_symlinks = vec![]; |
1155 | 5 | let mut output_file_symlinks = vec![]; |
1156 | 5 | |
1157 | 5 | if execution_result.exit_code != 0 { Branch (1157:12): [Folded - Ignored]
Branch (1157:12): [Folded - Ignored]
Branch (1157:12): [True: 2, False: 3]
|
1158 | | // Don't convert our stdout/stderr to strings unless we are need too. |
1159 | 2 | if enabled!(Level::ERROR) { |
1160 | 2 | let stdout = std::str::from_utf8(&execution_result.stdout).unwrap_or("<no-utf8>"); |
1161 | 2 | let stderr = std::str::from_utf8(&execution_result.stderr).unwrap_or("<no-utf8>"); |
1162 | 2 | event!( |
1163 | 2 | Level::ERROR, |
1164 | | exit_code = ?execution_result.exit_code, |
1165 | 2 | stdout = ?stdout[..min(stdout.len(), 1000)], |
1166 | 2 | stderr = ?stderr[..min(stderr.len(), 1000)], |
1167 | 2 | "Command returned non-zero exit code", |
1168 | | ); |
1169 | 0 | } |
1170 | 3 | } |
1171 | | |
1172 | 5 | let stdout_digest_fut = self.metrics().upload_stdout.wrap(async { |
1173 | 5 | let data = execution_result.stdout; |
1174 | 5 | let digest = compute_buf_digest(&data, &mut hasher.hasher()); |
1175 | 5 | cas_store |
1176 | 5 | .update_oneshot(digest, data) |
1177 | 5 | .await |
1178 | 5 | .err_tip(|| "Uploading stdout"0 )?0 ; |
1179 | 5 | Result::<DigestInfo, Error>::Ok(digest) |
1180 | 5 | }); |
1181 | 5 | let stderr_digest_fut = self.metrics().upload_stderr.wrap(async { |
1182 | 5 | let data = execution_result.stderr; |
1183 | 5 | let digest = compute_buf_digest(&data, &mut hasher.hasher()); |
1184 | 5 | cas_store |
1185 | 5 | .update_oneshot(digest, data) |
1186 | 5 | .await |
1187 | 5 | .err_tip(|| "Uploading stdout"0 )?0 ; |
1188 | 5 | Result::<DigestInfo, Error>::Ok(digest) |
1189 | 5 | }); |
1190 | | |
1191 | 5 | let upload_result = futures::try_join!(stdout_digest_fut, stderr_digest_fut, async { |
1192 | 7 | while let Some(output_type2 ) = output_path_futures.try_next().await?0 { Branch (1192:23): [Folded - Ignored]
Branch (1192:23): [Folded - Ignored]
Branch (1192:23): [True: 2, False: 5]
|
1193 | 2 | match output_type { |
1194 | 2 | OutputType::File(output_file) => output_files.push(output_file), |
1195 | 0 | OutputType::Directory(output_folder) => output_folders.push(output_folder), |
1196 | 0 | OutputType::FileSymlink(output_symlink) => { |
1197 | 0 | output_file_symlinks.push(output_symlink); |
1198 | 0 | } |
1199 | 0 | OutputType::DirectorySymlink(output_symlink) => { |
1200 | 0 | output_directory_symlinks.push(output_symlink); |
1201 | 0 | } |
1202 | 0 | OutputType::None => { /* Safe to ignore */ } |
1203 | | } |
1204 | | } |
1205 | 5 | Ok(()) |
1206 | 5 | }); |
1207 | 5 | drop(output_path_futures); |
1208 | 5 | let (stdout_digest, stderr_digest) = match upload_result { |
1209 | 5 | Ok((stdout_digest, stderr_digest, ())) => (stdout_digest, stderr_digest), |
1210 | 0 | Err(e) => return Err(e).err_tip(|| "Error while uploading results"), |
1211 | | }; |
1212 | | |
1213 | 5 | execution_metadata.output_upload_completed_timestamp = |
1214 | 5 | (self.running_actions_manager.callbacks.now_fn)(); |
1215 | 5 | output_files.sort_unstable_by(|a, b| a.name_or_path.cmp(&b.name_or_path)0 ); |
1216 | 5 | output_folders.sort_unstable_by(|a, b| a.path.cmp(&b.path)0 ); |
1217 | 5 | output_file_symlinks.sort_unstable_by(|a, b| a.name_or_path.cmp(&b.name_or_path)0 ); |
1218 | 5 | output_directory_symlinks.sort_unstable_by(|a, b| a.name_or_path.cmp(&b.name_or_path)0 ); |
1219 | 5 | { |
1220 | 5 | let mut state = self.state.lock(); |
1221 | 5 | execution_metadata.worker_completed_timestamp = |
1222 | 5 | (self.running_actions_manager.callbacks.now_fn)(); |
1223 | 5 | state.action_result = Some(ActionResult { |
1224 | 5 | output_files, |
1225 | 5 | output_folders, |
1226 | 5 | output_directory_symlinks, |
1227 | 5 | output_file_symlinks, |
1228 | 5 | exit_code: execution_result.exit_code, |
1229 | 5 | stdout_digest, |
1230 | 5 | stderr_digest, |
1231 | 5 | execution_metadata, |
1232 | 5 | server_logs: HashMap::default(), // TODO(allada) Not implemented. |
1233 | 5 | error: state.error.clone(), |
1234 | 5 | message: String::new(), // Will be filled in on cache_action_result if needed. |
1235 | 5 | }); |
1236 | 5 | } |
1237 | 5 | Ok(self) |
1238 | 5 | } |
1239 | | |
1240 | 5 | async fn inner_get_finished_result(self: Arc<Self>) -> Result<ActionResult, Error> { |
1241 | 5 | let mut state = self.state.lock(); |
1242 | 5 | state |
1243 | 5 | .action_result |
1244 | 5 | .take() |
1245 | 5 | .err_tip(|| "Expected action_result to exist in get_finished_result"0 ) |
1246 | 5 | } |
1247 | | } |
1248 | | |
1249 | | impl Drop for RunningActionImpl { |
1250 | 7 | fn drop(&mut self) { |
1251 | 7 | if self.did_cleanup.load(Ordering::Acquire) { Branch (1251:12): [True: 7, False: 0]
Branch (1251:12): [Folded - Ignored]
|
1252 | 7 | return; |
1253 | 0 | } |
1254 | 0 | let operation_id = self.operation_id.clone(); |
1255 | 0 | event!( |
1256 | 0 | Level::ERROR, |
1257 | | ?operation_id, |
1258 | 0 | "RunningActionImpl did not cleanup. This is a violation of the requirements, will attempt to do it in the background." |
1259 | | ); |
1260 | 0 | let running_actions_manager = self.running_actions_manager.clone(); |
1261 | 0 | let action_directory = self.action_directory.clone(); |
1262 | 0 | background_spawn!("running_action_impl_drop", async move { |
1263 | 0 | let Err(err) = Branch (1263:17): [True: 0, False: 0]
Branch (1263:17): [Folded - Ignored]
|
1264 | 0 | do_cleanup(&running_actions_manager, &operation_id, &action_directory).await |
1265 | | else { |
1266 | 0 | return; |
1267 | | }; |
1268 | 0 | event!( |
1269 | 0 | Level::ERROR, |
1270 | | ?operation_id, |
1271 | | ?action_directory, |
1272 | | ?err, |
1273 | 0 | "Error cleaning up action" |
1274 | | ); |
1275 | 0 | }); |
1276 | 7 | } |
1277 | | } |
1278 | | |
1279 | | impl RunningAction for RunningActionImpl { |
1280 | 0 | fn get_operation_id(&self) -> &OperationId { |
1281 | 0 | &self.operation_id |
1282 | 0 | } |
1283 | | |
1284 | 7 | async fn prepare_action(self: Arc<Self>) -> Result<Arc<Self>, Error> 0 { |
1285 | 7 | self.metrics() |
1286 | 7 | .clone() |
1287 | 7 | .prepare_action |
1288 | 7 | .wrap(Self::inner_prepare_action(self)) |
1289 | 7 | .await |
1290 | 7 | } |
1291 | | |
1292 | 5 | async fn execute(self: Arc<Self>) -> Result<Arc<Self>, Error> 0 { |
1293 | 5 | self.metrics() |
1294 | 5 | .clone() |
1295 | 5 | .execute |
1296 | 5 | .wrap(Self::inner_execute(self)) |
1297 | 5 | .await |
1298 | 5 | } |
1299 | | |
1300 | 5 | async fn upload_results(self: Arc<Self>) -> Result<Arc<Self>, Error> { |
1301 | 5 | self.metrics() |
1302 | 5 | .clone() |
1303 | 5 | .upload_results |
1304 | 5 | .wrap(Self::inner_upload_results(self)) |
1305 | 5 | .await |
1306 | 5 | } |
1307 | | |
1308 | 7 | async fn cleanup(self: Arc<Self>) -> Result<Arc<Self>, Error> 0 { |
1309 | 7 | self.metrics() |
1310 | 7 | .clone() |
1311 | 7 | .cleanup |
1312 | 7 | .wrap(async move { |
1313 | 7 | let result = do_cleanup( |
1314 | 7 | &self.running_actions_manager, |
1315 | 7 | &self.operation_id, |
1316 | 7 | &self.action_directory, |
1317 | 7 | ) |
1318 | 7 | .await; |
1319 | 7 | self.did_cleanup.store(true, Ordering::Release); |
1320 | 7 | result.map(move |()| self) |
1321 | 7 | }) |
1322 | 7 | .await |
1323 | 7 | } |
1324 | | |
1325 | 5 | async fn get_finished_result(self: Arc<Self>) -> Result<ActionResult, Error> { |
1326 | 5 | self.metrics() |
1327 | 5 | .clone() |
1328 | 5 | .get_finished_result |
1329 | 5 | .wrap(Self::inner_get_finished_result(self)) |
1330 | 5 | .await |
1331 | 5 | } |
1332 | | |
1333 | 2 | fn get_work_directory(&self) -> &String { |
1334 | 2 | &self.work_directory |
1335 | 2 | } |
1336 | | } |
1337 | | |
1338 | | pub trait RunningActionsManager: Sync + Send + Sized + Unpin + 'static { |
1339 | | type RunningAction: RunningAction; |
1340 | | |
1341 | | fn create_and_add_action( |
1342 | | self: &Arc<Self>, |
1343 | | worker_id: String, |
1344 | | start_execute: StartExecute, |
1345 | | ) -> impl Future<Output = Result<Arc<Self::RunningAction>, Error>> + Send; |
1346 | | |
1347 | | fn cache_action_result( |
1348 | | &self, |
1349 | | action_digest: DigestInfo, |
1350 | | action_result: &mut ActionResult, |
1351 | | hasher: DigestHasherFunc, |
1352 | | ) -> impl Future<Output = Result<(), Error>> + Send; |
1353 | | |
1354 | | fn complete_actions(&self, complete_msg: ShutdownGuard) -> impl Future<Output = ()> + Send; |
1355 | | |
1356 | | fn kill_all(&self) -> impl Future<Output = ()> + Send; |
1357 | | |
1358 | | fn kill_operation( |
1359 | | &self, |
1360 | | operation_id: &OperationId, |
1361 | | ) -> impl Future<Output = Result<(), Error>> + Send; |
1362 | | |
1363 | | fn metrics(&self) -> &Arc<Metrics>; |
1364 | | } |
1365 | | |
1366 | | /// A function to get the current system time, used to allow mocking for tests |
1367 | | type NowFn = fn() -> SystemTime; |
1368 | | type SleepFn = fn(Duration) -> BoxFuture<'static, ()>; |
1369 | | |
1370 | | /// Functions that may be injected for testing purposes, during standard control |
1371 | | /// flows these are specified by the new function. |
1372 | | pub struct Callbacks { |
1373 | | /// A function that gets the current time. |
1374 | | pub now_fn: NowFn, |
1375 | | /// A function that sleeps for a given Duration. |
1376 | | pub sleep_fn: SleepFn, |
1377 | | } |
1378 | | |
1379 | | /// The set of additional information for executing an action over and above |
1380 | | /// those given in the `ActionInfo` passed to the worker. This allows |
1381 | | /// modification of the action for execution on this particular worker. This |
1382 | | /// may be used to run the action with a particular set of additional |
1383 | | /// environment variables, or perhaps configure it to execute within a |
1384 | | /// container. |
1385 | | #[derive(Default)] |
1386 | | pub struct ExecutionConfiguration { |
1387 | | /// If set, will be executed instead of the first argument passed in the |
1388 | | /// `ActionInfo` with all of the arguments in the `ActionInfo` passed as |
1389 | | /// arguments to this command. |
1390 | | pub entrypoint: Option<String>, |
1391 | | /// The only environment variables that will be specified when the command |
1392 | | /// executes other than those in the `ActionInfo`. On Windows, `SystemRoot` |
1393 | | /// and PATH are also assigned (see `inner_execute`). |
1394 | | pub additional_environment: Option<HashMap<String, EnvironmentSource>>, |
1395 | | } |
1396 | | |
1397 | | struct UploadActionResults { |
1398 | | upload_ac_results_strategy: UploadCacheResultsStrategy, |
1399 | | upload_historical_results_strategy: UploadCacheResultsStrategy, |
1400 | | ac_store: Option<Store>, |
1401 | | historical_store: Store, |
1402 | | success_message_template: Template, |
1403 | | failure_message_template: Template, |
1404 | | } |
1405 | | |
1406 | | impl UploadActionResults { |
1407 | 15 | fn new( |
1408 | 15 | config: &UploadActionResultConfig, |
1409 | 15 | ac_store: Option<Store>, |
1410 | 15 | historical_store: Store, |
1411 | 15 | ) -> Result<Self, Error> { |
1412 | 15 | let upload_historical_results_strategy = config |
1413 | 15 | .upload_historical_results_strategy |
1414 | 15 | .unwrap_or(DEFAULT_HISTORICAL_RESULTS_STRATEGY); |
1415 | 8 | if !matches!( Branch (1415:12): [True: 8, False: 7]
Branch (1415:12): [Folded - Ignored]
|
1416 | 15 | config.upload_ac_results_strategy, |
1417 | | UploadCacheResultsStrategy::never |
1418 | 8 | ) && ac_store.is_none() Branch (1418:14): [True: 0, False: 8]
Branch (1418:14): [Folded - Ignored]
|
1419 | | { |
1420 | 0 | return Err(make_input_err!( |
1421 | 0 | "upload_ac_results_strategy is set, but no ac_store is configured" |
1422 | 0 | )); |
1423 | 15 | } |
1424 | 15 | Ok(Self { |
1425 | 15 | upload_ac_results_strategy: config.upload_ac_results_strategy, |
1426 | 15 | upload_historical_results_strategy, |
1427 | 15 | ac_store, |
1428 | 15 | historical_store, |
1429 | 15 | success_message_template: Template::new(&config.success_message_template).map_err( |
1430 | 15 | |e| { |
1431 | 0 | make_input_err!( |
1432 | 0 | "Could not convert success_message_template to rust template: {} : {e:?}", |
1433 | 0 | config.success_message_template |
1434 | 0 | ) |
1435 | 15 | }, |
1436 | 15 | )?0 , |
1437 | 15 | failure_message_template: Template::new(&config.failure_message_template).map_err( |
1438 | 15 | |e| { |
1439 | 0 | make_input_err!( |
1440 | 0 | "Could not convert failure_message_template to rust template: {} : {e:?}", |
1441 | 0 | config.success_message_template |
1442 | 0 | ) |
1443 | 15 | }, |
1444 | 15 | )?0 , |
1445 | | }) |
1446 | 15 | } |
1447 | | |
1448 | 0 | fn should_cache_result( |
1449 | 0 | strategy: UploadCacheResultsStrategy, |
1450 | 0 | action_result: &ActionResult, |
1451 | 0 | treat_infra_error_as_failure: bool, |
1452 | 0 | ) -> bool { |
1453 | 0 | let mut did_fail = action_result.exit_code != 0; |
1454 | 0 | if treat_infra_error_as_failure && action_result.error.is_some() { Branch (1454:12): [Folded - Ignored]
Branch (1454:44): [Folded - Ignored]
|
1455 | 0 | did_fail = true; |
1456 | 0 | } |
1457 | 0 | match strategy { |
1458 | 0 | UploadCacheResultsStrategy::success_only => !did_fail, |
1459 | 0 | UploadCacheResultsStrategy::never => false, |
1460 | | // Never cache internal errors or timeouts. |
1461 | | UploadCacheResultsStrategy::everything => { |
1462 | 0 | treat_infra_error_as_failure || action_result.error.is_none() Branch (1462:17): [Folded - Ignored]
|
1463 | | } |
1464 | 0 | UploadCacheResultsStrategy::failures_only => did_fail, |
1465 | | } |
1466 | 0 | } |
1467 | | |
1468 | | /// Formats the message field in `ExecuteResponse` from the `success_message_template` |
1469 | | /// or `failure_message_template` config templates. |
1470 | 5 | fn format_execute_response_message( |
1471 | 5 | mut template_str: Template, |
1472 | 5 | action_digest_info: DigestInfo, |
1473 | 5 | maybe_historical_digest_info: Option<DigestInfo>, |
1474 | 5 | hasher: DigestHasherFunc, |
1475 | 5 | ) -> Result<String, Error> { |
1476 | 5 | template_str.replace( |
1477 | 5 | "digest_function", |
1478 | 5 | hasher.proto_digest_func().as_str_name().to_lowercase(), |
1479 | 5 | ); |
1480 | 5 | template_str.replace( |
1481 | 5 | "action_digest_hash", |
1482 | 5 | action_digest_info.packed_hash().to_string(), |
1483 | 5 | ); |
1484 | 5 | template_str.replace("action_digest_size", action_digest_info.size_bytes()); |
1485 | 5 | if let Some(historical_digest_info3 ) = maybe_historical_digest_info { Branch (1485:16): [True: 3, False: 2]
Branch (1485:16): [Folded - Ignored]
|
1486 | 3 | template_str.replace( |
1487 | 3 | "historical_results_hash", |
1488 | 3 | format!("{}", historical_digest_info.packed_hash()), |
1489 | 3 | ); |
1490 | 3 | template_str.replace( |
1491 | 3 | "historical_results_size", |
1492 | 3 | historical_digest_info.size_bytes(), |
1493 | 3 | ); |
1494 | 3 | } else { |
1495 | 2 | template_str.replace("historical_results_hash", ""); |
1496 | 2 | template_str.replace("historical_results_size", ""); |
1497 | 2 | } |
1498 | 5 | template_str |
1499 | 5 | .text() |
1500 | 5 | .map_err(|e| make_input_err!("Could not convert template to text: {e:?}")0 ) |
1501 | 5 | } |
1502 | | |
1503 | 5 | async fn upload_ac_results( |
1504 | 5 | &self, |
1505 | 5 | action_digest: DigestInfo, |
1506 | 5 | action_result: ProtoActionResult, |
1507 | 5 | hasher: DigestHasherFunc, |
1508 | 5 | ) -> Result<(), Error> { |
1509 | 5 | let Some(ac_store) = self.ac_store.as_ref() else { Branch (1509:13): [Folded - Ignored]
Branch (1509:13): [Folded - Ignored]
Branch (1509:13): [True: 5, False: 0]
|
1510 | 0 | return Ok(()); |
1511 | | }; |
1512 | | // If we are a GrpcStore we shortcut here, as this is a special store. |
1513 | 5 | if let Some(grpc_store0 ) = ac_store.downcast_ref::<GrpcStore>(Some(action_digest.into())) { Branch (1513:16): [Folded - Ignored]
Branch (1513:16): [Folded - Ignored]
Branch (1513:16): [True: 0, False: 5]
|
1514 | 0 | let update_action_request = UpdateActionResultRequest { |
1515 | 0 | // This is populated by `update_action_result`. |
1516 | 0 | instance_name: String::new(), |
1517 | 0 | action_digest: Some(action_digest.into()), |
1518 | 0 | action_result: Some(action_result), |
1519 | 0 | results_cache_policy: None, |
1520 | 0 | digest_function: hasher.proto_digest_func().into(), |
1521 | 0 | }; |
1522 | 0 | return grpc_store |
1523 | 0 | .update_action_result(Request::new(update_action_request)) |
1524 | 0 | .await |
1525 | 0 | .map(|_| ()) |
1526 | 0 | .err_tip(|| "Caching ActionResult"); |
1527 | 5 | } |
1528 | 5 | |
1529 | 5 | let mut store_data = BytesMut::with_capacity(ESTIMATED_DIGEST_SIZE); |
1530 | 5 | action_result |
1531 | 5 | .encode(&mut store_data) |
1532 | 5 | .err_tip(|| "Encoding ActionResult for caching"0 )?0 ; |
1533 | | |
1534 | 5 | ac_store |
1535 | 5 | .update_oneshot(action_digest, store_data.split().freeze()) |
1536 | 5 | .await |
1537 | 5 | .err_tip(|| "Caching ActionResult"0 ) |
1538 | 5 | } |
1539 | | |
1540 | 3 | async fn upload_historical_results_with_message( |
1541 | 3 | &self, |
1542 | 3 | action_digest: DigestInfo, |
1543 | 3 | execute_response: ExecuteResponse, |
1544 | 3 | message_template: Template, |
1545 | 3 | hasher: DigestHasherFunc, |
1546 | 3 | ) -> Result<String, Error> { |
1547 | 3 | let historical_digest_info = serialize_and_upload_message( |
1548 | 3 | &HistoricalExecuteResponse { |
1549 | 3 | action_digest: Some(action_digest.into()), |
1550 | 3 | execute_response: Some(execute_response.clone()), |
1551 | 3 | }, |
1552 | 3 | self.historical_store.as_pin(), |
1553 | 3 | &mut hasher.hasher(), |
1554 | 3 | ) |
1555 | 3 | .await |
1556 | 3 | .err_tip(|| format!("Caching HistoricalExecuteResponse for digest: {action_digest}")0 )?0 ; |
1557 | | |
1558 | 3 | Self::format_execute_response_message( |
1559 | 3 | message_template, |
1560 | 3 | action_digest, |
1561 | 3 | Some(historical_digest_info), |
1562 | 3 | hasher, |
1563 | 3 | ) |
1564 | 3 | .err_tip(|| "Could not format message in upload_historical_results_with_message"0 ) |
1565 | 3 | } |
1566 | | |
1567 | 6 | async fn cache_action_result( |
1568 | 6 | &self, |
1569 | 6 | action_info: DigestInfo, |
1570 | 6 | action_result: &mut ActionResult, |
1571 | 6 | hasher: DigestHasherFunc, |
1572 | 6 | ) -> Result<(), Error> { |
1573 | 6 | let should_upload_historical_results = |
1574 | 6 | Self::should_cache_result(self.upload_historical_results_strategy, action_result, true); |
1575 | 6 | let should_upload_ac_results = |
1576 | 6 | Self::should_cache_result(self.upload_ac_results_strategy, action_result, false); |
1577 | 6 | // Shortcut so we don't need to convert to proto if not needed. |
1578 | 6 | if !should_upload_ac_results && !should_upload_historical_results1 { Branch (1578:12): [Folded - Ignored]
Branch (1578:41): [Folded - Ignored]
Branch (1578:12): [Folded - Ignored]
Branch (1578:41): [Folded - Ignored]
Branch (1578:12): [True: 1, False: 5]
Branch (1578:41): [True: 1, False: 0]
|
1579 | 1 | return Ok(()); |
1580 | 5 | } |
1581 | 5 | |
1582 | 5 | let mut execute_response = to_execute_response(action_result.clone()); |
1583 | | |
1584 | | // In theory exit code should always be != 0 if there's an error, but for safety we |
1585 | | // catch both. |
1586 | 5 | let message_template = if action_result.exit_code == 0 && action_result.error.is_none()4 { Branch (1586:35): [Folded - Ignored]
Branch (1586:67): [Folded - Ignored]
Branch (1586:35): [Folded - Ignored]
Branch (1586:67): [Folded - Ignored]
Branch (1586:35): [True: 4, False: 1]
Branch (1586:67): [True: 3, False: 1]
|
1587 | 3 | self.success_message_template.clone() |
1588 | | } else { |
1589 | 2 | self.failure_message_template.clone() |
1590 | | }; |
1591 | | |
1592 | 5 | let upload_historical_results_with_message_result = if should_upload_historical_results { Branch (1592:64): [Folded - Ignored]
Branch (1592:64): [Folded - Ignored]
Branch (1592:64): [True: 3, False: 2]
|
1593 | 3 | let maybe_message = self |
1594 | 3 | .upload_historical_results_with_message( |
1595 | 3 | action_info, |
1596 | 3 | execute_response.clone(), |
1597 | 3 | message_template, |
1598 | 3 | hasher, |
1599 | 3 | ) |
1600 | 3 | .await; |
1601 | 3 | match maybe_message { |
1602 | 3 | Ok(message) => { |
1603 | 3 | action_result.message.clone_from(&message); |
1604 | 3 | execute_response.message = message; |
1605 | 3 | Ok(()) |
1606 | | } |
1607 | 0 | Err(e) => Result::<(), Error>::Err(e), |
1608 | | } |
1609 | | } else { |
1610 | 2 | match Self::format_execute_response_message(message_template, action_info, None, hasher) |
1611 | | { |
1612 | 2 | Ok(message) => { |
1613 | 2 | action_result.message.clone_from(&message); |
1614 | 2 | execute_response.message = message; |
1615 | 2 | Ok(()) |
1616 | | } |
1617 | 0 | Err(e) => Err(e).err_tip(|| "Could not format message in cache_action_result"), |
1618 | | } |
1619 | | }; |
1620 | | |
1621 | | // Note: Done in this order because we assume most results will succed and most configs will |
1622 | | // either always upload upload historical results or only upload on filure. In which case |
1623 | | // we can avoid an extra clone of the protos by doing this last with the above assumption. |
1624 | 5 | let ac_upload_results = if should_upload_ac_results { Branch (1624:36): [Folded - Ignored]
Branch (1624:36): [Folded - Ignored]
Branch (1624:36): [True: 5, False: 0]
|
1625 | 5 | self.upload_ac_results( |
1626 | 5 | action_info, |
1627 | 5 | execute_response |
1628 | 5 | .result |
1629 | 5 | .err_tip(|| "No result set in cache_action_result"0 )?0 , |
1630 | 5 | hasher, |
1631 | 5 | ) |
1632 | 5 | .await |
1633 | | } else { |
1634 | 0 | Ok(()) |
1635 | | }; |
1636 | 5 | upload_historical_results_with_message_result.merge(ac_upload_results) |
1637 | 6 | } |
1638 | | } |
1639 | | |
1640 | | pub struct RunningActionsManagerArgs<'a> { |
1641 | | pub root_action_directory: String, |
1642 | | pub execution_configuration: ExecutionConfiguration, |
1643 | | pub cas_store: Arc<FastSlowStore>, |
1644 | | pub ac_store: Option<Store>, |
1645 | | pub historical_store: Store, |
1646 | | pub upload_action_result_config: &'a UploadActionResultConfig, |
1647 | | pub max_action_timeout: Duration, |
1648 | | pub timeout_handled_externally: bool, |
1649 | | } |
1650 | | |
1651 | | /// Holds state info about what is being executed and the interface for interacting |
1652 | | /// with actions while they are running. |
1653 | | pub struct RunningActionsManagerImpl { |
1654 | | root_action_directory: String, |
1655 | | execution_configuration: ExecutionConfiguration, |
1656 | | cas_store: Arc<FastSlowStore>, |
1657 | | filesystem_store: Arc<FilesystemStore>, |
1658 | | upload_action_results: UploadActionResults, |
1659 | | max_action_timeout: Duration, |
1660 | | timeout_handled_externally: bool, |
1661 | | running_actions: Mutex<HashMap<OperationId, Weak<RunningActionImpl>>>, |
1662 | | // Note: We don't use Notify because we need to support a .wait_for()-like function, which |
1663 | | // Notify does not support. |
1664 | | action_done_tx: watch::Sender<()>, |
1665 | | callbacks: Callbacks, |
1666 | | metrics: Arc<Metrics>, |
1667 | | } |
1668 | | |
1669 | | impl RunningActionsManagerImpl { |
1670 | 15 | pub fn new_with_callbacks( |
1671 | 15 | args: RunningActionsManagerArgs<'_>, |
1672 | 15 | callbacks: Callbacks, |
1673 | 15 | ) -> Result<Self, Error> { |
1674 | | // Sadly because of some limitations of how Any works we need to clone more times than optimal. |
1675 | 15 | let filesystem_store = args |
1676 | 15 | .cas_store |
1677 | 15 | .fast_store() |
1678 | 15 | .downcast_ref::<FilesystemStore>(None) |
1679 | 15 | .err_tip(|| { |
1680 | 0 | "Expected FilesystemStore store for .fast_store() in RunningActionsManagerImpl" |
1681 | 15 | })?0 |
1682 | 15 | .get_arc() |
1683 | 15 | .err_tip(|| "FilesystemStore's internal Arc was lost"0 )?0 ; |
1684 | 15 | let (action_done_tx, _) = watch::channel(()); |
1685 | 15 | Ok(Self { |
1686 | 15 | root_action_directory: args.root_action_directory, |
1687 | 15 | execution_configuration: args.execution_configuration, |
1688 | 15 | cas_store: args.cas_store, |
1689 | 15 | filesystem_store, |
1690 | 15 | upload_action_results: UploadActionResults::new( |
1691 | 15 | args.upload_action_result_config, |
1692 | 15 | args.ac_store, |
1693 | 15 | args.historical_store, |
1694 | 15 | ) |
1695 | 15 | .err_tip(|| "During RunningActionsManagerImpl construction"0 )?0 , |
1696 | 15 | max_action_timeout: args.max_action_timeout, |
1697 | 15 | timeout_handled_externally: args.timeout_handled_externally, |
1698 | 15 | running_actions: Mutex::new(HashMap::new()), |
1699 | 15 | action_done_tx, |
1700 | 15 | callbacks, |
1701 | 15 | metrics: Arc::new(Metrics::default()), |
1702 | | }) |
1703 | 15 | } |
1704 | | |
1705 | 9 | pub fn new(args: RunningActionsManagerArgs<'_>) -> Result<Self, Error> { |
1706 | 9 | Self::new_with_callbacks( |
1707 | 9 | args, |
1708 | 9 | Callbacks { |
1709 | 9 | now_fn: SystemTime::now, |
1710 | 9 | sleep_fn: |duration| Box::pin(tokio::time::sleep(duration))1 , |
1711 | 9 | }, |
1712 | 9 | ) |
1713 | 9 | } |
1714 | | |
1715 | 0 | fn make_action_directory<'a>( |
1716 | 0 | &'a self, |
1717 | 0 | operation_id: &'a OperationId, |
1718 | 0 | ) -> impl Future<Output = Result<String, Error>> + 'a { |
1719 | 7 | self.metrics.make_action_directory.wrap(async move { |
1720 | 7 | let action_directory = format!("{}/{}", self.root_action_directory, operation_id); |
1721 | 7 | fs::create_dir(&action_directory) |
1722 | 7 | .await |
1723 | 7 | .err_tip(|| format!("Error creating action directory {action_directory}")0 )?0 ; |
1724 | 7 | Ok(action_directory) |
1725 | 7 | }) |
1726 | 0 | } |
1727 | | |
1728 | 7 | fn create_action_info( |
1729 | 7 | &self, |
1730 | 7 | start_execute: StartExecute, |
1731 | 7 | queued_timestamp: SystemTime, |
1732 | 7 | ) -> impl Future<Output = Result<ActionInfo, Error>> + '_ { |
1733 | 7 | self.metrics.create_action_info.wrap(async move { |
1734 | 7 | let execute_request = start_execute |
1735 | 7 | .execute_request |
1736 | 7 | .err_tip(|| "Expected execute_request to exist in StartExecute"0 )?0 ; |
1737 | 7 | let action_digest: DigestInfo = execute_request |
1738 | 7 | .action_digest |
1739 | 7 | .clone() |
1740 | 7 | .err_tip(|| "Expected action_digest to exist on StartExecute"0 )?0 |
1741 | 7 | .try_into()?0 ; |
1742 | 7 | let load_start_timestamp = (self.callbacks.now_fn)(); |
1743 | 7 | let action = |
1744 | 7 | get_and_decode_digest::<Action>(self.cas_store.as_ref(), action_digest.into()) |
1745 | 7 | .await |
1746 | 7 | .err_tip(|| "During start_action"0 )?0 ; |
1747 | 7 | let action_info = ActionInfo::try_from_action_and_execute_request( |
1748 | 7 | execute_request, |
1749 | 7 | action, |
1750 | 7 | load_start_timestamp, |
1751 | 7 | queued_timestamp, |
1752 | 7 | ) |
1753 | 7 | .err_tip(|| "Could not create ActionInfo in create_and_add_action()"0 )?0 ; |
1754 | 7 | Ok(action_info) |
1755 | 7 | }) |
1756 | 7 | } |
1757 | | |
1758 | 7 | fn cleanup_action(&self, operation_id: &OperationId) -> Result<(), Error> { |
1759 | 7 | let mut running_actions = self.running_actions.lock(); |
1760 | 7 | let result = running_actions.remove(operation_id).err_tip(|| { |
1761 | 0 | format!("Expected action id '{operation_id:?}' to exist in RunningActionsManagerImpl") |
1762 | 7 | }); |
1763 | 7 | // No need to copy anything, we just are telling the receivers an event happened. |
1764 | 7 | self.action_done_tx.send_modify(|()| {}); |
1765 | 7 | result.map(|_| ()) |
1766 | 7 | } |
1767 | | |
1768 | | // Note: We do not capture metrics on this call, only `.kill_all()`. |
1769 | | // Important: When the future returns the process may still be running. |
1770 | 0 | async fn kill_operation(action: Arc<RunningActionImpl>) { |
1771 | 0 | event!( |
1772 | 0 | Level::WARN, |
1773 | 0 | operation_id = ?action.operation_id, |
1774 | 0 | "Sending kill to running operation", |
1775 | | ); |
1776 | 0 | let kill_channel_tx = { |
1777 | 0 | let mut action_state = action.state.lock(); |
1778 | 0 | action_state.kill_channel_tx.take() |
1779 | | }; |
1780 | 0 | if let Some(kill_channel_tx) = kill_channel_tx { Branch (1780:16): [Folded - Ignored]
Branch (1780:16): [Folded - Ignored]
Branch (1780:16): [True: 0, False: 0]
|
1781 | 0 | if kill_channel_tx.send(()).is_err() { Branch (1781:16): [Folded - Ignored]
Branch (1781:16): [Folded - Ignored]
Branch (1781:16): [True: 0, False: 0]
|
1782 | 0 | event!( |
1783 | 0 | Level::ERROR, |
1784 | 0 | operation_id = ?action.operation_id, |
1785 | 0 | "Error sending kill to running operation", |
1786 | | ); |
1787 | 0 | } |
1788 | 0 | } |
1789 | 0 | } |
1790 | | } |
1791 | | |
1792 | | impl RunningActionsManager for RunningActionsManagerImpl { |
1793 | | type RunningAction = RunningActionImpl; |
1794 | | |
1795 | 0 | async fn create_and_add_action( |
1796 | 0 | self: &Arc<Self>, |
1797 | 0 | worker_id: String, |
1798 | 0 | start_execute: StartExecute, |
1799 | 7 | ) -> Result<Arc<RunningActionImpl>, Error> { |
1800 | 7 | self.metrics |
1801 | 7 | .create_and_add_action |
1802 | 7 | .wrap(async move { |
1803 | 7 | let queued_timestamp = start_execute |
1804 | 7 | .queued_timestamp |
1805 | 7 | .and_then(|time| time.try_into().ok()3 ) |
1806 | 7 | .unwrap_or(SystemTime::UNIX_EPOCH); |
1807 | 7 | let operation_id = start_execute |
1808 | 7 | .operation_id.as_str().into(); |
1809 | 7 | let action_info = self.create_action_info(start_execute, queued_timestamp).await?0 ; |
1810 | 7 | event!( |
1811 | 7 | Level::INFO, |
1812 | | ?action_info, |
1813 | 0 | "Worker received action", |
1814 | | ); |
1815 | 7 | let action_directory = self.make_action_directory(&operation_id).await?0 ; |
1816 | 7 | let execution_metadata = ExecutionMetadata { |
1817 | 7 | worker: worker_id, |
1818 | 7 | queued_timestamp: action_info.insert_timestamp, |
1819 | 7 | worker_start_timestamp: action_info.load_timestamp, |
1820 | 7 | worker_completed_timestamp: SystemTime::UNIX_EPOCH, |
1821 | 7 | input_fetch_start_timestamp: SystemTime::UNIX_EPOCH, |
1822 | 7 | input_fetch_completed_timestamp: SystemTime::UNIX_EPOCH, |
1823 | 7 | execution_start_timestamp: SystemTime::UNIX_EPOCH, |
1824 | 7 | execution_completed_timestamp: SystemTime::UNIX_EPOCH, |
1825 | 7 | output_upload_start_timestamp: SystemTime::UNIX_EPOCH, |
1826 | 7 | output_upload_completed_timestamp: SystemTime::UNIX_EPOCH, |
1827 | 7 | }; |
1828 | 7 | let timeout = if action_info.timeout.is_zero() || self.timeout_handled_externally0 { Branch (1828:34): [Folded - Ignored]
Branch (1828:67): [Folded - Ignored]
Branch (1828:34): [Folded - Ignored]
Branch (1828:67): [Folded - Ignored]
Branch (1828:34): [True: 7, False: 0]
Branch (1828:67): [True: 0, False: 0]
|
1829 | 7 | self.max_action_timeout |
1830 | | } else { |
1831 | 0 | action_info.timeout |
1832 | | }; |
1833 | 7 | if timeout > self.max_action_timeout { Branch (1833:20): [Folded - Ignored]
Branch (1833:20): [Folded - Ignored]
Branch (1833:20): [True: 0, False: 7]
|
1834 | 0 | return Err(make_err!( |
1835 | 0 | Code::InvalidArgument, |
1836 | 0 | "Action timeout of {} seconds is greater than the maximum allowed timeout of {} seconds", |
1837 | 0 | timeout.as_secs_f32(), |
1838 | 0 | self.max_action_timeout.as_secs_f32() |
1839 | 0 | )); |
1840 | 7 | } |
1841 | 7 | let running_action = Arc::new(RunningActionImpl::new( |
1842 | 7 | execution_metadata, |
1843 | 7 | operation_id.clone(), |
1844 | 7 | action_directory, |
1845 | 7 | action_info, |
1846 | 7 | timeout, |
1847 | 7 | self.clone(), |
1848 | 7 | )); |
1849 | 7 | { |
1850 | 7 | let mut running_actions = self.running_actions.lock(); |
1851 | 7 | running_actions.insert(operation_id, Arc::downgrade(&running_action)); |
1852 | 7 | } |
1853 | 7 | Ok(running_action) |
1854 | 7 | }) |
1855 | 7 | .await |
1856 | 7 | } |
1857 | | |
1858 | 0 | async fn cache_action_result( |
1859 | 0 | &self, |
1860 | 0 | action_info: DigestInfo, |
1861 | 0 | action_result: &mut ActionResult, |
1862 | 0 | hasher: DigestHasherFunc, |
1863 | 6 | ) -> Result<(), Error> { |
1864 | 6 | self.metrics |
1865 | 6 | .cache_action_result |
1866 | 6 | .wrap(self.upload_action_results.cache_action_result( |
1867 | 6 | action_info, |
1868 | 6 | action_result, |
1869 | 6 | hasher, |
1870 | 6 | )) |
1871 | 6 | .await |
1872 | 6 | } |
1873 | | |
1874 | 0 | async fn kill_operation(&self, operation_id: &OperationId) -> Result<(), Error> { |
1875 | 0 | let running_action = { |
1876 | 0 | let running_actions = self.running_actions.lock(); |
1877 | 0 | running_actions |
1878 | 0 | .get(operation_id) |
1879 | 0 | .and_then(Weak::upgrade) |
1880 | 0 | .ok_or_else(|| make_input_err!("Failed to get running action {operation_id}"))? |
1881 | | }; |
1882 | 0 | Self::kill_operation(running_action).await; |
1883 | 0 | Ok(()) |
1884 | 0 | } |
1885 | | |
1886 | | // Waits for all running actions to complete and signals completion. |
1887 | | // Use the ShutdownGuard to signal the completion of the actions |
1888 | | // Dropping the sender automatically notifies the process to terminate. |
1889 | 0 | async fn complete_actions(&self, _complete_msg: ShutdownGuard) { |
1890 | 0 | let _ = self |
1891 | 0 | .action_done_tx |
1892 | 0 | .subscribe() |
1893 | 0 | .wait_for(|()| self.running_actions.lock().is_empty()) |
1894 | 0 | .await; |
1895 | 0 | } |
1896 | | |
1897 | | // Note: When the future returns the process should be fully killed and cleaned up. |
1898 | 0 | async fn kill_all(&self) { |
1899 | 0 | self.metrics |
1900 | 0 | .kill_all |
1901 | 0 | .wrap_no_capture_result(async move { |
1902 | 0 | let kill_operations: Vec<Arc<RunningActionImpl>> = { |
1903 | 0 | let running_actions = self.running_actions.lock(); |
1904 | 0 | running_actions |
1905 | 0 | .iter() |
1906 | 0 | .filter_map(|(_operation_id, action)| action.upgrade()) |
1907 | 0 | .collect() |
1908 | | }; |
1909 | 0 | for action in kill_operations { |
1910 | 0 | Self::kill_operation(action).await; |
1911 | | } |
1912 | 0 | }) |
1913 | 0 | .await; |
1914 | | // Ignore error. If error happens it means there's no sender, which is not a problem. |
1915 | | // Note: Sanity check this API will always check current value then future values: |
1916 | | // https://play.rust-lang.org/?version=stable&edition=2021&gist=23103652cc1276a97e5f9938da87fdb2 |
1917 | 0 | let _ = self |
1918 | 0 | .action_done_tx |
1919 | 0 | .subscribe() |
1920 | 0 | .wait_for(|()| self.running_actions.lock().is_empty()) |
1921 | 0 | .await; |
1922 | 0 | } |
1923 | | |
1924 | | #[inline] |
1925 | 2 | fn metrics(&self) -> &Arc<Metrics> { |
1926 | 2 | &self.metrics |
1927 | 2 | } |
1928 | | } |
1929 | | |
1930 | | #[derive(Default, MetricsComponent)] |
1931 | | pub struct Metrics { |
1932 | | #[metric(help = "Stats about the create_and_add_action command.")] |
1933 | | create_and_add_action: AsyncCounterWrapper, |
1934 | | #[metric(help = "Stats about the cache_action_result command.")] |
1935 | | cache_action_result: AsyncCounterWrapper, |
1936 | | #[metric(help = "Stats about the kill_all command.")] |
1937 | | kill_all: AsyncCounterWrapper, |
1938 | | #[metric(help = "Stats about the create_action_info command.")] |
1939 | | create_action_info: AsyncCounterWrapper, |
1940 | | #[metric(help = "Stats about the make_work_directory command.")] |
1941 | | make_action_directory: AsyncCounterWrapper, |
1942 | | #[metric(help = "Stats about the prepare_action command.")] |
1943 | | prepare_action: AsyncCounterWrapper, |
1944 | | #[metric(help = "Stats about the execute command.")] |
1945 | | execute: AsyncCounterWrapper, |
1946 | | #[metric(help = "Stats about the upload_results command.")] |
1947 | | upload_results: AsyncCounterWrapper, |
1948 | | #[metric(help = "Stats about the cleanup command.")] |
1949 | | cleanup: AsyncCounterWrapper, |
1950 | | #[metric(help = "Stats about the get_finished_result command.")] |
1951 | | get_finished_result: AsyncCounterWrapper, |
1952 | | #[metric(help = "Stats about the get_proto_command_from_store command.")] |
1953 | | get_proto_command_from_store: AsyncCounterWrapper, |
1954 | | #[metric(help = "Stats about the download_to_directory command.")] |
1955 | | download_to_directory: AsyncCounterWrapper, |
1956 | | #[metric(help = "Stats about the prepare_output_files command.")] |
1957 | | prepare_output_files: AsyncCounterWrapper, |
1958 | | #[metric(help = "Stats about the prepare_output_paths command.")] |
1959 | | prepare_output_paths: AsyncCounterWrapper, |
1960 | | #[metric(help = "Stats about the child_process command.")] |
1961 | | child_process: AsyncCounterWrapper, |
1962 | | #[metric(help = "Stats about the child_process_success_error_code command.")] |
1963 | | child_process_success_error_code: CounterWithTime, |
1964 | | #[metric(help = "Stats about the child_process_failure_error_code command.")] |
1965 | | child_process_failure_error_code: CounterWithTime, |
1966 | | #[metric(help = "Total time spent uploading stdout.")] |
1967 | | upload_stdout: AsyncCounterWrapper, |
1968 | | #[metric(help = "Total time spent uploading stderr.")] |
1969 | | upload_stderr: AsyncCounterWrapper, |
1970 | | #[metric(help = "Total number of task timeouts.")] |
1971 | | task_timeouts: CounterWithTime, |
1972 | | } |