1use std::path::Path;
11use std::time::Duration;
12
13use isothrum_runner::{ProcessRunner, version_found};
14
15use crate::exec;
16
17pub use isoloom_manifest::Provider;
20
21fn 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
30fn applicable(provider: Provider) -> bool {
32 applicable_on(provider, std::env::consts::OS, std::env::consts::ARCH)
33}
34
35fn 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
47fn plugin_minimum(provider: Provider) -> Option<&'static str> {
51 match provider {
52 Provider::Utm => Some("0.2.0"),
53 _ => None,
54 }
55}
56
57fn 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
66async 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
78fn 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
90async 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
103const UTM_APP: &str = "/Applications/UTM.app";
105
106fn 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
112const KVM: &str = "/dev/kvm";
114
115fn 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
132fn qemu_binary() -> &'static str {
134 qemu_binary_on(std::env::consts::ARCH)
135}
136
137fn qemu_binary_on(arch: &str) -> &'static str {
139 if arch == "aarch64" { "qemu-system-aarch64" } else { "qemu-system-x86_64" }
140}
141
142#[derive(Debug, Clone)]
144#[non_exhaustive]
145pub struct ProviderStatus {
146 pub provider: Provider,
148 pub reason: Option<String>,
150}
151
152fn 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
160fn 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
167fn older(installed: &str, min: &str) -> bool {
170 version_found(installed).zip(version_found(min)).is_some_and(|(found, min)| found < min)
171}
172
173async fn tool_present(runner: &dyn ProcessRunner, program: &str, args: &[&str]) -> bool {
176 exec::read(runner, program, args).await.is_ok()
177}
178
179async 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
187const NO_VAGRANT: &str = "Vagrant is not installed";
189
190const VBOX_PROBE: Duration = Duration::from_secs(8);
192
193const 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
198pub 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 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
256async 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
264async 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#[derive(Clone, Copy)]
275struct Detection<'a> {
276 hypervisor: Option<bool>,
278 hypervisor_version: Option<&'a str>,
280 unresponsive: bool,
282 plugin: Option<&'a str>,
284 plugin_installed: bool,
286 plugin_version: Option<&'a str>,
288 plugins_unknown: Option<&'a str>,
290 needs_admin: bool,
293 platform_problem: Option<&'a str>,
296}
297
298fn 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 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 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 fn isoloom_providers() -> Vec<String> {
345 let mut names = isothrum_runner::every_name::<Provider>();
346 names.sort();
347 names
348 }
349
350 #[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 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 #[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 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 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 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 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 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 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 #[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 #[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 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 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), ¬_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), ¬_allowed).await, "not installed says so instead");
611 assert!(!needs_admin(Provider::Virtualbox, Some(true), ¬_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 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}