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