Skip to main content

isothrum_machine/providers/
unavailable.rs

1//! Why a provider can't run VMs here, as a code a UI says in its user's language (with the values
2//! its sentence needs), and its English sentence for logs and the command line.
3
4use serde::{Deserialize, Serialize};
5
6/// Why a provider can't run VMs here: the first layer missing (Vagrant, the hypervisor, the
7/// account's rights, the machine's virtualization, its plugin, the VMware utility), as
8/// [`detect`](super::detect) found it. Its serde form is `{"code": "pluginMissing", "args":
9/// {"plugin": "vagrant-libvirt"}}`: a UI translates the code and fills in the args.
10#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
11#[cfg_attr(any(test, feature = "ts-rs"), derive(ts_rs::TS))]
12#[serde(tag = "code", content = "args", rename_all = "camelCase", rename_all_fields = "camelCase")]
13#[non_exhaustive]
14pub enum Unavailable {
15    /// Vagrant isn't installed.
16    VagrantMissing,
17    /// VirtualBox's background service is stuck: a call to it timed out.
18    VirtualboxStuck,
19    /// Hyper-V isn't turned on, or this edition of Windows doesn't have it.
20    HypervOff,
21    /// This account may not manage Hyper-V, which Vagrant needs (an administrator or a member of
22    /// Hyper-V Administrators may).
23    HypervNeedsAdmin,
24    /// Hyper-V is turned on, but Windows' hypervisor isn't running: virtualization is off in the
25    /// firmware, or `hypervisorlaunchtype` is off (often set so VirtualBox runs faster).
26    HypervisorStopped,
27    /// QEMU is installed, but not `mkisofs` (Linux), which Vagrant builds the cloud-init seed that
28    /// gives a QEMU VM its network with: QEMU's install brings it (`genisoimage`).
29    MkisofsMissing,
30    /// libvirt or QEMU is installed, but finds no virtiofsd (Linux), which it shares a folder of
31    /// this computer with a VM through: virtiofsd is its own package (`virtiofsd`).
32    VirtiofsdMissing {
33        /// The hypervisor's name (`libvirt`, `QEMU`).
34        hypervisor: String,
35    },
36    /// The hypervisor isn't installed.
37    NotInstalled {
38        /// The program looked for, which wasn't found; `None` for a hypervisor found otherwise
39        /// (an app bundle).
40        program: Option<String>,
41    },
42    /// The user joined `group` since logging in (libvirt's, or the group `/dev/kvm` is opened
43    /// through, for QEMU): it applies from the next login.
44    NewLogin {
45        /// The group joined.
46        group: String,
47    },
48    /// This machine has no `/dev/kvm`: virtualization is off in the firmware, or there is none.
49    NoKvm,
50    /// `/dev/kvm` exists, but this account may not open it: it isn't in `group`, the one
51    /// `/dev/kvm` belongs to (`kvm` on Debian, Ubuntu, Kali and openSUSE, whose `/dev/kvm` is
52    /// `0660`; Fedora's and Arch's is `0666`, open to everyone).
53    KvmDenied {
54        /// The group `/dev/kvm` belongs to.
55        group: String,
56    },
57    /// `/dev/kvm` exists and this account may open it, but opening it failed otherwise (the
58    /// device busy, no KVM behind it).
59    KvmUnusable {
60        /// What the OS said.
61        error: String,
62    },
63    /// The hypervisor is older than its Vagrant plugin drives.
64    HypervisorTooOld {
65        /// The hypervisor's name.
66        name: String,
67        /// The version installed.
68        version: String,
69        /// The oldest version the plugin drives.
70        min: String,
71    },
72    /// The Vagrant plugin is older than the one that works: installing it again updates it.
73    PluginTooOld {
74        /// The plugin's name.
75        plugin: String,
76        /// The version installed.
77        version: String,
78        /// The oldest version that works.
79        min: String,
80    },
81    /// The provider's Vagrant plugin isn't installed.
82    PluginMissing {
83        /// The plugin's name.
84        plugin: String,
85    },
86    /// Whether the provider's Vagrant plugin is installed can't be told: `vagrant plugin list`
87    /// failed (not read as "not installed": the user would be told to install a plugin that may
88    /// be there).
89    PluginsUnknown {
90        /// The plugin's name.
91        plugin: String,
92        /// What `vagrant plugin list` said.
93        reason: String,
94    },
95    /// The Vagrant VMware Utility is installed, but its service doesn't answer.
96    VmwareUtilityStopped,
97    /// Vagrant's VMware plugin (`vagrant-vmware-desktop`) is installed without the Vagrant VMware
98    /// Utility, whose key file it loads at every Vagrant command: Vagrant fails for every provider
99    /// (`vagrant status` on QEMU said "error while attempting to load the utility service key
100    /// file"). The fix: install the utility, or remove the plugin.
101    VmwarePluginWithoutUtility,
102    /// The Vagrant VMware Utility, HashiCorp's service the VMware plugin drives VMware through,
103    /// isn't installed.
104    VmwareUtilityMissing,
105    /// VirtualBox is installed, but its kernel driver (`vboxdrv`) isn't loaded on the running
106    /// kernel (Linux), so no VM starts: never built (the kernel's headers missing), or refused
107    /// (Secure Boot).
108    VirtualboxDriver {
109        /// The running kernel (`uname -r`).
110        kernel: String,
111    },
112    /// VirtualBox's kernel driver waits for a restart (Linux): the running kernel has no headers,
113    /// and a newer kernel installed with its headers has, which the driver is built for when the
114    /// computer starts it.
115    KernelRestart {
116        /// The newer kernel installed (`uname -r` once it runs).
117        kernel: String,
118    },
119    /// KVM holds the CPU's virtualization extensions (Linux): its module (`kvm_intel`, `kvm_amd`)
120    /// turns them on as it loads (`kvm.enable_virt_at_load`, the default since Linux 6.12), so no
121    /// VirtualBox VM starts ("VT-x is being used by another hypervisor"), installed or not. A
122    /// setup lets them share it ([`crate::setup::Action::ShareVirtualization`]).
123    KvmHoldsVirtualization,
124    /// KVM still holds the CPU's virtualization extensions, but is set to share them from the
125    /// next time its module loads (`options kvm enable_virt_at_load=0`): it was in use (a VM of
126    /// its own running) or couldn't be loaded again, so the setting applies once the computer
127    /// restarts.
128    KvmSharesAfterRestart,
129}
130
131impl Unavailable {
132    /// The English sentence, for logs and the command line; a UI says the code in its own words.
133    #[must_use]
134    pub fn message(&self) -> String {
135        match self {
136            Unavailable::VagrantMissing => "Vagrant is not installed.".to_owned(),
137            Unavailable::VirtualboxStuck => {
138                "VirtualBox isn't responding (its background service is stuck): quit VirtualBox and any VM windows, or restart the computer.".to_owned()
139            }
140            Unavailable::HypervOff => "Hyper-V isn't turned on (Windows Features > Hyper-V), or this edition of Windows doesn't have it.".to_owned(),
141            Unavailable::HypervNeedsAdmin => "Vagrant drives Hyper-V only for an administrator or a member of the Hyper-V Administrators group: \
142                add this account to that group and sign out of Windows and back in, or run elevated."
143                .to_owned(),
144            Unavailable::HypervisorStopped => "Hyper-V is turned on but Windows' hypervisor isn't running: turn virtualization on in the firmware, \
145                or run `bcdedit /set hypervisorlaunchtype auto` as an administrator, then restart Windows."
146                .to_owned(),
147            Unavailable::MkisofsMissing => "QEMU VMs need mkisofs, which isn't installed: Vagrant builds with it the disk that gives each VM its network. \
148                Install QEMU again (that adds it), or install genisoimage."
149                .to_owned(),
150            Unavailable::VirtiofsdMissing { hypervisor } => {
151                format!("{hypervisor} needs virtiofsd to share a folder of this computer with a VM, and finds none: install the virtiofsd package.")
152            }
153            Unavailable::NotInstalled { program: Some(program) } => format!("`{program}` was not found."),
154            Unavailable::NotInstalled { program: None } => "Not installed.".to_owned(),
155            Unavailable::NewLogin { group } => {
156                format!("You were added to the {group} group since you logged in: log out and back in (or restart) for it to apply.")
157            }
158            Unavailable::NoKvm => {
159                "KVM isn't available on this machine (no /dev/kvm): turn on virtualization in the firmware, or use another hypervisor.".to_owned()
160            }
161            Unavailable::KvmDenied { group } => format!("You can't use /dev/kvm yet: add yourself to the {group} group, then sign out and back in."),
162            Unavailable::KvmUnusable { error } => format!("/dev/kvm can't be opened: {error}."),
163            Unavailable::HypervisorTooOld { name, version, min } => format!("{name} {version} is too old: {min} or later is needed. Update {name}."),
164            Unavailable::PluginTooOld { plugin, version, min } => {
165                format!("Vagrant plugin `{plugin}` {version} is too old: {min} or later is needed. Install it again to update it.")
166            }
167            Unavailable::PluginMissing { plugin } => format!("Vagrant plugin `{plugin}` is not installed."),
168            Unavailable::PluginsUnknown { plugin, reason } => {
169                format!("Whether Vagrant plugin `{plugin}` is installed can't be told: `vagrant plugin list` failed ({reason}).")
170            }
171            Unavailable::VmwareUtilityStopped => {
172                "The Vagrant VMware Utility is installed, but its service isn't running: install it again (that restarts it), or restart the computer."
173                    .to_owned()
174            }
175            Unavailable::VmwarePluginWithoutUtility => {
176                "Vagrant's VMware plugin (vagrant-vmware-desktop) is installed without the Vagrant VMware Utility, which breaks Vagrant for every provider. \
177                Install the Vagrant VMware Utility, or remove the plugin (`vagrant plugin uninstall vagrant-vmware-desktop`)."
178                    .to_owned()
179            }
180            Unavailable::VmwareUtilityMissing => {
181                "The Vagrant VMware Utility is not installed: HashiCorp's service the VMware plugin drives VMware through.".to_owned()
182            }
183            Unavailable::VirtualboxDriver { kernel } => format!(
184                "VirtualBox's kernel driver (vboxdrv) isn't loaded on this kernel ({kernel}), so VirtualBox can't start VMs. \
185                Install the kernel's headers (linux-headers-{kernel} on Debian and Ubuntu), then build the driver \
186                (`sudo /sbin/vboxconfig` for Oracle's VirtualBox, `sudo dpkg-reconfigure virtualbox-dkms` for the distribution's). \
187                With Secure Boot on, the driver must be signed before it loads."
188            ),
189            Unavailable::KernelRestart { kernel } => {
190                format!("VirtualBox's kernel driver is built for the newer kernel installed with it ({kernel}): restart the computer to start that kernel.")
191            }
192            Unavailable::KvmHoldsVirtualization | Unavailable::KvmSharesAfterRestart => kvm_message(self).to_owned(),
193        }
194    }
195}
196
197/// The sentence of a reason about KVM holding the CPU's virtualization.
198fn kvm_message(reason: &Unavailable) -> &'static str {
199    if *reason == Unavailable::KvmSharesAfterRestart {
200        "KVM is set to share this computer's hardware virtualization with VirtualBox, from the next time its module loads: \
201        restart the computer for it to apply."
202    } else {
203        "KVM holds this computer's hardware virtualization (VT-x or AMD-V): Linux turns it on as soon as KVM's module loads \
204        (the default since Linux 6.12), so VirtualBox can't start VMs (\"VT-x is being used by another hypervisor\"). \
205        Use libvirt or QEMU, which run on KVM, or let KVM share it (`options kvm enable_virt_at_load=0` in /etc/modprobe.d): \
206        KVM then takes it only while one of its own VMs runs."
207    }
208}
209
210impl std::fmt::Display for Unavailable {
211    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
212        f.write_str(&self.message())
213    }
214}
215
216#[cfg(test)]
217mod tests {
218    use super::*;
219
220    /// Every code, with sample values.
221    fn samples() -> Vec<Unavailable> {
222        let s = String::from;
223        vec![
224            Unavailable::VagrantMissing,
225            Unavailable::VirtualboxStuck,
226            Unavailable::HypervOff,
227            Unavailable::HypervNeedsAdmin,
228            Unavailable::HypervisorStopped,
229            Unavailable::MkisofsMissing,
230            Unavailable::VirtiofsdMissing { hypervisor: s("QEMU") },
231            Unavailable::NotInstalled { program: Some(s("virsh")) },
232            Unavailable::NotInstalled { program: None },
233            Unavailable::NewLogin { group: s("libvirt") },
234            Unavailable::NoKvm,
235            Unavailable::KvmDenied { group: s("kvm") },
236            Unavailable::KvmUnusable {
237                error: s("Device or resource busy"),
238            },
239            Unavailable::HypervisorTooOld {
240                name: s("UTM"),
241                version: s("4.4.5"),
242                min: s("4.6.5"),
243            },
244            Unavailable::PluginTooOld {
245                plugin: s("vagrant_utm"),
246                version: s("0.1.0"),
247                min: s("0.2.0"),
248            },
249            Unavailable::PluginMissing { plugin: s("vagrant-libvirt") },
250            Unavailable::PluginsUnknown {
251                plugin: s("vagrant-libvirt"),
252                reason: s("exited with code 1"),
253            },
254            Unavailable::VmwareUtilityStopped,
255            Unavailable::VmwarePluginWithoutUtility,
256            Unavailable::VmwareUtilityMissing,
257            Unavailable::VirtualboxDriver {
258                kernel: s("6.12.86+deb13-amd64"),
259            },
260            Unavailable::KernelRestart {
261                kernel: s("6.12.116+deb13-amd64"),
262            },
263            Unavailable::KvmHoldsVirtualization,
264            Unavailable::KvmSharesAfterRestart,
265        ]
266    }
267
268    /// The wire form a UI translates: the code in camelCase, the args by name, a code without
269    /// args without them; and it reads back as it was.
270    #[test]
271    fn a_reason_is_a_code_with_its_args() {
272        assert_eq!(
273            serde_json::to_value(Unavailable::PluginMissing {
274                plugin: "vagrant-libvirt".into()
275            })
276            .unwrap(),
277            serde_json::json!({ "code": "pluginMissing", "args": { "plugin": "vagrant-libvirt" } })
278        );
279        assert_eq!(
280            serde_json::to_value(Unavailable::NotInstalled { program: None }).unwrap(),
281            serde_json::json!({ "code": "notInstalled", "args": { "program": null } })
282        );
283        assert_eq!(
284            serde_json::to_value(Unavailable::HypervisorStopped).unwrap(),
285            serde_json::json!({ "code": "hypervisorStopped" })
286        );
287        assert_eq!(
288            serde_json::to_value(Unavailable::KvmHoldsVirtualization).unwrap(),
289            serde_json::json!({ "code": "kvmHoldsVirtualization" })
290        );
291        for reason in samples() {
292            let wire = serde_json::to_value(&reason).unwrap();
293            assert_eq!(serde_json::from_value::<Unavailable>(wire.clone()).unwrap(), reason, "{wire}");
294        }
295    }
296
297    /// Each sentence is one sentence that names every value it was given, and speaks to no
298    /// particular program (no app name, no "re-check").
299    #[test]
300    fn every_reason_says_its_values_in_a_sentence_of_its_own() {
301        for reason in samples() {
302            let said = reason.message();
303            assert!(said.ends_with('.'), "{said}");
304            assert!(!said.contains("re-check") && !said.contains("Cyber CTF"), "{said}");
305            assert_eq!(reason.to_string(), said);
306            let wire = serde_json::to_value(&reason).unwrap();
307            for value in wire.get("args").and_then(|a| a.as_object()).into_iter().flat_map(|a| a.values()) {
308                if let Some(value) = value.as_str() {
309                    assert!(said.contains(value), "{said} doesn't say {value}");
310                }
311            }
312        }
313    }
314}