Skip to main content

isothrum_machine/providers/
needs.rs

1//! What Vagrant needs on this machine to drive a provider, beyond the hypervisor itself: Vagrant,
2//! the provider's plugin, and for VMware's desktop hypervisors HashiCorp's Vagrant VMware Utility
3//! (a system service of its own). [`needs`] is the one list readiness ([`super::detect`]) and a
4//! setup's steps both read.
5
6use std::time::Duration;
7
8use serde::{Deserialize, Serialize};
9
10use crate::host::{Host, HostOs};
11
12/// What is still missing on this machine for Vagrant to drive a provider, in the order a setup
13/// installs it. The one rule both sides read: a provider is ready only when this list is empty
14/// (and its hypervisor runs), and a setup offers an install for each entry, so finishing it can't
15/// leave the provider short of something no step installs. Exhaustive for that: a setup that
16/// matches on it fails to compile until a new one has its step.
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
18#[cfg_attr(any(test, feature = "ts-rs"), derive(ts_rs::TS))]
19#[serde(rename_all = "camelCase")]
20pub enum Need {
21    /// Vagrant itself.
22    Vagrant,
23    /// HashiCorp's Vagrant VMware Utility, installed and its service running: before the VMware
24    /// plugin, which breaks Vagrant for every provider without it
25    /// ([`super::Unavailable::VmwarePluginWithoutUtility`]).
26    VmwareUtility,
27    /// The provider's Vagrant plugin ([`super::ProviderStatus::plugin`]), or a newer one.
28    Plugin,
29}
30
31/// Where HashiCorp's Vagrant VMware Utility stands on this machine.
32#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
33#[cfg_attr(any(test, feature = "ts-rs"), derive(ts_rs::TS))]
34#[serde(rename_all = "camelCase")]
35pub enum UtilityState {
36    /// Not installed.
37    Missing,
38    /// Installed, but its service doesn't answer.
39    Stopped,
40    /// Installed, its service answering: what the plugin needs.
41    Running,
42}
43
44/// What is missing for Vagrant to drive a provider here, from whether Vagrant is installed, its
45/// plugin is (true when it needs none), and where the VMware Utility stands (`None` when it needs
46/// none). See [`Need`].
47#[must_use]
48pub fn needs(vagrant_installed: bool, plugin_installed: bool, utility: Option<UtilityState>) -> Vec<Need> {
49    let mut needs = Vec::new();
50    if !vagrant_installed {
51        needs.push(Need::Vagrant);
52    }
53    if utility.is_some_and(|u| u != UtilityState::Running) {
54        needs.push(Need::VmwareUtility);
55    }
56    if !plugin_installed {
57        needs.push(Need::Plugin);
58    }
59    needs
60}
61
62/// How long the VMware Utility's service gets to accept a connection.
63const UTILITY_WAIT: Duration = Duration::from_secs(2);
64
65/// Where the Vagrant VMware Utility stands on `host`: running when its service accepts a
66/// connection ([`crate::Devices::vmware_utility_service`], what the plugin talks to, whatever
67/// installed it), else installed or not by its marker ([`crate::Devices::vmware_utility`]).
68///
69/// On Linux it is missing, too, while no `netstat` is on `PATH` ([`crate::Devices::netstat`]):
70/// vagrant-vmware-desktop reads the routing table with it before it makes any private network,
71/// and stops with "The external program used to read TCP/IP routing tables ... could not be
72/// found" without one (Debian 13 and recent Ubuntu and Fedora ship no `net-tools`). The utility's
73/// install brings it ([`crate::install::linux::scripts::vmware_utility_script`]), so a setup that
74/// installs the utility again is what gives VMware what it needs here.
75pub async fn vmware_utility(host: &Host) -> UtilityState {
76    if host.os == HostOs::Linux && !host.devices.netstat.iter().any(|p| p.is_file()) {
77        return UtilityState::Missing;
78    }
79    let answers = tokio::time::timeout(UTILITY_WAIT, tokio::net::TcpStream::connect(host.devices.vmware_utility_service)).await;
80    if matches!(answers, Ok(Ok(_))) {
81        UtilityState::Running
82    } else if host.devices.vmware_utility.exists() {
83        UtilityState::Stopped
84    } else {
85        UtilityState::Missing
86    }
87}
88
89#[cfg(test)]
90mod tests {
91    use super::*;
92
93    /// A Linux host whose devices are under `root`.
94    fn host(root: &std::path::Path) -> Host {
95        crate::testing::linux_host(root)
96    }
97
98    #[test]
99    fn what_is_needed_is_in_setups_order_and_nothing_when_all_is_there() {
100        assert_eq!(
101            needs(false, false, Some(UtilityState::Missing)),
102            [Need::Vagrant, Need::VmwareUtility, Need::Plugin]
103        );
104        assert_eq!(needs(true, true, Some(UtilityState::Stopped)), [Need::VmwareUtility]);
105        assert_eq!(needs(true, true, Some(UtilityState::Running)), []);
106        assert_eq!(needs(true, true, None), []);
107        assert_eq!(serde_json::to_value(Need::VmwareUtility).unwrap(), "vmwareUtility");
108        assert_eq!(serde_json::to_value(UtilityState::Stopped).unwrap(), "stopped");
109    }
110
111    #[tokio::test]
112    async fn the_utility_runs_when_its_service_answers_else_its_marker_says_whether_it_is_installed() {
113        let dir = tempfile::tempdir().unwrap();
114        let mut host = host(dir.path());
115        given_netstat(&host);
116        assert_eq!(vmware_utility(&host).await, UtilityState::Missing);
117        let marker = &host.devices.vmware_utility;
118        std::fs::create_dir_all(marker.parent().unwrap()).unwrap();
119        std::fs::write(marker, "").unwrap();
120        assert_eq!(vmware_utility(&host).await, UtilityState::Stopped);
121        let service = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
122        host.devices.vmware_utility_service = service.local_addr().unwrap();
123        assert_eq!(vmware_utility(&host).await, UtilityState::Running);
124        std::fs::remove_file(&host.devices.vmware_utility).unwrap();
125        assert_eq!(vmware_utility(&host).await, UtilityState::Running, "installed otherwise: it answers");
126    }
127
128    /// A `netstat` where the host looks for one: what vagrant-vmware-desktop needs on Linux.
129    fn given_netstat(host: &Host) {
130        let netstat = &host.devices.netstat[0];
131        std::fs::create_dir_all(netstat.parent().unwrap()).unwrap();
132        std::fs::write(netstat, "").unwrap();
133    }
134
135    #[tokio::test]
136    async fn on_linux_the_utility_is_missing_while_no_netstat_is_there_for_the_plugin() {
137        // vagrant-vmware-desktop stopped at its first private network on a Debian 13 without
138        // net-tools: "The external program used to read TCP/IP routing tables ... could not be
139        // found". Its service running doesn't make VMware ready there.
140        let dir = tempfile::tempdir().unwrap();
141        let mut host = host(dir.path());
142        let marker = &host.devices.vmware_utility;
143        std::fs::create_dir_all(marker.parent().unwrap()).unwrap();
144        std::fs::write(marker, "").unwrap();
145        let service = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
146        host.devices.vmware_utility_service = service.local_addr().unwrap();
147        assert_eq!(vmware_utility(&host).await, UtilityState::Missing, "no netstat");
148        given_netstat(&host);
149        assert_eq!(vmware_utility(&host).await, UtilityState::Running);
150        let mut mac = host.clone();
151        mac.os = HostOs::Macos;
152        std::fs::remove_file(&host.devices.netstat[0]).unwrap();
153        assert_eq!(vmware_utility(&mac).await, UtilityState::Running, "Linux's need alone");
154    }
155}