pub(crate) mod compose;
pub(crate) mod docker;
mod installed;
pub(crate) mod listener;
pub(crate) mod prlctl;
pub(crate) mod qemu;
pub(crate) mod terraform;
pub(crate) mod utmctl;
pub(crate) mod vagrant;
pub(crate) mod vboxmanage;
pub(crate) mod virsh;
use std::fmt::Display;
use std::path::PathBuf;
use std::time::Duration;
use crate::events::Stream;
use crate::process::{Captured, ProcessError, ProcessRunner, ProcessSpec, capture_echoing};
pub(crate) struct Call<'a> {
pub(crate) runner: &'a dyn ProcessRunner,
pub(crate) cwd: Option<PathBuf>,
pub(crate) env: Vec<(String, String)>,
pub(crate) limit: Duration,
pub(crate) sink: &'a (dyn Fn(Stream, &str) + Send + Sync),
pub(crate) host_env: &'a crate::host_env::HostEnv,
}
#[derive(Debug, thiserror::Error)]
pub(crate) enum CliError<F: Display> {
#[error("`{tool}` isn't installed or isn't on PATH")]
Missing {
tool: &'static str,
},
#[error("`{tool}` is {found}, older than the {min} this runner drives")]
TooOld {
tool: &'static str,
found: String,
min: String,
},
#[error("`{tool}` was still running after {limit_s}s, and was stopped")]
TimedOut {
tool: &'static str,
limit_s: u64,
last_line: Option<String>,
},
#[error("`{tool}` printed nothing for {after_s}s and was stopped")]
Stalled {
tool: &'static str,
after_s: u64,
last_line: Option<String>,
},
#[error("`{tool}` printed what can't be read: {what}")]
Unexpected {
tool: &'static str,
what: String,
},
#[error("`{tool}` couldn't start: {why}")]
Spawn {
tool: &'static str,
why: String,
},
#[error("`{tool}` failed: {failure}")]
Failed {
tool: &'static str,
failure: F,
},
}
impl Call<'_> {
pub(crate) async fn run<F: Display>(&self, tool: &'static str, args: Vec<String>) -> Result<Captured, CliError<F>> {
self.run_spec(tool, self.spec(tool, args)).await
}
async fn run_spec<F: Display>(&self, tool: &'static str, spec: ProcessSpec) -> Result<Captured, CliError<F>> {
match self.run_once(tool, &spec).await {
Err(CliError::Missing { .. }) => match installed::find(tool, self.host_env) {
installed::Installed::At(path) => {
let mut at = spec;
at.program = path.display().to_string();
self.run_once(tool, &at).await
}
installed::Installed::AppWithout(why) => Err(CliError::Spawn { tool, why }),
installed::Installed::Nothing => Err(CliError::Missing { tool }),
},
other => other,
}
}
async fn run_once<F: Display>(&self, tool: &'static str, spec: &ProcessSpec) -> Result<Captured, CliError<F>> {
self.run_watched(tool, spec, None).await
}
async fn run_watched<F: Display>(&self, tool: &'static str, spec: &ProcessSpec, stall: Option<Duration>) -> Result<Captured, CliError<F>> {
let last: std::sync::Mutex<(Option<String>, tokio::time::Instant)> = std::sync::Mutex::new((None, tokio::time::Instant::now()));
let kept = || last.lock().unwrap_or_else(std::sync::PoisonError::into_inner).0.clone();
let mut echo = |stream: Stream, line: &str| {
if !line.trim().is_empty() {
*last.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = (Some(crate::error::kept_line(line.trim_end())), tokio::time::Instant::now());
}
(self.sink)(stream, line);
};
let watch = async {
let Some(stall) = stall else { return std::future::pending().await };
loop {
let due = last.lock().unwrap_or_else(std::sync::PoisonError::into_inner).1 + stall;
if tokio::time::Instant::now() >= due {
return stall;
}
tokio::time::sleep_until(due).await;
}
};
let ran = tokio::select! {
ran = tokio::time::timeout(self.limit, capture_echoing(self.runner, spec, &mut echo)) => ran,
after = watch => {
return Err(CliError::Stalled {
tool,
after_s: after.as_secs(),
last_line: kept(),
});
}
};
match ran {
Err(_) => Err(CliError::TimedOut {
tool,
limit_s: self.limit.as_secs(),
last_line: kept(),
}),
Ok(Err(ProcessError::Missing { .. })) => Err(CliError::Missing { tool }),
Ok(Err(e)) => Err(CliError::Spawn { tool, why: e.to_string() }),
Ok(Ok(out)) => Ok(out),
}
}
pub(crate) async fn ok_watched<F: Display>(
&self,
tool: &'static str,
args: Vec<String>,
stall: Duration,
failure_of: impl FnOnce(&Captured) -> F,
) -> Result<Captured, CliError<F>> {
let out = self.run_watched(tool, &self.spec(tool, args), Some(stall)).await?;
if out.success() {
Ok(out)
} else {
Err(CliError::Failed {
tool,
failure: failure_of(&out),
})
}
}
pub(crate) async fn ok<F: Display>(&self, tool: &'static str, args: Vec<String>, failure_of: impl FnOnce(&Captured) -> F) -> Result<Captured, CliError<F>> {
let out = self.run(tool, args).await?;
if out.success() {
Ok(out)
} else {
Err(CliError::Failed {
tool,
failure: failure_of(&out),
})
}
}
}
impl Call<'_> {
pub(crate) fn spec(&self, tool: &str, args: Vec<String>) -> ProcessSpec {
let mut spec = ProcessSpec::new(tool, args);
spec.cwd.clone_from(&self.cwd);
spec.env.clone_from(&self.env);
spec
}
}
pub(crate) fn version<F: Display>(tool: &'static str, said: &str, min: Option<&str>) -> Result<Option<crate::project::platform::Version>, CliError<F>> {
let Some(found) = crate::tool_output::version_found(said) else {
tracing::warn!(tool, said = said.trim(), "no version the runner reads: the tool is used, its minimum unchecked");
return Ok(None);
};
if let Some(min) = min.and_then(crate::project::platform::Version::parse)
&& found < min
{
return Err(CliError::TooOld {
tool,
found: found.to_string(),
min: min.to_string(),
});
}
Ok(Some(found))
}
pub(crate) fn said_any(out: &Captured, wordings: &[&str]) -> bool {
out.stdout.iter().chain(&out.stderr_tail).any(|l| {
let l = l.to_lowercase();
wordings.iter().any(|w| l.contains(w))
})
}
pub(crate) fn done_or_gone(tool: &'static str, out: &Captured, gone: &[&str]) -> Result<(), CliError<String>> {
if out.success() || said_any(out, gone) {
return Ok(());
}
Err(CliError::Failed { tool, failure: out.reason() })
}
pub(crate) async fn stop_then_delete(
call: &Call<'_>,
tool: &'static str,
stop: Vec<String>,
delete: Vec<String>,
gone: &[&str],
) -> Result<(), CliError<String>> {
drop(call.run::<String>(tool, stop).await?);
let out = call.run::<String>(tool, delete).await?;
done_or_gone(tool, &out, gone)
}
pub(crate) fn argv<const N: usize>(args: [&str; N]) -> Vec<String> {
args.map(str::to_owned).to_vec()
}
#[cfg(test)]
pub(crate) mod testing {
use std::time::Duration;
use super::Call;
use crate::process::fake::FakeProcesses;
pub(crate) fn quiet(_: crate::events::Stream, _: &str) {}
pub(crate) fn call(fake: &FakeProcesses) -> Call<'_> {
Call {
runner: fake,
cwd: None,
env: Vec::new(),
limit: Duration::from_secs(60),
sink: &quiet,
host_env: &crate::host_env::EMPTY,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::process::fake::{FakeProcesses, Reply};
#[tokio::test]
async fn a_missing_tool_and_a_failure_are_told_apart() {
let fake = FakeProcesses::script()
.expect("docker version", Reply::missing())
.expect("vagrant status", Reply::fail(1, "boom"))
.build();
let call = testing::call(&fake);
let missing = call.run::<String>("docker", argv(["version"])).await.unwrap_err();
assert!(matches!(missing, CliError::Missing { tool: "docker" }), "{missing}");
let failed = call.ok("vagrant", argv(["status"]), Captured::reason).await.unwrap_err();
assert!(
matches!(&failed, CliError::Failed { tool: "vagrant", failure } if failure == "boom (exited with code 1)"),
"{failed}"
);
}
#[tokio::test(start_paused = true)]
async fn a_tool_past_its_limit_is_ended_as_timed_out_keeping_its_last_line() {
let slow = Reply::ok("Waiting for machine to boot\nnever printed").paced(Duration::from_secs(40));
let fake = FakeProcesses::script().expect("vagrant up", slow).build();
let e = testing::call(&fake).run::<String>("vagrant", argv(["up"])).await.unwrap_err();
assert!(
matches!(&e, CliError::TimedOut { tool: "vagrant", limit_s: 60, last_line: Some(l) } if l == "Waiting for machine to boot"),
"{e:?}"
);
}
}