Skip to main content

isothrum_machine/
requirements.rs

1//! What a run needs on this computer, and what of it is missing here, with the plan that brings
2//! it.
3//!
4//! - [`Uses`]: what a run will use, in a few words: its project's format, the hypervisor a
5//!   Vagrant project runs on, the platform a Terraform module makes its machines on. Whoever
6//!   places a run can say it (an embedder from its own placement, `isothrum up` from the project
7//!   and its flags) without opening the project.
8//! - [`Requirement`]: one thing the computer must have for it, and [`Uses::requirements`], the
9//!   one table of which a run needs.
10//! - [`needs`]: each requirement asked of the machine, present or not, with the plan that brings
11//!   a missing one ([`Plan`]). Asking installs nothing.
12//! - [`Requirement::of_error`]: the requirement a run's failure says is missing (a tool not on
13//!   `PATH`, an engine that doesn't answer), so the failure can offer its plan.
14
15use std::collections::HashMap;
16use std::ffi::OsStr;
17use std::path::Path;
18
19use isothrum_runner::{Cloud, Detail, Error, Format};
20use serde::{Deserialize, Serialize};
21
22use crate::context::Context;
23use crate::install::{self, Dependency, Elevation, Refusal, Step};
24use crate::providers::{self, Provider, ProviderStatus, Unavailable};
25use crate::tools::{self, probes};
26
27#[cfg(test)]
28mod tests;
29
30/// Where VMware's OVF Tool is downloaded: Broadcom's site, behind a sign-in, so its user fetches
31/// it.
32pub const OVFTOOL_URL: &str = crate::install::OVFTOOL_PAGE.url;
33
34/// The platform a Terraform module makes its machines on.
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
36#[serde(tag = "kind", rename_all = "camelCase")]
37#[non_exhaustive]
38pub enum Target {
39    /// A public cloud, through its Terraform provider (and its CLI, for the clouds that sign in
40    /// with one).
41    Cloud {
42        /// The cloud.
43        cloud: Cloud,
44    },
45    /// A Proxmox VE server, through its API: nothing but Terraform.
46    Proxmox,
47    /// An ESXi host, its VMs uploaded with VMware's OVF Tool.
48    Esxi,
49}
50
51/// What a run will use: its project's format, the hypervisor a Vagrant project runs on, the
52/// platform a Terraform module makes its machines on.
53#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
54#[non_exhaustive]
55pub struct Uses {
56    /// The project's format.
57    pub format: Format,
58    /// The hypervisor (Vagrant's `--provider`), when the run names one.
59    pub provider: Option<Provider>,
60    /// The platform a Terraform module makes its machines on, when known.
61    pub target: Option<Target>,
62}
63
64impl Uses {
65    /// A run of a project of `format`, on nothing named yet.
66    #[must_use]
67    pub fn new(format: Format) -> Uses {
68        Uses {
69            format,
70            provider: None,
71            target: None,
72        }
73    }
74
75    /// A Vagrant project on hypervisor `provider`.
76    #[must_use]
77    pub fn vagrant(provider: Provider) -> Uses {
78        Uses::new(Format::Vagrant).on(provider)
79    }
80
81    /// A Terraform module making its machines on `target`.
82    #[must_use]
83    pub fn terraform(target: Target) -> Uses {
84        Uses::new(Format::Terraform).at(target)
85    }
86
87    /// The same, on hypervisor `provider`.
88    #[must_use]
89    pub fn on(self, provider: Provider) -> Uses {
90        Uses {
91            provider: Some(provider),
92            ..self
93        }
94    }
95
96    /// The same, making its machines on `target`.
97    #[must_use]
98    pub fn at(self, target: Target) -> Uses {
99        Uses { target: Some(target), ..self }
100    }
101
102    /// What this computer must have for the run, in the order they are put right (a tool before
103    /// what runs on it):
104    ///
105    /// - Compose: the container engine, its Compose plugin, the engine answering;
106    /// - Vagrant on hypervisor P: Vagrant, P itself (unless it runs on a server), the VMware
107    ///   Utility where P drives VMware through it (before the plugin, which breaks Vagrant for
108    ///   every provider without it), P's plugin, and VMware's OVF Tool for ESXi;
109    /// - Terraform: Terraform, and its target's: a cloud's CLI where it signs in with one, the
110    ///   OVF Tool for ESXi.
111    ///
112    /// A provider or target the format doesn't use is ignored.
113    #[must_use]
114    pub fn requirements(&self) -> Vec<Requirement> {
115        let mut needed = Vec::new();
116        match self.format {
117            Format::Compose => {
118                needed.extend([
119                    Requirement::Tool {
120                        dependency: Dependency::Docker,
121                    },
122                    Requirement::ComposePlugin,
123                    Requirement::EngineRunning,
124                ]);
125            }
126            Format::Vagrant => {
127                needed.push(Requirement::Tool {
128                    dependency: Dependency::Vagrant,
129                });
130                if let Some(provider) = self.provider {
131                    if !provider.is_remote() {
132                        needed.push(Requirement::Hypervisor { provider });
133                    }
134                    if providers::needs_vmware_utility(provider) {
135                        needed.push(Requirement::Tool {
136                            dependency: Dependency::VmwareUtility,
137                        });
138                    }
139                    if provider.plugin().is_some() {
140                        needed.push(Requirement::VagrantPlugin { provider });
141                    }
142                    if provider == Provider::VmwareEsxi {
143                        needed.push(Requirement::Ovftool);
144                    }
145                }
146            }
147            Format::Terraform => {
148                needed.push(Requirement::Tool {
149                    dependency: Dependency::Terraform,
150                });
151                match self.target {
152                    Some(Target::Cloud { cloud }) => {
153                        needed.extend(cloud_cli(cloud).map(|dependency| Requirement::Tool { dependency }));
154                    }
155                    Some(Target::Esxi) => needed.push(Requirement::Ovftool),
156                    Some(Target::Proxmox) | None => {}
157                }
158            }
159            // A format added to the runner needs nothing known here yet.
160            _ => {}
161        }
162        needed
163    }
164}
165
166/// The CLI a cloud's Terraform provider signs in with, where it uses one: the token and key
167/// clouds use none.
168#[must_use]
169pub fn cloud_cli(cloud: Cloud) -> Option<Dependency> {
170    match cloud {
171        Cloud::Aws => Some(Dependency::Awscli),
172        Cloud::Azure => Some(Dependency::Azurecli),
173        Cloud::Gcp => Some(Dependency::Gcloud),
174        _ => None,
175    }
176}
177
178/// One thing a run needs on this computer.
179#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
180#[cfg_attr(any(test, feature = "ts-rs"), derive(ts_rs::TS))]
181#[serde(tag = "kind", rename_all = "camelCase", rename_all_fields = "camelCase")]
182#[non_exhaustive]
183pub enum Requirement {
184    /// A tool a setup installs ([`Dependency`]), not a hypervisor (that is
185    /// [`Requirement::Hypervisor`]).
186    Tool {
187        /// The tool.
188        dependency: Dependency,
189    },
190    /// Docker's Compose plugin (`docker compose`), which comes with the engine's install.
191    ComposePlugin,
192    /// The container engine answering: started, not installed.
193    EngineRunning,
194    /// A hypervisor, installed and usable here as its provider's detection says.
195    Hypervisor {
196        /// Its provider.
197        provider: Provider,
198    },
199    /// The Vagrant plugin a provider runs through ([`Provider::plugin`]), at a version that
200    /// works.
201    VagrantPlugin {
202        /// The provider.
203        provider: Provider,
204    },
205    /// VMware's OVF Tool, which ESXi's VMs are uploaded with ([`crate::tools::ovftool`]).
206    Ovftool,
207}
208
209impl Requirement {
210    /// What a tool that isn't on `PATH` is, by its program's name as the runner says it
211    /// (`docker`, `VBoxManage`); none for a program no requirement installs.
212    #[must_use]
213    pub fn for_program(program: &str) -> Option<Requirement> {
214        let tool = |dependency| Some(Requirement::Tool { dependency });
215        let program = program.strip_suffix(".exe").unwrap_or(program);
216        match program {
217            "docker" => tool(Dependency::Docker),
218            "vagrant" => tool(Dependency::Vagrant),
219            "terraform" => tool(Dependency::Terraform),
220            "aws" => tool(Dependency::Awscli),
221            "az" => tool(Dependency::Azurecli),
222            "gcloud" => tool(Dependency::Gcloud),
223            "ovftool" => Some(Requirement::Ovftool),
224            "VBoxManage" => Some(Requirement::Hypervisor {
225                provider: Provider::Virtualbox,
226            }),
227            "virsh" => Some(Requirement::Hypervisor { provider: Provider::Libvirt }),
228            "qemu-img" => Some(Requirement::Hypervisor { provider: Provider::Qemu }),
229            "vmrun" => Some(Requirement::Hypervisor {
230                provider: Provider::VmwareDesktop,
231            }),
232            "prlctl" => Some(Requirement::Hypervisor { provider: Provider::Parallels }),
233            _ => None,
234        }
235    }
236
237    /// The requirement a run's failure says is missing: a tool not on `PATH`
238    /// ([`Error::ToolMissing`]), or the container engine not answering
239    /// ([`Error::ToolUnanswered`] of `docker`); none for any other failure.
240    #[must_use]
241    pub fn of_error(error: &Error) -> Option<Requirement> {
242        match error {
243            Error::ToolMissing { tool, .. } => Requirement::for_program(tool),
244            Error::ToolUnanswered { tool, .. } if tool == "docker" => Some(Requirement::EngineRunning),
245            _ => None,
246        }
247    }
248
249    /// The same, from a failure's detail as an event or a report carries it.
250    #[must_use]
251    pub fn of_detail(detail: &Detail) -> Option<Requirement> {
252        match detail {
253            Detail::ToolMissing { tool } => Requirement::for_program(tool),
254            Detail::ToolUnanswered { tool } if tool == "docker" => Some(Requirement::EngineRunning),
255            _ => None,
256        }
257    }
258}
259
260/// How a missing requirement is brought.
261#[derive(Debug)]
262#[non_exhaustive]
263pub enum Plan {
264    /// Installed by these steps ([`install::run_steps`]).
265    Install(Vec<Step>),
266    /// Started, not installed: the container engine ([`crate::docker::start_engine`]).
267    Start,
268    /// Installed, but KVM holds the CPU's virtualization ([`Unavailable::KvmHoldsVirtualization`],
269    /// VirtualBox's): KVM set to share it ([`crate::setup::share_virtualization`]).
270    ShareVirtualization,
271    /// Its user gets it from its vendor (behind a sign-in or a licence): from `page`, its vendor's
272    /// official download page, when known ([`crate::install::VendorPage::download`] says it).
273    ByHand {
274        /// Where.
275        page: Option<crate::install::VendorPage>,
276    },
277    /// No plan here, for this reason.
278    Refused(Refusal),
279    /// Brought once `requirement` is met, by its own plan then: a tool that serves a hypervisor
280    /// its user gets first ([`Dependency::serves`]: VMware's utility, before VMware); VMware's
281    /// plugin, after VMware and its utility (without the utility it breaks Vagrant for every
282    /// provider).
283    After {
284        /// What comes first.
285        requirement: Requirement,
286    },
287}
288
289impl Plan {
290    /// The plan of an install: its steps, or why there are none.
291    fn of(planned: Result<Vec<Step>, Refusal>) -> Plan {
292        planned.map_or_else(Plan::Refused, Plan::Install)
293    }
294}
295
296/// One requirement as asked of this computer.
297#[derive(Debug)]
298#[non_exhaustive]
299pub struct Need {
300    /// The requirement.
301    pub requirement: Requirement,
302    /// Whether it is met here; `None` when that can't be told (a Windows feature).
303    pub present: Option<bool>,
304    /// What brings it, when it isn't known to be met; for a hypervisor installed that KVM keeps
305    /// from running ([`Unavailable::KvmHoldsVirtualization`]), what lets it run.
306    pub plan: Option<Plan>,
307    /// For a hypervisor, why its provider can't run VMs here yet, as its detection says
308    /// ([`ProviderStatus::reason`]), whatever else it lacks: a hypervisor installed can still be
309    /// stopped, or this account lack the right to use it. None when it can, or for another
310    /// requirement.
311    pub unavailable: Option<Unavailable>,
312}
313
314impl Need {
315    /// `requirement`, `present` or not, brought by `plan`: what [`needs`] finds, made by hand
316    /// (an embedder's test).
317    #[must_use]
318    pub fn new(requirement: Requirement, present: Option<bool>, plan: Option<Plan>) -> Need {
319        Need {
320            requirement,
321            present,
322            plan,
323            unavailable: None,
324        }
325    }
326
327    /// Whether it is known to be missing.
328    #[must_use]
329    pub fn missing(&self) -> bool {
330        self.present == Some(false)
331    }
332}
333
334/// How [`needs`] asks and plans: who an install is for, how its root steps are elevated, and
335/// where the OVF Tool is looked for.
336#[derive(Debug, Clone, Copy)]
337pub struct Asking<'a> {
338    /// The account an install is for (Linux joins it to the groups a tool's devices need).
339    pub user: Option<&'a str>,
340    /// How a root step is elevated (Linux).
341    pub elevation: Elevation,
342    /// The caller's own folder of the OVF Tool ([`crate::tools::ovftool::place`]), if it keeps
343    /// one.
344    pub ovftool_dir: Option<&'a Path>,
345    /// The `PATH` the OVF Tool is looked for on.
346    pub path: Option<&'a OsStr>,
347}
348
349impl Default for Asking<'_> {
350    fn default() -> Self {
351        Asking {
352            user: None,
353            elevation: Elevation::Prompt,
354            ovftool_dir: None,
355            path: None,
356        }
357    }
358}
359
360/// Each of `requirements` asked of the context's host: present or not, and, unless it is known
361/// to be, the plan that brings it ([`install::plan`] for a tool, the hypervisor's own install or
362/// its vendor's page, the plugin's `vagrant plugin install`, the engine's start); a hypervisor
363/// installed that KVM keeps from running, KVM set to share ([`Plan::ShareVirtualization`]).
364/// Asking only reads: nothing is installed, started or changed.
365pub async fn needs(cx: &Context, requirements: &[Requirement], asking: &Asking<'_>) -> Vec<Need> {
366    let mut statuses: HashMap<Provider, Option<ProviderStatus>> = HashMap::new();
367    let mut found = Vec::new();
368    for &requirement in requirements {
369        let present = match requirement {
370            Requirement::Tool { dependency } => install::present(cx, dependency).await,
371            Requirement::ComposePlugin => Some(tools::version(cx, probes::COMPOSE).await.installed),
372            Requirement::EngineRunning => Some(crate::docker::daemon_info(cx, "{{.ServerVersion}}", None).await.is_ok()),
373            Requirement::Hypervisor { provider } => status(cx, &mut statuses, provider).await.and_then(|s| s.hypervisor),
374            Requirement::VagrantPlugin { provider } => status(cx, &mut statuses, provider).await.map(|s| s.plugin_installed),
375            Requirement::Ovftool => Some(crate::tools::ovftool::locate(cx, asking.ovftool_dir, asking.path).is_some()),
376        };
377        let first = comes_first(cx, &mut statuses, requirement).await;
378        let unavailable = match requirement {
379            Requirement::Hypervisor { provider } => status(cx, &mut statuses, provider).await.and_then(|s| s.reason.clone()),
380            _ => None,
381        };
382        let plan = if present == Some(true) {
383            (unavailable == Some(Unavailable::KvmHoldsVirtualization)).then_some(Plan::ShareVirtualization)
384        } else {
385            Some(match first {
386                Some(hypervisor) => Plan::After { requirement: hypervisor },
387                None => plan(cx, requirement, asking),
388            })
389        };
390        found.push(Need {
391            requirement,
392            present,
393            plan,
394            unavailable,
395        });
396    }
397    found
398}
399
400/// What `requirement` waits for, when it waits: a tool that serves a hypervisor not installed yet
401/// waits for it (VMware's utility, for VMware); VMware's plugin waits for VMware, then for its
402/// utility, so it is never installed without it.
403async fn comes_first(cx: &Context, statuses: &mut HashMap<Provider, Option<ProviderStatus>>, requirement: Requirement) -> Option<Requirement> {
404    let (provider, utility) = match requirement {
405        Requirement::Tool { dependency } => (dependency.serves()?, false),
406        Requirement::VagrantPlugin { provider } if providers::needs_vmware_utility(provider) => (provider, true),
407        _ => return None,
408    };
409    let status = status(cx, statuses, provider).await;
410    if status.and_then(|s| s.hypervisor) != Some(true) {
411        return Some(Requirement::Hypervisor { provider });
412    }
413    (utility && status.and_then(|s| s.utility) != Some(crate::providers::UtilityState::Running)).then_some(Requirement::Tool {
414        dependency: Dependency::VmwareUtility,
415    })
416}
417
418/// `provider`'s status, asked once.
419async fn status<'s>(cx: &Context, statuses: &'s mut HashMap<Provider, Option<ProviderStatus>>, provider: Provider) -> Option<&'s ProviderStatus> {
420    if let std::collections::hash_map::Entry::Vacant(slot) = statuses.entry(provider) {
421        slot.insert(providers::status(cx, provider).await);
422    }
423    statuses.get(&provider).and_then(Option::as_ref)
424}
425
426/// What brings `requirement` on the context's host.
427#[must_use]
428pub fn plan(cx: &Context, requirement: Requirement, asking: &Asking<'_>) -> Plan {
429    let install = |dep| Plan::of(install::plan(dep, &cx.host, asking.user, asking.elevation));
430    match requirement {
431        Requirement::Tool { dependency } => install(dependency),
432        // Docker's install brings its Compose plugin: Docker Desktop has it, Docker Engine's
433        // install adds it.
434        Requirement::ComposePlugin => install(Dependency::Docker),
435        Requirement::EngineRunning => Plan::Start,
436        Requirement::Hypervisor { provider } => match Dependency::of_hypervisor(provider) {
437            Some(dep) => install(dep),
438            None => Plan::ByHand {
439                page: providers::download_page(provider, cx.host.os),
440            },
441        },
442        Requirement::VagrantPlugin { provider } => {
443            let step = provider.plugin().and_then(install::vagrant_plugin);
444            step.map_or(Plan::ByHand { page: None }, |s| Plan::Install(vec![s]))
445        }
446        Requirement::Ovftool => Plan::ByHand {
447            page: Some(crate::install::OVFTOOL_PAGE),
448        },
449    }
450}