mod docker_context;
mod elevated;
#[cfg(any(test, feature = "fake"))]
pub mod fake;
#[cfg(windows)]
mod job;
#[cfg(windows)]
pub(crate) use job::process_runs;
pub mod ledger;
mod lines;
mod locale;
mod shim;
mod stopping;
mod system;
mod tail;
#[cfg(any(windows, test))]
mod win_command;
use std::path::PathBuf;
pub(crate) use docker_context::DockerContext;
pub(crate) use elevated::{DECLINED, Elevated, once as elevated_once};
pub use elevated::{HyperVRights, may_manage_hyperv};
pub use system::SystemProcesses;
pub(crate) use tail::Tail;
use crate::BoxFuture;
use crate::events::Stream;
#[cfg(any(unix, windows))]
pub async fn process_started_at(pid: u32) -> Option<u64> {
ledger::os_started_at(pid).await
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct ProcessSpec {
pub program: String,
pub args: Vec<String>,
pub cwd: Option<PathBuf>,
pub env: Vec<(String, String)>,
pub stdin: Option<PathBuf>,
pub ledger_dir: Option<PathBuf>,
pub container: Option<String>,
}
impl ProcessSpec {
pub fn new(program: &str, args: impl IntoIterator<Item = impl Into<String>>) -> ProcessSpec {
ProcessSpec {
program: program.to_owned(),
args: args.into_iter().map(Into::into).collect(),
..ProcessSpec::default()
}
}
#[must_use]
pub fn line(&self) -> String {
command_line(&self.program, &self.args)
}
#[must_use]
pub fn env(&self, name: &str) -> Option<&str> {
self.env.iter().rev().find(|(k, _)| k == name).map(|(_, v)| v.as_str())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct Exit {
pub code: Option<i32>,
}
impl Exit {
#[must_use]
pub fn new(code: Option<i32>) -> Exit {
Exit { code }
}
#[must_use]
pub fn success(self) -> bool {
self.code == Some(0)
}
}
impl std::fmt::Display for Exit {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self.code {
Some(code) => write!(f, "exited with code {code}"),
None => f.write_str("exited with a signal"),
}
}
}
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum ProcessError {
#[error("`{program}` isn't installed or isn't on PATH")]
Missing {
program: String,
},
#[error("refusing to run {program}: {why}")]
Refused {
program: String,
why: String,
},
#[error("elevation: {reason}")]
Elevation {
reason: String,
},
#[error("`{program}`: {source}")]
Io {
program: String,
source: std::io::Error,
},
}
pub type OnLine<'a> = &'a mut (dyn FnMut(Stream, &str) + Send);
pub trait ProcessRunner: Send + Sync {
fn run<'a>(&'a self, spec: &'a ProcessSpec, on_line: OnLine<'a>) -> BoxFuture<'a, Result<Exit, ProcessError>>;
}
pub(crate) const OPERATION_VAR: &str = "ISOTHRUM_OPERATION";
pub(crate) struct Recording {
inner: std::sync::Arc<dyn ProcessRunner>,
dir: PathBuf,
operation: Option<crate::store::OperationId>,
}
impl Recording {
pub(crate) fn new(inner: std::sync::Arc<dyn ProcessRunner>, dir: PathBuf, operation: Option<crate::store::OperationId>) -> Recording {
Recording { inner, dir, operation }
}
}
impl ProcessRunner for Recording {
fn run<'a>(&'a self, spec: &'a ProcessSpec, on_line: OnLine<'a>) -> BoxFuture<'a, Result<Exit, ProcessError>> {
Box::pin(async move {
let mut env = spec.env.clone();
if let Some(id) = self.operation {
env.insert(0, (OPERATION_VAR.to_owned(), id.0.to_string()));
}
let recorded = ProcessSpec {
ledger_dir: Some(self.dir.clone()),
env,
..spec.clone()
};
self.inner.run(&recorded, on_line).await
})
}
}
fn command_line(program: &str, args: &[String]) -> String {
std::iter::once(program)
.chain(args.iter().map(String::as_str))
.map(crate::console::sh_word)
.collect::<Vec<_>>()
.join(" ")
}
pub(crate) const STDOUT_REASON_LINES: usize = 5;
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Captured {
pub exit: Exit,
pub stdout: Vec<String>,
pub stderr_tail: Vec<String>,
record: Option<String>,
}
impl Captured {
pub(crate) fn new(program: &str, exit: Exit, stdout: Vec<String>, stderr: Vec<String>) -> Captured {
let record = crate::tool_output::failure_record(program, &stdout);
Captured {
exit,
stdout,
stderr_tail: stderr,
record,
}
}
#[must_use]
pub fn success(&self) -> bool {
self.exit.success()
}
#[must_use]
pub fn reason(&self) -> String {
let cause = self.record.clone().unwrap_or_else(|| {
let quiet = self.stderr_tail.iter().all(|l| l.trim().is_empty());
let said = if quiet {
self.stdout.get(self.stdout.len().saturating_sub(STDOUT_REASON_LINES)..).unwrap_or_default()
} else {
&self.stderr_tail[..]
};
said.join("\n")
});
if cause.trim().is_empty() {
self.exit.to_string()
} else {
format!("{} ({})", cause.trim(), self.exit)
}
}
pub fn output(&self) -> Result<String, ProcessFailed> {
if self.success() {
Ok(self.stdout.join("\n"))
} else {
Err(ProcessFailed {
exit: self.exit,
reason: self.reason(),
})
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("{reason}")]
#[non_exhaustive]
pub struct ProcessFailed {
pub exit: Exit,
pub reason: String,
}
pub async fn capture(runner: &dyn ProcessRunner, spec: &ProcessSpec) -> Result<Captured, ProcessError> {
capture_echoing(runner, spec, &mut |_, _| {}).await
}
pub(crate) async fn capture_echoing(runner: &dyn ProcessRunner, spec: &ProcessSpec, echo: OnLine<'_>) -> Result<Captured, ProcessError> {
let mut stdout = Vec::new();
let mut tail = Tail::default();
let mut keep = |stream: Stream, line: &str| {
echo(stream, line);
match stream {
Stream::Stdout => stdout.push(line.to_owned()),
Stream::Stderr => tail.push(line),
}
};
let exit = runner.run(spec, &mut keep).await?;
Ok(Captured::new(&spec.program, exit, stdout, tail.into_lines()))
}
#[cfg(test)]
mod tests {
use super::*;
fn reason(out: &Captured) -> String {
out.reason()
}
fn ended(code: Option<i32>, stderr: &[&str], stdout: &[&str]) -> Captured {
let lines = |l: &[&str]| l.iter().map(|s| (*s).to_owned()).collect();
Captured::new("vagrant", Exit::new(code), lines(stdout), lines(stderr))
}
#[test]
fn a_failure_says_why_from_stderr_else_the_end_of_stdout() {
assert_eq!(reason(&ended(Some(1), &["denied"], &["noise"])), "denied (exited with code 1)");
let refused = ended(Some(1), &["", " "], &["Please login as the user \"admin\" rather than the user \"root\"."]);
assert_eq!(
reason(&refused),
"Please login as the user \"admin\" rather than the user \"root\". (exited with code 1)"
);
let long: Vec<String> = (1..=9).map(|n| format!("line {n}")).collect();
let long: Vec<&str> = long.iter().map(String::as_str).collect();
assert_eq!(
reason(&ended(Some(2), &[], &long)),
"line 5\nline 6\nline 7\nline 8\nline 9 (exited with code 2)"
);
assert_eq!(reason(&ended(None, &[], &[])), "exited with a signal");
}
#[test]
fn a_machine_readable_vagrant_error_is_the_reason() {
let said = "Vagrant can't use the requested machine because it is locked! This\\nmeans that another Vagrant \
process is currently reading or modifying\\nthe machine.";
let ui = format!("1794342958,,ui,error,{said}");
let exit = format!("1794342958,,error-exit,Vagrant::Errors::MachineLocked,{said}");
let fog = "[fog][WARNING] Unrecognized arguments: libvirt_ip_command";
let want = "Vagrant can't use the requested machine because it is locked! This\nmeans that another Vagrant \
process is currently reading or modifying\nthe machine. (Vagrant::Errors::MachineLocked) (exited with code 1)";
assert_eq!(reason(&ended(Some(1), &[fog, fog, fog], &["1,web,state,running", &ui, &exit])), want);
assert_eq!(reason(&ended(Some(1), &[], &[&ui, &exit])), want);
assert_eq!(reason(&ended(Some(1), &["Traceback"], &[&exit])), want);
}
#[test]
fn a_silent_failure_reports_its_exit_status() {
assert_eq!(reason(&ended(Some(1), &[], &[])), "exited with code 1");
assert_eq!(reason(&ended(None, &[" "], &[])), "exited with a signal");
assert_eq!(reason(&ended(Some(2), &["no space left"], &[])), "no space left (exited with code 2)");
assert_eq!(ended(Some(0), &["warning"], &["a", "b"]).output(), Ok("a\nb".to_owned()));
let failed = ended(Some(3), &["bad"], &["a"]).output().unwrap_err();
assert_eq!((failed.exit, failed.to_string()), (Exit::new(Some(3)), "bad (exited with code 3)".to_owned()));
}
#[test]
fn a_spec_reads_as_its_command_line() {
let spec = ProcessSpec::new("docker", ["compose", "ps"]);
assert_eq!(spec.line(), "docker compose ps");
let spaced = ProcessSpec::new("vagrant", ["up", "web server", "--provider=hyperv"]);
assert_eq!(spaced.line(), "vagrant up 'web server' --provider=hyperv");
assert!(Exit { code: Some(0) }.success() && !Exit { code: None }.success());
}
}