use std::time::Duration;
use isothrum_runner::{BoxFuture, ErrorReport, RunOptions};
use super::super::Progress;
use super::{Failure, Found, RETRY, Ran, Step, StepProgress};
pub(super) trait Deployment: Sync {
fn up<'a>(&'a self, line: &'a (dyn Fn(&str) + Send + Sync)) -> BoxFuture<'a, Result<(), Box<ErrorReport>>>;
fn exec<'a>(&'a self, argv: &'a [&'a str]) -> BoxFuture<'a, Result<(i32, String), Box<ErrorReport>>>;
fn down<'a>(&'a self, line: &'a (dyn Fn(&str) + Send + Sync)) -> BoxFuture<'a, Result<(), Box<ErrorReport>>>;
}
pub(super) struct OnRunner<'r> {
pub(super) run: isothrum_runner::Running<'r>,
pub(super) opts: RunOptions,
pub(super) machine: &'static str,
}
fn lines(line: &(dyn Fn(&str) + Send + Sync)) -> impl Fn(&isothrum_runner::Event) + Send + Sync + '_ {
move |e: &isothrum_runner::Event| {
if let isothrum_runner::EventKind::Log { line: said, .. } = &e.kind {
line(said);
}
}
}
impl Deployment for OnRunner<'_> {
fn up<'a>(&'a self, line: &'a (dyn Fn(&str) + Send + Sync)) -> BoxFuture<'a, Result<(), Box<ErrorReport>>> {
Box::pin(async move { self.run.up(&self.opts, &lines(line)).await.map(drop).map_err(|e| Box::new(e.report())) })
}
fn exec<'a>(&'a self, argv: &'a [&'a str]) -> BoxFuture<'a, Result<(i32, String), Box<ErrorReport>>> {
Box::pin(async move {
let argv: Vec<String> = argv.iter().map(|a| (*a).to_owned()).collect();
let ran = self
.run
.exec(self.machine, &argv, &self.opts, &super::super::quiet)
.await
.map_err(|e| Box::new(e.report()))?;
Ok((ran.exit, ran.stdout))
})
}
fn down<'a>(&'a self, line: &'a (dyn Fn(&str) + Send + Sync)) -> BoxFuture<'a, Result<(), Box<ErrorReport>>> {
Box::pin(async move { self.run.down(&self.opts, &lines(line)).await.map_err(|e| Box::new(e.report())) })
}
}
pub(super) trait Course: Send + Sync {
const UP: &'static [Step];
fn machine(&self) -> &'static str;
fn ends(&mut self, line: &str) -> Option<usize>;
fn bytes(&self, _at: usize) -> Option<u64> {
None
}
fn found(&self, _at: usize) -> Found {
Found::Nothing
}
fn explain(&self, report: &ErrorReport) -> Option<(usize, Failure)>;
}
pub(super) async fn test<C: Course>(run: &impl Deployment, left: bool, course: C, progress: &(dyn Fn(StepProgress) + Send + Sync), ssh_wait: Duration) -> Ran {
if left {
progress(Progress::Passed(Step::Prepare, Found::Removing));
if let Err(report) = run.down(&|_| {}).await {
let why = Failure::Leftover(report);
progress(Progress::Failed(Step::Prepare, why.clone()));
return Ran {
passed: Err(why),
cleaned_up: None,
};
}
}
progress(Progress::Passed(Step::Prepare, Found::Nothing));
let passed = match Box::pin(up(run, course, progress)).await {
Ok(()) => Box::pin(inside(run, progress, C::UP.contains(&Step::Ssh), ssh_wait)).await,
Err((why, false)) => {
return Ran {
passed: Err(why),
cleaned_up: None,
};
}
Err((why, true)) => Err(why),
};
progress(Progress::Running(Step::Down));
let down = run
.down(&|l| {
progress(Progress::Passed(
Step::Down,
Found::Line {
text: l.to_owned(),
bytes: None,
},
));
})
.await;
let cleaned_up = match down {
Ok(()) => {
progress(Progress::Passed(Step::Down, Found::Nothing));
Ok(())
}
Err(report) => {
let why = Failure::Runner(report);
progress(Progress::Failed(Step::Down, why.clone()));
Err(why)
}
};
Ran {
passed,
cleaned_up: Some(cleaned_up),
}
}
pub(super) async fn up<C: Course>(run: &impl Deployment, course: C, progress: &(dyn Fn(StepProgress) + Send + Sync)) -> Result<(), (Failure, bool)> {
let course = std::sync::Mutex::new(UpSteps::new(course, progress));
lock(&course).start();
let up = run.up(&|line| lock(&course).line(line)).await;
let mut course = course.into_inner().unwrap_or_else(std::sync::PoisonError::into_inner);
match up {
Ok(()) => {
course.finish();
Ok(())
}
Err(report) => {
let changed = report.changed;
Err((course.fail(report), changed))
}
}
}
pub(super) async fn inside(run: &impl Deployment, progress: &(dyn Fn(StepProgress) + Send + Sync), ssh_up: bool, ssh_wait: Duration) -> Result<(), Failure> {
let step = super::super::Steps(progress);
if !ssh_up {
step.run(Step::Ssh, wait_ssh(run, ssh_wait)).await?;
}
step.run(Step::Exec, async {
let (exit, output) = run.exec(&["uname", "-sm"]).await.map_err(Failure::Runner)?;
let said = output.lines().map(str::trim).find(|l| !l.is_empty()).unwrap_or_default().to_owned();
if exit == 0 && said.contains("Linux") {
Ok(Found::Uname(said))
} else {
Err(Failure::Command { exit, output })
}
})
.await
}
pub(super) fn lock<T>(m: &std::sync::Mutex<T>) -> std::sync::MutexGuard<'_, T> {
m.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
}
pub(super) async fn wait_ssh(run: &impl Deployment, within: Duration) -> Result<Found, Failure> {
let deadline = tokio::time::Instant::now() + within;
loop {
match run.exec(&["true"]).await {
Ok(_) => return Ok(Found::Nothing),
Err(report) if tokio::time::Instant::now() >= deadline => return Err(Failure::NoSsh(report)),
Err(_) => tokio::time::sleep(RETRY).await,
}
}
}
pub(super) struct UpSteps<'p, C> {
course: C,
progress: &'p (dyn Fn(StepProgress) + Send + Sync),
done: usize,
}
impl<'p, C: Course> UpSteps<'p, C> {
fn new(course: C, progress: &'p (dyn Fn(StepProgress) + Send + Sync)) -> Self {
UpSteps { course, progress, done: 0 }
}
fn start(&self) {
if let Some(step) = C::UP.get(self.done) {
(self.progress)(Progress::Running(*step));
}
}
fn pass(&mut self) {
if let Some(step) = C::UP.get(self.done) {
(self.progress)(Progress::Passed(*step, self.course.found(self.done)));
}
self.done += 1;
}
fn line(&mut self, line: &str) {
match self.course.ends(line) {
Some(at) if at >= self.done => {
while self.done <= at.min(C::UP.len().saturating_sub(1)) {
self.pass();
}
self.start();
}
_ => {
if let Some(step) = C::UP.get(self.done) {
let bytes = self.course.bytes(self.done);
(self.progress)(Progress::Passed(*step, Found::Line { text: line.to_owned(), bytes }));
}
}
}
}
fn finish(&mut self) {
while self.done < C::UP.len() {
self.pass();
}
}
fn fail(&mut self, report: Box<ErrorReport>) -> Failure {
let last = C::UP.len().saturating_sub(1);
let (at, why) = match self.course.explain(&report) {
Some((at, why)) => (at.max(self.done).min(last), why),
None => (self.done.min(last), Failure::Runner(report)),
};
while self.done < at {
if let Some(step) = C::UP.get(self.done) {
(self.progress)(Progress::Skipped(*step, Found::Nothing));
}
self.done += 1;
}
if let Some(step) = C::UP.get(at) {
(self.progress)(Progress::Failed(*step, why.clone()));
}
self.done = C::UP.len();
why
}
}