Skip to main content

airlock/
host.rs

1//! Host programs as process groups, with streamed output and an exit that reports its signal.
2//!
3//! This is the host process primitive of the participant backends.
4//!
5//! A [`HostProcess`] leads a process group, so it and its descendants can be signalled together. Its output is an
6//! [`OutputStream`] of what the program writes to its standard output and error, and its exit is a watch that holds
7//! how the program exited once it has. The pipes stay read until they close, even when the stream is dropped, so a
8//! program is never blocked or signalled by its observer going away. Stopping sends SIGTERM to the group, then SIGKILL
9//! after a grace. Dropping a process sends SIGKILL to its group.
10
11use std::collections::BTreeMap;
12use std::path::PathBuf;
13use std::process::Stdio;
14use std::time::Duration;
15
16use bytes::Bytes;
17use futures::stream::{self, StreamExt as _};
18use saluki_error::{generic_error, ErrorContext as _, GenericError};
19use tokio::io::{AsyncRead, AsyncWriteExt as _};
20use tokio::process::Command;
21use tokio::sync::{mpsc, watch};
22use tokio_util::io::ReaderStream;
23
24use crate::container::{Output, OutputStream};
25
26/// How long [`HostProcess::stop`] waits after SIGKILL for the exit and for the group to empty.
27#[cfg(unix)]
28const KILL_WAIT: Duration = Duration::from_secs(2);
29
30/// How many chunks of output wait for whoever reads them, before the program's pipes fill.
31const OUTPUT_BUFFER: usize = 64;
32
33/// How often [`HostProcess::stop`] checks whether the group is empty after SIGKILL.
34#[cfg(unix)]
35const GROUP_POLL: Duration = Duration::from_millis(20);
36
37/// A program to run.
38#[derive(Clone, Debug)]
39pub struct HostCommand {
40    /// Names the process in messages.
41    pub name: String,
42    /// The file to execute.
43    pub program: PathBuf,
44    /// The arguments, not including the program itself.
45    pub args: Vec<String>,
46    /// The program's whole environment: nothing is inherited.
47    pub env: BTreeMap<String, String>,
48    /// The working directory.
49    pub dir: PathBuf,
50    /// Written to the program's standard input, which is then closed. Without it, the program has no standard input.
51    pub stdin: Option<Bytes>,
52}
53
54/// How a program exited.
55#[derive(Clone, Copy, Debug, Eq, PartialEq)]
56pub struct HostExit {
57    /// The exit code, or `None` if a signal ended the program.
58    pub code: Option<i32>,
59    /// The signal that ended the program, where the OS reports one.
60    pub signal: Option<i32>,
61}
62
63/// Holds `None` while the program runs, then how it exited, or why that cannot be told.
64pub type ExitWatch = watch::Receiver<Option<Result<HostExit, String>>>;
65
66/// A running program and its process group.
67///
68/// # Limits
69///
70/// - A descendant can leave the group, for example with `setsid`. Signals no longer reach it.
71/// - `Drop` does not run if the owning process is killed with SIGKILL, so a program may outlive it.
72/// - The OS may reuse the ID of an empty group before it is signalled, which would signal an unrelated group.
73#[derive(Debug)]
74pub struct HostProcess {
75    name: String,
76    #[cfg(unix)]
77    exit: ExitWatch,
78    /// The group to kill on drop, or `None` once it was sent SIGKILL.
79    #[cfg(unix)]
80    group: Option<i32>,
81}
82
83impl HostProcess {
84    /// Starts `command` in a new process group.
85    ///
86    /// Returns the process, its output, and the watch of its exit.
87    ///
88    /// # Errors
89    ///
90    /// Returns an error if the program cannot be started.
91    pub fn spawn(command: HostCommand) -> Result<(Self, OutputStream, ExitWatch), GenericError> {
92        let HostCommand {
93            name,
94            program,
95            args,
96            env,
97            dir,
98            stdin,
99        } = command;
100        let mut process = Command::new(&program);
101        process
102            .args(args)
103            .env_clear()
104            .envs(env)
105            .current_dir(dir)
106            .stdin(if stdin.is_some() { Stdio::piped() } else { Stdio::null() })
107            .stdout(Stdio::piped())
108            .stderr(Stdio::piped())
109            .kill_on_drop(true);
110        #[cfg(unix)]
111        process.process_group(0);
112        let mut child = process
113            .spawn()
114            .with_error_context(|| format!("Failed to start '{}' ({}).", name, program.display()))?;
115
116        #[cfg(unix)]
117        let group = child.id().and_then(|id| i32::try_from(id).ok());
118        let stdout = child
119            .stdout
120            .take()
121            .ok_or_else(|| generic_error!("No standard output."))?;
122        let stderr = child
123            .stderr
124            .take()
125            .ok_or_else(|| generic_error!("No standard error."))?;
126        if let (Some(payload), Some(mut input)) = (stdin, child.stdin.take()) {
127            // A program that stops reading early is its own business: the write simply ends.
128            tokio::spawn(async move {
129                let _ = input.write_all(&payload).await;
130                let _ = input.shutdown().await;
131            });
132        }
133
134        let stdout = output_of(stdout, &name, "output", Output::Stdout);
135        let stderr = output_of(stderr, &name, "error", Output::Stderr);
136        let output = keep_draining(stream::select(stdout, stderr).boxed());
137
138        let (sender, exit) = watch::channel(None);
139        let waited = name.clone();
140        // The task owns the child, so it is the only thing that reaps it.
141        tokio::spawn(async move {
142            let exited = match child.wait().await {
143                Ok(status) => Ok(HostExit {
144                    code: status.code(),
145                    signal: signal_of(&status),
146                }),
147                Err(e) => Err(format!("Failed to wait for '{}': {}", waited, e)),
148            };
149            sender.send_replace(Some(exited));
150        });
151
152        let process = Self {
153            name,
154            #[cfg(unix)]
155            exit: exit.clone(),
156            #[cfg(unix)]
157            group,
158        };
159        Ok((process, output, exit))
160    }
161
162    /// The name the process was given.
163    pub fn name(&self) -> &str {
164        &self.name
165    }
166
167    /// Stops the process and its group: SIGTERM, then SIGKILL after `grace`, then up to two seconds for the exit and
168    /// for the group to have no live member. A zombie left in the group does not count.
169    ///
170    /// Whatever is left in the group is killed even when the program itself exited. Dropping the future before the
171    /// SIGKILL drops the process, which sends SIGKILL.
172    ///
173    /// # Errors
174    ///
175    /// Returns an error if the process has not exited, or its group still has a live member, after the SIGKILL. A
176    /// process on a target with no process groups is not signalled, and stopping it does nothing.
177    #[cfg_attr(not(unix), allow(unused_mut, unused_variables))]
178    pub async fn stop(mut self, grace: Duration) -> Result<(), GenericError> {
179        #[cfg(unix)]
180        {
181            use tokio::time::timeout;
182
183            if self.exit.borrow().is_none() {
184                self.signal(libc::SIGTERM);
185                let _ = timeout(grace, self.exit.wait_for(Option::is_some)).await;
186            }
187            self.signal(libc::SIGKILL);
188            let group = self.group.take();
189            let gone = async {
190                let _ = self.exit.wait_for(Option::is_some).await;
191                if let Some(group) = group {
192                    while group_has_live_member(group) {
193                        tokio::time::sleep(GROUP_POLL).await;
194                    }
195                }
196            };
197            if timeout(KILL_WAIT, gone).await.is_err() {
198                return Err(generic_error!(
199                    "'{}' or something in its process group did not exit within {:?} of SIGKILL",
200                    self.name,
201                    KILL_WAIT
202                ));
203            }
204        }
205        Ok(())
206    }
207
208    /// Kills the group with SIGKILL without waiting for it to exit, for a caller that abandons the process on purpose.
209    /// Unlike a drop, it does not warn that the process leaked.
210    #[cfg_attr(not(unix), allow(unused_mut))]
211    pub fn kill(mut self) {
212        #[cfg(unix)]
213        {
214            self.signal(libc::SIGKILL);
215            self.group = None;
216        }
217    }
218
219    /// Sends `signal` to the group, ignoring failure: the group may already be empty.
220    #[cfg(unix)]
221    fn signal(&self, signal: libc::c_int) {
222        if let Some(group) = self.group {
223            // SAFETY: `killpg` takes no pointers and touches no memory of this process.
224            unsafe {
225                libc::killpg(group, signal);
226            }
227        }
228    }
229}
230
231impl Drop for HostProcess {
232    fn drop(&mut self) {
233        #[cfg(unix)]
234        if self.group.is_some() {
235            self.signal(libc::SIGKILL);
236            tracing::warn!(name = %self.name, "A host process was dropped before it was stopped. Killed its group.");
237        }
238    }
239}
240
241/// The chunks `reader` yields, as `tag` makes them, with `name`'s read errors.
242fn output_of<R>(reader: R, name: &str, stream: &'static str, tag: fn(Bytes) -> Output) -> OutputStream
243where
244    R: AsyncRead + Send + Unpin + 'static,
245{
246    let name = name.to_string();
247    ReaderStream::new(reader)
248        .map(move |chunk| match chunk {
249            Ok(bytes) => Ok(tag(bytes)),
250            Err(e) => Err(generic_error!(
251                "Failed to read the standard {} of '{}': {}",
252                stream,
253                name,
254                e
255            )),
256        })
257        .boxed()
258}
259
260/// Whether group `group` has a member that is not a zombie.
261///
262/// A zombie stays in its group until its parent reaps it, which may never happen when an orphan is adopted by a
263/// PID 1 that does not reap. A zombie is no longer running, so it is not a straggler.
264#[cfg(unix)]
265fn group_has_live_member(group: i32) -> bool {
266    // `killpg` cannot tell a zombie from a live process, so read the states from `/proc`.
267    #[cfg(target_os = "linux")]
268    if let Ok(entries) = std::fs::read_dir("/proc") {
269        return entries.flatten().any(|entry| {
270            // The process may exit, or be unreadable, during the scan. Such a process is not counted.
271            let Ok(stat) = std::fs::read_to_string(entry.path().join("stat")) else {
272                return false;
273            };
274            // The command name is in parentheses and may contain spaces or parentheses, so skip to the last `)`.
275            let Some((_, rest)) = stat.rsplit_once(')') else {
276                return false;
277            };
278            let mut fields = rest.split_whitespace();
279            let state = fields.next();
280            let pgrp = fields.nth(1).and_then(|pgrp| pgrp.parse::<i32>().ok());
281            pgrp == Some(group) && !matches!(state, Some("Z" | "X"))
282        });
283    }
284
285    // Other targets (macOS) hand orphans to an init that reaps them promptly, so no zombie lingers.
286    // SAFETY: `killpg` takes no pointers and touches no memory of this process. Signal 0 only checks.
287    let sent = unsafe { libc::killpg(group, 0) };
288    // A group that the process may not signal still exists.
289    sent == 0 || std::io::Error::last_os_error().raw_os_error() != Some(libc::ESRCH)
290}
291
292/// Passes on the chunks of `output`, and goes on reading it after the returned stream is dropped.
293///
294/// The stream owns the pipes only through the task, so whoever stops observing a program does not close its pipes,
295/// which would make the program's next write fail while it is still running.
296fn keep_draining(mut output: OutputStream) -> OutputStream {
297    let (sender, receiver) = mpsc::channel(OUTPUT_BUFFER);
298    tokio::spawn(async move {
299        let mut observed = true;
300        while let Some(chunk) = output.next().await {
301            if observed && sender.send(chunk).await.is_err() {
302                observed = false;
303            }
304        }
305    });
306    stream::unfold(receiver, |mut receiver| async move {
307        receiver.recv().await.map(|chunk| (chunk, receiver))
308    })
309    .boxed()
310}
311
312#[cfg(unix)]
313fn signal_of(status: &std::process::ExitStatus) -> Option<i32> {
314    std::os::unix::process::ExitStatusExt::signal(status)
315}
316
317#[cfg(not(unix))]
318fn signal_of(_status: &std::process::ExitStatus) -> Option<i32> {
319    None
320}
321
322#[cfg(all(test, unix))]
323mod tests {
324    use futures::StreamExt as _;
325
326    use super::*;
327
328    const WAIT: Duration = Duration::from_secs(5);
329
330    fn text_of(chunk: Output) -> String {
331        match chunk {
332            Output::Stdout(bytes) | Output::Stderr(bytes) => String::from_utf8_lossy(&bytes).into_owned(),
333        }
334    }
335
336    #[tokio::test]
337    async fn stop_signals_the_whole_group_and_kills_what_ignores_sigterm() {
338        // The subshell and its `sleep` ignore SIGTERM, so only SIGKILL ends them.
339        let script = "trap 'echo got-term' TERM; (trap '' TERM; sleep 60) & echo ready; wait";
340        let command = HostCommand {
341            name: "test".to_string(),
342            program: PathBuf::from("/bin/sh"),
343            args: vec!["-c".to_string(), script.to_string()],
344            env: BTreeMap::from([("PATH".to_string(), std::env::var("PATH").unwrap_or_default())]),
345            dir: std::env::temp_dir(),
346            stdin: None,
347        };
348        let (process, mut output, _exit) = HostProcess::spawn(command).unwrap();
349
350        let mut text = String::new();
351        tokio::time::timeout(WAIT, async {
352            while !text.contains("ready") {
353                text.push_str(&text_of(
354                    output.next().await.expect("output ended before ready").unwrap(),
355                ));
356            }
357        })
358        .await
359        .expect("the program should say ready");
360
361        tokio::time::timeout(WAIT, process.stop(Duration::from_millis(500)))
362            .await
363            .expect("stop should return")
364            .expect("stop should confirm the exit");
365
366        // The output ends once nothing in the group holds its pipes.
367        tokio::time::timeout(WAIT, async {
368            while let Some(chunk) = output.next().await {
369                text.push_str(&text_of(chunk.unwrap()));
370            }
371        })
372        .await
373        .expect("a process still holds the output pipes");
374        assert!(text.contains("got-term"), "{text}");
375    }
376}