1mod 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#[derive(Debug, Clone, Default, PartialEq, Eq)]
29#[non_exhaustive]
30pub struct ProcessSpec {
31 pub program: String,
33 pub args: Vec<String>,
35 pub cwd: Option<PathBuf>,
37 pub env: Vec<(String, String)>,
39 pub stdin: Option<PathBuf>,
41}
42
43impl ProcessSpec {
44 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 #[must_use]
55 pub fn line(&self) -> String {
56 command_line(&self.program, &self.args)
57 }
58
59 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
68#[non_exhaustive]
69pub struct Exit {
70 pub code: Option<i32>,
72}
73
74impl Exit {
75 #[must_use]
77 pub fn new(code: Option<i32>) -> Exit {
78 Exit { code }
79 }
80
81 #[must_use]
83 pub fn success(self) -> bool {
84 self.code == Some(0)
85 }
86}
87
88impl 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#[derive(Debug, thiserror::Error)]
100#[non_exhaustive]
101pub enum ProcessError {
102 #[error("`{program}` isn't installed or isn't on PATH")]
104 Missing {
105 program: String,
107 },
108 #[error("refusing to run {program}: {why}")]
111 Refused {
112 program: String,
114 why: String,
116 },
117 #[error("elevation: {reason}")]
120 Elevation {
121 reason: String,
123 },
124 #[error("`{program}`: {source}")]
126 Io {
127 program: String,
129 source: std::io::Error,
131 },
132}
133
134pub type OnLine<'a> = &'a mut (dyn FnMut(Stream, &str) + Send);
136
137pub trait ProcessRunner: Send + Sync {
140 fn run<'a>(&'a self, spec: &'a ProcessSpec, on_line: OnLine<'a>) -> BoxFuture<'a, Result<Exit, ProcessError>>;
142}
143
144fn command_line(program: &str, args: &[String]) -> String {
146 std::iter::once(program).chain(args.iter().map(String::as_str)).collect::<Vec<_>>().join(" ")
147}
148
149pub(crate) const STDOUT_REASON_LINES: usize = 5;
151
152#[derive(Debug, Clone, PartialEq, Eq)]
154#[non_exhaustive]
155pub struct Captured {
156 pub exit: Exit,
158 pub stdout: Vec<String>,
160 pub stderr: Vec<String>,
163}
164
165impl Captured {
166 #[must_use]
168 pub fn success(&self) -> bool {
169 self.exit.success()
170 }
171
172 #[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 pub fn output(&self) -> Result<String, String> {
201 if self.success() { Ok(self.stdout.join("\n")) } else { Err(self.reason()) }
202 }
203}
204
205pub async fn capture(runner: &dyn ProcessRunner, spec: &ProcessSpec) -> Result<Captured, ProcessError> {
211 capture_echoing(runner, spec, &mut |_, _| {}).await
212}
213
214pub(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 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 #[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 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}