1mod 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#[derive(Debug, Clone, Default, PartialEq, Eq)]
30#[non_exhaustive]
31pub struct ProcessSpec {
32 pub program: String,
34 pub args: Vec<String>,
36 pub cwd: Option<PathBuf>,
38 pub env: Vec<(String, String)>,
40 pub stdin: Option<PathBuf>,
42 pub tools: Option<PathBuf>,
46}
47
48impl ProcessSpec {
49 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 #[must_use]
60 pub fn line(&self) -> String {
61 command_line(&self.program, &self.args)
62 }
63
64 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
73#[non_exhaustive]
74pub struct Exit {
75 pub code: Option<i32>,
77}
78
79impl Exit {
80 #[must_use]
82 pub fn new(code: Option<i32>) -> Exit {
83 Exit { code }
84 }
85
86 #[must_use]
88 pub fn success(self) -> bool {
89 self.code == Some(0)
90 }
91}
92
93impl 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#[derive(Debug, thiserror::Error)]
105#[non_exhaustive]
106pub enum ProcessError {
107 #[error("`{program}` isn't installed or isn't on PATH")]
109 Missing {
110 program: String,
112 },
113 #[error("refusing to run {program}: {why}")]
116 Refused {
117 program: String,
119 why: String,
121 },
122 #[error("elevation: {reason}")]
125 Elevation {
126 reason: String,
128 },
129 #[error("`{program}`: {source}")]
131 Io {
132 program: String,
134 source: std::io::Error,
136 },
137}
138
139pub type OnLine<'a> = &'a mut (dyn FnMut(Stream, &str) + Send);
141
142pub trait ProcessRunner: Send + Sync {
145 fn run<'a>(&'a self, spec: &'a ProcessSpec, on_line: OnLine<'a>) -> BoxFuture<'a, Result<Exit, ProcessError>>;
147}
148
149pub(crate) struct Recording {
152 inner: std::sync::Arc<dyn ProcessRunner>,
153 dir: PathBuf,
154}
155
156impl Recording {
157 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
175fn command_line(program: &str, args: &[String]) -> String {
177 std::iter::once(program).chain(args.iter().map(String::as_str)).collect::<Vec<_>>().join(" ")
178}
179
180pub(crate) const STDOUT_REASON_LINES: usize = 5;
182
183#[derive(Debug, Clone, PartialEq, Eq)]
185#[non_exhaustive]
186pub struct Captured {
187 pub exit: Exit,
189 pub stdout: Vec<String>,
191 pub stderr: Vec<String>,
194}
195
196impl Captured {
197 #[must_use]
199 pub fn success(&self) -> bool {
200 self.exit.success()
201 }
202
203 #[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 pub fn output(&self) -> Result<String, String> {
232 if self.success() { Ok(self.stdout.join("\n")) } else { Err(self.reason()) }
233 }
234}
235
236pub async fn capture(runner: &dyn ProcessRunner, spec: &ProcessSpec) -> Result<Captured, ProcessError> {
242 capture_echoing(runner, spec, &mut |_, _| {}).await
243}
244
245pub(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 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 #[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 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}