blob: 1da95ef71a6b73cebf677566a775bb5d3d3b27c3 [file]
// Copyright 2026 The Fuchsia Authors
//
// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0
// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT
// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option.
// This file may not be copied, modified, or distributed except according to
// those terms.
//! Process-group supervision and log-bundle execution.
use std::{
collections::BTreeMap,
fs::{self, File},
path::Path,
process::{Command, Stdio},
time::Duration,
};
use serde_json::json;
use super::{
Invocation, ProcessOutcome, Termination, ensure_child_subreaper,
files::{path_utf8, reject_symlink_components, write_json, write_regular_file},
reproduce::reproduce_script,
supervise::supervise_child,
};
use crate::TestResult;
/// Supervises isolated process-group invocations with file-backed stdio and
/// deterministic replay bundle generation.
#[derive(Clone, Debug)]
pub struct ProcessSupervisor {
timeout: Duration,
}
impl ProcessSupervisor {
/// Create a supervisor enforcing `timeout` on every invocation.
pub fn new(timeout: Duration) -> TestResult<Self> {
if timeout.is_zero() {
return Err("process timeout must be positive".into());
}
ensure_child_subreaper()?;
Ok(Self { timeout })
}
/// Execute `invocation` with `current_dir = work_dir` and emit
/// `invocation.json`, `outcome.json`, `stdout`, `stderr`, and
/// `reproduce.py`
/// under `log_dir` (which must not already exist).
pub fn run(
&self,
invocation: &Invocation,
work_dir: &Path,
log_dir: &Path,
run_root: &Path,
) -> TestResult<ProcessOutcome> {
self.run_at_depth(invocation, work_dir, log_dir, run_root, 2)
}
pub(crate) fn run_at_depth(
&self,
invocation: &Invocation,
work_dir: &Path,
log_dir: &Path,
run_root: &Path,
parents_depth: usize,
) -> TestResult<ProcessOutcome> {
ensure_child_subreaper()?;
if !invocation.executable.is_absolute() {
return Err(format!(
"tool path must be absolute: {}",
invocation.executable.display()
));
}
reject_symlink_components(log_dir)?;
let parent = log_dir
.parent()
.ok_or_else(|| format!("log directory has no parent: {}", log_dir.display()))?;
fs::create_dir_all(parent)
.map_err(|error| format!("create command log parent: {error}"))?;
fs::create_dir(log_dir)
.map_err(|error| format!("create {}: {error}", log_dir.display()))?;
let exe_str = path_utf8(&invocation.executable, "executable")?;
let work_str = path_utf8(work_dir, "working_directory")?;
let root_str = path_utf8(run_root, "original_run_root")?;
let args_utf8: Vec<&str> = invocation
.arguments
.iter()
.map(|a| {
a.to_str().ok_or_else(|| {
format!("command argument is not valid UTF-8: {a:?}")
})
})
.collect::<TestResult<Vec<_>>>()?;
let mut env_utf8 = BTreeMap::new();
for (k, v) in &invocation.environment {
let ks = k
.to_str()
.ok_or_else(|| format!("env key is not valid UTF-8: {k:?}"))?;
let vs = v
.to_str()
.ok_or_else(|| format!("env value for {ks} is not valid UTF-8: {v:?}"))?;
env_utf8.insert(ks, vs);
}
write_json(
&log_dir.join("invocation.json"),
&json!({
"executable": exe_str,
"arguments": args_utf8,
"working_directory": work_str,
"environment": env_utf8,
"original_run_root": root_str,
}),
)?;
write_regular_file(
&log_dir.join("reproduce.py"),
reproduce_script(parents_depth).as_bytes(),
)?;
let stdout_path = log_dir.join("stdout");
let stderr_path = log_dir.join("stderr");
let stdout_file = File::create(&stdout_path)
.map_err(|error| format!("create {}: {error}", stdout_path.display()))?;
let stderr_file = File::create(&stderr_path)
.map_err(|error| format!("create {}: {error}", stderr_path.display()))?;
let mut command = Command::new(&invocation.executable);
command
.args(&invocation.arguments)
.current_dir(work_dir)
.env_clear()
.envs(&invocation.environment)
.stdin(Stdio::null())
.stdout(stdout_file)
.stderr(stderr_file);
#[cfg(unix)]
{
use std::os::unix::process::CommandExt;
command.process_group(0);
}
let termination = match command.spawn() {
Err(error) => Termination::LaunchFailed(error.to_string()),
Ok(child) => supervise_child(child, self.timeout, log_dir)?,
};
let observed = termination.describe();
write_json(&log_dir.join("outcome.json"), &termination.metadata()).map_err(
|error| {
format!(
"{} {:?}: {observed}; retain process outcome: {error}",
invocation.executable.display(),
invocation.arguments
)
},
)?;
let stdout = fs::read(&stdout_path).map_err(|error| {
format!("read {} after {observed}: {error}", stdout_path.display())
})?;
let stderr = fs::read(&stderr_path).map_err(|error| {
format!("read {} after {observed}: {error}", stderr_path.display())
})?;
Ok(ProcessOutcome {
invocation: invocation.clone(),
working_directory: work_dir.to_path_buf(),
log_dir: log_dir.to_path_buf(),
termination,
stdout,
stderr,
})
}
}