Skip to main content

isothrum_machine/
host.rs

1//! This computer as machine setup reads it: its OS, its CPU and its package manager, each a closed
2//! set, and the files detection reads (KVM's device, UTM's bundle, the kernel's module list...).
3//! It is worked out once ([`Host::here`]) and handed to every rule that depends on it. A rule
4//! matches on these enums (the OS and CPU are the runner's [`HostOs`] and [`Arch`]), never on
5//! `std::env::consts` strings: an OS, CPU or package manager added is a compile error at every
6//! rule that doesn't say what it does there yet.
7//!
8//! A test builds its own (`Host { os, arch, packages, devices: Devices::under(dir) }`), so each
9//! OS's rules run on any machine.
10
11use std::net::{Ipv4Addr, SocketAddr};
12use std::path::{Path, PathBuf};
13
14use isothrum_runner::{ProcessRunner, this_arch, this_host};
15
16use crate::exec;
17use crate::providers::virtiofsd::{VAGRANT_QEMU_FALLBACKS, VHOST_USER_DIRS, vagrant_qemu_candidates};
18
19/// The OS and the CPU machine setup runs on: the runner's ([`isothrum_runner::this_host`],
20/// [`isothrum_runner::this_arch`]), written as the runner writes them (`macos`, `amd64`).
21pub use isothrum_runner::{Arch, HostOs};
22
23pub mod tool_path;
24
25/// Every OS.
26pub const ALL_OSES: [HostOs; 3] = [HostOs::Macos, HostOs::Windows, HostOs::Linux];
27
28/// Every CPU.
29pub const ALL_ARCHES: [Arch; 2] = [Arch::Amd64, Arch::Arm64];
30
31/// `os`'s name as people write it (`macOS`).
32#[must_use]
33pub fn os_name(os: HostOs) -> &'static str {
34    match os {
35        HostOs::Macos => "macOS",
36        HostOs::Windows => "Windows",
37        HostOs::Linux => "Linux",
38    }
39}
40
41/// The package manager setup installs through on `os` when the machine has it: the one to name
42/// when it is missing (Linux's first, apt).
43#[must_use]
44pub fn usual_packages(os: HostOs) -> &'static str {
45    match os {
46        HostOs::Macos => "Homebrew",
47        HostOs::Windows => "winget",
48        HostOs::Linux => "apt",
49    }
50}
51
52/// QEMU's system emulator for a CPU `arch` (`qemu-system-x86_64`).
53#[must_use]
54pub fn qemu_system(arch: Arch) -> &'static str {
55    match arch {
56        Arch::Amd64 => "qemu-system-x86_64",
57        Arch::Arm64 => "qemu-system-aarch64",
58    }
59}
60
61/// The package manager setup installs and removes tools through.
62#[derive(Debug, Clone, Copy, PartialEq, Eq)]
63pub enum Packages {
64    /// Homebrew (macOS), at this path.
65    Homebrew(&'static str),
66    /// winget (Windows).
67    Winget,
68    /// A Linux distribution's.
69    Linux(LinuxPackages),
70}
71
72/// A Linux distribution's package manager setup goes through.
73#[derive(Debug, Clone, Copy, PartialEq, Eq)]
74pub enum LinuxPackages {
75    /// apt-get: Debian, Ubuntu and the distributions built on them.
76    Apt,
77    /// dnf: Fedora and the distributions built on it.
78    Dnf,
79}
80
81impl Packages {
82    /// Its name (`Homebrew`, `winget`, `apt`, `dnf`).
83    #[must_use]
84    pub fn name(self) -> &'static str {
85        match self {
86            Packages::Homebrew(_) => "Homebrew",
87            Packages::Winget => "winget",
88            Packages::Linux(LinuxPackages::Apt) => "apt",
89            Packages::Linux(LinuxPackages::Dnf) => "dnf",
90        }
91    }
92
93    /// The program that answers its `--version`.
94    #[must_use]
95    pub fn program(self) -> &'static str {
96        match self {
97            Packages::Homebrew(brew) => brew,
98            Packages::Winget => "winget",
99            Packages::Linux(LinuxPackages::Apt) => "apt-get",
100            Packages::Linux(LinuxPackages::Dnf) => "dnf",
101        }
102    }
103
104    /// The Linux distribution's, when it is one.
105    #[must_use]
106    pub fn linux(self) -> Option<LinuxPackages> {
107        match self {
108            Packages::Linux(packages) => Some(packages),
109            Packages::Homebrew(_) | Packages::Winget => None,
110        }
111    }
112}
113
114/// Where Homebrew's installer puts it: Apple silicon's, then Intel's.
115const HOMEBREW: [&str; 2] = ["/opt/homebrew/bin/brew", "/usr/local/bin/brew"];
116
117/// The files and the one local service detection reads instead of running a tool: each a path a
118/// test points into a folder of its own ([`Devices::under`]), so no test reads the machine running
119/// it.
120#[derive(Debug, Clone, PartialEq, Eq)]
121#[non_exhaustive]
122pub struct Devices {
123    /// KVM's device (`/dev/kvm`), which libvirt's and QEMU's guests run on (Linux).
124    pub kvm: PathBuf,
125    /// The group database (`/etc/group`): the name of the group `/dev/kvm` belongs to.
126    pub etc_group: PathBuf,
127    /// The kernel modules loaded (`/proc/modules`): VirtualBox's driver, KVM's CPU module.
128    pub proc_modules: PathBuf,
129    /// The running kernel's release (`/proc/sys/kernel/osrelease`, what `uname -r` says).
130    pub kernel_release: PathBuf,
131    /// The kernels' module folders (`/lib/modules`), each with a `build` link once its headers
132    /// are installed.
133    pub lib_modules: PathBuf,
134    /// KVM's `enable_virt_at_load` parameter (`/sys/module/kvm/parameters/enable_virt_at_load`,
135    /// Linux 6.12 and later).
136    pub kvm_virt_at_load: PathBuf,
137    /// The loaded modules' folders (`/sys/module`): each loadable module's `refcnt` (how many
138    /// hold it) and `holders` (the modules among them).
139    pub sys_module: PathBuf,
140    /// The folder of the options modprobe gives a module as it loads it (`/etc/modprobe.d`, its
141    /// `*.conf` files).
142    pub modprobe_d: PathBuf,
143    /// The Applications folder macOS apps install into (`/Applications`): a tool's app bundle
144    /// ([`crate::install::ToolRow::mac_app`]) is looked for there, and Docker Desktop's own
145    /// `docker` CLI inside its bundle.
146    pub applications: PathBuf,
147    /// Docker Desktop's socket (`~/.docker/run/docker.sock`, macOS), which listens once its
148    /// backend runs: never, while Docker Desktop waits for its user in its own window.
149    pub docker_desktop_socket: PathBuf,
150    /// Docker Desktop's settings files, the first there read: `settings-store.json`, then the
151    /// `settings.json` of a Docker Desktop before 4.34 (`~/Library/Group Containers/
152    /// group.com.docker` on macOS, `%APPDATA%\Docker` on Windows, `~/.docker/desktop` on Linux).
153    /// They record the version of the agreement its user accepted in its window
154    /// ([`crate::docker::agreement_accepted`]).
155    pub docker_desktop_settings: Vec<PathBuf>,
156    /// UTM's app bundle (macOS): in `/Applications`, else in the user's own `~/Applications` (an
157    /// install without an administrator's password); `/Applications/UTM.app` when in neither.
158    pub utm_app: PathBuf,
159    /// Hyper-V's Virtual Machine Management service (`%SystemRoot%\System32\vmms.exe`), there
160    /// once the Windows feature is on.
161    pub hyperv_service: PathBuf,
162    /// What proves HashiCorp's Vagrant VMware Utility is installed: its program on macOS and
163    /// Linux, the certificates its installer generates (under `%ProgramData%`) on Windows.
164    pub vmware_utility: PathBuf,
165    /// Where the Vagrant VMware Utility's service answers when it runs: this machine's port 9922,
166    /// the plugin's default (`utility_port`).
167    pub vmware_utility_service: SocketAddr,
168    /// Where VMware's apps install `vmrun`, looked at when it isn't on `PATH`: Fusion's
169    /// `Contents/Public/vmrun` in `/Applications`, then in `~/Applications` (macOS); Workstation's
170    /// folder under `%ProgramFiles(x86)%`, then `%ProgramFiles%` (Windows).
171    pub vmrun: Vec<PathBuf>,
172    /// Where Parallels Desktop installs `prlctl`, looked at when it isn't on `PATH`: the app's
173    /// `Contents/MacOS/prlctl` in `/Applications`, then in `~/Applications`.
174    pub prlctl: Vec<PathBuf>,
175    /// The folders libvirt reads QEMU's vhost-user descriptors from, in its order, a later
176    /// folder's file taking the place of an earlier one's of the same name: the distribution's
177    /// (`/usr/share/qemu/vhost-user`), then an administrator's (`/etc/qemu/vhost-user`) (Linux).
178    pub vhost_user: Vec<PathBuf>,
179    /// Where vagrant-qemu looks for the virtiofsd it shares folders through, in its order:
180    /// `virtiofsd` in each folder of `PATH`, then `/usr/libexec/virtiofsd`, then
181    /// `/usr/lib/qemu/virtiofsd` (Linux).
182    pub virtiofsd: Vec<PathBuf>,
183    /// Where vagrant-vmware-desktop looks for the `netstat` it reads the routing table with before
184    /// it makes a private network (its collision check): `netstat` in each folder of `PATH`
185    /// (Linux; macOS has it in `/usr/sbin`, Windows reads its routes otherwise).
186    pub netstat: Vec<PathBuf>,
187    /// Where VMware's hypervisors keep their own OVF Tool (`ovftool`), in the order to look:
188    /// Fusion's `Contents/Library/VMware OVF Tool` in `/Applications`, then in `~/Applications`
189    /// (macOS); Workstation's `OVFTool` folder under `%ProgramFiles(x86)%`, then `%ProgramFiles%`
190    /// (Windows). Workstation for Linux puts it in `/usr/bin`, on `PATH`.
191    pub ovftool: Vec<PathBuf>,
192    /// Rosetta 2's runtime (`/Library/Apple/usr/libexec/oah/libRosettaRuntime`), there once it is
193    /// installed (macOS on Apple silicon).
194    pub rosetta_runtime: PathBuf,
195}
196
197/// The port the Vagrant VMware Utility's service listens on.
198pub const VMWARE_UTILITY_PORT: u16 = 9922;
199
200/// Fusion's `vmrun` and Parallels Desktop's `prlctl` in the app bundles under each of `bases`
201/// (`/`, then the user's home), each base's `Applications` folder.
202fn mac_apps(bases: &[PathBuf]) -> (Vec<PathBuf>, Vec<PathBuf>) {
203    let apps = |bundle: &str, inside: &str| bases.iter().map(|b| b.join("Applications").join(bundle).join(inside)).collect();
204    (
205        apps("VMware Fusion.app", "Contents/Public/vmrun"),
206        apps("Parallels Desktop.app", "Contents/MacOS/prlctl"),
207    )
208}
209
210/// UTM's app bundle in the `Applications` folder of the first of `bases` (`/`, then the user's
211/// home) that has it; the first base's when none has.
212fn utm_app(bases: &[PathBuf]) -> PathBuf {
213    let in_each = bases.iter().map(|b| b.join("Applications").join("UTM.app"));
214    let first = in_each.clone().next().unwrap_or_else(|| PathBuf::from("/Applications/UTM.app"));
215    in_each.into_iter().find(|app| app.exists()).unwrap_or(first)
216}
217
218/// Fusion's OVF Tool in the app bundles under each of `bases` (`/`, then the user's home).
219fn fusion_ovftool(bases: &[PathBuf]) -> Vec<PathBuf> {
220    bases
221        .iter()
222        .map(|b| b.join("Applications/VMware Fusion.app/Contents/Library/VMware OVF Tool/ovftool"))
223        .collect()
224}
225
226/// Workstation's OVF Tool under each of the install folders `bases`.
227fn workstation_ovftool(bases: &[PathBuf]) -> Vec<PathBuf> {
228    bases.iter().map(|b| crate::tools::ovftool::workstation_dir(b).join("ovftool.exe")).collect()
229}
230
231/// Rosetta 2's runtime under `root`.
232const ROSETTA_RUNTIME: &str = "Library/Apple/usr/libexec/oah/libRosettaRuntime";
233
234/// Workstation's `vmrun.exe` under each of the install folders `bases`.
235/// Docker Desktop's settings folder on `os`, for this account.
236fn docker_desktop_folder(os: HostOs) -> PathBuf {
237    let home = std::env::var_os("HOME").map_or_else(|| PathBuf::from("/nonexistent"), PathBuf::from);
238    match os {
239        HostOs::Macos => home.join("Library/Group Containers/group.com.docker"),
240        HostOs::Windows => std::env::var_os("APPDATA")
241            .map_or_else(|| home.join("AppData").join("Roaming"), PathBuf::from)
242            .join("Docker"),
243        HostOs::Linux => home.join(".docker/desktop"),
244    }
245}
246
247/// Where vagrant-vmware-desktop looks for `netstat` on `os` ([`Devices::netstat`]): Linux's
248/// `PATH`, none elsewhere.
249fn netstat(os: HostOs) -> Vec<PathBuf> {
250    match os {
251        HostOs::Linux => on_path(std::env::var_os("PATH").as_deref(), "netstat"),
252        HostOs::Macos | HostOs::Windows => Vec::new(),
253    }
254}
255
256/// `program` in each folder of `path` (a `PATH`), in its order; an empty entry is skipped (it
257/// isn't the current folder).
258fn on_path(path: Option<&std::ffi::OsStr>, program: &str) -> Vec<PathBuf> {
259    path.into_iter()
260        .flat_map(std::env::split_paths)
261        .filter(|d| !d.as_os_str().is_empty())
262        .map(|d| d.join(program))
263        .collect()
264}
265
266/// Docker Desktop's settings files in its folder `dir`: today's, then the one before 4.34.
267fn docker_desktop_settings(dir: &Path) -> Vec<PathBuf> {
268    vec![dir.join("settings-store.json"), dir.join("settings.json")]
269}
270
271fn workstation(bases: &[PathBuf]) -> Vec<PathBuf> {
272    bases.iter().map(|b| b.join("VMware").join("VMware Workstation").join("vmrun.exe")).collect()
273}
274
275impl Devices {
276    /// This computer's, on `os`: where each OS keeps them.
277    #[must_use]
278    pub fn here(os: HostOs) -> Devices {
279        let windows_folder = |var: &str, default: &str| std::env::var_os(var).map_or_else(|| PathBuf::from(default), PathBuf::from);
280        let mut mac_bases = vec![PathBuf::from("/")];
281        mac_bases.extend(std::env::var_os("HOME").map(PathBuf::from));
282        let program_files: Vec<PathBuf> = ["ProgramFiles(x86)", "ProgramFiles"]
283            .iter()
284            .filter_map(std::env::var_os)
285            .map(PathBuf::from)
286            .collect();
287        let (vmrun, prlctl) = match os {
288            HostOs::Macos => mac_apps(&mac_bases),
289            HostOs::Windows => (workstation(&program_files), Vec::new()),
290            HostOs::Linux => (Vec::new(), Vec::new()),
291        };
292        let ovftool = match os {
293            HostOs::Macos => fusion_ovftool(&mac_bases),
294            HostOs::Windows => workstation_ovftool(&program_files),
295            HostOs::Linux => Vec::new(),
296        };
297        let vmware_utility = match os {
298            HostOs::Windows => windows_folder("ProgramData", "C:\\ProgramData")
299                .join("HashiCorp")
300                .join("vagrant-vmware-desktop")
301                .join("certificates"),
302            HostOs::Macos | HostOs::Linux => PathBuf::from("/opt/vagrant-vmware-desktop/bin/vagrant-vmware-utility"),
303        };
304        let (vhost_user, virtiofsd) = match os {
305            HostOs::Linux => (
306                VHOST_USER_DIRS.iter().map(PathBuf::from).collect(),
307                vagrant_qemu_candidates(std::env::var_os("PATH").as_deref(), &VAGRANT_QEMU_FALLBACKS),
308            ),
309            HostOs::Macos | HostOs::Windows => (Vec::new(), Vec::new()),
310        };
311        Devices {
312            kvm: PathBuf::from("/dev/kvm"),
313            etc_group: PathBuf::from("/etc/group"),
314            proc_modules: PathBuf::from("/proc/modules"),
315            kernel_release: PathBuf::from("/proc/sys/kernel/osrelease"),
316            lib_modules: PathBuf::from("/lib/modules"),
317            kvm_virt_at_load: PathBuf::from("/sys/module/kvm/parameters/enable_virt_at_load"),
318            sys_module: PathBuf::from("/sys/module"),
319            modprobe_d: PathBuf::from("/etc/modprobe.d"),
320            applications: PathBuf::from("/Applications"),
321            docker_desktop_socket: std::env::var_os("HOME")
322                .map_or_else(|| PathBuf::from("/nonexistent"), PathBuf::from)
323                .join(".docker/run/docker.sock"),
324            docker_desktop_settings: docker_desktop_settings(&docker_desktop_folder(os)),
325            utm_app: utm_app(&mac_bases),
326            hyperv_service: windows_folder("SystemRoot", "C:\\Windows").join("System32").join("vmms.exe"),
327            vmware_utility,
328            vmware_utility_service: SocketAddr::from((Ipv4Addr::LOCALHOST, VMWARE_UTILITY_PORT)),
329            vmrun,
330            prlctl,
331            vhost_user,
332            virtiofsd,
333            netstat: netstat(os),
334            ovftool,
335            rosetta_runtime: Path::new("/").join(ROSETTA_RUNTIME),
336        }
337    }
338
339    /// Each one under the folder `root`, where a test makes the ones it is about (`root/dev/kvm`,
340    /// `root/proc/modules`, `root/Applications/UTM.app`...), none of which exist until it does;
341    /// the VMware Utility's service at port 0 of this machine, which nothing answers. The apps'
342    /// tools (the hypervisors' OVF Tools too) are under `root` and `root/home` (macOS's), and
343    /// `root/Program Files (x86)` and `root/Program Files` (Workstation's); Rosetta's runtime
344    /// under `root`; libvirt's descriptor folders and vagrant-qemu's
345    /// virtiofsd fallbacks under `root`, with no `PATH` folder before them; `netstat` as
346    /// `root/usr/bin/netstat`.
347    #[must_use]
348    pub fn under(root: &Path) -> Devices {
349        let (fusion, prlctl) = mac_apps(&[root.to_path_buf(), root.join("home")]);
350        let mut vmrun = fusion;
351        let program_files = [root.join("Program Files (x86)"), root.join("Program Files")];
352        vmrun.extend(workstation(&program_files));
353        let mut ovftool = fusion_ovftool(&[root.to_path_buf(), root.join("home")]);
354        ovftool.extend(workstation_ovftool(&program_files));
355        Devices {
356            kvm: root.join("dev/kvm"),
357            etc_group: root.join("etc/group"),
358            proc_modules: root.join("proc/modules"),
359            kernel_release: root.join("proc/sys/kernel/osrelease"),
360            lib_modules: root.join("lib/modules"),
361            kvm_virt_at_load: root.join("sys/module/kvm/parameters/enable_virt_at_load"),
362            sys_module: root.join("sys/module"),
363            modprobe_d: root.join("etc/modprobe.d"),
364            applications: root.join("Applications"),
365            docker_desktop_socket: root.join("home/.docker/run/docker.sock"),
366            docker_desktop_settings: docker_desktop_settings(&root.join("home/Library/Group Containers/group.com.docker")),
367            utm_app: root.join("Applications/UTM.app"),
368            hyperv_service: root.join("Windows/System32/vmms.exe"),
369            vmware_utility: root.join("opt/vagrant-vmware-desktop/bin/vagrant-vmware-utility"),
370            vmware_utility_service: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
371            vmrun,
372            prlctl,
373            vhost_user: VHOST_USER_DIRS.iter().map(|d| root.join(d.trim_start_matches('/'))).collect(),
374            virtiofsd: VAGRANT_QEMU_FALLBACKS.iter().map(|f| root.join(f.trim_start_matches('/'))).collect(),
375            netstat: vec![root.join("usr/bin/netstat")],
376            ovftool,
377            rosetta_runtime: root.join(ROSETTA_RUNTIME),
378        }
379    }
380}
381
382impl Devices {
383    /// Where an app installs `program` off `PATH` ([`Devices::vmrun`], [`Devices::prlctl`]), in
384    /// the order to look; none for a tool no app here installs.
385    #[must_use]
386    pub fn app_tool(&self, program: &str) -> Vec<&Path> {
387        let at = match program {
388            "vmrun" => &self.vmrun,
389            "prlctl" => &self.prlctl,
390            _ => return Vec::new(),
391        };
392        at.iter().map(PathBuf::as_path).collect()
393    }
394}
395
396/// This computer: its OS, its CPU, the package manager setup goes through here (`None`: a Mac
397/// without Homebrew, a Linux distribution with neither apt nor dnf), and the files detection
398/// reads.
399#[derive(Debug, Clone, PartialEq, Eq)]
400pub struct Host {
401    /// The OS.
402    pub os: HostOs,
403    /// The CPU.
404    pub arch: Arch,
405    /// The package manager, when the machine has one setup goes through.
406    pub packages: Option<Packages>,
407    /// The files and the service detection reads.
408    pub devices: Devices,
409}
410
411impl Host {
412    /// This computer, its package manager looked up now: Homebrew where its installer puts it;
413    /// `apt-get`, else `dnf`, when it answers `--version` (through `runner`).
414    pub async fn here(runner: &dyn ProcessRunner) -> Host {
415        let os = this_host();
416        let packages = match os {
417            HostOs::Macos => HOMEBREW.into_iter().find(|brew| Path::new(brew).exists()).map(Packages::Homebrew),
418            HostOs::Windows => Some(Packages::Winget),
419            HostOs::Linux => linux_packages(runner).await.map(Packages::Linux),
420        };
421        Host {
422            os,
423            arch: this_arch(),
424            packages,
425            devices: Devices::here(os),
426        }
427    }
428
429    /// Whether it is a PC with Windows on Arm.
430    #[must_use]
431    pub fn is_windows_on_arm(&self) -> bool {
432        self.os == HostOs::Windows && self.arch == Arch::Arm64
433    }
434}
435
436/// The Linux distribution's package manager `runner` finds: apt-get, else dnf.
437async fn linux_packages(runner: &dyn ProcessRunner) -> Option<LinuxPackages> {
438    for (packages, program) in [(LinuxPackages::Apt, "apt-get"), (LinuxPackages::Dnf, "dnf")] {
439        if exec::read_ok(runner, crate::context::PROBE_TIMEOUT, program, &["--version"]).await.is_ok() {
440            return Some(packages);
441        }
442    }
443    None
444}
445
446#[cfg(test)]
447mod tests {
448    use isothrum_runner::fake::{FakeProcesses, Reply};
449
450    use super::*;
451
452    /// Every OS once, in the order a UI lists them, with its name and usual package manager.
453    #[test]
454    fn each_os_is_listed_once_with_its_name_and_its_usual_package_manager() {
455        let named: Vec<_> = ALL_OSES.iter().map(|os| (*os, os_name(*os), usual_packages(*os))).collect();
456        assert_eq!(
457            named,
458            [
459                (HostOs::Macos, "macOS", "Homebrew"),
460                (HostOs::Windows, "Windows", "winget"),
461                (HostOs::Linux, "Linux", "apt")
462            ]
463        );
464    }
465
466    /// Every CPU once, with QEMU's system emulator for it.
467    #[test]
468    fn each_cpu_is_listed_once_with_its_qemu_system() {
469        let named: Vec<_> = ALL_ARCHES.iter().map(|arch| (*arch, qemu_system(*arch))).collect();
470        assert_eq!(named, [(Arch::Amd64, "qemu-system-x86_64"), (Arch::Arm64, "qemu-system-aarch64")]);
471    }
472
473    #[test]
474    fn each_package_manager_names_its_program() {
475        let all = [
476            Packages::Homebrew("/opt/homebrew/bin/brew"),
477            Packages::Winget,
478            Packages::Linux(LinuxPackages::Apt),
479            Packages::Linux(LinuxPackages::Dnf),
480        ];
481        let named: Vec<_> = all.iter().map(|p| (p.name(), p.program(), p.linux())).collect();
482        assert_eq!(
483            named,
484            [
485                ("Homebrew", "/opt/homebrew/bin/brew", None),
486                ("winget", "winget", None),
487                ("apt", "apt-get", Some(LinuxPackages::Apt)),
488                ("dnf", "dnf", Some(LinuxPackages::Dnf)),
489            ]
490        );
491    }
492
493    #[test]
494    fn only_a_windows_pc_on_arm_is_windows_on_arm() {
495        let dir = Path::new("unused");
496        let on = |os, arch| Host {
497            os,
498            arch,
499            packages: None,
500            devices: Devices::under(dir),
501        };
502        assert!(on(HostOs::Windows, Arch::Arm64).is_windows_on_arm());
503        assert!(!on(HostOs::Windows, Arch::Amd64).is_windows_on_arm());
504        assert!(!on(HostOs::Macos, Arch::Arm64).is_windows_on_arm());
505    }
506
507    /// A test's host reads nothing of the machine running it: every path under its folder, the
508    /// apps' tools included, and no service that answers.
509    #[test]
510    fn a_tests_devices_are_all_under_its_folder() {
511        let root = Path::new("/the/test");
512        let devices = Devices::under(root);
513        let fixed = [
514            &devices.kvm,
515            &devices.etc_group,
516            &devices.proc_modules,
517            &devices.kernel_release,
518            &devices.lib_modules,
519            &devices.kvm_virt_at_load,
520            &devices.utm_app,
521            &devices.hyperv_service,
522            &devices.vmware_utility,
523        ];
524        let paths = fixed
525            .into_iter()
526            .chain(&devices.vmrun)
527            .chain(&devices.prlctl)
528            .chain(&devices.vhost_user)
529            .chain(&devices.virtiofsd)
530            .chain(&devices.netstat);
531        isothrum_test_support::assert_every!(paths, |path: &&PathBuf| path.starts_with(root));
532        assert_eq!(devices.vmware_utility_service.port(), 0);
533        assert!(devices.vmware_utility_service.ip().is_loopback());
534    }
535
536    #[test]
537    fn utm_is_found_in_the_users_own_applications_folder_too() {
538        // An install without an administrator's password goes in ~/Applications: only
539        // /Applications/UTM.app counted, so that UTM read as not installed.
540        let (system, home) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
541        let bases = [system.path().to_path_buf(), home.path().to_path_buf()];
542        let in_system = system.path().join("Applications/UTM.app");
543        assert_eq!(utm_app(&bases), in_system, "in neither: the system's, which isn't there");
544        std::fs::create_dir_all(home.path().join("Applications/UTM.app")).unwrap();
545        assert_eq!(utm_app(&bases), home.path().join("Applications/UTM.app"));
546        std::fs::create_dir_all(&in_system).unwrap();
547        assert_eq!(utm_app(&bases), in_system, "the system's first");
548        assert_eq!(utm_app(&[]), Path::new("/Applications/UTM.app"));
549    }
550
551    #[test]
552    fn each_oss_devices_are_where_it_keeps_them() {
553        let linux = Devices::here(HostOs::Linux);
554        assert_eq!(linux.kvm, Path::new("/dev/kvm"));
555        assert_eq!(linux.vmware_utility, Path::new("/opt/vagrant-vmware-desktop/bin/vagrant-vmware-utility"));
556        assert_eq!(linux.vmware_utility_service, SocketAddr::from((Ipv4Addr::LOCALHOST, 9922)));
557        assert_eq!(linux.vhost_user, [Path::new("/usr/share/qemu/vhost-user"), Path::new("/etc/qemu/vhost-user")]);
558        assert!(
559            linux
560                .virtiofsd
561                .ends_with(&[PathBuf::from("/usr/libexec/virtiofsd"), PathBuf::from("/usr/lib/qemu/virtiofsd")]),
562            "the PATH's, then vagrant-qemu's fallbacks: {:?}",
563            linux.virtiofsd
564        );
565        assert!(Devices::here(HostOs::Macos).virtiofsd.is_empty() && Devices::here(HostOs::Windows).vhost_user.is_empty());
566        let windows = Devices::here(HostOs::Windows);
567        assert!(
568            windows.vmware_utility.ends_with("HashiCorp/vagrant-vmware-desktop/certificates"),
569            "{:?}",
570            windows.vmware_utility
571        );
572        assert!(windows.hyperv_service.ends_with("System32/vmms.exe"), "{:?}", windows.hyperv_service);
573        assert!(Devices::here(HostOs::Macos).utm_app.ends_with("Applications/UTM.app"));
574    }
575
576    #[tokio::test(start_paused = true)]
577    async fn linux_goes_through_apt_else_dnf_else_none() {
578        let apt = FakeProcesses::script().expect("apt-get --version", Reply::ok("apt 2.9.8 (amd64)")).build();
579        assert_eq!(linux_packages(&apt).await, Some(LinuxPackages::Apt));
580        let dnf = FakeProcesses::script()
581            .expect("apt-get --version", Reply::missing())
582            .expect("dnf --version", Reply::ok("4.21.1"))
583            .build();
584        assert_eq!(linux_packages(&dnf).await, Some(LinuxPackages::Dnf));
585        let neither = FakeProcesses::script()
586            .expect("apt-get --version", Reply::missing())
587            .expect("dnf --version", Reply::fail(127, "dnf: command not found"))
588            .build();
589        assert_eq!(linux_packages(&neither).await, None);
590    }
591
592    #[tokio::test(start_paused = true)]
593    async fn this_computer_is_the_builds_os_and_cpu_with_its_oss_package_manager() {
594        let tools = FakeProcesses::script()
595            .allow("apt-get --version", Reply::ok("apt 2.9.8"))
596            .allow("dnf --version", Reply::missing())
597            .build();
598        let host = Host::here(&tools).await;
599        assert_eq!((host.os, host.arch), (this_host(), this_arch()));
600        assert_eq!(host.devices, Devices::here(this_host()));
601        match (host.os, host.packages) {
602            (HostOs::Macos, None | Some(Packages::Homebrew(_)))
603            | (HostOs::Windows, Some(Packages::Winget))
604            | (HostOs::Linux, Some(Packages::Linux(LinuxPackages::Apt))) => {}
605            other => panic!("{other:?}"),
606        }
607    }
608}