use std::path::Path;
use std::time::Duration;
use isoloom_manifest::{Provider, Step};
use super::{READ_LIMIT, Vagrant, lock, status};
use crate::Result;
use crate::error::Error;
use crate::events::{Stream, WarningCode};
use crate::executor::{Cx, Echo, call, call_ok, plan};
use crate::process::{Captured, ProcessSpec};
use crate::status::MachineState;
use crate::store::if_there;
use isoloom_manifest::contract::{CONTROLLER, HALTING};
const RECONCILE_DESTROY_LIMIT: Duration = Duration::from_secs(180);
const HALT_POLLS: u32 = 60;
const WAKE_PATIENCE: Duration = Duration::from_secs(180);
const PROBE_LIMIT: Duration = Duration::from_secs(20);
const BOOT_LIMIT: Duration = Duration::from_secs(1800);
const HALT_LIMIT: Duration = Duration::from_secs(300);
pub(super) fn recorded_providers(dotfile: &Path) -> std::io::Result<Vec<String>> {
let Some(machines) = if_there(std::fs::read_dir(dotfile.join("machines")))? else {
return Ok(Vec::new());
};
let mut out = Vec::new();
for machine in machines {
let machine = machine?.path();
if !machine.is_dir() {
continue;
}
let Some(providers) = if_there(std::fs::read_dir(&machine))? else {
continue;
};
for provider in providers {
let provider = provider?;
if provider.path().join("id").is_file() {
out.push(provider.file_name().to_string_lossy().into_owned());
}
}
}
out.sort();
out.dedup();
Ok(out)
}
pub(super) async fn reconcile_provider(v: &Vagrant, cx: &Cx<'_>, step: &Step) -> Result<()> {
let dotfile = v.dotfile(cx)?;
let asked = cx.scope.provider.map(|p| crate::wire_name(&p)).unwrap_or_default();
let recorded = recorded_providers(&dotfile).map_err(Error::io(dotfile.join("machines"), "read"))?;
if !recorded.iter().any(|p| *p != asked) {
return Ok(());
}
let id = step.id.as_str();
cx.events
.warning(WarningCode::OtherProvider, "this run last ran on another provider: clearing that run first");
let destroy = v.vagrant(cx, id, &["destroy", "--force"])?;
let destroyed = lock::call_retrying(cx, id, &destroy, RECONCILE_DESTROY_LIMIT, Echo::Shown).await;
if let Err(reason) = destroyed.map_err(|e| e.to_string()).and_then(|out| out.output().map(drop)) {
let said = format!("the run on the other provider couldn't be destroyed: {reason}");
cx.events.warning(WarningCode::CleanupFailed, &said);
}
remove_dir(&dotfile)
}
pub(super) fn reset_state(v: &Vagrant, cx: &Cx<'_>) -> Result<()> {
remove_dir(&v.dotfile(cx)?)
}
fn remove_dir(dir: &Path) -> Result<()> {
crate::store::remove(dir)
}
pub(super) fn vm_names(cx: &Cx<'_>, provider: Provider) -> Vec<String> {
cx.run
.manifest()
.machines
.iter()
.filter_map(|m| match &m.native {
Some(isoloom_manifest::Native::Vagrant { vm_names, .. }) => vm_names.get(&provider).cloned(),
_ => None,
})
.collect()
}
pub(super) fn vboxmanage(args: &[&str]) -> ProcessSpec {
ProcessSpec::new("VBoxManage", args.iter().copied())
}
pub(super) async fn discard_aborted_saved(cx: &Cx<'_>, step: &Step) -> Result<()> {
let id = step.id.as_str();
for name in vm_names(cx, Provider::Virtualbox) {
let info = call(cx, id, &vboxmanage(&["showvminfo", &name, "--machinereadable"]), READ_LIMIT, Echo::Quiet).await?;
if !info.success() {
tracing::debug!(vm = %name, reason = %info.reason(), "the VM's state couldn't be read: its saved state, if any, is left as it is");
continue;
}
if !aborted_saved(&info.stdout) {
continue;
}
cx.events.warning(
WarningCode::SavedStateDiscarded,
&format!("{name}: its saved state was cut off; it boots fresh"),
);
call_ok(cx, id, &vboxmanage(&["discardstate", &name]), READ_LIMIT, Echo::Quiet).await?;
}
Ok(())
}
pub(super) fn aborted_saved(lines: &[String]) -> bool {
lines.iter().any(|l| l.trim() == "VMState=\"aborted-saved\"")
}
pub(super) async fn wake_controller(v: &Vagrant, cx: &Cx<'_>, list: &str, step: &Step) -> Result<()> {
let id = step.id.as_str();
let machine = controller(cx, list, step)?;
let deadline = tokio::time::Instant::now() + WAKE_PATIENCE;
while running(v, cx, id, &machine).await? {
let left = deadline.saturating_duration_since(tokio::time::Instant::now());
if left.is_zero() {
return Err(Error::ToolFailed {
step: id.to_owned(),
reason: format!(
"`{machine}` still reads as running after {} s without saying over SSH that it stays up: \
it may be stuck halting, or its SSH may not answer",
WAKE_PATIENCE.as_secs()
),
});
}
let probe = v.vagrant(cx, id, &["ssh", &machine, "-c", &halting_probe()])?;
match call(cx, id, &probe, PROBE_LIMIT.min(left), Echo::Quiet).await {
Ok(said) if said.success() && said.stdout.iter().any(|l| l.trim() == STAYS_UP) => return Ok(()),
Ok(_) | Err(Error::Timeout { .. }) => {}
Err(e) => return Err(e),
}
tokio::time::sleep(Duration::from_secs(2).min(deadline.saturating_duration_since(tokio::time::Instant::now()))).await;
}
let limit = plan::limit_or(step, &cx.scope, BOOT_LIMIT);
let up = v.vagrant(cx, id, &["up", &machine, "--no-provision"])?;
lock::call_ok_retrying(cx, id, &up, limit, Echo::Shown).await.map(drop)
}
const STAYS_UP: &str = "up";
fn halting_probe() -> String {
format!("if test -e {HALTING}; then echo halting; else echo {STAYS_UP}; fi")
}
const ESXI_ALREADY_OFF: [&str; 2] = ["existingState = \"poweredOff\"", "in the current state (Powered off)"];
pub(super) async fn park_controller(v: &Vagrant, cx: &Cx<'_>, list: &str, step: &Step) -> Result<()> {
let id = step.id.as_str();
let machine = controller(cx, list, step)?;
let limit = plan::limit_or(step, &cx.scope, HALT_LIMIT);
let halt = lock::call_retrying(cx, id, &v.vagrant(cx, id, &["halt", &machine])?, limit, Echo::Quiet).await?;
let halted = halt.success();
if !halted && already_off(&halt) {
cx.events.log(id, Stream::Stdout, &format!("{machine} was already off."));
return Ok(());
}
let said = halt
.stdout
.iter()
.map(|l| (Stream::Stdout, l))
.chain(halt.stderr.iter().map(|l| (Stream::Stderr, l)));
for (stream, line) in said {
cx.events.log(id, stream, line);
}
if halted {
return Ok(());
}
for _ in 0..HALT_POLLS {
if !running(v, cx, id, &machine).await? {
return Ok(());
}
tokio::time::sleep(Duration::from_secs(2)).await;
}
Err(Error::ToolFailed {
step: id.to_owned(),
reason: cx.events.mask(&format!("`vagrant halt {machine}` failed: {}", halt.reason())),
})
}
fn already_off(halt: &Captured) -> bool {
halt.stdout
.iter()
.chain(&halt.stderr)
.any(|line| ESXI_ALREADY_OFF.iter().any(|said| line.contains(said)))
}
fn controller(cx: &Cx<'_>, list: &str, step: &Step) -> Result<String> {
let at = crate::executor::plan::at(list, step);
let named = cx.vars.with_arg(crate::driver::with_of(step), &at, "machine")?;
Ok(named.unwrap_or_else(|| CONTROLLER.to_owned()))
}
async fn running(v: &Vagrant, cx: &Cx<'_>, id: &str, machine: &str) -> Result<bool> {
let spec = v.vagrant(cx, id, &["status", machine, "--machine-readable"])?;
let read = lock::call_ok_retrying(cx, id, &spec, READ_LIMIT, Echo::Quiet).await?;
Ok(status::parse(&read).states.get(machine).map(String::as_str).is_some_and(up))
}
fn up(label: &str) -> bool {
!matches!(status::machine_state(label), MachineState::Stopped | MachineState::Absent)
}