use std::collections::VecDeque;
use std::time::Duration;
use isoloom_manifest::{Action, Run, Step};
use regex::Regex;
use super::delivery::step_env;
use super::progress::{Progress, downloading, within};
use super::retry::Retry;
use super::{Cx, plan};
use crate::Result;
use crate::error::Error;
use crate::events::Stream;
use crate::process::{Captured, ProcessError, ProcessSpec, STDOUT_REASON_LINES, Tail, capture_echoing};
use crate::scope::Scope;
pub(crate) async fn run_argv(cx: &Cx<'_>, list: &str, step: &Step, observe: &mut (dyn FnMut(&str) + Send)) -> Result<()> {
let mut retry = Retry::default();
loop {
let stale = cx.stale.seen();
let done = run_argv_once(cx, list, step, observe).await;
let Err(Error::DownloadFailed { reason, .. }) = &done else { return done };
if !step.download || !retry.again(cx, step.id.as_str(), reason).await {
return done;
}
cx.stale.rewind(stale);
}
}
async fn run_argv_once(cx: &Cx<'_>, list: &str, step: &Step, observe: &mut (dyn FnMut(&str) + Send)) -> Result<()> {
if let Some(wait) = crate::ssh::wait_of(cx, list, step)? {
return super::reconnect::run(cx, list, step, observe, &wait).await;
}
cx.run.driver.run_argv(cx, list, step, observe).await
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Hold {
No,
UntilOutput,
}
#[derive(Debug)]
pub(crate) struct Ended {
pub(crate) last: Captured,
pub(crate) printed: bool,
lead: Option<String>,
held: Vec<String>,
}
impl Ended {
pub(crate) fn result(self, cx: &Cx<'_>, step: &Step) -> Result<()> {
if self.last.success() {
return Ok(());
}
let reason = cx.events.mask(&self.lead.unwrap_or_else(|| self.last.reason()));
let id = step.id.to_string();
Err(if step.download {
Error::DownloadFailed { step: id, reason }
} else {
Error::ToolFailed { step: id, reason }
})
}
pub(crate) fn show_held(&mut self, cx: &Cx<'_>, step: &Step, observe: &mut (dyn FnMut(&str) + Send)) {
for line in std::mem::take(&mut self.held) {
cx.events.log(step.id.as_str(), Stream::Stderr, &line);
observe(&line);
}
}
}
pub(crate) async fn once(cx: &Cx<'_>, list: &str, step: &Step, observe: &mut (dyn FnMut(&str) + Send), hold: Hold) -> Result<Ended> {
let id = step.id.as_str();
let spec = spec_for(cx, list, step)?;
let verdict = match &step.verdict {
Some(pattern) => Some(Regex::new(pattern).map_err(|e| Error::Malformed {
at: format!("{}.verdict", plan::at(list, step)),
reason: format!("`{pattern}` isn't a regular expression ({e})"),
})?),
None => None,
};
let (mut tail, mut lead, mut printed, mut kept_back) = (Tail::default(), None, false, Vec::new());
let mut last_out = VecDeque::with_capacity(STDOUT_REASON_LINES);
let progress = Progress::new();
let mut on_line = |stream: Stream, line: &str| {
progress.saw(line);
if stream == Stream::Stderr {
tail.push(line);
} else {
if last_out.len() == STDOUT_REASON_LINES {
last_out.pop_front();
}
last_out.push_back(line.to_owned());
}
if hold == Hold::UntilOutput && !printed && stream == Stream::Stderr {
kept_back.push(line.to_owned());
return;
}
if stream == Stream::Stdout && !printed {
printed = true;
for earlier in kept_back.drain(..) {
cx.events.log(id, Stream::Stderr, &earlier);
observe(&earlier);
}
}
cx.events.log(id, stream, line);
observe(line);
if let Some(found) = verdict.as_ref().and_then(|v| verdict_of(v, line)) {
lead = Some(found);
}
};
let run = cx.processes.run(&spec, &mut on_line);
let exit = if step.download {
downloading(id, plan::limit(step, &cx.scope), &progress, run).await
} else {
timed(step, &cx.scope, &progress, run).await
}
.map_err(|e| masked(cx, e))?;
Ok(Ended {
last: Captured {
exit,
stdout: last_out.into(),
stderr: tail.into_lines(),
},
printed,
lead,
held: kept_back,
})
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Echo {
Quiet,
Shown,
}
pub(crate) async fn call(cx: &Cx<'_>, id: &str, spec: &ProcessSpec, limit: Duration, echo: Echo) -> Result<Captured> {
let progress = Progress::new();
let mut shown = |stream: Stream, line: &str| {
progress.saw(line);
if echo == Echo::Shown {
cx.events.log(id, stream, line);
}
};
within(id, limit, &progress, capture_echoing(cx.processes.as_ref(), spec, &mut shown))
.await
.map_err(|e| masked(cx, e))
}
pub(crate) async fn download(cx: &Cx<'_>, id: &str, spec: &ProcessSpec, stall: Duration) -> Result<Captured> {
let mut retry = Retry::default();
loop {
let out = download_once(cx, id, spec, stall).await?;
if out.success() || !retry.again(cx, id, &cx.events.mask(&out.reason())).await {
return Ok(out);
}
}
}
async fn download_once(cx: &Cx<'_>, id: &str, spec: &ProcessSpec, stall: Duration) -> Result<Captured> {
let progress = Progress::new();
let mut shown = |stream: Stream, line: &str| {
progress.saw(line);
cx.events.log(id, stream, line);
};
downloading(id, stall, &progress, capture_echoing(cx.processes.as_ref(), spec, &mut shown))
.await
.map_err(|e| masked(cx, e))
}
fn masked(cx: &Cx<'_>, e: Error) -> Error {
match e {
Error::Timeout { step, timed_out } => Error::Timeout {
step,
timed_out: timed_out.masked(|l| cx.events.mask(l)),
},
Error::DownloadStalled { step, after_s, last_line } => Error::DownloadStalled {
step,
after_s,
last_line: last_line.map(|l| cx.events.mask(&l)),
},
other => other,
}
}
pub(crate) async fn call_ok(cx: &Cx<'_>, id: &str, spec: &ProcessSpec, limit: Duration, echo: Echo) -> Result<String> {
let out = call(cx, id, spec, limit, echo).await?;
stdout_of(cx, id, Some(spec), &out)
}
pub(crate) fn stdout_of(cx: &Cx<'_>, id: &str, call: Option<&ProcessSpec>, out: &Captured) -> Result<String> {
out.output().map_err(|why| {
let reason = match call {
Some(spec) => format!("`{}` failed: {why}", spec.line()),
None => why,
};
Error::ToolFailed {
step: id.to_owned(),
reason: cx.events.mask(&reason),
}
})
}
pub(crate) async fn capture_step(cx: &Cx<'_>, list: &str, step: &Step) -> Result<String> {
let out = capture_output(cx, list, step).await?;
stdout_of(cx, step.id.as_str(), None, &out)
}
pub(crate) async fn capture_output(cx: &Cx<'_>, list: &str, step: &Step) -> Result<Captured> {
let spec = spec_for(cx, list, step)?;
let progress = Progress::new();
let run = progress.capture(cx.processes.as_ref(), &spec);
timed(step, &cx.scope, &progress, run).await.map_err(|e| masked(cx, e))
}
pub(crate) fn spec_for(cx: &Cx<'_>, list: &str, step: &Step) -> Result<ProcessSpec> {
let at = plan::at(list, step);
let argv = match &step.run {
Run::Argv(argv) => argv,
Run::Action { action: Action::SshRun, with } => return crate::ssh::step_spec(cx, list, step, with),
Run::Action { .. } => {
return Err(Error::Unsupported {
what: format!("{at}: an action where a command was expected"),
});
}
};
let command = plan::command(argv, cx.scope.host, &cx.vars, &at)?;
let dir = cx.run.dir();
let spec = ProcessSpec {
program: command.program,
args: command.args,
cwd: Some(step.cwd.as_ref().map_or_else(|| dir.to_path_buf(), |c| dir.join(c.as_str()))),
env: env_of(cx, list, step)?,
stdin: stdin_of(cx, list, step)?,
tools: None,
};
Ok(crate::container::wrap(cx, spec))
}
pub(crate) fn stdin_of(cx: &Cx<'_>, list: &str, step: &Step) -> Result<Option<std::path::PathBuf>> {
let Some(path) = &step.stdin else { return Ok(None) };
let filled = cx.vars.render(path.template(), &format!("{}.stdin", plan::at(list, step)))?;
Ok(Some(cx.run.dir().join(filled)))
}
pub(crate) fn env_of(cx: &Cx<'_>, list: &str, step: &Step) -> Result<Vec<(String, String)>> {
let at = plan::at(list, step);
let mut env = cx.run.driver.env(cx)?;
for (name, value) in &step.env {
env.push((name.to_string(), cx.vars.render(value, &at)?));
}
Ok(with_delivered(cx, step.id.as_str(), env))
}
pub(crate) fn with_delivered(cx: &Cx<'_>, id: &str, mut env: Vec<(String, String)>) -> Vec<(String, String)> {
env.extend(step_env(cx, id));
env.extend(cx.relayed.iter().flat_map(|r| r.env.iter().cloned()));
env
}
async fn timed<T>(step: &Step, scope: &Scope, progress: &Progress, run: impl Future<Output = Result<T, ProcessError>>) -> Result<T> {
within(step.id.as_str(), plan::limit(step, scope), progress, run).await
}
pub(super) fn process_error(step: &str, e: ProcessError) -> Error {
match e {
ProcessError::Missing { program } => Error::ToolMissing {
step: step.to_owned(),
tool: program,
},
ProcessError::Elevation { reason } => Error::Elevation { reason },
other => Error::ToolFailed {
step: step.to_owned(),
reason: other.to_string(),
},
}
}
const VERDICT_MAX: usize = 300;
fn verdict_of(verdict: &Regex, line: &str) -> Option<String> {
let found = verdict.find(line)?;
Some(cut(line.get(found.start()..)?.trim_end(), VERDICT_MAX))
}
pub(super) fn cut(text: &str, max: usize) -> String {
if text.len() <= max {
return text.to_owned();
}
let end = (0..=max.saturating_sub(3)).rev().find(|&i| text.is_char_boundary(i)).unwrap_or(0);
format!("{}...", text.get(..end).unwrap_or_default())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_verdict_keeps_the_fatal_line_without_vagrants_prefix_and_short() {
let v = Regex::new("fatal: \\[[^\\]]+\\]: (UNREACHABLE|FAILED)!.*").unwrap();
let line = " isoloom-controller: fatal: [ws01]: UNREACHABLE! => {\"msg\": \"winrm connection error\"}";
assert_eq!(
verdict_of(&v, line).as_deref(),
Some("fatal: [ws01]: UNREACHABLE! => {\"msg\": \"winrm connection error\"}")
);
assert_eq!(verdict_of(&v, " dc01: ok: [dc01]"), None);
let ascii = format!("fatal: [a]: FAILED! => {}", "x".repeat(400));
assert_eq!(verdict_of(&v, &ascii).map(|c| c.len()), Some(VERDICT_MAX), "cut at the limit, `...` included");
let long = format!("fatal: [a]: FAILED! => {}", "é".repeat(300));
let cut = verdict_of(&v, &long).unwrap();
assert!(cut.ends_with("...") && cut.len() <= VERDICT_MAX, "{} bytes", cut.len());
}
}