1
//! A command run in its own process group so a termination signal reaches all of it.
2

            
3
use std::os::unix::process::CommandExt;
4
use std::process::{Child, Command, ExitStatus, Stdio};
5
use std::time::Duration;
6

            
7
use anyhow::{Context, Result, bail};
8

            
9
use super::group::{Group, Termination};
10

            
11
const 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.
21
11
pub fn run_supervised(
22
11
    program: &str,
23
11
    args: &[String],
24
11
    env: &[(&str, &str)],
25
11
    termination: &Termination,
26
11
) -> Result<()> {
27
11
    if termination.requested() {
28
1
        bail!("{program} not started: a termination signal arrived first");
29
10
    }
30
10
    let mut child = Command::new(program)
31
10
        .args(args)
32
10
        .envs(env.iter().copied())
33
10
        .stdin(Stdio::null())
34
10
        .process_group(0)
35
10
        .spawn()
36
        .with_context(|| format!("failed to run {program}"))?;
37
10
    let group = Group::of(&child);
38
10
    let outcome = wait(&mut child, termination);
39
10
    group.kill();
40
10
    let _ = child.wait();
41

            
42
10
    match outcome? {
43
6
        Some(status) if status.success() => Ok(()),
44
3
        Some(status) => bail!("{program} {} exited with {status}", args.join(" ")),
45
4
        None => bail!("{program} interrupted by a termination signal"),
46
    }
47
11
}
48

            
49
10
fn wait(child: &mut Child, termination: &Termination) -> Result<Option<ExitStatus>> {
50
    loop {
51
24
        if let Some(status) = child.try_wait().context("waiting on the child")? {
52
6
            return Ok(Some(status));
53
18
        }
54
18
        if termination.requested() {
55
4
            return Ok(None);
56
14
        }
57
14
        std::thread::sleep(POLL);
58
    }
59
10
}