Skip to main content

runnerd_core/
command.rs

1//! The commands runnerd runs (the doctor's `systemctl` and `gh`, and `gh auth token` for the GitHub client), each in
2//! a process group of its own, so none outlives its deadline or the daemon: past its deadline, its whole group is
3//! killed, whatever its processes did with the pipes, and once the daemon stops, every group still running is killed
4//! and no command starts (ADRs 0132 and 0134).
5//!
6//! It must not run anything its caller did not ask for, or signal a process it did not start.
7
8use std::io::{self, Read as _};
9use std::os::unix::process::CommandExt as _;
10use std::process::{Child, Command, ExitStatus, Output, Stdio};
11use std::sync::{Mutex, MutexGuard, PoisonError, mpsc};
12use std::time::{Duration, Instant};
13
14use crate::api;
15use rustix::process::{Pid, Signal, kill_process_group};
16
17/// The commands of this process: those running, and whether it stopped. Only its methods here write it.
18#[derive(Debug)]
19pub struct Running(Mutex<Groups>);
20
21#[derive(Debug)]
22struct Groups {
23    /// The process groups of the commands running: each command's own, led by it.
24    running: Vec<Pid>,
25    /// The daemon stopped: no command starts.
26    stopped: bool,
27}
28
29/// The daemon's commands: the doctor's and the GitHub client's.
30pub static RUNNING: Running = Running::new();
31
32impl Default for Running {
33    fn default() -> Running {
34        Running::new()
35    }
36}
37
38impl Running {
39    /// None running, not stopped.
40    pub const fn new() -> Running {
41        Running(Mutex::new(Groups {
42            running: Vec::new(),
43            stopped: false,
44        }))
45    }
46
47    fn lock(&self) -> MutexGuard<'_, Groups> {
48        self.0.lock().unwrap_or_else(PoisonError::into_inner)
49    }
50
51    /// Kills every command running and what it started, and starts none after: their reads end at once.
52    pub fn stop(&self) {
53        let mut groups = self.lock();
54        groups.stopped = true;
55        for group in &groups.running {
56            let _ = kill_process_group(*group, Signal::KILL);
57        }
58    }
59
60    /// Starts `command` in a group of its own, unless the daemon stopped.
61    fn spawn(&self, command: &mut Command) -> io::Result<(Child, Pid)> {
62        let mut groups = self.lock();
63        if groups.stopped {
64            return Err(io::Error::other("runnerd is stopping"));
65        }
66        let child = command.process_group(0).spawn()?;
67        let group = Pid::from_child(&child);
68        groups.running.push(group);
69        Ok((child, group))
70    }
71
72    fn ended(&self, group: Pid) {
73        self.lock().running.retain(|running| *running != group);
74    }
75}
76
77/// `command`'s output, as `Command::output` gives it, with no input; with its group killed past `deadline`, which
78/// covers reading what it wrote too: a process it left behind holding its pipes does not hold the read.
79pub fn output_within(
80    command: &mut Command,
81    deadline: Duration,
82    running: &Running,
83) -> io::Result<Output> {
84    let until = Instant::now() + deadline;
85    command
86        .stdin(Stdio::null())
87        .stdout(Stdio::piped())
88        .stderr(Stdio::piped());
89    let (mut child, group) = running.spawn(command)?;
90    let read = collect(&mut child, until);
91    if !matches!(read, Some(Ok(_))) {
92        // Before the leader is reaped, so the ID is still the group's.
93        let _ = kill_process_group(group, Signal::KILL);
94    }
95    // Reaps the leader, if it was not; once killed, at once.
96    let _ = child.wait();
97    running.ended(group);
98    read.ok_or_else(|| {
99        io::Error::new(
100            io::ErrorKind::TimedOut,
101            format!(
102                "it did not finish within {}",
103                api::duration(deadline.as_secs())
104            ),
105        )
106    })?
107}
108
109/// What `child` wrote and how it ended, or `None` when that did not all come by `until`.
110fn collect(child: &mut Child, until: Instant) -> Option<io::Result<Output>> {
111    // Read as it runs, so a full pipe never stops it.
112    let (sender, read) = mpsc::channel();
113    let pipes: [Option<Box<dyn io::Read + Send>>; 2] = [
114        child
115            .stdout
116            .take()
117            .map(|pipe| Box::new(pipe) as Box<dyn io::Read + Send>),
118        child
119            .stderr
120            .take()
121            .map(|pipe| Box::new(pipe) as Box<dyn io::Read + Send>),
122    ];
123    for (index, pipe) in pipes.into_iter().enumerate() {
124        let sender = sender.clone();
125        // Not joined: one whose writer outlives the deadline ends when the group is killed.
126        std::thread::spawn(move || {
127            let mut bytes = Vec::new();
128            if let Some(mut pipe) = pipe {
129                let _ = pipe.read_to_end(&mut bytes);
130            }
131            let _ = sender.send((index, bytes));
132        });
133    }
134    let status: ExitStatus = loop {
135        match child.try_wait() {
136            Ok(Some(status)) => break status,
137            Ok(None) => {}
138            Err(error) => return Some(Err(error)),
139        }
140        if Instant::now() >= until {
141            return None;
142        }
143        std::thread::sleep(Duration::from_millis(10));
144    };
145    let mut output = Output {
146        status,
147        stdout: Vec::new(),
148        stderr: Vec::new(),
149    };
150    for _ in 0..2 {
151        let (index, bytes) = read
152            .recv_timeout(until.saturating_duration_since(Instant::now()))
153            .ok()?;
154        if index == 0 {
155            output.stdout = bytes;
156        } else {
157            output.stderr = bytes;
158        }
159    }
160    Some(Ok(output))
161}
162
163#[cfg(test)]
164mod tests;