Skip to main content

isothrum_machine/selftest/
hypervisor.rs

1//! The hypervisor self-test: a throwaway VM, run through a runner of its own. It checks Vagrant
2//! answers, the hypervisor the caller picks answers, a small test box is here (added when it
3//! isn't), the VM boots, a command runs inside it, and this computer reaches it on a private
4//! network. The VM is always taken down, and so are the host networks the test made. A VM an
5//! earlier test left that Vagrant no longer knows is removed first, but only when it is surely the
6//! test's: on Hyper-V every disk of it is under the test folder, on VirtualBox its description
7//! names the test folder.
8//!
9//! On Hyper-V the start and the command inside share one elevation: one administrator prompt for
10//! both ([`isothrum_runner::Running::sharing_elevation`]).
11
12mod boxes;
13mod leftover;
14mod networks;
15mod ping;
16mod vboxmanage;
17
18use std::path::Path;
19use std::time::Duration;
20
21use isothrum_runner::{Arch, BoxFuture, Provider, RunOptions, Runner};
22
23pub use crate::boxes::{add_box, box_provider};
24pub use boxes::{box_for, candidate_boxes};
25pub use leftover::hyperv_leftover_script;
26
27use super::{Progress, throwaway};
28use crate::Context;
29use ping::{answers_ping, ping_once};
30
31/// The run's name in the test's own runner.
32const RUN: &str = "hypervisor-selftest";
33/// The test VM's address on its private network (VirtualBox's default host-only range): the
34/// first of these nothing answers on yet. One that answers already (another VM on it) would make
35/// the ping pass whatever the test VM does.
36pub const ADDRESSES: [&str; 4] = ["192.168.56.250", "192.168.56.249", "192.168.56.248", "192.168.56.247"];
37/// The test VM's addresses on VMware: a range of their own. vagrant-vmware-desktop refuses a
38/// static address whose network another host device has already ("would collide with another
39/// device"), and VirtualBox's host-only adapter holds 192.168.56.0/24 on a machine with both.
40pub const VMWARE_ADDRESSES: [&str; 4] = ["192.168.212.250", "192.168.212.249", "192.168.212.248", "192.168.212.247"];
41
42/// The test VM's addresses on `provider`, in the order they're tried.
43#[must_use]
44pub fn addresses(provider: Provider) -> &'static [&'static str] {
45    if provider == Provider::VmwareDesktop { &VMWARE_ADDRESSES } else { &ADDRESSES }
46}
47/// Pings, [`PING_GAP`] apart, for the VM to answer on its private network.
48const PING_TRIES: u32 = 5;
49const PING_GAP: Duration = Duration::from_secs(1);
50
51/// The test VM, as the caller names it.
52#[derive(Debug, Clone, Copy)]
53#[non_exhaustive]
54pub struct TestVm<'a> {
55    /// How it shows in the hypervisor's own app; also how a VM an earlier test left is found.
56    pub name: &'a str,
57    /// Its host name inside; also the prefix of its libvirt domain, and the tag of the VirtualBox
58    /// description that marks a VM as the test's.
59    pub hostname: &'a str,
60}
61
62impl<'a> TestVm<'a> {
63    /// The test VM named `name` in the hypervisor's app, `hostname` inside.
64    #[must_use]
65    pub fn new(name: &'a str, hostname: &'a str) -> TestVm<'a> {
66        TestVm { name, hostname }
67    }
68}
69
70/// A step of the hypervisor self-test.
71#[derive(Debug, Clone, Copy, PartialEq, Eq)]
72#[non_exhaustive]
73pub enum Step {
74    /// A VM an earlier test left was removed (said only when one was, or couldn't be).
75    Leftover,
76    /// Vagrant answers.
77    Vagrant,
78    /// The caller picked a hypervisor.
79    Provider,
80    /// The hypervisor answers.
81    Hypervisor,
82    /// The test box is here, added when it wasn't.
83    Box,
84    /// The VM boots.
85    Boot,
86    /// A command runs inside it.
87    Exec,
88    /// This computer reaches it on its private network.
89    Network,
90    /// The host networks the test made were removed (said only when one was, or couldn't be).
91    Networks,
92}
93
94/// What a step that passed (or was skipped) found.
95#[derive(Debug, Clone, PartialEq, Eq)]
96#[non_exhaustive]
97pub enum Found {
98    /// Vagrant's version line.
99    Version(String),
100    /// The hypervisor picked.
101    Provider(Provider),
102    /// It answered.
103    Responds,
104    /// It has no probe to answer.
105    NothingToProbe,
106    /// The test box: whether it was here already.
107    Box {
108        /// Its name.
109        name: &'static str,
110        /// Here before the test.
111        held: bool,
112    },
113    /// The VM booted from `name` on `provider`.
114    Booted {
115        /// The box's name.
116        name: &'static str,
117        /// The hypervisor.
118        provider: Provider,
119    },
120    /// What `uname -srm` printed inside.
121    Uname(String),
122    /// The VM answered a ping at `address`.
123    Reached {
124        /// Its address.
125        address: &'static str,
126    },
127    /// Skipped: the hypervisor's plugin gives a VM no private network.
128    NoPrivateNetwork(Provider),
129    /// Skipped: every address of [`addresses`] answers already.
130    AddressesTaken,
131    /// The hypervisors a VM an earlier test left was removed from.
132    Removed(Vec<&'static str>),
133    /// The host networks removed.
134    NetworksRemoved(Vec<String>),
135    /// A line a step's tool printed while it ran.
136    Line(String),
137}
138
139/// Why a step failed.
140#[derive(Debug, Clone, PartialEq, Eq)]
141#[non_exhaustive]
142pub enum Failure {
143    /// What the tool said.
144    Said(String),
145    /// The runner's refusal or failure, as it reports it.
146    Runner(Box<isothrum_runner::ErrorReport>),
147    /// A VM of the test's name that isn't the test's is on `hypervisor`: left alone.
148    Foreign {
149        /// The hypervisor.
150        hypervisor: &'static str,
151    },
152    /// No box exists for `hypervisor` on this computer's CPU (`arch`): the test has nothing to
153    /// boot. Hyper-V on Arm, until a box of ours is published.
154    NoTestBox {
155        /// The hypervisor.
156        hypervisor: &'static str,
157        /// The computer's CPU.
158        arch: Arch,
159    },
160    /// The VM never answered a ping at `address`; the last answer.
161    NoReply {
162        /// Its address.
163        address: &'static str,
164        /// What the last ping said.
165        last: String,
166    },
167}
168
169impl std::fmt::Display for Failure {
170    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
171        match self {
172            Failure::Said(said) => f.write_str(said),
173            Failure::Runner(e) => e.fmt(f),
174            Failure::Foreign { hypervisor } => write!(f, "{hypervisor} has a VM of the test's name that isn't the test's"),
175            Failure::NoTestBox { hypervisor, arch } => write!(
176                f,
177                "no test VM exists yet for {hypervisor} on {} computers, so the test has nothing to boot here",
178                crate::boxes::arch_name(*arch)
179            ),
180            Failure::NoReply { address, last } => write!(f, "{address} did not answer ping: {last}"),
181        }
182    }
183}
184
185/// A step's progress, as the test says it. [`Progress::Passed`] with [`Found::Line`] is a line
186/// its tool printed while it still runs.
187pub type StepProgress = Progress<Step, Found, Failure>;
188
189/// How the test went.
190#[derive(Debug)]
191#[non_exhaustive]
192pub struct Ran {
193    /// Whether every step passed; why not.
194    pub passed: Result<(), Failure>,
195    /// Whether the test VM was taken down; why not. None: no VM was started.
196    pub cleaned_up: Option<Result<(), Failure>>,
197}
198
199/// What the caller decides during the test: the hypervisor, once Vagrant answers; the test box,
200/// once the hypervisor answers (added by [`add_box`], or waited for while a fetch ahead of the
201/// test adds it).
202pub trait Choices: Send + Sync {
203    /// The hypervisor to test; why none can be.
204    fn provider(&self) -> BoxFuture<'_, Result<Provider, String>>;
205
206    /// Makes sure box `name` is here for `provider`, each line its fetch prints said to `line`:
207    /// whether it was here already.
208    fn fetch_box<'a>(&'a self, provider: Provider, name: &'static str, line: &'a (dyn Fn(String) + Send + Sync)) -> BoxFuture<'a, Result<bool, String>>;
209}
210
211/// Providers whose Vagrant plugin can put the VM on a static private network.
212#[must_use]
213pub fn has_private_network(p: Provider) -> bool {
214    matches!(p, Provider::Virtualbox | Provider::VmwareDesktop | Provider::Parallels | Provider::Libvirt)
215}
216
217/// The Hyper-V switch the test VM joins: Windows' own NAT switch (Windows 10 and 11).
218pub const HYPERV_SWITCH: &str = "Default Switch";
219
220/// The test's Vagrantfile: `vm` booted from `name` on `p`, at `address` on a private network when
221/// it gets one. The VM boots as any deployment's VMs do: on QEMU with the hypervisor's
222/// acceleration (vagrant-qemu's default), never software emulation, which boots where no
223/// deployment could start. `dir`: the test's folder, which a VirtualBox VM's description names, so
224/// a VM an earlier test left is known as the test's.
225#[must_use]
226pub fn vagrantfile(vm: &TestVm<'_>, p: Provider, name: &str, address: Option<&str>, dir: &Path) -> String {
227    let mut v = vec![
228        "Vagrant.configure(\"2\") do |config|".to_owned(),
229        format!("  config.vm.box = \"{name}\""),
230        "  config.vm.boot_timeout = 600".to_owned(),
231        "  config.vm.synced_folder \".\", \"/vagrant\", disabled: true".to_owned(),
232    ];
233    // Vagrant sets a hostname by renewing the guest's DHCP lease (`ifdown -a; ifup -a` on Alpine),
234    // and on Hyper-V's Default Switch the address it then gets isn't the one its SSH session is
235    // on: `up` failed at "Setting hostname..." with "The SSH connection was unexpectedly closed".
236    // On Hyper-V the VM keeps its box's hostname.
237    if p != Provider::Hyperv {
238        v.push(format!("  config.vm.hostname = \"{}\"", vm.hostname));
239    }
240    if let Some(address) = address.filter(|_| has_private_network(p)) {
241        v.push(format!("  config.vm.network \"private_network\", ip: \"{address}\""));
242    }
243    // Hyper-V connects a VM to one virtual switch, and Vagrant asks which on its standard input
244    // when there are several (WSL 2 adds its own beside the Default Switch): a run has no one to
245    // answer, so `vagrant up` waited for ever. The test names Windows' Default Switch.
246    if p == Provider::Hyperv {
247        v.push(format!("  config.vm.network \"public_network\", bridge: \"{HYPERV_SWITCH}\""));
248    }
249    let named = vm.name;
250    let settings = match p {
251        Provider::Virtualbox => format!(
252            "    h.name = \"{named}\"\n    h.memory = 512\n    h.customize [\"modifyvm\", :id, \"--description\", {}]\n",
253            ruby_quote(&leftover::vbox_description(vm, dir))
254        ),
255        Provider::Parallels => format!("    h.name = \"{named}\"\n    h.memory = 512\n"),
256        // Off a Mac, Workstation as the Pro product it is: Broadcom's free Workstation Pro reports a
257        // `standard` licence, which vagrant-vmware-desktop 3.0.5 takes for VMware's edition without
258        // snapshots, and its `vmrun snapshot` (a linked clone's first step) then fails "The
259        // operation is not supported" (Workstation 26.0.1).
260        Provider::VmwareDesktop => format!(
261            "    h.vmx[\"displayName\"] = \"{named}\"\n    h.memory = 512\n    h.force_vmware_license = \"workstation\" unless RUBY_PLATFORM.include?(\"darwin\")\n"
262        ),
263        Provider::Libvirt => format!("    h.default_prefix = \"{}-\"\n    h.memory = 512\n", vm.hostname),
264        Provider::Hyperv => format!("    h.vmname = \"{named}\"\n"),
265        Provider::Utm => format!("    h.name = \"{named}\"\n"),
266        // vagrant-qemu's default is 4G, much more than a test VM needs.
267        Provider::Qemu => "    h.memory = \"1G\"\n".to_owned(),
268        Provider::VmwareEsxi => String::new(),
269    };
270    if !settings.is_empty() {
271        v.push(format!("  config.vm.provider \"{}\" do |h|\n{settings}  end", p.id()));
272    }
273    v.push("end\n".to_owned());
274    v.join("\n")
275}
276
277/// `s` as a Ruby single-quoted string (a Windows path's backslashes kept as they are).
278fn ruby_quote(s: &str) -> String {
279    format!("'{}'", s.replace('\\', "\\\\").replace('\'', "\\'"))
280}
281
282/// A read-only command that succeeds only when `p`'s service is up and usable by this account,
283/// and opens no window.
284fn responds(p: Provider) -> Option<(String, &'static [&'static str])> {
285    let tool = |t: &str| Some(t.to_owned());
286    let (program, args): (Option<String>, &'static [&'static str]) = match p {
287        Provider::Virtualbox => (tool("VBoxManage"), &["list", "hostinfo"]),
288        Provider::VmwareDesktop => (tool("vmrun"), &["list"]),
289        Provider::Parallels => (tool("prlctl"), &["list", "--all"]),
290        Provider::Libvirt => (tool("virsh"), &["-c", "qemu:///system", "list", "--all"]),
291        // `utmctl list` opens UTM with its window in front: it is asked as a start asks it
292        // ([`crate::providers::ready::utm`]), hidden.
293        Provider::Utm | Provider::Hyperv | Provider::Qemu | Provider::VmwareEsxi => (None, &[]),
294    };
295    program.map(|found| (found, args))
296}
297
298/// Whether `program` answers `args`: from `PATH`, else where its app installs it (VMware's
299/// `vmrun`, Parallels' `prlctl`), as detection finds it. What it said when neither answers.
300async fn answers(cx: &Context, program: &str, args: &[&str]) -> Result<(), String> {
301    let on_path = cx.read_ok(program, args).await;
302    let Err(said) = on_path else { return Ok(()) };
303    match cx.host.devices.app_tool(program).into_iter().find(|t| t.is_file()) {
304        Some(at) => cx.read_ok(&at.display().to_string(), args).await.map(drop),
305        None => Err(said),
306    }
307}
308
309/// The first test address on `provider` nothing answers on yet.
310async fn free_address(cx: &Context, provider: Provider) -> Option<&'static str> {
311    for &address in addresses(provider) {
312        if !answers_ping(cx, address).await {
313            return Some(address);
314        }
315    }
316    None
317}
318
319/// Runs the test, its runner's home and project in `dir` (the test's own folder), `choices`
320/// deciding the hypervisor and fetching the box, each step's progress said to `progress`.
321pub async fn run(cx: &Context, dir: &Path, vm: &TestVm<'_>, choices: &dyn Choices, progress: &(dyn Fn(StepProgress) + Send + Sync)) -> Ran {
322    let (runner, project) = match throwaway(cx, dir, "Vagrantfile", "") {
323        Ok(test) => test,
324        Err(e) => {
325            return Ran {
326                passed: Err(Failure::Said(e)),
327                cleaned_up: None,
328            };
329        }
330    };
331    match clear_earlier(cx, &runner, &project, dir, vm).await {
332        Ok(removed) if removed.is_empty() => {}
333        Ok(removed) => progress(Progress::Passed(Step::Leftover, Found::Removed(removed))),
334        Err(why) => {
335            progress(Progress::Failed(Step::Leftover, why.clone()));
336            return Ran {
337                passed: Err(why),
338                cleaned_up: None,
339            };
340        }
341    }
342    let mut test = Test {
343        cx,
344        runner: &runner,
345        project: &project,
346        dir,
347        vm,
348        provider: None,
349        before: networks::Networks::default(),
350        run: None,
351    };
352    let passed = Box::pin(test.steps(choices, progress)).await;
353    let cleaned_up = match test.provider {
354        Some(provider) => {
355            // Through the handle that started it, when there is one: on Hyper-V, its elevation.
356            let down = match &test.run {
357                Some(run) => down_with(run, provider).await,
358                None => down(&runner, &project, provider).await,
359            };
360            if down.is_ok() {
361                remove_networks(cx, provider, &test.before, progress).await;
362            }
363            Some(down)
364        }
365        _ => None,
366    };
367    Ran { passed, cleaned_up }
368}
369
370/// The test's run, opened.
371fn open<'a>(runner: &'a Runner, project: &Path) -> Result<isothrum_runner::Running<'a>, Failure> {
372    super::open(runner, project, RUN).map_err(Failure::Said)
373}
374
375/// Takes the test VM down on `provider`.
376async fn down(runner: &Runner, project: &Path, provider: Provider) -> Result<(), Failure> {
377    down_with(&open(runner, project)?, provider).await
378}
379
380/// Takes the test VM down on `provider` through `run`.
381async fn down_with(run: &isothrum_runner::Running<'_>, provider: Provider) -> Result<(), Failure> {
382    let opts = RunOptions::new().with_provider(provider);
383    run.down(&opts, &super::quiet).await.map_err(|e| Failure::Runner(Box::new(e.report())))
384}
385
386/// What a test interrupted last time may have left: its VM, taken down through the runner when
387/// it still records it as up, else found by its name and removed when it is surely the test's
388/// ([`leftover`]): the hypervisors it was removed from.
389async fn clear_earlier(cx: &Context, runner: &Runner, project: &Path, dir: &Path, vm: &TestVm<'_>) -> Result<Vec<&'static str>, Failure> {
390    let recorded = isothrum_runner::RunName::new(RUN).ok().and_then(|name| runner.run_record(&name).ok().flatten());
391    // Best effort: what the runner couldn't take down is found by its name next.
392    if let Some(record) = recorded.filter(|r| r.state != isothrum_runner::RunState::Absent)
393        && let Some(provider) = record.provider
394    {
395        drop(down(runner, project, provider).await);
396    }
397    leftover::clear(cx, dir, vm).await
398}
399
400/// Removes the host networks the test made, said when it removed one or couldn't.
401async fn remove_networks(cx: &Context, provider: Provider, before: &networks::Networks, progress: &(dyn Fn(StepProgress) + Send + Sync)) {
402    match networks::remove_made_since(cx, provider, before).await {
403        Ok(removed) if removed.is_empty() => {}
404        Ok(removed) => progress(Progress::Passed(Step::Networks, Found::NetworksRemoved(removed))),
405        Err(why) => progress(Progress::Failed(Step::Networks, Failure::Said(why))),
406    }
407}
408
409/// What the steps work on.
410struct Test<'a> {
411    cx: &'a Context,
412    runner: &'a Runner,
413    project: &'a Path,
414    dir: &'a Path,
415    vm: &'a TestVm<'a>,
416    /// The hypervisor, once picked.
417    provider: Option<Provider>,
418    /// The host networks there before the VM booted.
419    before: networks::Networks,
420    /// The test's run, once its VM is started: its operations share one elevation.
421    run: Option<isothrum_runner::Running<'a>>,
422}
423
424impl<'a> Test<'a> {
425    /// The steps, in order: the first that fails ends the test.
426    async fn steps(&mut self, choices: &dyn Choices, progress: &(dyn Fn(StepProgress) + Send + Sync)) -> Result<(), Failure> {
427        let cx = self.cx;
428        let step = super::Steps(progress);
429        step.run(Step::Vagrant, async {
430            let v = cx.read_ok("vagrant", &["--version"]).await.map_err(Failure::Said)?;
431            Ok(Found::Version(v.trim().to_owned()))
432        })
433        .await?;
434        let mut picked = None;
435        step.run(Step::Provider, async {
436            let p = choices.provider().await.map_err(Failure::Said)?;
437            picked = Some(p);
438            Ok(Found::Provider(p))
439        })
440        .await?;
441        let Some(provider) = picked else { return Ok(()) };
442        step.run(Step::Hypervisor, async {
443            if provider == Provider::Utm {
444                let ready = crate::providers::ready::utm(cx, crate::providers::ready::UTM_WAIT, &mut || {}).await;
445                return ready.map(|()| Found::Responds).map_err(|e| Failure::Said(e.to_string()));
446            }
447            let Some((program, args)) = responds(provider) else {
448                return Ok(Found::NothingToProbe);
449            };
450            answers(cx, &program, args).await.map(|()| Found::Responds).map_err(Failure::Said)
451        })
452        .await?;
453        self.before = networks::Networks::here(cx, provider).await;
454        let chosen = box_for(cx, provider).await;
455        let box_line = |l: String| progress(Progress::Passed(Step::Box, Found::Line(l)));
456        let mut name = "";
457        step.run(Step::Box, async {
458            let (chosen, _) = chosen.ok_or(Failure::NoTestBox {
459                hypervisor: provider.id(),
460                arch: cx.host.arch,
461            })?;
462            let held = choices.fetch_box(provider, chosen, &box_line).await.map_err(Failure::Said)?;
463            name = chosen;
464            Ok(Found::Box { name: chosen, held })
465        })
466        .await?;
467        // An address for the ping that nothing answers on before the VM exists.
468        let address = if has_private_network(provider) {
469            free_address(cx, provider).await
470        } else {
471            None
472        };
473        let written = std::fs::write(self.project.join("Vagrantfile"), vagrantfile(self.vm, provider, name, address, self.dir));
474        written.map_err(|e| Failure::Said(format!("{} couldn't be written: {e}", self.project.display())))?;
475        self.provider = Some(provider);
476        self.boot_and_exec(provider, name, progress).await?;
477        network(cx, provider, address, progress).await
478    }
479
480    /// Boots the VM from box `name` on `provider`, then runs a command inside, through one
481    /// handle: on Hyper-V, one elevation for both (and for the VM's removal after).
482    async fn boot_and_exec(&mut self, provider: Provider, name: &'static str, progress: &(dyn Fn(StepProgress) + Send + Sync)) -> Result<(), Failure> {
483        let step = super::Steps(progress);
484        let run: &isothrum_runner::Running<'a> = self.run.insert(open(self.runner, self.project)?.sharing_elevation());
485        let opts = RunOptions::new().with_provider(provider);
486        let boot_line = |e: &isothrum_runner::Event| {
487            if let isothrum_runner::EventKind::Log { line, .. } = &e.kind {
488                progress(Progress::Passed(Step::Boot, Found::Line(line.clone())));
489            }
490        };
491        let up = Box::pin(async {
492            run.up(&opts, &boot_line)
493                .await
494                .map(|_| Found::Booted { name, provider })
495                .map_err(|e| Failure::Runner(Box::new(e.report())))
496        });
497        step.run(Step::Boot, up).await?;
498        step.run(Step::Exec, async {
499            let argv = ["uname", "-srm"].map(str::to_owned);
500            let ran = run
501                .exec("default", &argv, &opts, &super::quiet)
502                .await
503                .map_err(|e| Failure::Runner(Box::new(e.report())))?;
504            Ok(Found::Uname(uname_line(&ran.stdout)))
505        })
506        .await
507    }
508}
509
510/// The VM answers ping on its private network (skipped without one, or a free address).
511async fn network(cx: &Context, provider: Provider, address: Option<&'static str>, progress: &(dyn Fn(StepProgress) + Send + Sync)) -> Result<(), Failure> {
512    let Some(address) = address else {
513        let why = if has_private_network(provider) {
514            Found::AddressesTaken
515        } else {
516            Found::NoPrivateNetwork(provider)
517        };
518        progress(Progress::Skipped(Step::Network, why));
519        return Ok(());
520    };
521    super::Steps(progress)
522        .run(Step::Network, async {
523            let mut last = String::new();
524            for _ in 0..PING_TRIES {
525                match ping_once(cx, address).await {
526                    Ok(out) if ping::replied(&out) => return Ok(Found::Reached { address }),
527                    Ok(out) => out
528                        .lines()
529                        .map(str::trim)
530                        .filter(|l| !l.is_empty())
531                        .nth(1)
532                        .unwrap_or("no reply")
533                        .clone_into(&mut last),
534                    Err(e) => last = e,
535                }
536                tokio::time::sleep(PING_GAP).await;
537            }
538            Err(Failure::NoReply { address, last })
539        })
540        .await
541}
542
543/// What `uname -srm` printed: its first line that says something.
544fn uname_line(out: &str) -> String {
545    out.lines().map(str::trim).find(|l| !l.is_empty()).unwrap_or_default().to_owned()
546}
547
548#[cfg(test)]
549mod tests;