mod course;
mod esxi;
mod proxmox;
use std::path::Path;
use std::time::Duration;
use isothrum_runner::{ErrorReport, RunName, RunOptions, RunState, Runner};
#[cfg(test)]
use course::Deployment;
use course::{Course, OnRunner, test};
#[cfg(test)]
use isothrum_runner::BoxFuture;
pub use esxi::Esxi;
pub use proxmox::{Key, Proxmox, SignIn};
use super::hypervisor::TestVm;
use super::{Progress, throwaway};
use crate::Context;
const RUN: &str = "server-selftest";
const HOST_WAIT: Duration = Duration::from_secs(30);
const SSH_WAIT: Duration = Duration::from_secs(300);
const RETRY: Duration = Duration::from_secs(3);
const CONNECT_LIMIT: Duration = Duration::from_secs(4);
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum Server {
Proxmox(Box<Proxmox>),
Esxi(Esxi),
}
impl Server {
#[must_use]
pub fn address(&self) -> String {
match self {
Server::Proxmox(p) => p.api_address(),
Server::Esxi(e) => e.ssh_address(),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Step {
Host,
Prepare,
Image,
Network,
Vm,
Address,
Ssh,
Exec,
Down,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Found {
Nothing,
Answers(String),
Removing,
Box {
name: String,
version: Option<String>,
arch: Option<String>,
},
Line {
text: String,
bytes: Option<u64>,
},
Uname(String),
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Failure {
Unreachable(String),
Said(String),
Leftover(Box<ErrorReport>),
ImageDownload(Box<ErrorReport>),
NoBridge(Box<ErrorReport>),
NameTaken,
Upload(String),
NoBox(Box<ErrorReport>),
PowerOn(Box<ErrorReport>),
NoAddress(Box<ErrorReport>),
NoSsh(Box<ErrorReport>),
Command {
exit: i32,
output: String,
},
Runner(Box<ErrorReport>),
}
impl Failure {
#[must_use]
pub fn report(&self) -> Option<&ErrorReport> {
match self {
Failure::Leftover(r)
| Failure::ImageDownload(r)
| Failure::NoBridge(r)
| Failure::NoBox(r)
| Failure::PowerOn(r)
| Failure::NoAddress(r)
| Failure::NoSsh(r)
| Failure::Runner(r) => Some(r),
Failure::Unreachable(_) | Failure::Said(_) | Failure::NameTaken | Failure::Upload(_) | Failure::Command { .. } => None,
}
}
}
impl std::fmt::Display for Failure {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Failure::Unreachable(address) => write!(f, "no answer on {address}"),
Failure::Said(said) | Failure::Upload(said) => f.write_str(said),
Failure::NameTaken => f.write_str("a VM of the test's name is on the host already"),
Failure::Command { exit, output } => write!(f, "the command inside exited with {exit}: {}", output.trim()),
other => other.report().map_or(Ok(()), |r| r.fmt(f)),
}
}
}
pub type StepProgress = Progress<Step, Found, Failure>;
#[derive(Debug)]
#[non_exhaustive]
pub struct Ran {
pub passed: Result<(), Failure>,
pub cleaned_up: Option<Result<(), Failure>>,
}
pub async fn run(cx: &Context, dir: &Path, server: &Server, vm: &TestVm<'_>, progress: &(dyn Fn(StepProgress) + Send + Sync)) -> Ran {
let step = super::Steps(progress);
let address = server.address();
let reached = step.run(Step::Host, async {
if answers(&address, HOST_WAIT).await {
Ok(Found::Answers(address.clone()))
} else {
Err(Failure::Unreachable(address.clone()))
}
});
if let Err(why) = reached.await {
return Ran {
passed: Err(why),
cleaned_up: None,
};
}
match server {
Server::Proxmox(p) => {
let (file, text) = proxmox::project();
Box::pin(on_runner(cx, dir, (file, &text), progress, async |runner: &Runner| {
proxmox::prepared(p, vm, runner).await
}))
.await
}
Server::Esxi(e) => {
let (file, text) = e.project(vm);
Box::pin(on_runner(cx, dir, (file, &text), progress, async |_: &Runner| {
Ok((e.options(), esxi::course(e)))
}))
.await
}
}
}
async fn on_runner<C: Course>(
cx: &Context,
dir: &Path,
(file, text): (&str, &str),
progress: &(dyn Fn(StepProgress) + Send + Sync),
ready: impl AsyncFnOnce(&Runner) -> Result<(RunOptions, C), String>,
) -> Ran {
progress(Progress::Running(Step::Prepare));
let opened = async {
let (runner, project) = throwaway(cx, dir, file, text)?;
let (opts, course) = ready(&runner).await?;
Ok::<_, String>((runner, project, opts, course))
};
let unprepared = |why: String| {
let why = Failure::Said(why);
progress(Progress::Failed(Step::Prepare, why.clone()));
Ran {
passed: Err(why),
cleaned_up: None,
}
};
let (runner, project, opts, course) = match opened.await {
Ok(opened) => opened,
Err(why) => return unprepared(why),
};
let run = match super::open(&runner, &project, RUN) {
Ok(run) => run,
Err(why) => return unprepared(why),
};
let left = RunName::new(RUN)
.ok()
.and_then(|name| runner.run_record(&name).ok().flatten())
.is_some_and(|r| r.state != RunState::Absent);
let deployment = OnRunner {
run,
opts,
machine: course.machine(),
};
Box::pin(test(&deployment, left, course, progress, SSH_WAIT)).await
}
async fn answers(address: &str, within: Duration) -> bool {
let deadline = tokio::time::Instant::now() + within;
loop {
if matches!(tokio::time::timeout(CONNECT_LIMIT, tokio::net::TcpStream::connect(address)).await, Ok(Ok(_))) {
return true;
}
if tokio::time::Instant::now() >= deadline {
return false;
}
tokio::time::sleep(RETRY).await;
}
}
#[cfg(test)]
mod tests;