Skip to main content

isothrum_machine/
providers.rs

1//! The Vagrant providers (hypervisors) this computer can drive, and detecting which are usable.
2//! Vagrant abstracts the hypervisor; we detect what is installed here and let `vagrant up
3//! --provider` do the rest.
4//!
5//! Whether this account may manage Hyper-V is the runner's own check
6//! ([`isothrum_runner::may_manage_hyperv`], `whoami /groups` through the same [`ProcessRunner`]),
7//! the one it decides an elevated session by: when the account may not, Hyper-V's status says it
8//! needs an administrator.
9
10use std::path::Path;
11use std::time::Duration;
12
13use isothrum_runner::{ProcessRunner, version_found};
14
15use crate::exec;
16
17/// A Vagrant provider (the value given to `vagrant up --provider`): Isoloom's, the one its run
18/// manifests name.
19pub use isoloom_manifest::Provider;
20
21/// Every provider Isoloom names, in its order: read from its type, so one Isoloom adds is
22/// detected without a list here to keep in step.
23fn all() -> Vec<Provider> {
24    isothrum_runner::every_name::<Provider>()
25        .iter()
26        .filter_map(|name| isothrum_runner::from_wire_name(name))
27        .collect()
28}
29
30/// Whether this provider can run on the current OS and CPU at all ([`applicable_on`]).
31fn applicable(provider: Provider) -> bool {
32    applicable_on(provider, std::env::consts::OS, std::env::consts::ARCH)
33}
34
35/// Whether `provider` can run on OS `os` and CPU `arch` (as [`std::env::consts`] names them):
36/// local hypervisors are platform-specific, remote ones apply anywhere.
37fn applicable_on(provider: Provider, os: &str, arch: &str) -> bool {
38    match provider {
39        Provider::Virtualbox | Provider::VmwareDesktop if os == "windows" && arch == "aarch64" => false,
40        Provider::Hyperv => os == "windows",
41        Provider::Parallels | Provider::Utm => os == "macos",
42        Provider::Libvirt => os == "linux",
43        _ => true,
44    }
45}
46
47/// The oldest version of the provider's plugin that works: `vagrant_utm` before 0.2.0 reads
48/// a VM's forwarded ports through a script UTM refuses (`-600`, `-1743`) and has no `started`
49/// state.
50fn plugin_minimum(provider: Provider) -> Option<&'static str> {
51    match provider {
52        Provider::Utm => Some("0.2.0"),
53        _ => None,
54    }
55}
56
57/// The hypervisor's name and the oldest version its plugin drives: `vagrant_utm` refuses a
58/// UTM before 4.6.5 (no import of a box, no registry for its shared folders).
59fn hypervisor_minimum(provider: Provider) -> Option<(&'static str, &'static str)> {
60    match provider {
61        Provider::Utm => Some(("UTM", "4.6.5")),
62        _ => None,
63    }
64}
65
66/// The hypervisor's own version, when it is installed and says it: UTM's app bundle
67/// (`CFBundleShortVersionString`); the others aren't held to a version yet.
68async fn hypervisor_version(provider: Provider, runner: &dyn ProcessRunner) -> Option<String> {
69    if provider != Provider::Utm {
70        return None;
71    }
72    let plist = format!("{UTM_APP}/Contents/Info.plist");
73    let out = exec::read(runner, "defaults", &["read", &plist, "CFBundleShortVersionString"]).await.ok()?;
74    let version = out.trim().to_owned();
75    (!version.is_empty()).then_some(version)
76}
77
78/// The local tool that proves the hypervisor itself is installed, if there is one.
79fn probe(provider: Provider) -> Option<(&'static str, &'static [&'static str])> {
80    match provider {
81        Provider::Virtualbox => Some(("VBoxManage", &["--version"])),
82        Provider::VmwareDesktop => Some(("vmrun", &[])),
83        Provider::Parallels => Some(("prlctl", &["--version"])),
84        Provider::Libvirt => Some(("virsh", &["--version"])),
85        Provider::Qemu => Some((qemu_binary(), &["--version"])),
86        _ => None,
87    }
88}
89
90/// Whether the hypervisor itself is installed here, `None` when there is nothing local to
91/// check (remote providers). UTM is an app bundle; Hyper-V is a Windows feature.
92async fn hypervisor_installed(provider: Provider, runner: &dyn ProcessRunner) -> Option<bool> {
93    match provider {
94        Provider::Utm => Some(Path::new(UTM_APP).exists()),
95        Provider::Hyperv => Some(hyperv_enabled()),
96        _ => {
97            let (program, args) = probe(provider)?;
98            Some(tool_present(runner, program, args).await)
99        }
100    }
101}
102
103/// Where UTM is installed on macOS.
104const UTM_APP: &str = "/Applications/UTM.app";
105
106/// Whether the Hyper-V feature is on: its Virtual Machine Management service is installed with it.
107fn hyperv_enabled() -> bool {
108    let root = std::env::var_os("SystemRoot").map_or_else(|| std::path::PathBuf::from("C:\\Windows"), std::path::PathBuf::from);
109    root.join("System32").join("vmms.exe").is_file()
110}
111
112/// KVM's device, which vagrant-libvirt's guests run on.
113const KVM: &str = "/dev/kvm";
114
115/// Why libvirt can't run VMs here although `virsh` is installed: vagrant-libvirt boots KVM guests,
116/// so it needs KVM's device `dev`, and the user must be allowed to open it. `None` when it is
117/// fine. It reads the file system: [`detect`] asks it, [`unavailable_reason`] reads the answer.
118/// A device the user may not open says how to get leave; any other failure is said as it is.
119fn kvm_problem(dev: &Path) -> Option<String> {
120    if !dev.exists() {
121        return Some("KVM isn't available on this machine (no /dev/kvm): turn on virtualization in the firmware, or use another hypervisor".to_owned());
122    }
123    match std::fs::OpenOptions::new().read(true).write(true).open(dev) {
124        Ok(_) => None,
125        Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied => {
126            Some("you can't use /dev/kvm yet: add yourself to the kvm and libvirt groups, then sign out and back in".to_owned())
127        }
128        Err(e) => Some(format!("/dev/kvm can't be opened: {e}")),
129    }
130}
131
132/// The QEMU binary for this machine's CPU.
133fn qemu_binary() -> &'static str {
134    qemu_binary_on(std::env::consts::ARCH)
135}
136
137/// The QEMU binary for a CPU `arch` (as [`std::env::consts::ARCH`] names it).
138fn qemu_binary_on(arch: &str) -> &'static str {
139    if arch == "aarch64" { "qemu-system-aarch64" } else { "qemu-system-x86_64" }
140}
141
142/// One provider's readiness on this machine.
143#[derive(Debug, Clone)]
144#[non_exhaustive]
145pub struct ProviderStatus {
146    /// The provider.
147    pub provider: Provider,
148    /// Why it is not ready to use here, `None` when it is.
149    pub reason: Option<String>,
150}
151
152/// The version `installed` of `provider`'s plugin when it is older than the one that works
153/// (`plugin_minimum`), with that minimum; `None` when it is recent enough, unknown, or the
154/// plugin has no minimum.
155fn plugin_too_old(provider: Provider, installed: Option<&str>) -> Option<(&str, &'static str)> {
156    let (version, min) = installed.zip(plugin_minimum(provider))?;
157    older(version, min).then_some((version, min))
158}
159
160/// The version `installed` of `provider`'s hypervisor when it is older than the one its plugin
161/// drives (`hypervisor_minimum`), with the hypervisor's name and that minimum.
162fn hypervisor_too_old(provider: Provider, installed: Option<&str>) -> Option<(&'static str, &str, &'static str)> {
163    let (version, (name, min)) = installed.zip(hypervisor_minimum(provider))?;
164    older(version, min).then_some((name, version, min))
165}
166
167/// Whether the version `installed` says is before `min`, in Isoloom's order (a pre-release before
168/// its release); not when either says no version.
169fn older(installed: &str, min: &str) -> bool {
170    version_found(installed).zip(version_found(min)).is_some_and(|(found, min)| found < min)
171}
172
173/// Whether `program` is installed: it is, as long as it could be started (a tool that prints usage
174/// and exits non-zero, like `vmrun`, still exists).
175async fn tool_present(runner: &dyn ProcessRunner, program: &str, args: &[&str]) -> bool {
176    exec::read(runner, program, args).await.is_ok()
177}
178
179/// The Vagrant plugins installed, each with its version when it says one
180/// ([`isothrum_runner::vagrant_plugins`]); why not when `vagrant plugin list` doesn't answer.
181async fn installed_plugins(runner: &dyn ProcessRunner) -> Result<Vec<(String, Option<String>)>, String> {
182    exec::read_ok(runner, "vagrant", &["plugin", "list", "--machine-readable"])
183        .await
184        .map(|out| isothrum_runner::vagrant_plugins(&out))
185}
186
187/// Every provider's reason without Vagrant.
188const NO_VAGRANT: &str = "Vagrant is not installed";
189
190/// How long the VirtualBox liveness probe may take before VirtualBox counts as wedged.
191const VBOX_PROBE: Duration = Duration::from_secs(8);
192
193/// Why Hyper-V can't be used by this account yet, and the two ways out. Folded into Hyper-V's
194/// status when the account may not manage it ([`needs_admin`]).
195const HYPERV_NEEDS_ADMIN: &str = "Vagrant drives Hyper-V only for an administrator or a member of the Hyper-V Administrators group: \
196add this account to that group and sign out of Windows and back in, or run elevated";
197
198/// The readiness of every provider that applies to this computer's OS and CPU, usable or not:
199/// `None` when it is ready, else why not (its hypervisor, its plugin, Hyper-V needing an
200/// administrator...). Without Vagrant (`vagrant_installed`, the caller's to know) each says so,
201/// and nothing is probed.
202pub async fn detect(runner: &dyn ProcessRunner, vagrant_installed: bool) -> Vec<ProviderStatus> {
203    if !vagrant_installed {
204        return all()
205            .into_iter()
206            .filter(|p| applicable(*p))
207            .map(|provider| ProviderStatus {
208                provider,
209                reason: Some(NO_VAGRANT.to_owned()),
210            })
211            .collect();
212    }
213    let plugins = installed_plugins(runner).await;
214    // Vagrant that can't list its plugins says nothing of them: one reason for every provider
215    // that needs one, rather than each plugin "not installed".
216    let (plugins, plugins_unknown) = match plugins {
217        Ok(plugins) => (plugins, None),
218        Err(why) => (Vec::new(), Some(why)),
219    };
220    let mut statuses = Vec::new();
221    for provider in all() {
222        if !applicable(provider) {
223            continue;
224        }
225        let hypervisor = hypervisor_installed(provider, runner).await;
226        let hypervisor_version = if hypervisor == Some(true) {
227            hypervisor_version(provider, runner).await
228        } else {
229            None
230        };
231        let plugin = provider.plugin();
232        let installed = plugin.and_then(|needed| plugins.iter().find(|(i, _)| i == needed));
233        let plugin_installed = plugin.is_none() || installed.is_some();
234        let plugin_version = installed.and_then(|(_, v)| v.as_deref());
235        let unresponsive = provider == Provider::Virtualbox && hypervisor == Some(true) && vbox_wedged(runner).await;
236        let needs_admin = needs_admin(provider, hypervisor, runner).await;
237        let platform_problem = if provider == Provider::Libvirt { kvm_problem(Path::new(KVM)) } else { None };
238        let platform_problem = platform_problem.as_deref();
239        let detection = Detection {
240            hypervisor,
241            hypervisor_version: hypervisor_version.as_deref(),
242            unresponsive,
243            plugin,
244            plugin_installed,
245            plugin_version,
246            plugins_unknown: plugins_unknown.as_deref(),
247            needs_admin,
248            platform_problem,
249        };
250        let reason = unavailable_reason(provider, detection);
251        statuses.push(ProviderStatus { provider, reason });
252    }
253    statuses
254}
255
256/// Whether `provider` is an installed Hyper-V (`hypervisor`) that this account may not manage.
257/// Vagrant's Hyper-V provider refuses every command (status reads included) from such an
258/// account: said here with the way out, not as a raw error mid-boot. When the runner's check
259/// can't say, no reason is added.
260async fn needs_admin(provider: Provider, hypervisor: Option<bool>, runner: &dyn ProcessRunner) -> bool {
261    provider == Provider::Hyperv && hypervisor == Some(true) && isothrum_runner::may_manage_hyperv(runner).await == Some(false)
262}
263
264/// Whether VirtualBox's background service is wedged: `VBoxManage --version` never talks to it, so
265/// ask it something that does and see whether that times out.
266async fn vbox_wedged(runner: &dyn ProcessRunner) -> bool {
267    let probe = exec::read(runner, "VBoxManage", &["list", "runningvms"]);
268    tokio::time::timeout(VBOX_PROBE, probe).await.is_err()
269}
270
271/// What `detect` learned about one provider, grouped so `unavailable_reason` reads one value
272/// rather than a handful of flags that always travel together: every probe of the machine is
273/// `detect`'s, so `unavailable_reason` only decides.
274#[derive(Clone, Copy)]
275struct Detection<'a> {
276    /// Whether the hypervisor is installed, `None` when there is nothing to probe.
277    hypervisor: Option<bool>,
278    /// The hypervisor's version, when it says one.
279    hypervisor_version: Option<&'a str>,
280    /// Whether the hypervisor's service is wedged (its liveness probe timed out).
281    unresponsive: bool,
282    /// The Vagrant plugin it needs, if it is not built in.
283    plugin: Option<&'a str>,
284    /// Whether that plugin is installed.
285    plugin_installed: bool,
286    /// That plugin's version, when `vagrant plugin list` says one.
287    plugin_version: Option<&'a str>,
288    /// Why `vagrant plugin list` didn't answer, when it didn't.
289    plugins_unknown: Option<&'a str>,
290    /// Whether this account may not manage Hyper-V (Hyper-V only), as
291    /// `isothrum_runner::may_manage_hyperv` answers.
292    needs_admin: bool,
293    /// Why this machine can't run the provider's guests although its tool is installed (libvirt:
294    /// KVM's device missing or not the user's to open).
295    platform_problem: Option<&'a str>,
296}
297
298/// Why a provider can't be used here, Vagrant being installed; `None` when it can: the first
299/// layer that is missing.
300fn unavailable_reason(provider: Provider, detection: Detection<'_>) -> Option<String> {
301    let Detection {
302        hypervisor,
303        hypervisor_version,
304        unresponsive,
305        plugin,
306        plugin_installed,
307        plugin_version,
308        plugins_unknown,
309        needs_admin,
310        platform_problem,
311    } = detection;
312    if unresponsive {
313        Some("VirtualBox isn't responding (its background service is stuck): quit VirtualBox and any VM windows, or restart the computer".to_owned())
314    } else if hypervisor == Some(false) && provider == Provider::Hyperv {
315        Some("Hyper-V isn't turned on (Windows Features > Hyper-V), or this edition of Windows doesn't have it".to_owned())
316    } else if needs_admin {
317        Some(HYPERV_NEEDS_ADMIN.to_owned())
318    } else if hypervisor == Some(false) {
319        Some(probe(provider).map_or_else(|| "not installed".to_owned(), |(program, _)| format!("`{program}` was not found")))
320    } else if let Some(why) = platform_problem {
321        Some(why.to_owned())
322    } else if let Some((name, version, min)) = hypervisor_too_old(provider, hypervisor_version) {
323        // Said before the plugin: updating the plugin wouldn't help.
324        Some(format!("{name} {version} is too old: {min} or later is needed. Update {name}"))
325    } else if let Some(why) = plugins_unknown.filter(|_| plugin.is_some()) {
326        Some(format!("Vagrant couldn't say which plugins it has (`vagrant plugin list`: {why})"))
327    } else if !plugin_installed {
328        plugin.map(|p| format!("Vagrant plugin `{p}` is not installed"))
329    } else if let Some((version, min)) = plugin_too_old(provider, plugin_version) {
330        // Installing the plugin again updates it.
331        plugin.map(|p| format!("Vagrant plugin `{p}` {version} is too old: {min} or later is needed. Install it again to update it"))
332    } else {
333        None
334    }
335}
336
337#[cfg(test)]
338mod tests {
339    use isothrum_runner::fake::{FakeProcesses, Reply};
340
341    use super::*;
342
343    /// The names Isoloom's `Provider` takes, sorted.
344    fn isoloom_providers() -> Vec<String> {
345        let mut names = isothrum_runner::every_name::<Provider>();
346        names.sort();
347        names
348    }
349
350    /// Detection covers every provider Isoloom names: one added there fails this until it is
351    /// listed.
352    #[test]
353    fn every_provider_isoloom_names_is_listed() {
354        let mut listed: Vec<String> = all().iter().map(isothrum_runner::wire_name).collect();
355        listed.sort();
356        assert_eq!(listed, isoloom_providers());
357    }
358
359    /// The problem of a device the user may not open: one only its owner reads (root reads any,
360    /// so as root the text is the one it would be).
361    fn denied_device(dir: &Path) -> String {
362        #[cfg(unix)]
363        {
364            use std::os::unix::fs::PermissionsExt;
365            let device = dir.join("denied");
366            std::fs::write(&device, "").unwrap();
367            std::fs::set_permissions(&device, std::fs::Permissions::from_mode(0o400)).unwrap();
368            if let Some(said) = kvm_problem(&device) {
369                assert!(said.starts_with("you can't use /dev/kvm yet"), "{said}");
370                return said;
371            }
372        }
373        let _ = dir;
374        "you can't use /dev/kvm yet: add yourself to the kvm and libvirt groups, then sign out and back in".to_owned()
375    }
376
377    /// Each provider on each OS and CPU, not only this host's.
378    #[test]
379    fn a_provider_applies_where_its_hypervisor_runs() {
380        let platforms = [
381            ("linux", "x86_64"),
382            ("linux", "aarch64"),
383            ("macos", "aarch64"),
384            ("macos", "x86_64"),
385            ("windows", "x86_64"),
386            ("windows", "aarch64"),
387        ];
388        let table = [
389            (Provider::Virtualbox, [true, true, true, true, true, false]),
390            (Provider::VmwareDesktop, [true, true, true, true, true, false]),
391            (Provider::Hyperv, [false, false, false, false, true, true]),
392            (Provider::Parallels, [false, false, true, true, false, false]),
393            (Provider::Utm, [false, false, true, true, false, false]),
394            (Provider::Libvirt, [true, true, false, false, false, false]),
395            (Provider::Qemu, [true; 6]),
396            (Provider::VmwareEsxi, [true; 6]),
397        ];
398        assert_eq!(table.len(), all().len(), "every provider is in the table");
399        for (provider, expected) in table {
400            for ((os, arch), applies) in platforms.iter().zip(expected) {
401                assert_eq!(applicable_on(provider, os, arch), applies, "{provider:?} on {os} {arch}");
402            }
403        }
404        assert_eq!(qemu_binary_on("aarch64"), "qemu-system-aarch64");
405        assert_eq!(qemu_binary_on("x86_64"), "qemu-system-x86_64");
406    }
407
408    #[test]
409    fn a_providers_id_is_the_one_vagrant_and_the_manifest_use() {
410        let ids: Vec<String> = all().iter().map(isothrum_runner::wire_name).collect();
411        assert_eq!(
412            ids,
413            ["virtualbox", "vmware_desktop", "hyperv", "parallels", "libvirt", "qemu", "utm", "vmware_esxi"]
414        );
415    }
416
417    #[test]
418    fn utm_and_its_plugin_are_held_to_a_version() {
419        let detection = |hv: Option<&'static str>, pl: Option<&'static str>, installed: bool| Detection {
420            hypervisor: Some(true),
421            hypervisor_version: hv,
422            unresponsive: false,
423            plugin: Some("vagrant_utm"),
424            plugin_installed: installed,
425            plugin_version: pl,
426            plugins_unknown: None,
427            needs_admin: false,
428            platform_problem: None,
429        };
430        assert_eq!(plugin_too_old(Provider::Utm, Some("0.1.6")), Some(("0.1.6", "0.2.0")));
431        // Regression: a suffix was dropped, so a pre-release of the minimum passed for it; it comes
432        // before its release, as the runner's tool probes (Isoloom's Version) order it.
433        assert_eq!(plugin_too_old(Provider::Utm, Some("0.2.0-beta")), Some(("0.2.0-beta", "0.2.0")));
434        assert_eq!(plugin_too_old(Provider::Utm, Some("unknown")), None, "no version to judge");
435        assert_eq!(
436            unavailable_reason(Provider::Utm, detection(Some("4.7.5"), Some("0.1.6"), true)).as_deref(),
437            Some("Vagrant plugin `vagrant_utm` 0.1.6 is too old: 0.2.0 or later is needed. Install it again to update it")
438        );
439        // A UTM the plugin refuses, said before the plugin (updating the plugin wouldn't help).
440        assert_eq!(
441            unavailable_reason(Provider::Utm, detection(Some("4.5.1"), Some("0.1.6"), true)).as_deref(),
442            Some("UTM 4.5.1 is too old: 4.6.5 or later is needed. Update UTM")
443        );
444        // Recent enough, or no version to judge: nothing stands in the way.
445        assert_eq!(unavailable_reason(Provider::Utm, detection(Some("4.7.5"), Some("0.2.0"), true)), None);
446        assert_eq!(unavailable_reason(Provider::Utm, detection(None, None, true)), None);
447        assert_eq!(plugin_too_old(Provider::Utm, None), None);
448        // Other providers aren't held to a version.
449        assert_eq!(plugin_too_old(Provider::Qemu, Some("0.1.0")), None);
450        assert_eq!(hypervisor_too_old(Provider::Virtualbox, Some("6.0")), None);
451    }
452
453    #[tokio::test]
454    async fn detect_reports_a_ready_qemu_and_an_unavailable_one_by_its_plugin() {
455        // QEMU installed, its plugin present: available. A missing plugin makes it unavailable.
456        let with = FakeProcesses::rules(&[
457            ("qemu-system", Reply::ok("QEMU 10.0")),
458            (
459                "vagrant plugin list --machine-readable",
460                Reply::ok("1,,plugin-name,vagrant-qemu\n1,vagrant-qemu,plugin-version,0.6.3%!(VAGRANT_COMMA) global"),
461            ),
462        ]);
463        let qemu = detect(&with, true).await.into_iter().find(|s| s.provider == Provider::Qemu).unwrap();
464        assert!(qemu.reason.is_none(), "{qemu:?}");
465
466        let without = FakeProcesses::rules(&[("qemu-system", Reply::ok("QEMU 10.0")), ("vagrant plugin list", Reply::ok(""))]);
467        let no_plugin = detect(&without, true).await.into_iter().find(|s| s.provider == Provider::Qemu).unwrap();
468        assert_eq!(no_plugin.reason.as_deref(), Some("Vagrant plugin `vagrant-qemu` is not installed"),);
469    }
470
471    #[tokio::test]
472    async fn a_vagrant_that_cant_list_its_plugins_is_one_reason_not_each_plugin_missing() {
473        let broken = FakeProcesses::rules(&[
474            ("qemu-system", Reply::ok("QEMU 10.0")),
475            ("VBoxManage", Reply::ok("7.1.4")),
476            ("vagrant plugin list", Reply::fail(1, "Vagrant failed to initialize at a very early stage")),
477        ]);
478        let statuses = detect(&broken, true).await;
479        let qemu = statuses.iter().find(|s| s.provider == Provider::Qemu).unwrap();
480        assert_eq!(
481            qemu.reason.as_deref(),
482            Some("Vagrant couldn't say which plugins it has (`vagrant plugin list`: Vagrant failed to initialize at a very early stage (exited with code 1))")
483        );
484        // A provider built into Vagrant needs no plugin: what Vagrant lists doesn't matter to it.
485        let virtualbox = statuses.iter().find(|s| s.provider == Provider::Virtualbox);
486        assert!(virtualbox.is_none_or(|s| s.reason.is_none()), "{virtualbox:?}");
487    }
488
489    /// Each missing layer is said for what it is: Hyper-V turned off (a Windows feature, not a
490    /// program), a hypervisor whose program isn't installed.
491    #[test]
492    fn a_hypervisor_that_is_off_or_not_installed_says_which() {
493        let absent = Detection {
494            hypervisor: Some(false),
495            hypervisor_version: None,
496            unresponsive: false,
497            plugin: None,
498            plugin_installed: true,
499            plugin_version: None,
500            plugins_unknown: None,
501            needs_admin: false,
502            platform_problem: None,
503        };
504        assert_eq!(
505            unavailable_reason(Provider::Hyperv, absent).as_deref(),
506            Some("Hyper-V isn't turned on (Windows Features > Hyper-V), or this edition of Windows doesn't have it")
507        );
508        assert_eq!(unavailable_reason(Provider::Virtualbox, absent).as_deref(), Some("`VBoxManage` was not found"));
509    }
510
511    /// libvirt needs KVM's device, and the user's leave to open it: each is said, read once by
512    /// `detect`, and comes after the tool itself (no `virsh` is said first).
513    #[test]
514    fn libvirt_without_kvm_or_its_leave_says_which() {
515        let dir = tempfile::tempdir().unwrap();
516        let missing = kvm_problem(&dir.path().join("kvm")).unwrap();
517        assert!(missing.starts_with("KVM isn't available on this machine (no /dev/kvm)"), "{missing}");
518        // Regression: any failure to open it (a folder here; EBUSY, ENXIO on a real device) was
519        // said as a device the user may not open.
520        let other = kvm_problem(dir.path()).unwrap();
521        assert!(other.starts_with("/dev/kvm can't be opened: "), "{other}");
522        let device = dir.path().join("device");
523        std::fs::write(&device, "").unwrap();
524        assert_eq!(kvm_problem(&device), None);
525        let denied = denied_device(dir.path());
526        let (missing, denied) = (missing.as_str(), denied.as_str());
527        let libvirt = |hypervisor, platform_problem| Detection {
528            hypervisor: Some(hypervisor),
529            hypervisor_version: None,
530            unresponsive: false,
531            plugin: Some("vagrant-libvirt"),
532            plugin_installed: true,
533            plugin_version: None,
534            plugins_unknown: None,
535            needs_admin: false,
536            platform_problem,
537        };
538        assert_eq!(unavailable_reason(Provider::Libvirt, libvirt(true, Some(missing))).as_deref(), Some(missing));
539        assert_eq!(unavailable_reason(Provider::Libvirt, libvirt(true, Some(denied))).as_deref(), Some(denied));
540        assert_eq!(
541            unavailable_reason(Provider::Libvirt, libvirt(false, Some(missing))).as_deref(),
542            Some("`virsh` was not found")
543        );
544        assert_eq!(unavailable_reason(Provider::Libvirt, libvirt(true, None)), None);
545    }
546
547    #[tokio::test]
548    async fn a_virtualbox_that_isnt_installed_is_detected_as_such() {
549        let tools = FakeProcesses::rules(&[("VBoxManage", Reply::missing())]);
550        let statuses = detect(&tools, true).await;
551        let virtualbox = statuses.iter().find(|s| s.provider == Provider::Virtualbox);
552        assert!(
553            virtualbox.is_none_or(|s| s.reason.as_deref() == Some("`VBoxManage` was not found")),
554            "{virtualbox:?}"
555        );
556    }
557
558    #[tokio::test]
559    async fn without_vagrant_every_provider_says_so_and_nothing_is_probed() {
560        let tools = FakeProcesses::rules(&[]);
561        let statuses = detect(&tools, false).await;
562        assert_eq!(statuses.len(), all().iter().filter(|p| applicable(**p)).count());
563        assert!(statuses.iter().all(|s| s.reason.as_deref() == Some(NO_VAGRANT)), "{statuses:?}");
564        assert_eq!(tools.calls(), [], "no probe runs without Vagrant");
565    }
566
567    /// A tool that never answers.
568    struct Stuck;
569
570    impl ProcessRunner for Stuck {
571        fn run<'a>(
572            &'a self,
573            _spec: &'a isothrum_runner::ProcessSpec,
574            _on_line: isothrum_runner::OnLine<'a>,
575        ) -> isothrum_runner::BoxFuture<'a, Result<isothrum_runner::Exit, isothrum_runner::ProcessError>> {
576            Box::pin(async {
577                tokio::time::sleep(Duration::from_secs(3600)).await;
578                Ok(isothrum_runner::Exit::new(Some(0)))
579            })
580        }
581    }
582
583    #[tokio::test(start_paused = true)]
584    async fn a_virtualbox_whose_service_never_answers_is_wedged() {
585        assert!(vbox_wedged(&Stuck).await);
586        let answering = FakeProcesses::rules(&[("VBoxManage list runningvms", Reply::ok(""))]);
587        assert!(!vbox_wedged(&answering).await);
588    }
589
590    #[tokio::test]
591    async fn only_utm_is_asked_its_version() {
592        let tools = FakeProcesses::rules(&[("defaults read", Reply::ok("4.7.5\n"))]);
593        assert_eq!(hypervisor_version(Provider::Utm, &tools).await.as_deref(), Some("4.7.5"));
594        assert_eq!(hypervisor_version(Provider::Qemu, &tools).await, None);
595        let silent = FakeProcesses::rules(&[("defaults read", Reply::ok(""))]);
596        assert_eq!(hypervisor_version(Provider::Utm, &silent).await, None, "no version said, none read");
597        let call = tools.calls().into_iter().next().unwrap();
598        assert_eq!(call.args, ["read", "/Applications/UTM.app/Contents/Info.plist", "CFBundleShortVersionString"]);
599    }
600
601    #[tokio::test]
602    async fn an_installed_hyperv_needs_admin_only_when_whoami_says_the_account_may_not_manage_it() {
603        let groups = |sid: &str| format!("\"Label\",\"Label\",\"{sid}\",");
604        let not_allowed = FakeProcesses::rules(&[("whoami /groups", Reply::ok(&groups("S-1-16-8192")))]);
605        let allowed = FakeProcesses::rules(&[("whoami /groups", Reply::ok(&groups("S-1-5-32-578")))]);
606        let unknown = FakeProcesses::rules(&[("whoami", Reply::missing())]);
607        assert!(needs_admin(Provider::Hyperv, Some(true), &not_allowed).await);
608        assert!(!needs_admin(Provider::Hyperv, Some(true), &allowed).await);
609        assert!(!needs_admin(Provider::Hyperv, Some(true), &unknown).await, "no answer adds no reason");
610        assert!(!needs_admin(Provider::Hyperv, Some(false), &not_allowed).await, "not installed says so instead");
611        assert!(!needs_admin(Provider::Virtualbox, Some(true), &not_allowed).await);
612        assert_eq!(not_allowed.calls().len(), 1, "whoami is asked for an installed Hyper-V only");
613    }
614
615    #[test]
616    fn hyperv_needs_admin_folds_into_its_reason() {
617        // Hyper-V's `applicable()` gate keeps it out of `detect` off Windows, so `needs_admin` is
618        // tested on its own (above) and through `unavailable_reason` here.
619        let hyperv = |needs_admin| Detection {
620            hypervisor: Some(true),
621            hypervisor_version: None,
622            unresponsive: false,
623            plugin: None,
624            plugin_installed: true,
625            plugin_version: None,
626            plugins_unknown: None,
627            needs_admin,
628            platform_problem: None,
629        };
630        assert_eq!(unavailable_reason(Provider::Hyperv, hyperv(true)).as_deref(), Some(HYPERV_NEEDS_ADMIN));
631        assert_eq!(unavailable_reason(Provider::Hyperv, hyperv(false)), None);
632    }
633}