use std::path::Path;
use std::time::Duration;
use isothrum_runner::ProcessRunner;
use serde::{Deserialize, Serialize};
use crate::exec;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum Provider {
Virtualbox,
VmwareDesktop,
Hyperv,
Parallels,
Libvirt,
Qemu,
Utm,
VmwareEsxi,
Proxmox,
Aws,
Azure,
Gcp,
#[serde(rename = "digitalocean")]
DigitalOcean,
Linode,
Oci,
}
impl Provider {
pub const ALL: [Provider; 9] = [
Provider::Virtualbox,
Provider::VmwareDesktop,
Provider::Hyperv,
Provider::Parallels,
Provider::Libvirt,
Provider::Qemu,
Provider::Utm,
Provider::VmwareEsxi,
Provider::Proxmox,
];
#[must_use]
pub fn id(self) -> &'static str {
match self {
Provider::Virtualbox => "virtualbox",
Provider::VmwareDesktop => "vmware_desktop",
Provider::Hyperv => "hyperv",
Provider::Parallels => "parallels",
Provider::Libvirt => "libvirt",
Provider::Qemu => "qemu",
Provider::Utm => "utm",
Provider::VmwareEsxi => "vmware_esxi",
Provider::Proxmox => "proxmox",
Provider::Aws => "aws",
Provider::Azure => "azure",
Provider::Gcp => "gcp",
Provider::DigitalOcean => "digitalocean",
Provider::Linode => "linode",
Provider::Oci => "oci",
}
}
#[must_use]
pub fn is_remote(self) -> bool {
matches!(
self,
Provider::VmwareEsxi
| Provider::Proxmox
| Provider::Aws
| Provider::Azure
| Provider::Gcp
| Provider::DigitalOcean
| Provider::Linode
| Provider::Oci
)
}
#[must_use]
pub fn is_cloud(self) -> bool {
self.is_remote() && !matches!(self, Provider::VmwareEsxi | Provider::Proxmox)
}
fn applicable(self) -> bool {
use std::env::consts::{ARCH, OS};
match self {
Provider::Virtualbox | Provider::VmwareDesktop
if OS == "windows" && ARCH == "aarch64" =>
{
false
}
Provider::Hyperv => OS == "windows",
Provider::Parallels | Provider::Utm => OS == "macos",
Provider::Libvirt => OS == "linux",
_ => true,
}
}
fn plugin(self) -> Option<&'static str> {
match self {
Provider::Virtualbox
| Provider::Hyperv
| Provider::Aws
| Provider::Azure
| Provider::Gcp
| Provider::DigitalOcean
| Provider::Linode
| Provider::Oci => None,
Provider::VmwareDesktop => Some("vagrant-vmware-desktop"),
Provider::Parallels => Some("vagrant-parallels"),
Provider::Libvirt => Some("vagrant-libvirt"),
Provider::Qemu => Some("vagrant-qemu"),
Provider::Utm => Some("vagrant_utm"),
Provider::VmwareEsxi => Some("vagrant-vmware-esxi"),
Provider::Proxmox => Some("vagrant-proxmox"),
}
}
fn probe(self) -> Option<(&'static str, &'static [&'static str])> {
match self {
Provider::Virtualbox => Some(("VBoxManage", &["--version"])),
Provider::VmwareDesktop => Some(("vmrun", &[])),
Provider::Parallels => Some(("prlctl", &["--version"])),
Provider::Libvirt => Some(("virsh", &["--version"])),
Provider::Qemu => Some((qemu_binary(), &["--version"])),
_ => None,
}
}
async fn hypervisor_installed(self, runner: &dyn ProcessRunner) -> Option<bool> {
match self {
Provider::Utm => Some(Path::new(UTM_APP).exists()),
Provider::Hyperv => Some(hyperv_enabled()),
_ => {
let (program, args) = self.probe()?;
Some(tool_present(runner, program, args).await)
}
}
}
}
const UTM_APP: &str = "/Applications/UTM.app";
fn hyperv_enabled() -> bool {
let root = std::env::var_os("SystemRoot").map_or_else(
|| std::path::PathBuf::from("C:\\Windows"),
std::path::PathBuf::from,
);
root.join("System32").join("vmms.exe").is_file()
}
#[must_use]
pub fn kvm_problem() -> Option<String> {
let dev = Path::new("/dev/kvm");
if !dev.exists() {
return Some("KVM isn't available on this machine (no /dev/kvm): turn on virtualization in the firmware, or use another hypervisor".to_owned());
}
if std::fs::OpenOptions::new()
.read(true)
.write(true)
.open(dev)
.is_err()
{
return Some("you can't use /dev/kvm yet: add yourself to the kvm and libvirt groups, then sign out and back in".to_owned());
}
None
}
fn qemu_binary() -> &'static str {
if std::env::consts::ARCH == "aarch64" {
"qemu-system-aarch64"
} else {
"qemu-system-x86_64"
}
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct ProviderStatus {
pub provider: Provider,
pub remote: bool,
pub available: bool,
pub hypervisor: Option<bool>,
pub plugin: Option<String>,
pub plugin_installed: bool,
pub reason: Option<String>,
}
#[must_use]
pub fn parse_plugins(out: &str) -> Vec<String> {
out.lines()
.filter_map(|l| l.split_whitespace().next())
.filter(|name| name.starts_with("vagrant-") || name.starts_with("vagrant_"))
.map(str::to_owned)
.collect()
}
async fn tool_present(runner: &dyn ProcessRunner, program: &str, args: &[&str]) -> bool {
exec::read(runner, program, args, None).await.is_ok()
}
async fn installed_plugins(runner: &dyn ProcessRunner) -> Vec<String> {
match exec::read(runner, "vagrant", &["plugin", "list"], None).await {
Ok(out) => parse_plugins(&out),
Err(_) => Vec::new(),
}
}
const VBOX_PROBE: Duration = Duration::from_secs(8);
pub const HYPERV_NEEDS_ADMIN: &str = "Vagrant drives Hyper-V only for an administrator or a member of the Hyper-V Administrators group: \
add this account to that group and sign out of Windows and back in, or run the app as administrator";
pub async fn detect(
runner: &dyn ProcessRunner,
vagrant_installed: bool,
may_manage_hyperv: Option<bool>,
) -> Vec<ProviderStatus> {
let plugins = if vagrant_installed {
installed_plugins(runner).await
} else {
Vec::new()
};
let mut statuses = Vec::new();
for provider in Provider::ALL {
if !provider.applicable() {
continue;
}
let hypervisor = provider.hypervisor_installed(runner).await;
let plugin = provider.plugin().map(str::to_owned);
let plugin_installed = match &plugin {
None => true,
Some(needed) => vagrant_installed && plugins.iter().any(|i| i == needed),
};
let unresponsive = provider == Provider::Virtualbox
&& hypervisor == Some(true)
&& vbox_wedged(runner).await;
let needs_admin = provider == Provider::Hyperv
&& hypervisor == Some(true)
&& may_manage_hyperv == Some(false);
let detection = Detection {
hypervisor,
unresponsive,
plugin: plugin.as_deref(),
plugin_installed,
needs_admin,
};
let reason = unavailable_reason(provider, vagrant_installed, detection);
statuses.push(ProviderStatus {
provider,
remote: provider.is_remote(),
available: reason.is_none(),
hypervisor,
plugin,
plugin_installed,
reason,
});
}
statuses
}
async fn vbox_wedged(runner: &dyn ProcessRunner) -> bool {
let probe = exec::read(runner, "VBoxManage", &["list", "runningvms"], None);
matches!(
exec::within("VBoxManage", VBOX_PROBE, probe).await,
Err(crate::Error::Timeout { .. })
)
}
#[derive(Clone, Copy)]
struct Detection<'a> {
hypervisor: Option<bool>,
unresponsive: bool,
plugin: Option<&'a str>,
plugin_installed: bool,
needs_admin: bool,
}
fn unavailable_reason(
provider: Provider,
vagrant_installed: bool,
detection: Detection<'_>,
) -> Option<String> {
let Detection {
hypervisor,
unresponsive,
plugin,
plugin_installed,
needs_admin,
} = detection;
if !vagrant_installed {
Some("Vagrant is not installed".to_owned())
} else if unresponsive {
Some("VirtualBox isn't responding (its background service is stuck). Quit VirtualBox and any VM windows, or restart the computer, then re-check.".to_owned())
} else if hypervisor == Some(false) && provider == Provider::Hyperv {
Some("Hyper-V isn't turned on (Windows Features > Hyper-V), or this edition of Windows doesn't have it".to_owned())
} else if needs_admin {
Some(HYPERV_NEEDS_ADMIN.to_owned())
} else if hypervisor == Some(false) {
Some(provider.probe().map_or_else(
|| "not installed".to_owned(),
|(program, _)| format!("`{program}` was not found"),
))
} else if let Some(why) = (provider == Provider::Libvirt).then(kvm_problem).flatten() {
Some(why)
} else if !plugin_installed {
plugin.map(|p| format!("Vagrant plugin `{p}` is not installed"))
} else {
None
}
}
#[cfg(test)]
mod tests {
use isothrum_runner::process::fake::{FakeProcesses, Reply};
use super::*;
#[test]
fn plugin_lines_are_parsed_to_names() {
let out = "vagrant-libvirt (0.12.2, global)\nvagrant_utm (1.0.0)\nnot-a-plugin (1)\n";
assert_eq!(parse_plugins(out), ["vagrant-libvirt", "vagrant_utm"]);
}
#[test]
fn remote_and_cloud_are_classified() {
assert!(Provider::Proxmox.is_remote() && !Provider::Proxmox.is_cloud());
assert!(Provider::Aws.is_remote() && Provider::Aws.is_cloud());
assert!(!Provider::Qemu.is_remote());
}
#[tokio::test]
async fn detect_reports_a_ready_qemu_and_an_unavailable_one_by_its_plugin() {
let with = FakeProcesses::rules(&[
("qemu-system", Reply::ok("QEMU 10.0")),
(
"vagrant plugin list",
Reply::ok("vagrant-qemu (0.6.3, global)"),
),
]);
let qemu = detect(&with, true, None)
.await
.into_iter()
.find(|s| s.provider == Provider::Qemu)
.unwrap();
assert!(
qemu.hypervisor == Some(true) && qemu.plugin_installed && qemu.available,
"{qemu:?}"
);
let without = FakeProcesses::rules(&[
("qemu-system", Reply::ok("QEMU 10.0")),
("vagrant plugin list", Reply::ok("")),
]);
let no_plugin = detect(&without, true, None)
.await
.into_iter()
.find(|s| s.provider == Provider::Qemu)
.unwrap();
assert!(
!no_plugin.available && no_plugin.reason.is_some(),
"{no_plugin:?}"
);
}
#[test]
fn hyperv_needs_admin_only_when_the_caller_says_the_account_cannot_manage_it() {
let hyperv = |needs_admin| Detection {
hypervisor: Some(true),
unresponsive: false,
plugin: None,
plugin_installed: true,
needs_admin,
};
assert_eq!(
unavailable_reason(Provider::Hyperv, true, hyperv(true)).as_deref(),
Some(HYPERV_NEEDS_ADMIN)
);
assert_eq!(
unavailable_reason(Provider::Hyperv, true, hyperv(false)),
None
);
let needs = |mmh: Option<bool>| mmh == Some(false);
assert!(needs(Some(false)) && !needs(None) && !needs(Some(true)));
}
}