Skip to main content

isothrum_runner/
process.rs

1//! Running the tools a manifest names: the [`ProcessRunner`] port. [`SystemProcesses`] starts
2//! real processes (never through a shell, headless on Windows, each tool in a process group or
3//! job object so a timeout or a cancellation ends the whole tree it started, after asking it to
4//! stop on Unix); the `fake` feature's
5//! `fake::FakeProcesses` answers from a test's script instead.
6
7mod elevated;
8#[cfg(any(test, feature = "fake"))]
9pub mod fake;
10pub(crate) mod ledger;
11mod lines;
12mod shim;
13mod stopping;
14mod system;
15mod tail;
16
17use std::path::PathBuf;
18
19pub(crate) use elevated::Elevated;
20pub use elevated::may_manage_hyperv;
21pub(crate) use shim::TERRAFORM_PROGRAMS;
22pub use system::SystemProcesses;
23pub(crate) use tail::Tail;
24
25use crate::BoxFuture;
26use crate::events::Stream;
27
28/// One process to start.
29#[derive(Debug, Clone, Default, PartialEq, Eq)]
30#[non_exhaustive]
31pub struct ProcessSpec {
32    /// The program: a bare tool name, found on PATH.
33    pub program: String,
34    /// Its arguments, passed as they are (no shell ever reads them).
35    pub args: Vec<String>,
36    /// Its working folder (default: the runner's).
37    pub cwd: Option<PathBuf>,
38    /// Variables added to the runner's environment.
39    pub env: Vec<(String, String)>,
40    /// A file piped into its standard input (default: none).
41    pub stdin: Option<PathBuf>,
42    /// The folder the tool is recorded in while it runs (its process group; its process tree on
43    /// Windows), so the next operation can end it if the process that started it is killed first
44    /// (default: not recorded). An operation's tools are recorded in the run's state folder.
45    pub tools: Option<PathBuf>,
46}
47
48impl ProcessSpec {
49    /// `program` with `args`, everything else at its default.
50    pub fn new(program: &str, args: impl IntoIterator<Item = impl Into<String>>) -> ProcessSpec {
51        ProcessSpec {
52            program: program.to_owned(),
53            args: args.into_iter().map(Into::into).collect(),
54            ..ProcessSpec::default()
55        }
56    }
57
58    /// The command as one line (`docker compose ps`), for messages and tests.
59    #[must_use]
60    pub fn line(&self) -> String {
61        command_line(&self.program, &self.args)
62    }
63
64    /// The value it is given for variable `name` (the last, when it is given twice).
65    #[must_use]
66    pub fn env(&self, name: &str) -> Option<&str> {
67        self.env.iter().rev().find(|(k, _)| k == name).map(|(_, v)| v.as_str())
68    }
69}
70
71/// How a process ended.
72#[derive(Debug, Clone, Copy, PartialEq, Eq)]
73#[non_exhaustive]
74pub struct Exit {
75    /// Its exit code, when it exited (not killed by a signal).
76    pub code: Option<i32>,
77}
78
79impl Exit {
80    /// A process that ended with `code` (`None`: killed by a signal).
81    #[must_use]
82    pub fn new(code: Option<i32>) -> Exit {
83        Exit { code }
84    }
85
86    /// Whether it exited with 0.
87    #[must_use]
88    pub fn success(self) -> bool {
89        self.code == Some(0)
90    }
91}
92
93/// How it ended, as a failure's reason says it: `exited with code 1`, `exited with a signal`.
94impl std::fmt::Display for Exit {
95    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
96        match self.code {
97            Some(code) => write!(f, "exited with code {code}"),
98            None => f.write_str("exited with a signal"),
99        }
100    }
101}
102
103/// Why a process couldn't run to its end.
104#[derive(Debug, thiserror::Error)]
105#[non_exhaustive]
106pub enum ProcessError {
107    /// The program isn't on PATH.
108    #[error("`{program}` isn't installed or isn't on PATH")]
109    Missing {
110        /// The program.
111        program: String,
112    },
113    /// A call the way it would run can't carry as asked (an elevated call: an argument
114    /// PowerShell would mangle, a standard input it can't be given).
115    #[error("refusing to run {program}: {why}")]
116    Refused {
117        /// The program.
118        program: String,
119        /// Why.
120        why: String,
121    },
122    /// It needed elevation (Hyper-V's), which couldn't be had: the prompt declined, the
123    /// elevated session ended.
124    #[error("elevation: {reason}")]
125    Elevation {
126        /// Why.
127        reason: String,
128    },
129    /// Starting it, piping it or waiting for it failed.
130    #[error("`{program}`: {source}")]
131    Io {
132        /// The program.
133        program: String,
134        /// The OS's reason.
135        source: std::io::Error,
136    },
137}
138
139/// Receives each line a process prints, with the output it came from.
140pub type OnLine<'a> = &'a mut (dyn FnMut(Stream, &str) + Send);
141
142/// Starts processes. Dropping the future of [`ProcessRunner::run`] before it resolves (a timeout,
143/// a cancelled operation) ends the process and everything it started.
144pub trait ProcessRunner: Send + Sync {
145    /// Runs `spec` to its end, handing each line it prints to `on_line` (decoded lossily).
146    fn run<'a>(&'a self, spec: &'a ProcessSpec, on_line: OnLine<'a>) -> BoxFuture<'a, Result<Exit, ProcessError>>;
147}
148
149/// Runs every tool of `inner` recorded in the folder `dir` ([`ProcessSpec::tools`]): an
150/// operation's tools, in its run's state folder.
151pub(crate) struct Recording {
152    inner: std::sync::Arc<dyn ProcessRunner>,
153    dir: PathBuf,
154}
155
156impl Recording {
157    /// `inner`'s tools, recorded in `dir`.
158    pub(crate) fn new(inner: std::sync::Arc<dyn ProcessRunner>, dir: PathBuf) -> Recording {
159        Recording { inner, dir }
160    }
161}
162
163impl ProcessRunner for Recording {
164    fn run<'a>(&'a self, spec: &'a ProcessSpec, on_line: OnLine<'a>) -> BoxFuture<'a, Result<Exit, ProcessError>> {
165        Box::pin(async move {
166            let recorded = ProcessSpec {
167                tools: Some(self.dir.clone()),
168                ..spec.clone()
169            };
170            self.inner.run(&recorded, on_line).await
171        })
172    }
173}
174
175/// `program` and `args` as one line, separated by spaces.
176fn command_line(program: &str, args: &[String]) -> String {
177    std::iter::once(program).chain(args.iter().map(String::as_str)).collect::<Vec<_>>().join(" ")
178}
179
180/// How many of its last output lines stand in for a failed tool's silent standard error.
181pub(crate) const STDOUT_REASON_LINES: usize = 5;
182
183/// What a process printed, kept: its standard output, and its last standard error lines.
184#[derive(Debug, Clone, PartialEq, Eq)]
185#[non_exhaustive]
186pub struct Captured {
187    /// How it ended.
188    pub exit: Exit,
189    /// Its standard output, one line each.
190    pub stdout: Vec<String>,
191    /// Its last standard error lines (a Ruby backtrace's frames and known-harmless warnings left
192    /// out).
193    pub stderr: Vec<String>,
194}
195
196impl Captured {
197    /// Whether it exited 0 ([`Exit::success`]).
198    #[must_use]
199    pub fn success(&self) -> bool {
200        self.exit.success()
201    }
202
203    /// Why it failed, the one wording every failed tool's error uses: the error it printed as a
204    /// machine-readable record on its standard output (Vagrant's `error-exit`, with
205    /// `--machine-readable`), else its last error lines, else its last output lines (a tool, or a
206    /// cloud image refusing a login, may print its refusal there), with how it ended (`denied
207    /// (exited with code 1)`, `exited with a signal`).
208    #[must_use]
209    pub fn reason(&self) -> String {
210        let cause = crate::tool_output::vagrant_error(&self.stdout).unwrap_or_else(|| {
211            let quiet = self.stderr.iter().all(|l| l.trim().is_empty());
212            let said = if quiet {
213                self.stdout.get(self.stdout.len().saturating_sub(STDOUT_REASON_LINES)..).unwrap_or_default()
214            } else {
215                &self.stderr[..]
216            };
217            said.join("\n")
218        });
219        if cause.trim().is_empty() {
220            self.exit.to_string()
221        } else {
222            format!("{} ({})", cause.trim(), self.exit)
223        }
224    }
225
226    /// Its standard output when it exited 0, else why it failed ([`Captured::reason`]).
227    ///
228    /// # Errors
229    ///
230    /// It didn't exit 0: the error is its reason.
231    pub fn output(&self) -> Result<String, String> {
232        if self.success() { Ok(self.stdout.join("\n")) } else { Err(self.reason()) }
233    }
234}
235
236/// Runs `spec`, keeping what it prints.
237///
238/// # Errors
239///
240/// The process can't start (missing, refused, an I/O error).
241pub async fn capture(runner: &dyn ProcessRunner, spec: &ProcessSpec) -> Result<Captured, ProcessError> {
242    capture_echoing(runner, spec, &mut |_, _| {}).await
243}
244
245/// [`capture`], each line also handed to `echo` as it comes.
246pub(crate) async fn capture_echoing(runner: &dyn ProcessRunner, spec: &ProcessSpec, echo: OnLine<'_>) -> Result<Captured, ProcessError> {
247    let mut stdout = Vec::new();
248    let mut tail = Tail::default();
249    let mut keep = |stream: Stream, line: &str| {
250        echo(stream, line);
251        match stream {
252            Stream::Stdout => stdout.push(line.to_owned()),
253            Stream::Stderr => tail.push(line),
254        }
255    };
256    let exit = runner.run(spec, &mut keep).await?;
257    Ok(Captured {
258        exit,
259        stdout,
260        stderr: tail.into_lines(),
261    })
262}
263
264#[cfg(test)]
265mod tests {
266    use super::*;
267
268    fn reason(out: &Captured) -> String {
269        out.reason()
270    }
271
272    fn ended(code: Option<i32>, stderr: &[&str], stdout: &[&str]) -> Captured {
273        let lines = |l: &[&str]| l.iter().map(|s| (*s).to_owned()).collect();
274        Captured {
275            exit: Exit::new(code),
276            stdout: lines(stdout),
277            stderr: lines(stderr),
278        }
279    }
280
281    #[test]
282    fn a_failure_says_why_from_stderr_else_the_end_of_stdout() {
283        assert_eq!(reason(&ended(Some(1), &["denied"], &["noise"])), "denied (exited with code 1)");
284        // Debian on AWS refuses root on stdout, with nothing on stderr.
285        let refused = ended(Some(1), &["", " "], &["Please login as the user \"admin\" rather than the user \"root\"."]);
286        assert_eq!(
287            reason(&refused),
288            "Please login as the user \"admin\" rather than the user \"root\". (exited with code 1)"
289        );
290        let long: Vec<String> = (1..=9).map(|n| format!("line {n}")).collect();
291        let long: Vec<&str> = long.iter().map(String::as_str).collect();
292        assert_eq!(
293            reason(&ended(Some(2), &[], &long)),
294            "line 5\nline 6\nline 7\nline 8\nline 9 (exited with code 2)"
295        );
296        assert_eq!(reason(&ended(None, &[], &[])), "exited with a signal");
297    }
298
299    /// Regression: on libvirt, a `vagrant status --machine-readable` refused for another
300    /// process's lock failed with only fog's warnings on standard error, which stood in for the
301    /// error Vagrant printed on its standard output.
302    #[test]
303    fn a_machine_readable_vagrant_error_is_the_reason() {
304        let said = "Vagrant can't use the requested machine because it is locked! This\\nmeans that another Vagrant \
305                    process is currently reading or modifying\\nthe machine.";
306        let ui = format!("1794342958,,ui,error,{said}");
307        let exit = format!("1794342958,,error-exit,Vagrant::Errors::MachineLocked,{said}");
308        let fog = "[fog][WARNING] Unrecognized arguments: libvirt_ip_command";
309        let want = "Vagrant can't use the requested machine because it is locked! This\nmeans that another Vagrant \
310                    process is currently reading or modifying\nthe machine. (Vagrant::Errors::MachineLocked) (exited with code 1)";
311        assert_eq!(reason(&ended(Some(1), &[fog, fog, fog], &["1,web,state,running", &ui, &exit])), want);
312        assert_eq!(reason(&ended(Some(1), &[], &[&ui, &exit])), want);
313        // A Ruby error on standard error yields to Vagrant's own record of it.
314        assert_eq!(reason(&ended(Some(1), &["Traceback"], &[&exit])), want);
315    }
316
317    #[test]
318    fn a_silent_failure_reports_its_exit_status() {
319        assert_eq!(reason(&ended(Some(1), &[], &[])), "exited with code 1");
320        assert_eq!(reason(&ended(None, &[" "], &[])), "exited with a signal");
321        assert_eq!(reason(&ended(Some(2), &["no space left"], &[])), "no space left (exited with code 2)");
322        assert_eq!(ended(Some(0), &["warning"], &["a", "b"]).output(), Ok("a\nb".to_owned()));
323        assert_eq!(ended(Some(3), &["bad"], &["a"]).output(), Err("bad (exited with code 3)".to_owned()));
324    }
325
326    #[test]
327    fn a_spec_reads_as_its_command_line() {
328        let spec = ProcessSpec::new("docker", ["compose", "ps"]);
329        assert_eq!(spec.line(), "docker compose ps");
330        assert!(Exit { code: Some(0) }.success() && !Exit { code: None }.success());
331    }
332}