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