isothrum-machine 3.0.1

Machine-setup domain for Isothrum: check this computer's tools, Docker engines and WSL 2, and detect the Vagrant providers (hypervisors) it can drive.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
use std::sync::Arc;

use isothrum_runner::fake::{Call, FakeProcesses, Reply};
use isothrum_runner::{Cloud, Detail, Error, Format, HostOs};

use super::*;
use crate::host::{Host, LinuxPackages, Packages};

/// A tool.
fn tool(dependency: Dependency) -> Requirement {
    Requirement::Tool { dependency }
}

/// A Linux host with apt, its devices under `root`.
fn apt_host(root: &Path) -> Host {
    Host {
        packages: Some(Packages::Linux(LinuxPackages::Apt)),
        ..crate::testing::linux_host(root)
    }
}

/// A context on `host` whose tools answer as `answer` says, each call kept.
fn on(host: Host, answer: impl Fn(&Call) -> Reply + Send + Sync + 'static) -> (Context, Arc<FakeProcesses>) {
    let fake = Arc::new(FakeProcesses::model(answer));
    {
        let runner: Arc<dyn isothrum_runner::ProcessRunner> = Arc::<FakeProcesses>::clone(&fake);
        (Context::new(runner, host), fake)
    }
}

/// What a Vagrant run on `provider` needs on an apt host with Vagrant and no plugin, nothing else
/// installed; and the tools, to read the calls made.
async fn vagrant_needs(provider: Provider) -> (Vec<Need>, Arc<FakeProcesses>) {
    let root = tempfile::tempdir().unwrap();
    let (cx, fake) = on(apt_host(root.path()), |call| match call.line().as_str() {
        "vagrant --version" => Reply::ok("Vagrant 2.4.9"),
        "vagrant plugin list --machine-readable" => Reply::ok(""),
        _ => Reply::missing(),
    });
    (needs(&cx, &Uses::vagrant(provider).requirements(), &Asking::default()).await, fake)
}

/// Whether Vagrant's plugin, among `found`, is planned after `requirement`.
fn plugin_comes_after(found: &[Need], requirement: Requirement) -> bool {
    let plugin = found.iter().find(|n| matches!(n.requirement, Requirement::VagrantPlugin { .. })).unwrap();
    matches!(&plugin.plan, Some(Plan::After { requirement: r }) if *r == requirement)
}

#[test]
fn a_compose_run_needs_the_engine_its_plugin_and_the_engine_answering() {
    assert_eq!(
        Uses::new(Format::Compose).requirements(),
        [tool(Dependency::Docker), Requirement::ComposePlugin, Requirement::EngineRunning]
    );
}

#[test]
fn a_vagrant_run_needs_vagrant_its_hypervisor_and_what_vagrant_drives_it_through() {
    assert_eq!(
        Uses::vagrant(Provider::Virtualbox).requirements(),
        [
            tool(Dependency::Vagrant),
            Requirement::Hypervisor {
                provider: Provider::Virtualbox
            }
        ],
        "VirtualBox is built into Vagrant"
    );
    assert_eq!(
        Uses::vagrant(Provider::Libvirt).requirements(),
        [
            tool(Dependency::Vagrant),
            Requirement::Hypervisor { provider: Provider::Libvirt },
            Requirement::VagrantPlugin { provider: Provider::Libvirt }
        ]
    );
    assert_eq!(
        Uses::vagrant(Provider::VmwareDesktop).requirements(),
        [
            tool(Dependency::Vagrant),
            Requirement::Hypervisor {
                provider: Provider::VmwareDesktop
            },
            tool(Dependency::VmwareUtility),
            Requirement::VagrantPlugin {
                provider: Provider::VmwareDesktop
            }
        ]
    );
    assert_eq!(
        Uses::new(Format::Vagrant).requirements(),
        [tool(Dependency::Vagrant)],
        "no hypervisor named yet"
    );
}

#[test]
fn an_esxi_run_needs_no_hypervisor_here_but_its_plugin_and_the_ovf_tool() {
    assert_eq!(
        Uses::vagrant(Provider::VmwareEsxi).requirements(),
        [
            tool(Dependency::Vagrant),
            Requirement::VagrantPlugin {
                provider: Provider::VmwareEsxi
            },
            Requirement::Ovftool
        ]
    );
}

#[test]
fn a_terraform_run_needs_terraform_and_its_targets_cli_or_the_ovf_tool() {
    let cloud = |cloud| Uses::terraform(Target::Cloud { cloud }).requirements();
    assert_eq!(cloud(Cloud::Aws), [tool(Dependency::Terraform), tool(Dependency::Awscli)]);
    assert_eq!(cloud(Cloud::Azure), [tool(Dependency::Terraform), tool(Dependency::Azurecli)]);
    assert_eq!(cloud(Cloud::Gcp), [tool(Dependency::Terraform), tool(Dependency::Gcloud)]);
    for keyed in [Cloud::Digitalocean, Cloud::Linode, Cloud::Oci] {
        assert_eq!(cloud(keyed), [tool(Dependency::Terraform)], "{keyed:?} signs in with a token or keys");
    }
    assert_eq!(Uses::terraform(Target::Proxmox).requirements(), [tool(Dependency::Terraform)]);
    assert_eq!(
        Uses::terraform(Target::Esxi).requirements(),
        [tool(Dependency::Terraform), Requirement::Ovftool]
    );
    assert_eq!(Uses::new(Format::Terraform).requirements(), [tool(Dependency::Terraform)]);
}

#[test]
fn a_provider_or_target_the_format_doesnt_use_is_ignored() {
    let compose = Uses::new(Format::Compose).on(Provider::Libvirt).at(Target::Esxi);
    assert_eq!(compose.requirements(), Uses::new(Format::Compose).requirements());
    let vagrant = Uses::vagrant(Provider::Virtualbox).at(Target::Esxi);
    assert_eq!(vagrant.requirements(), Uses::vagrant(Provider::Virtualbox).requirements());
}

#[test]
fn a_requirement_is_named_as_a_ui_reads_it() {
    let json = |r: Requirement| serde_json::to_value(r).unwrap();
    assert_eq!(json(tool(Dependency::Vagrant)), serde_json::json!({"kind": "tool", "dependency": "vagrant"}));
    assert_eq!(json(Requirement::ComposePlugin), serde_json::json!({"kind": "composePlugin"}));
    assert_eq!(
        json(Requirement::VagrantPlugin {
            provider: Provider::VmwareEsxi
        }),
        serde_json::json!({"kind": "vagrantPlugin", "provider": "vmware_esxi"})
    );
    let back: Requirement = serde_json::from_value(serde_json::json!({"kind": "ovftool"})).unwrap();
    assert_eq!(back, Requirement::Ovftool);
}

#[test]
fn a_missing_tool_the_runner_names_is_its_requirement() {
    let missing = |tool: &str| Error::ToolMissing {
        step: "up".to_owned(),
        tool: tool.to_owned(),
    };
    assert_eq!(Requirement::of_error(&missing("docker")), Some(tool(Dependency::Docker)));
    assert_eq!(Requirement::of_error(&missing("vagrant")), Some(tool(Dependency::Vagrant)));
    assert_eq!(Requirement::of_error(&missing("terraform.exe")), Some(tool(Dependency::Terraform)));
    assert_eq!(Requirement::of_error(&missing("ovftool")), Some(Requirement::Ovftool));
    assert_eq!(
        Requirement::of_error(&missing("VBoxManage")),
        Some(Requirement::Hypervisor {
            provider: Provider::Virtualbox
        })
    );
    assert_eq!(Requirement::of_error(&missing("ssh")), None, "nothing a setup installs");
    let unanswered = Error::ToolUnanswered {
        step: "tools".to_owned(),
        tool: "docker".to_owned(),
        reason: "Cannot connect to the Docker daemon".to_owned(),
    };
    assert_eq!(Requirement::of_error(&unanswered), Some(Requirement::EngineRunning));
    assert_eq!(Requirement::of_error(&Error::Locked { run: "a".to_owned() }), None, "not a missing requirement");
    let detail = Detail::ToolMissing { tool: "aws".to_owned() };
    assert_eq!(Requirement::of_detail(&detail), Some(tool(Dependency::Awscli)));
}

#[tokio::test(start_paused = true)]
async fn present_tools_have_no_plan_and_missing_ones_the_hosts() {
    let root = tempfile::tempdir().unwrap();
    let (cx, fake) = on(apt_host(root.path()), |call| match call.line().as_str() {
        "docker --version" => Reply::ok("Docker version 27.3.1"),
        "docker compose version --short" => Reply::ok("2.29.7"),
        _ => Reply::missing(),
    });
    let needs = needs(&cx, &Uses::new(Format::Compose).requirements(), &Asking::default()).await;
    let [docker, compose, engine] = needs.as_slice() else { panic!("{needs:?}") };
    assert_eq!((docker.present, compose.present), (Some(true), Some(true)));
    assert!(docker.plan.is_none() && compose.plan.is_none(), "{needs:?}");
    assert!(engine.missing());
    assert!(matches!(engine.plan, Some(Plan::Start)), "{engine:?}");
    let ran: Vec<String> = fake.calls().iter().map(Call::line).collect();
    assert!(
        ran.iter().all(|l| !l.contains("install") && !l.starts_with("pkexec") && !l.starts_with("sudo")),
        "asking installs nothing: {ran:?}"
    );
}

#[tokio::test(start_paused = true)]
async fn a_missing_tool_is_planned_as_its_install_here() {
    let root = tempfile::tempdir().unwrap();
    let (cx, _fake) = on(apt_host(root.path()), |_| Reply::missing());
    let asking = Asking {
        user: Some("ada"),
        elevation: Elevation::Unattended { root: false },
        ..Asking::default()
    };
    let found = needs(&cx, &[tool(Dependency::Terraform), Requirement::ComposePlugin], &asking).await;
    for need in &found {
        assert!(need.missing(), "{need:?}");
        let Some(Plan::Install(steps)) = &need.plan else { panic!("{need:?}") };
        assert_eq!(steps.iter().map(|s| s.program.as_str()).collect::<Vec<_>>(), ["sudo"], "{need:?}");
    }
}

#[tokio::test(start_paused = true)]
async fn a_tool_without_packages_here_is_refused_with_why() {
    let root = tempfile::tempdir().unwrap();
    let (cx, _fake) = on(crate::testing::linux_host(root.path()), |_| Reply::missing());
    let found = needs(&cx, &[tool(Dependency::Vagrant)], &Asking::default()).await;
    assert!(
        matches!(
            &found[0].plan,
            Some(Plan::Refused(Refusal::WithoutPackages {
                dependency: Dependency::Vagrant
            }))
        ),
        "{found:?}"
    );
}

#[tokio::test(start_paused = true)]
async fn a_vagrant_runs_needs_read_its_providers_status_once() {
    let (found, fake) = vagrant_needs(Provider::Libvirt).await;
    let [vagrant, hypervisor, plugin] = found.as_slice() else {
        panic!("{found:?}")
    };
    assert_eq!(vagrant.present, Some(true));
    assert!(hypervisor.missing(), "{hypervisor:?}");
    assert!(hypervisor.unavailable.is_some(), "its detection says why: {hypervisor:?}");
    assert!(vagrant.unavailable.is_none() && plugin.unavailable.is_none(), "a hypervisor's only");
    assert!(matches!(&hypervisor.plan, Some(Plan::Install(_))), "libvirt's own install: {hypervisor:?}");
    assert!(plugin.missing(), "{plugin:?}");
    let Some(Plan::Install(steps)) = &plugin.plan else { panic!("{plugin:?}") };
    assert_eq!(install::command_line(&steps[0]), "$ vagrant plugin install vagrant-libvirt");
    assert_eq!(fake.made("vagrant plugin list --machine-readable").len(), 1, "one status for both");
}

#[tokio::test(start_paused = true)]
async fn virtualbox_installed_while_kvm_holds_the_cpus_virtualization_is_planned_as_kvm_sharing_it() {
    let root = tempfile::tempdir().unwrap();
    let host = apt_host(root.path());
    crate::testing::kvm_holding(&host, "kvm_intel 1 0 - Live 0x0\nkvm 2 1 kvm_intel, Live 0x0\n");
    let modprobe_d = host.devices.modprobe_d.clone();
    let (cx, _fake) = on(host, |call| match call.line().as_str() {
        "VBoxManage --version" => Reply::ok("7.2.4r170995"),
        "vagrant --version" => Reply::ok("Vagrant 2.4.9"),
        _ => Reply::missing(),
    });
    let wanted = [Requirement::Hypervisor {
        provider: Provider::Virtualbox,
    }];
    let [vbox] = &needs(&cx, &wanted, &Asking::default()).await[..] else {
        panic!()
    };
    assert_eq!(vbox.present, Some(true));
    assert_eq!(vbox.unavailable, Some(Unavailable::KvmHoldsVirtualization));
    assert!(matches!(vbox.plan, Some(Plan::ShareVirtualization)), "{vbox:?}");

    std::fs::create_dir_all(&modprobe_d).unwrap();
    std::fs::write(modprobe_d.join("isothrum-kvm.conf"), "options kvm enable_virt_at_load=0\n").unwrap();
    let [restart] = &needs(&cx, &wanted, &Asking::default()).await[..] else {
        panic!()
    };
    assert_eq!(restart.unavailable, Some(Unavailable::KvmSharesAfterRestart));
    assert!(restart.plan.is_none(), "a restart: nothing a setup runs: {restart:?}");
}

#[tokio::test(start_paused = true)]
async fn a_hypervisor_no_setup_installs_is_its_vendors_to_get() {
    let root = tempfile::tempdir().unwrap();
    let host = Host {
        os: HostOs::Macos,
        packages: Some(Packages::Homebrew("/opt/homebrew/bin/brew")),
        ..crate::testing::linux_host(root.path())
    };
    let (cx, _fake) = on(host, |_| Reply::missing());
    let plan = plan(&cx, Requirement::Hypervisor { provider: Provider::Parallels }, &Asking::default());
    assert!(
        matches!(plan, Plan::ByHand { page: Some(p) } if p.url.contains("parallels") && p.name == "Parallels"),
        "{plan:?}"
    );
}

#[tokio::test(start_paused = true)]
async fn vmware_and_the_ovf_tool_are_downloads_by_hand_from_broadcom_on_each_os_they_run_on() {
    use crate::install::{BROADCOM_DOWNLOADS, Interaction, OVFTOOL_PAGE, VMWARE_FUSION_PAGE, VMWARE_WORKSTATION_PAGE};
    let root = tempfile::tempdir().unwrap();
    for os in crate::host::ALL_OSES {
        let host = Host {
            os,
            ..crate::testing::linux_host(root.path())
        };
        let (cx, _fake) = on(host, |_| Reply::missing());
        // VMware Workstation Pro (Windows, Linux), VMware Fusion Pro (macOS): Broadcom's portal.
        let vmware = plan(
            &cx,
            Requirement::Hypervisor {
                provider: Provider::VmwareDesktop,
            },
            &Asking::default(),
        );
        let page = if os == HostOs::Macos { VMWARE_FUSION_PAGE } else { VMWARE_WORKSTATION_PAGE };
        assert!(matches!(vmware, Plan::ByHand { page: Some(p) } if p == page), "{os:?}: {vmware:?}");
        let ovftool = plan(&cx, Requirement::Ovftool, &Asking::default());
        assert!(matches!(ovftool, Plan::ByHand { page: Some(OVFTOOL_PAGE) }), "{os:?}: {ovftool:?}");
    }
    assert_eq!(BROADCOM_DOWNLOADS.name, "Broadcom");
    assert!(
        [BROADCOM_DOWNLOADS, VMWARE_FUSION_PAGE, VMWARE_WORKSTATION_PAGE]
            .iter()
            .all(|p| p.url.starts_with("https://support.broadcom.com/group/ecx/"))
    );
    assert!(VMWARE_FUSION_PAGE.url.contains("VMware%20Fusion") && VMWARE_WORKSTATION_PAGE.url.contains("VMware%20Workstation%20Pro"));
    assert_eq!(OVFTOOL_PAGE.url, OVFTOOL_URL);
    assert_eq!(
        OVFTOOL_PAGE.download(),
        Interaction::DownloadByHand {
            vendor: "Broadcom",
            url: OVFTOOL_URL
        }
    );
}

#[tokio::test(start_paused = true)]
async fn the_ovf_tool_is_found_on_the_path_given_else_fetched_by_hand() {
    let root = tempfile::tempdir().unwrap();
    let (cx, _fake) = on(apt_host(root.path()), |_| Reply::missing());
    let missing = needs(&cx, &[Requirement::Ovftool], &Asking::default()).await;
    assert!(missing[0].missing());
    assert!(
        matches!(missing[0].plan, Some(Plan::ByHand { page: Some(p) }) if p.url == OVFTOOL_URL),
        "{missing:?}"
    );

    let bin = root.path().join("bin");
    std::fs::create_dir_all(&bin).unwrap();
    std::fs::write(bin.join("ovftool"), "#!/bin/sh\n").unwrap();
    let path = std::env::join_paths([&bin]).unwrap();
    let asking = Asking {
        path: Some(&path),
        ..Asking::default()
    };
    let found = needs(&cx, &[Requirement::Ovftool], &asking).await;
    assert_eq!(found[0].present, Some(true), "{found:?}");
    assert!(found[0].plan.is_none());
}

/// Regression: VMware's utility was planned as an install on a computer without VMware, so a run
/// that installs what it needs ran it first: its Windows installer exits 1603 ("requires a valid
/// installation of VMware Workstation"), and on Linux its service never answers. It comes after
/// VMware, which its user gets from its vendor.
#[tokio::test(start_paused = true)]
async fn vmwares_utility_comes_after_vmware_which_its_user_gets_first() {
    let (found, _fake) = vagrant_needs(Provider::VmwareDesktop).await;
    let utility = found.iter().find(|n| n.requirement == tool(Dependency::VmwareUtility)).unwrap();
    assert!(utility.missing(), "{utility:?}");
    assert!(
        matches!(
            utility.plan,
            Some(Plan::After {
                requirement: Requirement::Hypervisor {
                    provider: Provider::VmwareDesktop
                }
            })
        ),
        "{utility:?}"
    );
    let vmware = found
        .iter()
        .find(|n| {
            n.requirement
                == Requirement::Hypervisor {
                    provider: Provider::VmwareDesktop,
                }
        })
        .unwrap();
    assert!(matches!(vmware.plan, Some(Plan::ByHand { .. })), "VMware from its vendor first: {vmware:?}");
    // Its plugin too: without VMware's utility it breaks Vagrant for every provider.
    assert!(
        plugin_comes_after(
            &found,
            Requirement::Hypervisor {
                provider: Provider::VmwareDesktop
            }
        ),
        "{found:?}"
    );
    assert_eq!(Dependency::VmwareUtility.serves(), Some(Provider::VmwareDesktop));
    assert!(Dependency::ALL.iter().all(|d| *d == Dependency::VmwareUtility || d.serves().is_none()));
}

/// Regression: VMware's plugin, installed without its utility (studio, which has no VMware), broke
/// every Vagrant command, QEMU's `vagrant status` too. With VMware here it waits for the utility;
/// another provider's plugin waits for nothing.
#[tokio::test(start_paused = true)]
async fn vmwares_plugin_comes_after_its_utility_and_no_other_plugin_waits() {
    let root = tempfile::tempdir().unwrap();
    let (cx, _fake) = on(apt_host(root.path()), |call| {
        let line = call.line();
        if line == "vagrant --version" {
            Reply::ok("Vagrant 2.4.9")
        } else if line == "vagrant plugin list --machine-readable" {
            Reply::ok("")
        } else if line.starts_with("vmrun") {
            Reply::ok("vmrun version 1.17.0 build-24995812")
        } else {
            Reply::missing()
        }
    });
    let found = needs(&cx, &Uses::vagrant(Provider::VmwareDesktop).requirements(), &Asking::default()).await;
    assert!(
        plugin_comes_after(
            &found,
            Requirement::Tool {
                dependency: Dependency::VmwareUtility
            }
        ),
        "{found:?}"
    );
    let utility = found.iter().find(|n| n.requirement == tool(Dependency::VmwareUtility)).unwrap();
    assert!(
        matches!(utility.plan, Some(Plan::Install(_))),
        "VMware is here: its utility installs: {utility:?}"
    );
    let libvirt = needs(&cx, &[Requirement::VagrantPlugin { provider: Provider::Libvirt }], &Asking::default()).await;
    assert!(matches!(libvirt[0].plan, Some(Plan::Install(_))), "{libvirt:?}");
}