1mod 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#[cfg(any(unix, windows))]
41pub async fn process_started_at(pid: u32) -> Option<u64> {
42 ledger::os_started_at(pid).await
43}
44
45#[derive(Debug, Clone, Default, PartialEq, Eq)]
47#[non_exhaustive]
48pub struct ProcessSpec {
49 pub program: String,
51 pub args: Vec<String>,
53 pub cwd: Option<PathBuf>,
55 pub env: Vec<(String, String)>,
57 pub stdin: Option<PathBuf>,
59 pub ledger_dir: Option<PathBuf>,
68 pub container: Option<String>,
72}
73
74impl ProcessSpec {
75 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 #[must_use]
86 pub fn line(&self) -> String {
87 command_line(&self.program, &self.args)
88 }
89
90 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
99#[non_exhaustive]
100pub struct Exit {
101 pub code: Option<i32>,
103}
104
105impl Exit {
106 #[must_use]
108 pub fn new(code: Option<i32>) -> Exit {
109 Exit { code }
110 }
111
112 #[must_use]
114 pub fn success(self) -> bool {
115 self.code == Some(0)
116 }
117}
118
119impl 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#[derive(Debug, thiserror::Error)]
131#[non_exhaustive]
132pub enum ProcessError {
133 #[error("`{program}` isn't installed or isn't on PATH")]
135 Missing {
136 program: String,
138 },
139 #[error("refusing to run {program}: {why}")]
142 Refused {
143 program: String,
145 why: String,
147 },
148 #[error("elevation: {reason}")]
151 Elevation {
152 reason: String,
154 },
155 #[error("`{program}`: {source}")]
157 Io {
158 program: String,
160 source: std::io::Error,
162 },
163}
164
165pub type OnLine<'a> = &'a mut (dyn FnMut(Stream, &str) + Send);
167
168pub trait ProcessRunner: Send + Sync {
171 fn run<'a>(&'a self, spec: &'a ProcessSpec, on_line: OnLine<'a>) -> BoxFuture<'a, Result<Exit, ProcessError>>;
173}
174
175pub(crate) const OPERATION_VAR: &str = "ISOTHRUM_OPERATION";
178
179pub(crate) struct Recording {
183 inner: std::sync::Arc<dyn ProcessRunner>,
184 dir: PathBuf,
185 operation: Option<crate::store::OperationId>,
186}
187
188impl Recording {
189 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 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
213fn 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
223pub(crate) const STDOUT_REASON_LINES: usize = 5;
225
226#[derive(Debug, Clone, PartialEq, Eq)]
228#[non_exhaustive]
229pub struct Captured {
230 pub exit: Exit,
232 pub stdout: Vec<String>,
234 pub stderr_tail: Vec<String>,
237 record: Option<String>,
240}
241
242impl Captured {
243 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 #[must_use]
257 pub fn success(&self) -> bool {
258 self.exit.success()
259 }
260
261 #[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 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#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
304#[error("{reason}")]
305#[non_exhaustive]
306pub struct ProcessFailed {
307 pub exit: Exit,
309 pub reason: String,
311}
312
313pub async fn capture(runner: &dyn ProcessRunner, spec: &ProcessSpec) -> Result<Captured, ProcessError> {
319 capture_echoing(runner, spec, &mut |_, _| {}).await
320}
321
322pub(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 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 #[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 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 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}