use std::io::Write as _;
use std::path::Path;
use std::process::{Child, Output};
use std::sync::mpsc::{channel, RecvTimeoutError, Sender};
use std::sync::Arc;
use std::time::Duration;
use crate::child::owned::{ChildWaitOutcome, OwnedChild};
use crate::elevation::front::TrackedKind;
use crate::identity::ProcessId;
use crate::os_process::child::ExitRecord;
use crate::signal::Sig;
pub(crate) fn run_fixture_output_within(
fixture: &str,
marker_env: &str,
program: &Path,
bound: Duration,
) -> Result<Output, Output> {
let mut cmd = crate::test_reexec::command(program);
super::configure_fixture_command(&mut cmd, fixture);
crate::test_reexec::with_json_events(&mut cmd);
cmd.env(marker_env, std::process::id().to_string());
let child = crate::test_spawn::spawn(&mut cmd).expect("spawn fixture child");
output_within(child, bound)
}
fn output_within(mut child: Child, bound: Duration) -> Result<Output, Output> {
fn drain(mut pipe: impl std::io::Read + Send + 'static) -> std::thread::JoinHandle<Vec<u8>> {
std::thread::spawn(move || {
let mut bytes = Vec::new();
if let Err(e) = pipe.read_to_end(&mut bytes) {
bytes.extend(format!("\n[the capture ended early: {e}]\n").bytes());
}
bytes
})
}
let stdout = drain(child.stdout.take().expect("piped stdout"));
let stderr = drain(child.stderr.take().expect("piped stderr"));
let id = ProcessId::of(child.id())
.found()
.expect("the live child has an identity");
let shared = Arc::new(OwnedChild::adopt(child, id, TrackedKind::Own).unwrap_or_else(|(e, _)| panic!("adopt: {e}")));
let (tx, rx) = channel();
let waiter = {
let shared = Arc::clone(&shared);
std::thread::spawn(move || _ = tx.send(shared.wait(None)))
};
let (status, in_time) = match rx.recv_timeout(bound) {
Ok(status) => (status, true),
Err(RecvTimeoutError::Timeout) => {
shared.signal(Sig::Kill).expect("kill the hung fixture");
(rx.recv().expect("the waiter ended without a result"), false)
}
Err(RecvTimeoutError::Disconnected) => panic!("the waiter ended without a result"),
};
waiter.join().expect("the waiter");
let output = Output {
status: match status {
Ok(ChildWaitOutcome::Exited(ExitRecord::Status(status))) => status,
other => panic!("wait for the fixture: {other:?}"),
},
stdout: stdout.join().expect("stdout reader"),
stderr: stderr.join().expect("stderr reader"),
};
if in_time {
Ok(output)
} else {
Err(output)
}
}
pub(crate) struct Watchdog(#[allow(dead_code, reason = "dropping the sender ends the watchdog")] Sender<()>);
pub(crate) fn watchdog(name: &'static str, bound: Duration) -> Watchdog {
let (tx, rx) = channel::<()>();
std::thread::spawn(move || {
if rx.recv_timeout(bound) == Err(RecvTimeoutError::Timeout) {
_ = writeln!(
std::io::stderr(),
"WATCHDOG: {name} still running after {bound:?}; last step: {}",
step_name()
);
std::process::abort();
}
});
Watchdog(tx)
}
static STEP: std::sync::Mutex<&'static str> = std::sync::Mutex::new("start");
pub(crate) fn step(name: &'static str) {
_ = writeln!(std::io::stderr(), "step: {name}");
*STEP.lock().unwrap_or_else(|e| e.into_inner()) = name;
}
fn step_name() -> &'static str {
*STEP.lock().unwrap_or_else(|e| e.into_inner())
}
#[cfg(test)]
#[path = "bounded_tests.rs"]
mod bounded_tests;