use std::time::Duration;
use isoloom_manifest::{ReadyGrammar, ReadyLine};
use super::not_ready;
use crate::Result;
use crate::error::Error;
use crate::events::ReadyState;
use crate::executor::{Cx, Echo, call};
use crate::ssh::{self, Login};
const UNREACHABLE_DEFAULT: Duration = Duration::from_secs(600);
const READ_LIMIT: Duration = Duration::from_secs(60);
const LOG_TAIL: usize = 25;
const LOG_MARK: &str = "--isoloom-log--";
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Progress {
Booting,
Running(String),
Ready,
Failed(String),
}
pub(crate) fn progress(grammar: ReadyGrammar, line: &str) -> Progress {
match grammar {
ReadyGrammar::V1 => progress_v1(line),
}
}
fn progress_v1(line: &str) -> Progress {
match ReadyLine::parse(line) {
Some(ReadyLine::Ready) => Progress::Ready,
Some(ReadyLine::Running { step }) => Progress::Running(step),
Some(ReadyLine::Failed { step }) => Progress::Failed(step),
None => Progress::Booting,
}
}
#[derive(Debug, Clone)]
pub(crate) struct Wait {
pub(crate) condition: String,
pub(crate) login: Login,
pub(crate) path: String,
pub(crate) log: Option<String>,
pub(crate) grammar: ReadyGrammar,
pub(crate) within: Duration,
pub(crate) unreachable: Option<Duration>,
pub(crate) every: Duration,
}
fn read_command(path: &str, log: Option<&str>) -> String {
let tail = log.map_or(String::new(), |l| format!("tail -n {LOG_TAIL} {} 2>/dev/null; ", crate::console::sh_quote(l)));
format!("head -n 1 {} 2>/dev/null; echo {LOG_MARK}; {tail}true", crate::console::sh_quote(path))
}
fn split(out: &[String]) -> (String, Vec<String>) {
let mark = out.iter().position(|l| l == LOG_MARK).unwrap_or(out.len());
let first = out.get(..mark).and_then(|f| f.first()).cloned().unwrap_or_default();
let tail = out
.get(mark + 1..)
.unwrap_or_default()
.iter()
.filter(|l| !l.trim().is_empty())
.cloned()
.collect();
(first, tail)
}
pub(crate) async fn wait(cx: &Cx<'_>, w: &Wait) -> Result<()> {
let spec = ssh::spec(cx, &w.login, &read_command(&w.path, w.log.as_deref()), Vec::new())?;
let started = tokio::time::Instant::now();
let unreachable = w.unreachable.unwrap_or(UNREACHABLE_DEFAULT);
let (mut reached, mut last, mut failed) = (false, Progress::Booting, None::<String>);
loop {
match call(cx, &w.condition, &spec, READ_LIMIT, Echo::Quiet).await {
Ok(out) if out.success() => {
(reached, failed) = (true, None);
let (line, tail) = split(&out.stdout);
if let Some(done) = settle(cx, w, progress(w.grammar, &line), &tail, &mut last) {
return done;
}
}
Err(e @ Error::ToolMissing { .. }) => return Err(e),
read => {
let why = cx.events.mask(&read.map_or_else(|e| e.to_string(), |out| out.reason()));
if failed.as_deref() != Some(why.as_str()) {
cx.events.ready(&w.condition, ReadyState::Waiting, &format!("no answer over SSH yet: {why}"));
}
if !reached && started.elapsed() >= unreachable {
let detail = format!("{} didn't answer over SSH within {}s: {why}", w.login.target, unreachable.as_secs());
return Err(not_ready(cx, w.condition.clone(), detail));
}
failed = Some(why);
}
}
if started.elapsed() >= w.within {
return Err(not_ready(cx, w.condition.clone(), out_of_time(w, &last, failed.as_deref())));
}
tokio::time::sleep(w.every).await;
}
}
fn out_of_time(w: &Wait, last: &Progress, failed: Option<&str>) -> String {
let step = match last {
Progress::Running(s) => s.as_str(),
_ => "booting",
};
let detail = format!("not done within {}s (last step: {step})", w.within.as_secs());
match failed {
Some(why) => format!("{detail}; its last read over SSH failed: {why}"),
None => detail,
}
}
fn settle(cx: &Cx<'_>, w: &Wait, now: Progress, tail: &[String], last: &mut Progress) -> Option<Result<()>> {
match &now {
Progress::Ready => {
cx.events.ready(&w.condition, ReadyState::Ok, "ready");
return Some(Ok(()));
}
Progress::Failed(step) => {
let mut detail = format!("failed: {step}");
if !tail.is_empty() {
detail = format!("{detail}\n{}", tail.join("\n"));
}
return Some(Err(not_ready(cx, w.condition.clone(), cx.events.mask(&detail))));
}
Progress::Running(step) if *last != now => cx.events.ready(&w.condition, ReadyState::Waiting, &format!("running: {step}")),
_ => {}
}
*last = now;
None
}
#[cfg(test)]
mod tests {
use proptest::prelude::*;
use super::*;
#[test]
fn the_first_line_says_how_far_the_bootstrap_got() {
assert_eq!(progress(ReadyGrammar::V1, "ready\n"), Progress::Ready);
assert_eq!(
progress(ReadyGrammar::V1, "running: provision/web.sh"),
Progress::Running("provision/web.sh".into())
);
assert_eq!(
progress(ReadyGrammar::V1, "failed: waiting for cache "),
Progress::Failed("waiting for cache".into())
);
assert_eq!(progress(ReadyGrammar::V1, ""), Progress::Booting, "no file yet");
assert_eq!(progress(ReadyGrammar::V1, "ready now"), Progress::Booting);
}
#[test]
fn a_read_is_the_files_line_then_the_logs_tail() {
let cmd = read_command("/var/lib/isoloom/ready", Some("/var/log/cloud-init-output.log"));
assert_eq!(
cmd,
"head -n 1 '/var/lib/isoloom/ready' 2>/dev/null; echo --isoloom-log--; tail -n 25 '/var/log/cloud-init-output.log' 2>/dev/null; true"
);
let out: Vec<String> = ["failed: provision/web.sh", LOG_MARK, "", "E: Unable to locate package nginx"]
.map(String::from)
.into();
assert_eq!(
split(&out),
("failed: provision/web.sh".into(), vec!["E: Unable to locate package nginx".to_owned()])
);
assert_eq!(split(&[LOG_MARK.to_owned()]), (String::new(), Vec::new()), "no file yet");
}
#[test]
fn a_wait_out_of_time_says_why_its_last_read_failed() {
let w = Wait {
condition: "ready_file 10.0.0.9".into(),
login: Login::new("isoloom", "10.0.0.9", None, "").unwrap(),
path: "/var/lib/isoloom/ready".into(),
log: None,
grammar: ReadyGrammar::V1,
within: Duration::from_secs(900),
unreachable: None,
every: Duration::from_secs(5),
};
let running = Progress::Running("provision/web.sh".into());
assert_eq!(out_of_time(&w, &running, None), "not done within 900s (last step: provision/web.sh)");
assert_eq!(
out_of_time(&w, &Progress::Booting, Some("Connection reset (exited with code 255)")),
"not done within 900s (last step: booting); its last read over SSH failed: Connection reset (exited with code 255)"
);
}
#[test]
fn every_grammar_isoloom_lists_is_read() {
let grammars = crate::testing::every_variant::<ReadyGrammar>();
assert_ne!(grammars, []);
for grammar in grammars {
assert_eq!(progress(grammar, "ready"), Progress::Ready, "{grammar:?}");
}
}
proptest! {
#[test]
fn any_line_reads_as_some_progress(line in ".{0,60}") {
let p = progress(ReadyGrammar::V1, &line);
if line.trim() == "ready" { prop_assert_eq!(p, Progress::Ready) }
}
}
}