mod boxes;
mod leftover;
mod networks;
mod ping;
mod vboxmanage;
use std::path::Path;
use std::time::Duration;
use isothrum_runner::{Arch, BoxFuture, Provider, RunOptions, Runner};
pub use crate::boxes::{add_box, box_provider};
pub use boxes::{box_for, candidate_boxes};
pub use leftover::hyperv_leftover_script;
use super::{Progress, throwaway};
use crate::Context;
use ping::{answers_ping, ping_once};
const RUN: &str = "hypervisor-selftest";
pub const ADDRESSES: [&str; 4] = ["192.168.56.250", "192.168.56.249", "192.168.56.248", "192.168.56.247"];
pub const VMWARE_ADDRESSES: [&str; 4] = ["192.168.212.250", "192.168.212.249", "192.168.212.248", "192.168.212.247"];
#[must_use]
pub fn addresses(provider: Provider) -> &'static [&'static str] {
if provider == Provider::VmwareDesktop { &VMWARE_ADDRESSES } else { &ADDRESSES }
}
const PING_TRIES: u32 = 5;
const PING_GAP: Duration = Duration::from_secs(1);
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub struct TestVm<'a> {
pub name: &'a str,
pub hostname: &'a str,
}
impl<'a> TestVm<'a> {
#[must_use]
pub fn new(name: &'a str, hostname: &'a str) -> TestVm<'a> {
TestVm { name, hostname }
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Step {
Leftover,
Vagrant,
Provider,
Hypervisor,
Box,
Boot,
Exec,
Network,
Networks,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Found {
Version(String),
Provider(Provider),
Responds,
NothingToProbe,
Box {
name: &'static str,
held: bool,
},
Booted {
name: &'static str,
provider: Provider,
},
Uname(String),
Reached {
address: &'static str,
},
NoPrivateNetwork(Provider),
AddressesTaken,
Removed(Vec<&'static str>),
NetworksRemoved(Vec<String>),
Line(String),
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Failure {
Said(String),
Runner(Box<isothrum_runner::ErrorReport>),
Foreign {
hypervisor: &'static str,
},
NoTestBox {
hypervisor: &'static str,
arch: Arch,
},
NoReply {
address: &'static str,
last: String,
},
}
impl std::fmt::Display for Failure {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Failure::Said(said) => f.write_str(said),
Failure::Runner(e) => e.fmt(f),
Failure::Foreign { hypervisor } => write!(f, "{hypervisor} has a VM of the test's name that isn't the test's"),
Failure::NoTestBox { hypervisor, arch } => write!(
f,
"no test VM exists yet for {hypervisor} on {} computers, so the test has nothing to boot here",
crate::boxes::arch_name(*arch)
),
Failure::NoReply { address, last } => write!(f, "{address} did not answer ping: {last}"),
}
}
}
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 trait Choices: Send + Sync {
fn provider(&self) -> BoxFuture<'_, Result<Provider, String>>;
fn fetch_box<'a>(&'a self, provider: Provider, name: &'static str, line: &'a (dyn Fn(String) + Send + Sync)) -> BoxFuture<'a, Result<bool, String>>;
}
#[must_use]
pub fn has_private_network(p: Provider) -> bool {
matches!(p, Provider::Virtualbox | Provider::VmwareDesktop | Provider::Parallels | Provider::Libvirt)
}
pub const HYPERV_SWITCH: &str = "Default Switch";
#[must_use]
pub fn vagrantfile(vm: &TestVm<'_>, p: Provider, name: &str, address: Option<&str>, dir: &Path) -> String {
let mut v = vec![
"Vagrant.configure(\"2\") do |config|".to_owned(),
format!(" config.vm.box = \"{name}\""),
" config.vm.boot_timeout = 600".to_owned(),
" config.vm.synced_folder \".\", \"/vagrant\", disabled: true".to_owned(),
];
if p != Provider::Hyperv {
v.push(format!(" config.vm.hostname = \"{}\"", vm.hostname));
}
if let Some(address) = address.filter(|_| has_private_network(p)) {
v.push(format!(" config.vm.network \"private_network\", ip: \"{address}\""));
}
if p == Provider::Hyperv {
v.push(format!(" config.vm.network \"public_network\", bridge: \"{HYPERV_SWITCH}\""));
}
let named = vm.name;
let settings = match p {
Provider::Virtualbox => format!(
" h.name = \"{named}\"\n h.memory = 512\n h.customize [\"modifyvm\", :id, \"--description\", {}]\n",
ruby_quote(&leftover::vbox_description(vm, dir))
),
Provider::Parallels => format!(" h.name = \"{named}\"\n h.memory = 512\n"),
Provider::VmwareDesktop => format!(
" h.vmx[\"displayName\"] = \"{named}\"\n h.memory = 512\n h.force_vmware_license = \"workstation\" unless RUBY_PLATFORM.include?(\"darwin\")\n"
),
Provider::Libvirt => format!(" h.default_prefix = \"{}-\"\n h.memory = 512\n", vm.hostname),
Provider::Hyperv => format!(" h.vmname = \"{named}\"\n"),
Provider::Utm => format!(" h.name = \"{named}\"\n"),
Provider::Qemu => " h.memory = \"1G\"\n".to_owned(),
Provider::VmwareEsxi => String::new(),
};
if !settings.is_empty() {
v.push(format!(" config.vm.provider \"{}\" do |h|\n{settings} end", p.id()));
}
v.push("end\n".to_owned());
v.join("\n")
}
fn ruby_quote(s: &str) -> String {
format!("'{}'", s.replace('\\', "\\\\").replace('\'', "\\'"))
}
fn responds(p: Provider) -> Option<(String, &'static [&'static str])> {
let tool = |t: &str| Some(t.to_owned());
let (program, args): (Option<String>, &'static [&'static str]) = match p {
Provider::Virtualbox => (tool("VBoxManage"), &["list", "hostinfo"]),
Provider::VmwareDesktop => (tool("vmrun"), &["list"]),
Provider::Parallels => (tool("prlctl"), &["list", "--all"]),
Provider::Libvirt => (tool("virsh"), &["-c", "qemu:///system", "list", "--all"]),
Provider::Utm | Provider::Hyperv | Provider::Qemu | Provider::VmwareEsxi => (None, &[]),
};
program.map(|found| (found, args))
}
async fn answers(cx: &Context, program: &str, args: &[&str]) -> Result<(), String> {
let on_path = cx.read_ok(program, args).await;
let Err(said) = on_path else { return Ok(()) };
match cx.host.devices.app_tool(program).into_iter().find(|t| t.is_file()) {
Some(at) => cx.read_ok(&at.display().to_string(), args).await.map(drop),
None => Err(said),
}
}
async fn free_address(cx: &Context, provider: Provider) -> Option<&'static str> {
for &address in addresses(provider) {
if !answers_ping(cx, address).await {
return Some(address);
}
}
None
}
pub async fn run(cx: &Context, dir: &Path, vm: &TestVm<'_>, choices: &dyn Choices, progress: &(dyn Fn(StepProgress) + Send + Sync)) -> Ran {
let (runner, project) = match throwaway(cx, dir, "Vagrantfile", "") {
Ok(test) => test,
Err(e) => {
return Ran {
passed: Err(Failure::Said(e)),
cleaned_up: None,
};
}
};
match clear_earlier(cx, &runner, &project, dir, vm).await {
Ok(removed) if removed.is_empty() => {}
Ok(removed) => progress(Progress::Passed(Step::Leftover, Found::Removed(removed))),
Err(why) => {
progress(Progress::Failed(Step::Leftover, why.clone()));
return Ran {
passed: Err(why),
cleaned_up: None,
};
}
}
let mut test = Test {
cx,
runner: &runner,
project: &project,
dir,
vm,
provider: None,
before: networks::Networks::default(),
run: None,
};
let passed = Box::pin(test.steps(choices, progress)).await;
let cleaned_up = match test.provider {
Some(provider) => {
let down = match &test.run {
Some(run) => down_with(run, provider).await,
None => down(&runner, &project, provider).await,
};
if down.is_ok() {
remove_networks(cx, provider, &test.before, progress).await;
}
Some(down)
}
_ => None,
};
Ran { passed, cleaned_up }
}
fn open<'a>(runner: &'a Runner, project: &Path) -> Result<isothrum_runner::Running<'a>, Failure> {
super::open(runner, project, RUN).map_err(Failure::Said)
}
async fn down(runner: &Runner, project: &Path, provider: Provider) -> Result<(), Failure> {
down_with(&open(runner, project)?, provider).await
}
async fn down_with(run: &isothrum_runner::Running<'_>, provider: Provider) -> Result<(), Failure> {
let opts = RunOptions::new().with_provider(provider);
run.down(&opts, &super::quiet).await.map_err(|e| Failure::Runner(Box::new(e.report())))
}
async fn clear_earlier(cx: &Context, runner: &Runner, project: &Path, dir: &Path, vm: &TestVm<'_>) -> Result<Vec<&'static str>, Failure> {
let recorded = isothrum_runner::RunName::new(RUN).ok().and_then(|name| runner.run_record(&name).ok().flatten());
if let Some(record) = recorded.filter(|r| r.state != isothrum_runner::RunState::Absent)
&& let Some(provider) = record.provider
{
drop(down(runner, project, provider).await);
}
leftover::clear(cx, dir, vm).await
}
async fn remove_networks(cx: &Context, provider: Provider, before: &networks::Networks, progress: &(dyn Fn(StepProgress) + Send + Sync)) {
match networks::remove_made_since(cx, provider, before).await {
Ok(removed) if removed.is_empty() => {}
Ok(removed) => progress(Progress::Passed(Step::Networks, Found::NetworksRemoved(removed))),
Err(why) => progress(Progress::Failed(Step::Networks, Failure::Said(why))),
}
}
struct Test<'a> {
cx: &'a Context,
runner: &'a Runner,
project: &'a Path,
dir: &'a Path,
vm: &'a TestVm<'a>,
provider: Option<Provider>,
before: networks::Networks,
run: Option<isothrum_runner::Running<'a>>,
}
impl<'a> Test<'a> {
async fn steps(&mut self, choices: &dyn Choices, progress: &(dyn Fn(StepProgress) + Send + Sync)) -> Result<(), Failure> {
let cx = self.cx;
let step = super::Steps(progress);
step.run(Step::Vagrant, async {
let v = cx.read_ok("vagrant", &["--version"]).await.map_err(Failure::Said)?;
Ok(Found::Version(v.trim().to_owned()))
})
.await?;
let mut picked = None;
step.run(Step::Provider, async {
let p = choices.provider().await.map_err(Failure::Said)?;
picked = Some(p);
Ok(Found::Provider(p))
})
.await?;
let Some(provider) = picked else { return Ok(()) };
step.run(Step::Hypervisor, async {
if provider == Provider::Utm {
let ready = crate::providers::ready::utm(cx, crate::providers::ready::UTM_WAIT, &mut || {}).await;
return ready.map(|()| Found::Responds).map_err(|e| Failure::Said(e.to_string()));
}
let Some((program, args)) = responds(provider) else {
return Ok(Found::NothingToProbe);
};
answers(cx, &program, args).await.map(|()| Found::Responds).map_err(Failure::Said)
})
.await?;
self.before = networks::Networks::here(cx, provider).await;
let chosen = box_for(cx, provider).await;
let box_line = |l: String| progress(Progress::Passed(Step::Box, Found::Line(l)));
let mut name = "";
step.run(Step::Box, async {
let (chosen, _) = chosen.ok_or(Failure::NoTestBox {
hypervisor: provider.id(),
arch: cx.host.arch,
})?;
let held = choices.fetch_box(provider, chosen, &box_line).await.map_err(Failure::Said)?;
name = chosen;
Ok(Found::Box { name: chosen, held })
})
.await?;
let address = if has_private_network(provider) {
free_address(cx, provider).await
} else {
None
};
let written = std::fs::write(self.project.join("Vagrantfile"), vagrantfile(self.vm, provider, name, address, self.dir));
written.map_err(|e| Failure::Said(format!("{} couldn't be written: {e}", self.project.display())))?;
self.provider = Some(provider);
self.boot_and_exec(provider, name, progress).await?;
network(cx, provider, address, progress).await
}
async fn boot_and_exec(&mut self, provider: Provider, name: &'static str, progress: &(dyn Fn(StepProgress) + Send + Sync)) -> Result<(), Failure> {
let step = super::Steps(progress);
let run: &isothrum_runner::Running<'a> = self.run.insert(open(self.runner, self.project)?.sharing_elevation());
let opts = RunOptions::new().with_provider(provider);
let boot_line = |e: &isothrum_runner::Event| {
if let isothrum_runner::EventKind::Log { line, .. } = &e.kind {
progress(Progress::Passed(Step::Boot, Found::Line(line.clone())));
}
};
let up = Box::pin(async {
run.up(&opts, &boot_line)
.await
.map(|_| Found::Booted { name, provider })
.map_err(|e| Failure::Runner(Box::new(e.report())))
});
step.run(Step::Boot, up).await?;
step.run(Step::Exec, async {
let argv = ["uname", "-srm"].map(str::to_owned);
let ran = run
.exec("default", &argv, &opts, &super::quiet)
.await
.map_err(|e| Failure::Runner(Box::new(e.report())))?;
Ok(Found::Uname(uname_line(&ran.stdout)))
})
.await
}
}
async fn network(cx: &Context, provider: Provider, address: Option<&'static str>, progress: &(dyn Fn(StepProgress) + Send + Sync)) -> Result<(), Failure> {
let Some(address) = address else {
let why = if has_private_network(provider) {
Found::AddressesTaken
} else {
Found::NoPrivateNetwork(provider)
};
progress(Progress::Skipped(Step::Network, why));
return Ok(());
};
super::Steps(progress)
.run(Step::Network, async {
let mut last = String::new();
for _ in 0..PING_TRIES {
match ping_once(cx, address).await {
Ok(out) if ping::replied(&out) => return Ok(Found::Reached { address }),
Ok(out) => out
.lines()
.map(str::trim)
.filter(|l| !l.is_empty())
.nth(1)
.unwrap_or("no reply")
.clone_into(&mut last),
Err(e) => last = e,
}
tokio::time::sleep(PING_GAP).await;
}
Err(Failure::NoReply { address, last })
})
.await
}
fn uname_line(out: &str) -> String {
out.lines().map(str::trim).find(|l| !l.is_empty()).unwrap_or_default().to_owned()
}
#[cfg(test)]
mod tests;