Skip to main content

isothrum_machine/selftest/hypervisor/
leftover.rs

1//! The VM an earlier test left behind: one Vagrant no longer knows (its runner's state gone, say
2//! with the caller's data folder) keeps running from the test folder, holds its disk, and the next
3//! `vagrant up` fails on it ("the file is being used by another process" on Hyper-V, "a machine
4//! with this name already exists" on VirtualBox). It is found by the test VM's name and removed,
5//! but only when it is surely the test's: on Hyper-V every disk of it is under the test folder; on
6//! VirtualBox its description names the test folder (set by the test's Vagrantfile). A VM of that
7//! name that is anyone else's is left alone, and said.
8
9use std::path::Path;
10
11use isothrum_runner::{HostOs, ProcessSpec};
12
13use super::{Failure, TestVm, vboxmanage};
14use crate::Context;
15
16/// What a removal found of a VM by its name.
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub(super) enum Leftover {
19    /// No VM has the name.
20    None,
21    /// Every VM of the name was the test's: each was turned off and removed.
22    Removed,
23    /// A VM of the name isn't the test's: left alone.
24    Foreign,
25}
26
27/// The exit codes of [`hyperv_leftover_script`]: what it found and did.
28const HYPERV_REMOVED: i32 = 10;
29const HYPERV_FOREIGN: i32 = 20;
30/// Windows' code for a declined elevation prompt.
31const ERROR_CANCELLED: i32 = 1223;
32
33/// What a test VM's VirtualBox description says: it is the test's in `dir`.
34pub(super) fn vbox_description(vm: &TestVm<'_>, dir: &Path) -> String {
35    format!("{}:{}", vm.hostname, dir.display())
36}
37
38/// Removes a test VM an earlier run left on any hypervisor that can be asked by name: the
39/// hypervisors it was removed from (none: nothing was left).
40///
41/// # Errors
42///
43/// A VM of the test's name that isn't the test's ([`Failure::Foreign`]), or a removal that
44/// failed: the test can't boot its own VM until it is gone.
45pub(super) async fn clear(cx: &Context, dir: &Path, vm: &TestVm<'_>) -> Result<Vec<&'static str>, Failure> {
46    let mut removed = Vec::new();
47    // Hyper-V asks for administrator rights: only when a VM disk is under the test folder.
48    if cx.host.os == HostOs::Windows && holds_vhd(dir) {
49        removed.extend(found("Hyper-V", remove_hyperv(cx, dir, vm).await?)?);
50    }
51    removed.extend(found("VirtualBox", remove_vbox(cx, dir, vm).await?)?);
52    Ok(removed)
53}
54
55/// `hypervisor` when its leftover was removed; one of another's is [`Failure::Foreign`].
56fn found(hypervisor: &'static str, leftover: Leftover) -> Result<Option<&'static str>, Failure> {
57    match leftover {
58        Leftover::None => Ok(None),
59        Leftover::Removed => Ok(Some(hypervisor)),
60        Leftover::Foreign => Err(Failure::Foreign { hypervisor }),
61    }
62}
63
64/// Whether a Hyper-V disk (`.vhdx`) is anywhere under `dir`.
65fn holds_vhd(dir: &Path) -> bool {
66    std::fs::read_dir(dir).is_ok_and(|entries| {
67        entries.flatten().any(|e| {
68            let path = e.path();
69            if e.file_type().is_ok_and(|t| t.is_dir()) {
70                holds_vhd(&path)
71            } else {
72                path.extension().is_some_and(|x| x.eq_ignore_ascii_case("vhdx"))
73            }
74        })
75    })
76}
77
78/// [`clear`] on VirtualBox: its VMs of the test's exact name. None when VirtualBox isn't here.
79async fn remove_vbox(cx: &Context, dir: &Path, vm: &TestVm<'_>) -> Result<Leftover, Failure> {
80    let Ok(list) = cx.read_ok("VBoxManage", &["list", "vms"]).await else {
81        return Ok(Leftover::None);
82    };
83    let ids: Vec<String> = isothrum_runner::virtualbox_vms(&list)
84        .into_iter()
85        .filter(|(name, _)| name == vm.name)
86        .map(|(_, uuid)| uuid)
87        .collect();
88    if ids.is_empty() {
89        return Ok(Leftover::None);
90    }
91    let ours = vbox_description(vm, dir);
92    for id in &ids {
93        let info = cx
94            .read_ok("VBoxManage", &["showvminfo", id, "--machinereadable"])
95            .await
96            .map_err(Failure::Said)?;
97        if vboxmanage::value(&info, "description").as_deref() != Some(ours.as_str()) {
98            return Ok(Leftover::Foreign);
99        }
100    }
101    for id in &ids {
102        // A VM that isn't running refuses the power-off: only the removal must work.
103        drop(cx.read_ok("VBoxManage", &["controlvm", id, "poweroff"]).await);
104        cx.read_ok("VBoxManage", &["unregistervm", id, "--delete"]).await.map_err(Failure::Said)?;
105    }
106    Ok(Leftover::Removed)
107}
108
109/// `s` as a PowerShell single-quoted string; the typographic single quotes PowerShell also takes
110/// as quotes doubled too.
111fn ps_quote(s: &str) -> String {
112    let doubled: String = s
113        .chars()
114        .flat_map(|c| std::iter::repeat_n(c, if matches!(c, '\'' | '\u{2018}'..='\u{201B}') { 2 } else { 1 }))
115        .collect();
116    format!("'{doubled}'")
117}
118
119/// `folder` as the `under` of [`hyperv_leftover_script`]: quoted, with one separator at its end.
120fn folder_expr(folder: &Path) -> String {
121    ps_quote(&format!("{}\\", folder.display().to_string().trim_end_matches(['\\', '/'])))
122}
123
124/// The PowerShell script that turns off and removes every Hyper-V VM named `name` whose disks are
125/// all under the folder `under` (a PowerShell expression of its path, ending in a separator so a
126/// sibling folder of the same prefix isn't under it), and nothing if any VM of that name has a
127/// disk elsewhere (or none): it exits 0 (none), 10 (removed) or 20 (another's, left alone), so an
128/// elevated run (whose output can't be read) says what it did too. An uninstaller can run it for
129/// the test's folder.
130#[must_use]
131pub fn hyperv_leftover_script(name: &str, under: &str) -> String {
132    format!(
133        "$ErrorActionPreference = 'Stop'\n\
134         $vms = @(Get-VM -Name {name} -ErrorAction SilentlyContinue | Where-Object {{ $_.Name -ceq {name} }})\n\
135         if ($vms.Count -eq 0) {{ exit 0 }}\n\
136         foreach ($vm in $vms) {{\n\
137         \x20 $disks = @(Get-VMHardDiskDrive -VM $vm | ForEach-Object {{ $_.Path }})\n\
138         \x20 $outside = @($disks | Where-Object {{ -not $_.StartsWith({under}, [System.StringComparison]::OrdinalIgnoreCase) }})\n\
139         \x20 if ($disks.Count -eq 0 -or $outside.Count -gt 0) {{ exit {HYPERV_FOREIGN} }}\n\
140         }}\n\
141         foreach ($vm in $vms) {{ Stop-VM -VM $vm -TurnOff -Force; Remove-VM -VM $vm -Force }}\n\
142         exit {HYPERV_REMOVED}\n",
143        name = ps_quote(name),
144    )
145}
146
147/// What [`hyperv_leftover_script`]'s exit `code` says.
148fn hyperv_outcome(code: Option<i32>) -> Result<Leftover, Failure> {
149    match code {
150        Some(0) => Ok(Leftover::None),
151        Some(HYPERV_REMOVED) => Ok(Leftover::Removed),
152        Some(HYPERV_FOREIGN) => Ok(Leftover::Foreign),
153        Some(ERROR_CANCELLED) => Err(Failure::Said(
154            "the Windows permission prompt was declined, so the VM an earlier test left wasn't removed".to_owned(),
155        )),
156        other => Err(Failure::Said(format!(
157            "removing the VM an earlier test left on Hyper-V failed (PowerShell exited with {})",
158            other.map_or_else(|| "no code".to_owned(), |c| c.to_string())
159        ))),
160    }
161}
162
163/// [`clear`] on Hyper-V: [`hyperv_leftover_script`] run in an elevated Windows PowerShell (one prompt),
164/// its exit code passed back through the PowerShell that started it.
165async fn remove_hyperv(cx: &Context, dir: &Path, vm: &TestVm<'_>) -> Result<Leftover, Failure> {
166    let inner = crate::wsl::encoded(&hyperv_leftover_script(vm.name, &folder_expr(dir)));
167    let outer = format!(
168        "try {{ $p = Start-Process -FilePath powershell.exe -ArgumentList '-NoProfile','-NonInteractive','-EncodedCommand','{inner}' -Verb RunAs -WindowStyle Hidden -Wait -PassThru; exit $p.ExitCode }} catch {{ exit {ERROR_CANCELLED} }}"
169    );
170    let spec = ProcessSpec::new("powershell", ["-NoProfile", "-NonInteractive", "-Command", &outer]);
171    let ran = cx
172        .probe_within(super::super::PROMPT_LIMIT, &spec)
173        .await
174        .map_err(|e| Failure::Said(e.to_string()))?;
175    hyperv_outcome(ran.exit.code)
176}
177
178#[cfg(test)]
179mod tests;