Coverage Report

Created: 2025-03-08 07:13

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