mod delivery;
pub(crate) mod plan;
mod progress;
mod reconnect;
mod retry;
pub(crate) mod state_files;
mod step;
pub(crate) use delivery::{env_deliveries, every_delivery, slot_value};
use std::collections::BTreeSet;
use std::sync::{Mutex, PoisonError};
use isoloom_manifest::{Action, Failure, Run, Step, When};
use tracing::Instrument;
pub(crate) use progress::{DOWNLOAD_STALL, Progress, within};
pub(crate) use step::{
Echo, Hold, call, call_ok, capture_output, capture_step, download, env_of, once, run_argv, spec_for, stdin_of, stdout_of, with_delivered,
};
use crate::Result;
use crate::error::Error;
use crate::events::WarningCode;
use crate::events::{Emitter, StepState};
use crate::run::Running;
use crate::scope::Scope;
use crate::secrets::Secrets;
use crate::vars::Vars;
pub(crate) struct Cx<'a> {
pub(crate) run: &'a Running<'a>,
pub(crate) state_dir: std::path::PathBuf,
pub(crate) vars: Vars,
pub(crate) secrets: &'a Secrets,
pub(crate) events: &'a Emitter<'a>,
pub(crate) scope: Scope,
pub(crate) processes: std::sync::Arc<dyn crate::process::ProcessRunner>,
pub(crate) stale: LineWatch,
pub(crate) gone: LineWatch,
pub(crate) ssh_jump: Option<String>,
pub(crate) expires_at: Option<u64>,
pub(crate) relayed: Option<crate::relay::Relayed>,
pub(crate) set_up: std::collections::BTreeSet<String>,
pub(crate) query: bool,
}
impl Cx<'_> {
pub(crate) fn state_dir(&self) -> &std::path::Path {
&self.state_dir
}
}
#[derive(Debug, Default)]
pub(crate) struct LineWatch {
any_case: bool,
texts: Mutex<BTreeSet<String>>,
seen: Mutex<BTreeSet<String>>,
}
impl LineWatch {
pub(crate) fn any_case(texts: &[String]) -> LineWatch {
let watch = LineWatch {
any_case: true,
..LineWatch::default()
};
watch.watch(texts.iter().cloned());
watch
}
pub(crate) fn watch(&self, texts: impl IntoIterator<Item = String>) {
let texts = texts.into_iter().filter(|t| !t.is_empty());
*self.texts.lock().unwrap_or_else(PoisonError::into_inner) = if self.any_case {
texts.map(|t| t.to_lowercase()).collect()
} else {
texts.collect()
};
self.seen.lock().unwrap_or_else(PoisonError::into_inner).clear();
}
fn notice(&self, line: &str) {
let texts = self.texts.lock().unwrap_or_else(PoisonError::into_inner);
if texts.is_empty() {
return;
}
let line = if self.any_case { line.to_lowercase() } else { line.to_owned() };
let found = texts.iter().filter(|t| line.contains(t.as_str())).cloned();
self.seen.lock().unwrap_or_else(PoisonError::into_inner).extend(found);
}
pub(crate) fn seen(&self) -> BTreeSet<String> {
self.seen.lock().unwrap_or_else(PoisonError::into_inner).clone()
}
pub(crate) fn rewind(&self, seen: BTreeSet<String>) {
*self.seen.lock().unwrap_or_else(PoisonError::into_inner) = seen;
}
pub(crate) fn take(&self) -> BTreeSet<String> {
std::mem::take(&mut *self.seen.lock().unwrap_or_else(PoisonError::into_inner))
}
pub(crate) fn end(&self) -> BTreeSet<String> {
self.texts.lock().unwrap_or_else(PoisonError::into_inner).clear();
self.take()
}
}
#[derive(Debug, Default)]
pub(crate) struct Ran {
pub(crate) ok: BTreeSet<String>,
}
pub(crate) const UP: &str = "lifecycle.up";
pub(crate) const DOWN: &str = "lifecycle.down";
const GONE_ROUNDS: u8 = 3;
pub(crate) async fn run_steps(cx: &mut Cx<'_>, list: &str, steps: &[Step]) -> Result<Ran> {
run_list(cx, list, steps, AfterStep::Nothing).await
}
pub(crate) async fn run_up_steps(cx: &mut Cx<'_>, steps: &[Step]) -> Result<Ran> {
run_list(cx, UP, steps, AfterStep::DeliverToGuests).await
}
pub(crate) async fn run_down_steps(cx: &mut Cx<'_>) -> Result<Ran> {
let down = cx.run.manifest().lifecycle.down.as_slice();
for _ in 0..GONE_ROUNDS {
cx.gone.watch(cx.run.driver.gone(cx)?.into_iter().map(|g| g.text));
let done = run_steps(cx, DOWN, down).await;
let seen = cx.gone.end();
let failed = match &done {
Err(Error::ToolFailed { step, .. }) if !seen.is_empty() => down.iter().find(|s| s.id.as_str() == step),
_ => None,
};
let Some(step) = failed else { return done };
if !cx.run.driver.forget_gone(cx, DOWN, step, &seen).await? {
return done;
}
}
run_steps(cx, DOWN, down).await
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum AfterStep {
Nothing,
DeliverToGuests,
}
async fn run_list(cx: &mut Cx<'_>, list: &str, steps: &[Step], after: AfterStep) -> Result<Ran> {
let mut ran = Ran::default();
let mut failure: Option<Error> = None;
for step in steps {
let id = step.id.as_str();
if !plan::applies(&cx.scope, step) {
ran.ok.insert(id.to_owned());
continue;
}
if failure.is_some() && step.when == When::IfOk {
cx.events.step(id, StepState::Skipped, None);
continue;
}
let span = tracing::info_span!("step", list, step = id);
let done = match run_step(cx, list, step).instrument(span).await {
Ok(()) if after == AfterStep::DeliverToGuests => crate::guest::deliver(cx, Some(id)).await,
other => other,
};
match done {
Ok(()) => {
ran.ok.insert(id.to_owned());
}
Err(e) if step.failure == Failure::Tolerate => {
cx.events.warning(WarningCode::StepTolerated, &e.to_string());
}
Err(e) => {
failure.get_or_insert(e);
}
}
}
failure.map_or(Ok(ran), Err)
}
async fn run_step(cx: &mut Cx<'_>, list: &str, step: &Step) -> Result<()> {
if !awaits_state(&cx.vars, step) {
cx.run.driver.before_step(cx, list, step).await?;
}
let events = cx.events;
let done = events.stepped(step.id.as_str(), step.note.as_deref(), step_work(cx, list, step)).await;
match &done {
Ok(()) => tracing::debug!("step done"),
Err(e) => tracing::debug!(error = %e, "step failed"),
}
done
}
async fn step_work(cx: &mut Cx<'_>, list: &str, step: &Step) -> Result<()> {
if awaits_state(&cx.vars, step) {
let run = cx.run;
let observed = run.observe(cx).await?;
run.bind_observed(cx, observed);
}
let cx: &Cx<'_> = cx;
match &step.run {
Run::Argv(_) | Run::Action { action: Action::SshRun, .. } => {
run_argv(cx, list, step, &mut |line| {
cx.stale.notice(line);
cx.gone.notice(line);
})
.await
}
Run::Action {
action: Action::ProjectArchive,
with,
} => crate::archive::project(cx, list, step, with).await,
Run::Action { action, .. } => cx.run.driver.action(cx, list, step, *action).await,
}
}
fn awaits_state(vars: &Vars, step: &Step) -> bool {
let argvs: Vec<&isoloom_manifest::Argv> = match &step.run {
Run::Argv(argv) => plan::every_argv(argv).collect(),
Run::Action { .. } => Vec::new(),
};
let with = match &step.run {
Run::Action { with, .. } => with.values().collect(),
Run::Argv(_) => Vec::new(),
};
argvs
.into_iter()
.flat_map(|a| a.args().iter())
.chain(with)
.chain(step.env.values())
.chain(step.stdin.iter().map(isoloom_manifest::PathTemplate::template))
.flat_map(isoloom_manifest::Template::placeholders)
.any(|p| vars.awaits_state(p))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_step_naming_an_output_or_a_host_without_a_value_awaits_the_drivers_state() {
let step = |json: &str| serde_json::from_str::<Step>(json).unwrap();
let ssh = step(r#"{"id":"copy","action":"ssh.run","with":{"host":"${outputs.ip}","command":"true"}}"#);
let piped = step(r#"{"id":"open","argv":["curl","http://${host.web}/"]}"#);
let plain = step(r#"{"id":"apply","argv":["terraform","apply"],"env":{"TF_DATA_DIR":"${run.state_dir}/.terraform"}}"#);
let mut vars = Vars::default();
assert!(awaits_state(&vars, &ssh) && awaits_state(&vars, &piped));
assert!(!awaits_state(&vars, &plain));
vars.set_output("ip", "10.0.0.7".into());
vars.set_hosts(std::collections::BTreeMap::from([("web".to_owned(), "127.0.0.1".to_owned())]));
assert!(!awaits_state(&vars, &ssh) && !awaits_state(&vars, &piped));
}
#[test]
fn a_stale_marker_is_seen_in_any_line_whatever_its_case() {
let stale = LineWatch::any_case(&["VERR_already_exists".into(), "is locked".into()]);
stale.notice(" web: Progress state: VBOX_E_FILE_ERROR");
assert_eq!(stale.take(), BTreeSet::new());
stale.notice("VBoxManage: error: Details: code VERR_ALREADY_EXISTS (0x80004005)");
stale.notice("ok");
assert_eq!(stale.take().into_iter().collect::<Vec<_>>(), ["verr_already_exists"]);
assert_eq!(stale.take(), BTreeSet::new(), "taken once");
stale.notice("the machine is locked");
assert_eq!(stale.take().len(), 1, "still watched after a take");
let none = LineWatch::any_case(&[]);
none.notice("anything");
assert_eq!(none.take(), BTreeSet::new());
}
#[test]
fn a_watched_text_is_seen_exactly_as_written_until_taken() {
let watched = LineWatch::default();
watched.notice("no such IPSet 'iso1n0'");
assert_eq!(watched.take(), BTreeSet::new(), "nothing watched yet");
watched.watch(["no such IPSet 'iso1n0'".to_owned(), "no such IPSet 'iso1n1'".to_owned(), String::new()]);
watched.notice("Error: error getting IPSet content: received an HTTP 500 response - Reason: NO SUCH IPSET 'ISO1N0'");
watched.notice("Error: error getting IPSet content: received an HTTP 500 response - Reason: no such IPSet 'iso1n00'");
watched.notice("anything");
assert_eq!(watched.take(), BTreeSet::new(), "another case, another set: not the text");
watched.watch(["no such IPSet 'iso1n0'".to_owned()]);
watched.notice("Error: error getting IPSet content: received an HTTP 500 response - Reason: no such IPSet 'iso1n0'");
assert_eq!(watched.end().into_iter().collect::<Vec<_>>(), ["no such IPSet 'iso1n0'"]);
watched.notice("no such IPSet 'iso1n0'");
assert_eq!(watched.take(), BTreeSet::new(), "ending it ends the watch");
}
}