Skip to main content

isothrum_machine/
setup.rs

1//! A guided setup of this computer: what to install, start or restart, in which order, for the
2//! kinds of project wanted (containers, VMs), with which engine and which hypervisor. The one
3//! place these rules live:
4//! - [`options`] works out, from what the machine check found ([`Machine`]), what each choice a
5//!   setup offers takes here: a UI renders those actions and runs each, never working them out
6//!   itself;
7//! - [`plan()`] puts them in order for a whole setup, from what is [`Wanted`];
8//! - [`walk()`] runs that plan step by step through the caller's own runner of each step, the
9//!   machine checked again after each (an install changes what comes next);
10//! - on Windows, [`join_hyperv_admins`] and [`schedule_restart`] carry out what a setup asks
11//!   beyond installs, as [`crate::docker::start_engine`] starts an engine; on Linux,
12//!   [`share_virtualization`] lets VirtualBox share the CPU's virtualization with KVM.
13//!
14//! Why something is passed over or left alone is a code ([`PassedOver`], [`LeftAlone`]) a UI says
15//! in its own words.
16
17mod kvm;
18mod plan;
19mod walk;
20mod windows;
21
22pub use kvm::{OPTION, OPTION_FILE, ShareFailed, Shared, share_script, share_step, share_virtualization, sharing};
23pub use plan::{LeftAlone, PassedOver, Plan, SetupPath, Step, Wanted, left_alone, plan};
24pub use walk::{Event, OnFailure, Steps, Walked, walk};
25pub use windows::{RESTART_NOTE_MAX, Restart, RestartFailed, join_hyperv_admins, join_hyperv_admins_step, schedule_restart};
26
27use serde::{Deserialize, Serialize};
28
29use crate::check::Check;
30use crate::docker::{self, Engine};
31use crate::host::{Host, HostOs};
32use crate::install::{Dependency, Elevation, Interaction};
33use crate::providers::{self, Need, Provider, ProviderStatus, Unavailable};
34use crate::wsl::WslState;
35
36/// One thing a setup does, or leaves to its user, on this computer.
37#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
38#[cfg_attr(any(test, feature = "ts-rs"), derive(ts_rs::TS), ts(rename = "SetupAction"))]
39#[serde(tag = "kind", rename_all = "camelCase")]
40pub enum Action {
41    /// Installs `dependency` ([`crate::install`]): the container engine, WSL 2, Vagrant, a
42    /// hypervisor, the Vagrant VMware Utility.
43    Install {
44        /// The tool to install.
45        dependency: Dependency,
46        /// What its install asks of the person at the computer ([`crate::install::interactions`]),
47        /// for a UI to say before it runs.
48        interactions: Vec<Interaction>,
49    },
50    /// Installs the Vagrant plugin `plugin` ([`crate::install::vagrant_plugin`]).
51    Plugin {
52        /// The plugin's name (`vagrant-qemu`, …).
53        plugin: String,
54    },
55    /// Starts the installed engine `engine`.
56    StartEngine {
57        /// The engine to start.
58        engine: Engine,
59    },
60    /// Points Docker at `engine`, which runs already ([`docker::use_engine`]).
61    UseEngine {
62        /// The engine Docker is to use.
63        engine: Engine,
64    },
65    /// Restarts the computer, which finishes turning `feature` on.
66    Restart {
67        /// The feature the restart starts.
68        feature: WindowsFeature,
69    },
70    /// Lets VirtualBox share the CPU's virtualization with KVM (Linux), which holds it as soon as
71    /// its module loads ([`Unavailable::KvmHoldsVirtualization`]): KVM set to take it only while
72    /// one of its own VMs runs ([`share_virtualization`]), as root. It applies at once when
73    /// nothing uses KVM, else from the next restart ([`Unavailable::KvmSharesAfterRestart`]).
74    ShareVirtualization {
75        /// What it asks of the person at the computer: the password prompt of its root step.
76        interactions: Vec<Interaction>,
77    },
78    /// Signs out and back in: a group the account was added to (Linux's `docker`, `libvirt` and
79    /// `kvm`, the libvirt and QEMU installs' too) applies from the next login.
80    Relogin,
81    /// Not something a setup does here: its user gets it (`dependency`, when it is one a setup
82    /// installs elsewhere; from `url`, when there is one), then checks the machine again.
83    Manual {
84        /// What it asks of them: a vendor's download by hand ([`Interaction::DownloadByHand`]),
85        /// for a UI to link to.
86        interactions: Vec<Interaction>,
87        /// Why it is the user's to get.
88        reason: ManualReason,
89        /// The tool, when it is one a setup installs elsewhere.
90        dependency: Option<Dependency>,
91        /// Where to get it, when there is a page for it.
92        url: Option<String>,
93    },
94    /// Installed, but it can't run here, and nothing a setup installs mends that: `reason`.
95    Blocked {
96        /// Why it can't run here, as a code a UI says in its own words.
97        reason: Unavailable,
98    },
99}
100
101impl Action {
102    /// Whether it ends a setup pass: what follows waits for the restart or the new login. A
103    /// hypervisor blocked until the computer restarts (VirtualBox's driver, built for the newer
104    /// kernel its install brought; KVM set to share the CPU's virtualization from its next load)
105    /// ends it too, as a restart.
106    #[must_use]
107    pub fn ends_pass(&self) -> bool {
108        matches!(
109            self,
110            Action::Restart { .. }
111                | Action::Relogin
112                | Action::Blocked {
113                    reason: Unavailable::KernelRestart { .. } | Unavailable::KvmSharesAfterRestart
114                }
115        )
116    }
117
118    /// Its kind, as an event and a log's name say it.
119    #[must_use]
120    pub fn kind(&self) -> &'static str {
121        match self {
122            Action::Install { .. } => "install",
123            Action::Plugin { .. } => "plugin",
124            Action::StartEngine { .. } => "start",
125            Action::UseEngine { .. } => "use",
126            Action::ShareVirtualization { .. } => "share",
127            Action::Restart { .. } => "restart",
128            Action::Relogin => "relogin",
129            Action::Manual { .. } => "manual",
130            Action::Blocked { .. } => "blocked",
131        }
132    }
133
134    /// What it asks of the person at the computer, in order: an install's or KVM's sharing's (a
135    /// password prompt, a licence, a setting to allow), a restart's or a new login's itself.
136    /// Empty when it asks nothing.
137    #[must_use]
138    pub fn interactions(&self) -> Vec<Interaction> {
139        match self {
140            Action::Install { interactions, .. } | Action::ShareVirtualization { interactions } | Action::Manual { interactions, .. } => interactions.clone(),
141            Action::Restart { .. } => vec![Interaction::Restart],
142            Action::Relogin => vec![Interaction::Relogin],
143            Action::Plugin { .. } | Action::StartEngine { .. } | Action::UseEngine { .. } | Action::Blocked { .. } => Vec::new(),
144        }
145    }
146}
147
148/// A Windows feature that starts only after a restart.
149#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
150#[cfg_attr(any(test, feature = "ts-rs"), derive(ts_rs::TS))]
151#[serde(rename_all = "camelCase")]
152pub enum WindowsFeature {
153    /// WSL 2: the Virtual Machine Platform and the Windows Subsystem for Linux.
154    Wsl,
155    /// Hyper-V.
156    Hyperv,
157}
158
159/// Why something is the user's to get.
160#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
161#[cfg_attr(any(test, feature = "ts-rs"), derive(ts_rs::TS))]
162#[serde(rename_all = "camelCase")]
163pub enum ManualReason {
164    /// From its vendor (behind a login or a licence): a UI links out.
165    Vendor,
166    /// A setup doesn't install on this Linux distribution yet (it installs through apt or dnf).
167    Distribution,
168}
169
170/// What each choice of a setup takes on this computer.
171#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
172#[cfg_attr(any(test, feature = "ts-rs"), derive(ts_rs::TS), ts(rename = "SetupOptions"))]
173#[serde(rename_all = "camelCase")]
174pub struct Options {
175    /// What turns WSL 2 on (Windows): nothing once it is ready, or elsewhere.
176    pub wsl: Vec<Action>,
177    /// The engine a setup installs in one click on this OS.
178    pub recommended_engine: Engine,
179    /// The engine a setup works on until its user picks one: the one in use, else the
180    /// recommended one.
181    pub engine: Engine,
182    /// The engines offered on this OS, in the order shown, each with what makes it the one Docker
183    /// uses here (nothing: it is).
184    pub engines: Vec<EngineOption>,
185    /// The hypervisor a setup works on until its user picks one: an installed one that can run
186    /// VMs, else an installed one, else the first a setup installs, else the first.
187    pub hypervisor: Option<Provider>,
188    /// The local hypervisors offered here, in the machine check's order.
189    pub hypervisors: Vec<HypervisorOption>,
190}
191
192impl Options {
193    /// None yet: what a report holds until its options are worked out.
194    #[must_use]
195    pub fn empty() -> Options {
196        Options {
197            wsl: Vec::new(),
198            recommended_engine: Engine::Native,
199            engine: Engine::Native,
200            engines: Vec::new(),
201            hypervisor: None,
202            hypervisors: Vec::new(),
203        }
204    }
205}
206
207/// A container engine, and what makes it the one Docker uses here.
208#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
209#[cfg_attr(any(test, feature = "ts-rs"), derive(ts_rs::TS))]
210#[serde(rename_all = "camelCase")]
211pub struct EngineOption {
212    /// Which engine it is (Docker Desktop, Colima, the Linux daemon…).
213    pub engine: Engine,
214    /// What makes it the one Docker uses here, in order: nothing when it is.
215    pub actions: Vec<Action>,
216}
217
218/// A local hypervisor: what gets it here (`get`: nothing once it is installed and can run), then
219/// what Vagrant needs to drive it (`vagrant`: Vagrant, its plugin, VMware's utility, in order).
220#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
221#[cfg_attr(any(test, feature = "ts-rs"), derive(ts_rs::TS))]
222#[serde(rename_all = "camelCase")]
223pub struct HypervisorOption {
224    /// Which hypervisor, as the Vagrant provider that drives it.
225    pub provider: Provider,
226    /// What installs it or turns it on, in order: nothing when it is ready.
227    pub get: Vec<Action>,
228    /// What Vagrant needs to drive it: Vagrant, its plugin, VMware's utility, in order.
229    pub vagrant: Vec<Action>,
230}
231
232/// What a setup reads of the machine check ([`Check`]): the computer, its package manager, Docker
233/// and its engines, WSL 2, the Vagrant providers and the groups pending a login.
234#[derive(Clone, Debug, PartialEq, Eq)]
235pub struct Machine {
236    /// The computer ([`providers::login_groups`] reads which group opens `/dev/kvm` on it).
237    pub host: Host,
238    /// Whether the package manager a setup installs through is there.
239    pub packages_installed: bool,
240    /// Docker and its engines.
241    pub docker: DockerFound,
242    /// WSL 2's state (Windows), when it was checked.
243    pub wsl: Option<WslState>,
244    /// Every Vagrant provider offered here.
245    pub providers: Vec<ProviderStatus>,
246    /// The groups this account joined since logging in (Linux).
247    pub groups_pending: Vec<String>,
248    /// How a setup's administrator steps are elevated here: whether they raise a password prompt.
249    pub elevation: Elevation,
250    /// The account a setup installs for (Linux joins it to a tool's groups).
251    pub user: Option<String>,
252}
253
254/// Docker and its engines, as the machine check found them.
255#[derive(Clone, Debug, Default, PartialEq, Eq)]
256pub struct DockerFound {
257    /// Whether the Docker CLI is installed.
258    pub installed: bool,
259    /// Whether the daemon the Docker CLI uses answers this account.
260    pub running: bool,
261    /// Whether that daemon runs but refused this account.
262    pub denied: bool,
263    /// The engine behind that daemon, when it answered.
264    pub engine: Option<Engine>,
265    /// The engines found running.
266    pub engines_running: Vec<Engine>,
267}
268
269impl DockerFound {
270    /// Whether Docker answers: its CLI is installed and its daemon runs for this account.
271    #[must_use]
272    pub fn ready(&self) -> bool {
273        self.installed && self.running
274    }
275}
276
277impl Machine {
278    /// What `check` found on `host`, a setup's administrator steps elevated `elevation`'s way
279    /// for the account `user`.
280    #[must_use]
281    pub fn of(check: &Check, host: Host, elevation: Elevation, user: Option<String>) -> Machine {
282        Machine {
283            host,
284            packages_installed: check.packages.installed,
285            docker: DockerFound {
286                installed: check.docker.installed,
287                running: check.daemon.running(),
288                denied: check.daemon.denied(),
289                engine: check.daemon.engine,
290                engines_running: docker::running_of(&check.engines),
291            },
292            wsl: check.wsl.as_ref().map(|w| w.state),
293            providers: check.providers.clone(),
294            groups_pending: check.groups_pending.clone(),
295            elevation,
296            user,
297        }
298    }
299
300    /// Its local hypervisors.
301    fn local(&self) -> impl Iterator<Item = &ProviderStatus> {
302        self.providers.iter().filter(|p| !p.remote)
303    }
304}
305
306/// The engines a setup offers on `os`, in the order it shows them.
307#[must_use]
308pub fn engines_on(os: HostOs) -> &'static [Engine] {
309    match os {
310        HostOs::Macos => &[Engine::DockerDesktop, Engine::Orbstack, Engine::Colima],
311        HostOs::Windows => &[Engine::DockerDesktop],
312        HostOs::Linux => &[Engine::DockerDesktop, Engine::Native, Engine::Colima],
313    }
314}
315
316/// The engine a setup installs in one click on `os`: Docker Desktop on macOS and Windows, Docker
317/// Engine on Linux.
318#[must_use]
319pub fn recommended_engine(os: HostOs) -> Engine {
320    match os {
321        HostOs::Macos | HostOs::Windows => Engine::DockerDesktop,
322        HostOs::Linux => Engine::Native,
323    }
324}
325
326/// The hypervisor a setup installs as `provider` on `os`, when it installs it.
327#[must_use]
328pub fn installable(provider: Provider, os: HostOs) -> Option<Dependency> {
329    Dependency::of_hypervisor(provider).filter(|d| d.runs_on(os))
330}
331
332/// An installed hypervisor that still can't run VMs once everything Vagrant needs is in (no
333/// `/dev/kvm`, not in the kvm group, a stuck service): its `reason` says why.
334#[must_use]
335pub fn cant_run(p: &ProviderStatus) -> bool {
336    p.hypervisor == Some(true) && !p.available && p.reason.is_some() && p.needs.is_empty()
337}
338
339/// Installing `dependency` here: its install, or on a Linux distribution without a package
340/// manager a setup installs through, its user's to do.
341fn install(m: &Machine, dependency: Dependency) -> Action {
342    if m.host.os == HostOs::Linux && !m.packages_installed {
343        return Action::Manual {
344            interactions: Vec::new(),
345            reason: ManualReason::Distribution,
346            dependency: Some(dependency),
347            url: dependency.row().own_url.map(str::to_owned),
348        };
349    }
350    Action::Install {
351        dependency,
352        interactions: crate::install::interactions(dependency, &m.host, m.elevation, m.user.as_deref()),
353    }
354}
355
356/// What turns WSL 2 on: nothing off Windows, once it is ready, or once a Docker engine runs (proof
357/// enough, whatever the check could tell); the restart once it waits for one; else its install
358/// (also when the check couldn't tell).
359fn wsl(m: &Machine) -> Vec<Action> {
360    if m.host.os != HostOs::Windows || m.docker.ready() {
361        return Vec::new();
362    }
363    match m.wsl.unwrap_or(WslState::Unknown) {
364        WslState::Ready => Vec::new(),
365        WslState::NeedsReboot => vec![Action::Restart { feature: WindowsFeature::Wsl }],
366        WslState::Missing | WslState::Unknown => vec![install(m, Dependency::Wsl)],
367    }
368}
369
370/// What makes `engine` the one Docker uses: nothing when it is; switching to it when it runs; a
371/// new login when the daemon refuses this account (Linux's docker group); starting it when Docker
372/// is installed but doesn't answer; installing it when it is the recommended one and there is no
373/// Docker; else its vendor's site.
374fn engine_actions(m: &Machine, engine: Engine) -> Vec<Action> {
375    let action = if m.docker.ready() && m.docker.engine == Some(engine) {
376        return Vec::new();
377    } else if m.docker.engines_running.contains(&engine) {
378        Action::UseEngine { engine }
379    } else if m.docker.denied && engine == Engine::Native {
380        Action::Relogin
381    } else if m.docker.installed && !m.docker.ready() {
382        Action::StartEngine { engine }
383    } else if engine == recommended_engine(m.host.os) && !m.docker.installed {
384        install(m, Dependency::Docker)
385    } else {
386        by_hand(crate::install::VendorPage {
387            name: engine.label(),
388            url: engine.url(),
389        })
390    };
391    vec![action]
392}
393
394/// What gets hypervisor `p` here: nothing once it is installed (a new login when the account
395/// joined its groups since logging in, libvirt's or `/dev/kvm`'s; else why it still can't run);
396/// the restart Hyper-V waits for once a setup turned it on (`hyperv_restart`); its install; else
397/// its vendor's site. VirtualBox while KVM holds the CPU's virtualization: its install when it
398/// is missing, then KVM set to share it (or the restart that applies that).
399fn hypervisor_get(m: &Machine, p: &ProviderStatus, hyperv_restart: bool) -> Vec<Action> {
400    if let Some(reason @ (Unavailable::KvmHoldsVirtualization | Unavailable::KvmSharesAfterRestart)) = &p.reason {
401        let mut get: Vec<Action> = (p.hypervisor != Some(true)).then(|| get_hypervisor(m, p)).into_iter().collect();
402        get.push(match reason {
403            Unavailable::KvmHoldsVirtualization => share_virtualization_action(m),
404            _ => Action::Blocked { reason: reason.clone() },
405        });
406        return get;
407    }
408    if p.hypervisor == Some(true) {
409        // The groups its install added the account to (libvirt's, /dev/kvm's) apply from the
410        // next login: a setup asks for it, as it does for the docker group.
411        let groups = providers::login_groups(p.provider, &m.host);
412        if m.groups_pending.iter().any(|g| groups.contains(g)) {
413            return vec![Action::Relogin];
414        }
415        return match &p.reason {
416            Some(reason) if cant_run(p) => vec![Action::Blocked { reason: reason.clone() }],
417            _ => Vec::new(),
418        };
419    }
420    if p.provider == Provider::Hyperv && hyperv_restart {
421        return vec![Action::Restart {
422            feature: WindowsFeature::Hyperv,
423        }];
424    }
425    vec![get_hypervisor(m, p)]
426}
427
428/// Letting VirtualBox share the CPU's virtualization with KVM: its root step raises pkexec's
429/// prompt unless it runs unattended.
430fn share_virtualization_action(m: &Machine) -> Action {
431    let prompt = Interaction::AdminPassword {
432        via: crate::install::Prompt::Pkexec,
433    };
434    Action::ShareVirtualization {
435        interactions: (m.elevation == Elevation::Prompt).then_some(prompt).into_iter().collect(),
436    }
437}
438
439/// What brings hypervisor `p` here: its install, else its vendor's site.
440fn get_hypervisor(m: &Machine, p: &ProviderStatus) -> Action {
441    match installable(p.provider, m.host.os) {
442        Some(dependency) => install(m, dependency),
443        None => match providers::download_page(p.provider, m.host.os) {
444            Some(page) => by_hand(page),
445            None => Action::Manual {
446                interactions: Vec::new(),
447                reason: ManualReason::Vendor,
448                dependency: None,
449                url: None,
450            },
451        },
452    }
453}
454
455/// Getting it from its vendor's own download page, `page`: its user downloads and installs it
456/// there, then checks again.
457fn by_hand(page: crate::install::VendorPage) -> Action {
458    Action::Manual {
459        interactions: vec![page.download()],
460        reason: ManualReason::Vendor,
461        dependency: None,
462        url: Some(page.url.to_owned()),
463    }
464}
465
466/// What Vagrant needs to drive `p` ([`ProviderStatus::needs`]), each with the item it is about:
467/// `vagrant`, `vmware-utility`, `plugin:<name>`. A provider driven through VMware's utility gets
468/// neither the utility nor its plugin before its hypervisor is installed, and its plugin only in
469/// the same plan as the utility's install (or once the utility is there): the plugin without the
470/// utility breaks Vagrant for every provider ([`Unavailable::VmwarePluginWithoutUtility`]).
471fn vagrant_steps(m: &Machine, p: &ProviderStatus) -> Vec<(String, Action)> {
472    let through_utility = providers::needs_vmware_utility(p.provider);
473    if through_utility && p.hypervisor != Some(true) {
474        return p
475            .needs
476            .contains(&Need::Vagrant)
477            .then(|| ("vagrant".to_owned(), install(m, Dependency::Vagrant)))
478            .into_iter()
479            .collect();
480    }
481    let utility = install(m, Dependency::VmwareUtility);
482    let utility_installs = !p.needs.contains(&Need::VmwareUtility) || matches!(utility, Action::Install { .. });
483    p.needs
484        .iter()
485        .filter_map(|need| {
486            Some(match need {
487                Need::Vagrant => ("vagrant".to_owned(), install(m, Dependency::Vagrant)),
488                Need::VmwareUtility => ("vmware-utility".to_owned(), utility.clone()),
489                Need::Plugin if through_utility && !utility_installs => return None,
490                Need::Plugin => {
491                    let plugin = p.plugin.clone()?;
492                    (format!("plugin:{plugin}"), Action::Plugin { plugin })
493                }
494            })
495        })
496        .collect()
497}
498
499/// What each choice takes on machine `m`; `hyperv_restart`: a setup turned Hyper-V on in this
500/// boot, so it waits for a restart.
501#[must_use]
502pub fn options(m: &Machine, hyperv_restart: bool) -> Options {
503    let offered = engines_on(m.host.os);
504    let recommended = recommended_engine(m.host.os);
505    let engine = match m.docker.engine {
506        Some(e) if offered.contains(&e) => e,
507        Some(_) => offered.first().copied().unwrap_or(recommended),
508        None => recommended,
509    };
510    let hypervisors: Vec<HypervisorOption> = m
511        .local()
512        .map(|p| HypervisorOption {
513            provider: p.provider,
514            get: hypervisor_get(m, p, hyperv_restart),
515            vagrant: vagrant_steps(m, p).into_iter().map(|(_, action)| action).collect(),
516        })
517        .collect();
518    let installed = |o: &&HypervisorOption| m.local().any(|p| p.provider == o.provider && p.hypervisor == Some(true));
519    // One a setup installs only to then share KVM's virtualization with it (VirtualBox) comes
520    // after one that just installs.
521    let installs = |o: &&HypervisorOption| matches!(o.get.first(), Some(Action::Install { .. }));
522    let shares = |o: &&HypervisorOption| o.get.iter().any(|a| matches!(a, Action::ShareVirtualization { .. }));
523    let hypervisor = hypervisors
524        .iter()
525        .find(|o| installed(o) && o.get.is_empty())
526        .or_else(|| hypervisors.iter().find(installed))
527        .or_else(|| hypervisors.iter().find(|o| installs(o) && !shares(o)))
528        .or_else(|| hypervisors.iter().find(installs))
529        .or_else(|| hypervisors.first())
530        .map(|o| o.provider);
531    Options {
532        wsl: wsl(m),
533        recommended_engine: recommended,
534        engine,
535        engines: offered
536            .iter()
537            .map(|&e| EngineOption {
538                engine: e,
539                actions: engine_actions(m, e),
540            })
541            .collect(),
542        hypervisor,
543        hypervisors,
544    }
545}
546
547#[cfg(test)]
548mod tests;