Skip to main content

xtask/watchdog/
supervised.rs

1//! A command run in its own process group so a termination signal reaches all of it.
2
3use std::os::unix::process::CommandExt;
4use std::process::{Child, Command, ExitStatus, Stdio};
5use std::time::Duration;
6
7use anyhow::{Context, Result, bail};
8
9use super::group::{Group, Termination};
10
11const POLL: Duration = Duration::from_millis(100);
12
13/// Runs a command with inherited stdio to completion, with no stall budget.
14///
15/// On SIGHUP, SIGINT, SIGQUIT or SIGTERM the group is killed and an error returned, so the
16/// caller unwinds and drops whatever it holds, such as a Postgres cluster.
17/// `termination` is watched by the caller from before it acquired that state.
18///
19/// The group is a background one on the terminal, so stdin is closed:
20/// interactive commands are not supported.
21pub fn run_supervised(
22    program: &str,
23    args: &[String],
24    env: &[(&str, &str)],
25    termination: &Termination,
26) -> Result<()> {
27    if termination.requested() {
28        bail!("{program} not started: a termination signal arrived first");
29    }
30    let mut child = Command::new(program)
31        .args(args)
32        .envs(env.iter().copied())
33        .stdin(Stdio::null())
34        .process_group(0)
35        .spawn()
36        .with_context(|| format!("failed to run {program}"))?;
37    let group = Group::of(&child);
38    let outcome = wait(&mut child, termination);
39    group.kill();
40    let _ = child.wait();
41
42    match outcome? {
43        Some(status) if status.success() => Ok(()),
44        Some(status) => bail!("{program} {} exited with {status}", args.join(" ")),
45        None => bail!("{program} interrupted by a termination signal"),
46    }
47}
48
49fn wait(child: &mut Child, termination: &Termination) -> Result<Option<ExitStatus>> {
50    loop {
51        if let Some(status) = child.try_wait().context("waiting on the child")? {
52            return Ok(Some(status));
53        }
54        if termination.requested() {
55            return Ok(None);
56        }
57        std::thread::sleep(POLL);
58    }
59}