Skip to main content

isothrum_machine/setup/
plan.rs

1//! A whole setup on one computer, in order: the options worked out for it ([`super::options`]),
2//! for the kinds of project, engine and hypervisors wanted.
3
4use serde::Deserialize;
5
6use super::{Action, HypervisorOption, Machine, ManualReason, Options, engines_on, vagrant_steps};
7use crate::docker::Engine;
8use crate::host::HostOs;
9use crate::install::Dependency;
10use crate::providers::{Provider, Unavailable};
11
12/// A kind of project a setup readies this computer for.
13#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize)]
14#[serde(rename_all = "lowercase")]
15pub enum SetupPath {
16    /// Containers: WSL 2 on Windows, a Docker engine.
17    Docker,
18    /// VMs: a hypervisor, Vagrant and what it needs to drive it.
19    Vm,
20}
21
22/// What a whole setup is for.
23#[derive(Clone, Debug, Default, PartialEq, Eq)]
24pub struct Wanted {
25    /// The kinds of project to ready the computer for.
26    pub paths: Vec<SetupPath>,
27    /// The engine to set up; none: the setup's own ([`Options::engine`]).
28    pub engine: Option<Engine>,
29    /// The hypervisors to set up, in order: the first a setup can set up is the one. None: the
30    /// setup's own ([`Options::hypervisor`]).
31    pub hypervisors: Vec<Provider>,
32}
33
34/// One action of a plan, with the item it is about (`wsl`, `docker`, `engine:<id>`, `vagrant`,
35/// `<hypervisor>`, `plugin:<name>`, `vmware-utility`).
36#[derive(Clone, Debug, PartialEq, Eq)]
37pub struct Step {
38    /// The item it is about.
39    pub item: String,
40    /// What it does.
41    pub action: Action,
42}
43
44/// Why a hypervisor wanted isn't the one a setup sets up. A UI says each in its own words.
45#[derive(Clone, Debug, PartialEq, Eq)]
46#[non_exhaustive]
47pub enum PassedOver {
48    /// Its user gets it from its vendor: the page, when there is one.
49    LinksOut {
50        /// The vendor's page.
51        url: Option<String>,
52    },
53    /// A setup doesn't install on this Linux distribution yet: its user installs it.
54    Distribution,
55    /// It can't run here.
56    CantRun {
57        /// Why.
58        reason: Unavailable,
59    },
60    /// Not offered on this computer.
61    NotOffered,
62    /// Not needed: `chosen`, wanted before it, is set up.
63    NotNeeded {
64        /// The hypervisor set up.
65        chosen: Provider,
66    },
67}
68
69/// A whole setup on one computer.
70#[derive(Clone, Debug, Default, PartialEq, Eq)]
71pub struct Plan {
72    /// What to do, in order: what ends a pass (a restart, a new login) last.
73    pub steps: Vec<Step>,
74    /// The hypervisor set up, when VMs are wanted and one can be.
75    pub hypervisor: Option<Provider>,
76    /// The wanted hypervisors not set up, each with why.
77    pub passed_over: Vec<(Provider, PassedOver)>,
78    /// Every item the setup covers, whether or not it has anything to do for it.
79    pub items: Vec<String>,
80}
81
82/// Why a setup leaves a step alone: its user's to take, or it can't run here ([`left_alone`]).
83#[derive(Clone, Debug, PartialEq, Eq)]
84#[non_exhaustive]
85pub enum LeftAlone {
86    /// A setup doesn't install on this Linux distribution yet: its user installs `dependency`.
87    Distribution {
88        /// The tool, when it is one a setup installs elsewhere.
89        dependency: Option<Dependency>,
90    },
91    /// Its user gets it from its vendor: the page, when there is one.
92    LinksOut {
93        /// The vendor's page.
94        url: Option<String>,
95    },
96    /// It can't run here: a failure, not a skip.
97    CantRun {
98        /// Why.
99        reason: Unavailable,
100    },
101}
102
103impl LeftAlone {
104    /// Whether it counts as the step failing (it can't run here), not as one skipped.
105    #[must_use]
106    pub fn fails(&self) -> bool {
107        matches!(self, LeftAlone::CantRun { .. })
108    }
109}
110
111/// Why a setup doesn't run `action` itself, when it doesn't: its user's to take, or it can't run
112/// here. None for a step a setup runs (a restart and a new login it leaves to its caller).
113#[must_use]
114pub fn left_alone(action: &Action) -> Option<LeftAlone> {
115    Some(match action {
116        Action::Manual {
117            reason: ManualReason::Distribution,
118            dependency,
119            ..
120        } => LeftAlone::Distribution { dependency: *dependency },
121        Action::Manual {
122            reason: ManualReason::Vendor,
123            url,
124            ..
125        } => LeftAlone::LinksOut { url: url.clone() },
126        Action::Blocked { reason } => LeftAlone::CantRun { reason: reason.clone() },
127        _ => return None,
128    })
129}
130
131/// Why `option` can't be the hypervisor a setup sets up, if it can't: something its user gets,
132/// or why it can't run here.
133fn not_settable(option: &HypervisorOption) -> Option<PassedOver> {
134    option.get.iter().find_map(|action| match action {
135        Action::Manual {
136            reason: ManualReason::Vendor,
137            url,
138            ..
139        } => Some(PassedOver::LinksOut { url: url.clone() }),
140        Action::Manual {
141            reason: ManualReason::Distribution,
142            ..
143        } => Some(PassedOver::Distribution),
144        // A restart sets up one blocked until it (VirtualBox's driver, built for a newer kernel).
145        Action::Blocked { reason } if !action.ends_pass() => Some(PassedOver::CantRun { reason: reason.clone() }),
146        _ => None,
147    })
148}
149
150/// The hypervisor a setup sets up of `wanted`, and why each other one wanted isn't. None given:
151/// the setup's own, else the first other one offered here that can be set up, in the check's
152/// order (VirtualBox with a driver that won't load gives way to libvirt or QEMU), those before it
153/// that can't passed over.
154fn pick_hypervisor(o: &Options, wanted: &[Provider]) -> (Option<Provider>, Vec<(Provider, PassedOver)>) {
155    let mut passed_over = Vec::new();
156    if wanted.is_empty() {
157        let others = o.hypervisors.iter().map(|h| h.provider).filter(|p| Some(*p) != o.hypervisor);
158        for option in o
159            .hypervisor
160            .into_iter()
161            .chain(others)
162            .filter_map(|p| o.hypervisors.iter().find(|h| h.provider == p))
163        {
164            match not_settable(option) {
165                Some(why) => passed_over.push((option.provider, why)),
166                None => return (Some(option.provider), passed_over),
167            }
168        }
169        return (None, passed_over);
170    }
171    let mut chosen: Option<Provider> = None;
172    for &provider in wanted {
173        let Some(option) = o.hypervisors.iter().find(|h| h.provider == provider) else {
174            passed_over.push((provider, PassedOver::NotOffered));
175            continue;
176        };
177        match (chosen, not_settable(option)) {
178            (_, Some(why)) => passed_over.push((provider, why)),
179            (Some(first), None) => passed_over.push((provider, PassedOver::NotNeeded { chosen: first })),
180            (None, None) => chosen = Some(provider),
181        }
182    }
183    (chosen, passed_over)
184}
185
186/// Whether `action` is Docker's own install left to its user (a distribution without apt or dnf).
187fn docker_install(action: &Action) -> bool {
188    matches!(
189        action,
190        Action::Manual {
191            reason: ManualReason::Distribution,
192            ..
193        }
194    )
195}
196
197/// The whole setup `wanted` on machine `m` with its `options` ([`super::options`]), in a setup's
198/// order: WSL 2 and the engine, then the hypervisor and what Vagrant needs for it; a restart or a
199/// new login last, so everything else is done first.
200#[must_use]
201pub fn plan(m: &Machine, options: &Options, wanted: &Wanted) -> Plan {
202    let mut plan = Plan::default();
203    if wanted.paths.contains(&SetupPath::Docker) {
204        let wsl = &options.wsl;
205        plan.steps.extend(wsl.iter().map(|a| Step {
206            item: "wsl".into(),
207            action: a.clone(),
208        }));
209        let engine = wanted.engine.filter(|e| engines_on(m.host.os).contains(e)).unwrap_or(options.engine);
210        let engine_item = format!("engine:{}", engine.id());
211        let actions = options
212            .engines
213            .iter()
214            .find(|e| e.engine == engine)
215            .map(|e| e.actions.clone())
216            .unwrap_or_default();
217        for action in actions {
218            // Docker Desktop runs on WSL 2: it starts once WSL is ready, after the restart.
219            if !wsl.is_empty() && matches!(action, Action::StartEngine { .. }) {
220                continue;
221            }
222            let item = if matches!(action, Action::Install { .. } | Action::Relogin) || docker_install(&action) {
223                "docker".into()
224            } else {
225                engine_item.clone()
226            };
227            plan.steps.push(Step { item, action });
228        }
229        if m.host.os == HostOs::Windows {
230            plan.items.push("wsl".into());
231        }
232        plan.items.extend(["docker".to_owned(), engine_item]);
233    }
234    if wanted.paths.contains(&SetupPath::Vm) {
235        let (chosen, passed_over) = pick_hypervisor(options, &wanted.hypervisors);
236        plan.hypervisor = chosen;
237        plan.passed_over = passed_over;
238        if let Some(p) = chosen.and_then(|c| m.local().find(|p| p.provider == c)) {
239            let option = options.hypervisors.iter().find(|h| h.provider == p.provider);
240            plan.steps.extend(option.into_iter().flat_map(|o| {
241                o.get.iter().map(|a| Step {
242                    item: p.provider.id().into(),
243                    action: a.clone(),
244                })
245            }));
246            plan.steps.extend(vagrant_steps(m, p).into_iter().map(|(item, action)| Step { item, action }));
247            plan.items.extend(["vagrant".to_owned(), p.provider.id().to_owned()]);
248            plan.items.extend(p.plugin.iter().map(|name| format!("plugin:{name}")));
249            if p.utility.is_some() {
250                plan.items.push("vmware-utility".into());
251            }
252        }
253    }
254    // What ends a pass goes last, in its order.
255    let (ends, rest): (Vec<Step>, Vec<Step>) = plan.steps.into_iter().partition(|s| s.action.ends_pass());
256    plan.steps = rest.into_iter().chain(ends).collect();
257    plan
258}