1mod boxes;
13mod leftover;
14mod networks;
15mod ping;
16mod vboxmanage;
17
18use std::path::Path;
19use std::time::Duration;
20
21use isothrum_runner::{Arch, BoxFuture, Provider, RunOptions, Runner};
22
23pub use crate::boxes::{add_box, box_provider};
24pub use boxes::{box_for, candidate_boxes};
25pub use leftover::hyperv_leftover_script;
26
27use super::{Progress, throwaway};
28use crate::Context;
29use ping::{answers_ping, ping_once};
30
31const RUN: &str = "hypervisor-selftest";
33pub const ADDRESSES: [&str; 4] = ["192.168.56.250", "192.168.56.249", "192.168.56.248", "192.168.56.247"];
37pub const VMWARE_ADDRESSES: [&str; 4] = ["192.168.212.250", "192.168.212.249", "192.168.212.248", "192.168.212.247"];
41
42#[must_use]
44pub fn addresses(provider: Provider) -> &'static [&'static str] {
45 if provider == Provider::VmwareDesktop { &VMWARE_ADDRESSES } else { &ADDRESSES }
46}
47const PING_TRIES: u32 = 5;
49const PING_GAP: Duration = Duration::from_secs(1);
50
51#[derive(Debug, Clone, Copy)]
53#[non_exhaustive]
54pub struct TestVm<'a> {
55 pub name: &'a str,
57 pub hostname: &'a str,
60}
61
62impl<'a> TestVm<'a> {
63 #[must_use]
65 pub fn new(name: &'a str, hostname: &'a str) -> TestVm<'a> {
66 TestVm { name, hostname }
67 }
68}
69
70#[derive(Debug, Clone, Copy, PartialEq, Eq)]
72#[non_exhaustive]
73pub enum Step {
74 Leftover,
76 Vagrant,
78 Provider,
80 Hypervisor,
82 Box,
84 Boot,
86 Exec,
88 Network,
90 Networks,
92}
93
94#[derive(Debug, Clone, PartialEq, Eq)]
96#[non_exhaustive]
97pub enum Found {
98 Version(String),
100 Provider(Provider),
102 Responds,
104 NothingToProbe,
106 Box {
108 name: &'static str,
110 held: bool,
112 },
113 Booted {
115 name: &'static str,
117 provider: Provider,
119 },
120 Uname(String),
122 Reached {
124 address: &'static str,
126 },
127 NoPrivateNetwork(Provider),
129 AddressesTaken,
131 Removed(Vec<&'static str>),
133 NetworksRemoved(Vec<String>),
135 Line(String),
137}
138
139#[derive(Debug, Clone, PartialEq, Eq)]
141#[non_exhaustive]
142pub enum Failure {
143 Said(String),
145 Runner(Box<isothrum_runner::ErrorReport>),
147 Foreign {
149 hypervisor: &'static str,
151 },
152 NoTestBox {
155 hypervisor: &'static str,
157 arch: Arch,
159 },
160 NoReply {
162 address: &'static str,
164 last: String,
166 },
167}
168
169impl std::fmt::Display for Failure {
170 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
171 match self {
172 Failure::Said(said) => f.write_str(said),
173 Failure::Runner(e) => e.fmt(f),
174 Failure::Foreign { hypervisor } => write!(f, "{hypervisor} has a VM of the test's name that isn't the test's"),
175 Failure::NoTestBox { hypervisor, arch } => write!(
176 f,
177 "no test VM exists yet for {hypervisor} on {} computers, so the test has nothing to boot here",
178 crate::boxes::arch_name(*arch)
179 ),
180 Failure::NoReply { address, last } => write!(f, "{address} did not answer ping: {last}"),
181 }
182 }
183}
184
185pub type StepProgress = Progress<Step, Found, Failure>;
188
189#[derive(Debug)]
191#[non_exhaustive]
192pub struct Ran {
193 pub passed: Result<(), Failure>,
195 pub cleaned_up: Option<Result<(), Failure>>,
197}
198
199pub trait Choices: Send + Sync {
203 fn provider(&self) -> BoxFuture<'_, Result<Provider, String>>;
205
206 fn fetch_box<'a>(&'a self, provider: Provider, name: &'static str, line: &'a (dyn Fn(String) + Send + Sync)) -> BoxFuture<'a, Result<bool, String>>;
209}
210
211#[must_use]
213pub fn has_private_network(p: Provider) -> bool {
214 matches!(p, Provider::Virtualbox | Provider::VmwareDesktop | Provider::Parallels | Provider::Libvirt)
215}
216
217pub const HYPERV_SWITCH: &str = "Default Switch";
219
220#[must_use]
226pub fn vagrantfile(vm: &TestVm<'_>, p: Provider, name: &str, address: Option<&str>, dir: &Path) -> String {
227 let mut v = vec![
228 "Vagrant.configure(\"2\") do |config|".to_owned(),
229 format!(" config.vm.box = \"{name}\""),
230 " config.vm.boot_timeout = 600".to_owned(),
231 " config.vm.synced_folder \".\", \"/vagrant\", disabled: true".to_owned(),
232 ];
233 if p != Provider::Hyperv {
238 v.push(format!(" config.vm.hostname = \"{}\"", vm.hostname));
239 }
240 if let Some(address) = address.filter(|_| has_private_network(p)) {
241 v.push(format!(" config.vm.network \"private_network\", ip: \"{address}\""));
242 }
243 if p == Provider::Hyperv {
247 v.push(format!(" config.vm.network \"public_network\", bridge: \"{HYPERV_SWITCH}\""));
248 }
249 let named = vm.name;
250 let settings = match p {
251 Provider::Virtualbox => format!(
252 " h.name = \"{named}\"\n h.memory = 512\n h.customize [\"modifyvm\", :id, \"--description\", {}]\n",
253 ruby_quote(&leftover::vbox_description(vm, dir))
254 ),
255 Provider::Parallels => format!(" h.name = \"{named}\"\n h.memory = 512\n"),
256 Provider::VmwareDesktop => format!(
261 " h.vmx[\"displayName\"] = \"{named}\"\n h.memory = 512\n h.force_vmware_license = \"workstation\" unless RUBY_PLATFORM.include?(\"darwin\")\n"
262 ),
263 Provider::Libvirt => format!(" h.default_prefix = \"{}-\"\n h.memory = 512\n", vm.hostname),
264 Provider::Hyperv => format!(" h.vmname = \"{named}\"\n"),
265 Provider::Utm => format!(" h.name = \"{named}\"\n"),
266 Provider::Qemu => " h.memory = \"1G\"\n".to_owned(),
268 Provider::VmwareEsxi => String::new(),
269 };
270 if !settings.is_empty() {
271 v.push(format!(" config.vm.provider \"{}\" do |h|\n{settings} end", p.id()));
272 }
273 v.push("end\n".to_owned());
274 v.join("\n")
275}
276
277fn ruby_quote(s: &str) -> String {
279 format!("'{}'", s.replace('\\', "\\\\").replace('\'', "\\'"))
280}
281
282fn responds(p: Provider) -> Option<(String, &'static [&'static str])> {
285 let tool = |t: &str| Some(t.to_owned());
286 let (program, args): (Option<String>, &'static [&'static str]) = match p {
287 Provider::Virtualbox => (tool("VBoxManage"), &["list", "hostinfo"]),
288 Provider::VmwareDesktop => (tool("vmrun"), &["list"]),
289 Provider::Parallels => (tool("prlctl"), &["list", "--all"]),
290 Provider::Libvirt => (tool("virsh"), &["-c", "qemu:///system", "list", "--all"]),
291 Provider::Utm | Provider::Hyperv | Provider::Qemu | Provider::VmwareEsxi => (None, &[]),
294 };
295 program.map(|found| (found, args))
296}
297
298async fn answers(cx: &Context, program: &str, args: &[&str]) -> Result<(), String> {
301 let on_path = cx.read_ok(program, args).await;
302 let Err(said) = on_path else { return Ok(()) };
303 match cx.host.devices.app_tool(program).into_iter().find(|t| t.is_file()) {
304 Some(at) => cx.read_ok(&at.display().to_string(), args).await.map(drop),
305 None => Err(said),
306 }
307}
308
309async fn free_address(cx: &Context, provider: Provider) -> Option<&'static str> {
311 for &address in addresses(provider) {
312 if !answers_ping(cx, address).await {
313 return Some(address);
314 }
315 }
316 None
317}
318
319pub async fn run(cx: &Context, dir: &Path, vm: &TestVm<'_>, choices: &dyn Choices, progress: &(dyn Fn(StepProgress) + Send + Sync)) -> Ran {
322 let (runner, project) = match throwaway(cx, dir, "Vagrantfile", "") {
323 Ok(test) => test,
324 Err(e) => {
325 return Ran {
326 passed: Err(Failure::Said(e)),
327 cleaned_up: None,
328 };
329 }
330 };
331 match clear_earlier(cx, &runner, &project, dir, vm).await {
332 Ok(removed) if removed.is_empty() => {}
333 Ok(removed) => progress(Progress::Passed(Step::Leftover, Found::Removed(removed))),
334 Err(why) => {
335 progress(Progress::Failed(Step::Leftover, why.clone()));
336 return Ran {
337 passed: Err(why),
338 cleaned_up: None,
339 };
340 }
341 }
342 let mut test = Test {
343 cx,
344 runner: &runner,
345 project: &project,
346 dir,
347 vm,
348 provider: None,
349 before: networks::Networks::default(),
350 run: None,
351 };
352 let passed = Box::pin(test.steps(choices, progress)).await;
353 let cleaned_up = match test.provider {
354 Some(provider) => {
355 let down = match &test.run {
357 Some(run) => down_with(run, provider).await,
358 None => down(&runner, &project, provider).await,
359 };
360 if down.is_ok() {
361 remove_networks(cx, provider, &test.before, progress).await;
362 }
363 Some(down)
364 }
365 _ => None,
366 };
367 Ran { passed, cleaned_up }
368}
369
370fn open<'a>(runner: &'a Runner, project: &Path) -> Result<isothrum_runner::Running<'a>, Failure> {
372 super::open(runner, project, RUN).map_err(Failure::Said)
373}
374
375async fn down(runner: &Runner, project: &Path, provider: Provider) -> Result<(), Failure> {
377 down_with(&open(runner, project)?, provider).await
378}
379
380async fn down_with(run: &isothrum_runner::Running<'_>, provider: Provider) -> Result<(), Failure> {
382 let opts = RunOptions::new().with_provider(provider);
383 run.down(&opts, &super::quiet).await.map_err(|e| Failure::Runner(Box::new(e.report())))
384}
385
386async fn clear_earlier(cx: &Context, runner: &Runner, project: &Path, dir: &Path, vm: &TestVm<'_>) -> Result<Vec<&'static str>, Failure> {
390 let recorded = isothrum_runner::RunName::new(RUN).ok().and_then(|name| runner.run_record(&name).ok().flatten());
391 if let Some(record) = recorded.filter(|r| r.state != isothrum_runner::RunState::Absent)
393 && let Some(provider) = record.provider
394 {
395 drop(down(runner, project, provider).await);
396 }
397 leftover::clear(cx, dir, vm).await
398}
399
400async fn remove_networks(cx: &Context, provider: Provider, before: &networks::Networks, progress: &(dyn Fn(StepProgress) + Send + Sync)) {
402 match networks::remove_made_since(cx, provider, before).await {
403 Ok(removed) if removed.is_empty() => {}
404 Ok(removed) => progress(Progress::Passed(Step::Networks, Found::NetworksRemoved(removed))),
405 Err(why) => progress(Progress::Failed(Step::Networks, Failure::Said(why))),
406 }
407}
408
409struct Test<'a> {
411 cx: &'a Context,
412 runner: &'a Runner,
413 project: &'a Path,
414 dir: &'a Path,
415 vm: &'a TestVm<'a>,
416 provider: Option<Provider>,
418 before: networks::Networks,
420 run: Option<isothrum_runner::Running<'a>>,
422}
423
424impl<'a> Test<'a> {
425 async fn steps(&mut self, choices: &dyn Choices, progress: &(dyn Fn(StepProgress) + Send + Sync)) -> Result<(), Failure> {
427 let cx = self.cx;
428 let step = super::Steps(progress);
429 step.run(Step::Vagrant, async {
430 let v = cx.read_ok("vagrant", &["--version"]).await.map_err(Failure::Said)?;
431 Ok(Found::Version(v.trim().to_owned()))
432 })
433 .await?;
434 let mut picked = None;
435 step.run(Step::Provider, async {
436 let p = choices.provider().await.map_err(Failure::Said)?;
437 picked = Some(p);
438 Ok(Found::Provider(p))
439 })
440 .await?;
441 let Some(provider) = picked else { return Ok(()) };
442 step.run(Step::Hypervisor, async {
443 if provider == Provider::Utm {
444 let ready = crate::providers::ready::utm(cx, crate::providers::ready::UTM_WAIT, &mut || {}).await;
445 return ready.map(|()| Found::Responds).map_err(|e| Failure::Said(e.to_string()));
446 }
447 let Some((program, args)) = responds(provider) else {
448 return Ok(Found::NothingToProbe);
449 };
450 answers(cx, &program, args).await.map(|()| Found::Responds).map_err(Failure::Said)
451 })
452 .await?;
453 self.before = networks::Networks::here(cx, provider).await;
454 let chosen = box_for(cx, provider).await;
455 let box_line = |l: String| progress(Progress::Passed(Step::Box, Found::Line(l)));
456 let mut name = "";
457 step.run(Step::Box, async {
458 let (chosen, _) = chosen.ok_or(Failure::NoTestBox {
459 hypervisor: provider.id(),
460 arch: cx.host.arch,
461 })?;
462 let held = choices.fetch_box(provider, chosen, &box_line).await.map_err(Failure::Said)?;
463 name = chosen;
464 Ok(Found::Box { name: chosen, held })
465 })
466 .await?;
467 let address = if has_private_network(provider) {
469 free_address(cx, provider).await
470 } else {
471 None
472 };
473 let written = std::fs::write(self.project.join("Vagrantfile"), vagrantfile(self.vm, provider, name, address, self.dir));
474 written.map_err(|e| Failure::Said(format!("{} couldn't be written: {e}", self.project.display())))?;
475 self.provider = Some(provider);
476 self.boot_and_exec(provider, name, progress).await?;
477 network(cx, provider, address, progress).await
478 }
479
480 async fn boot_and_exec(&mut self, provider: Provider, name: &'static str, progress: &(dyn Fn(StepProgress) + Send + Sync)) -> Result<(), Failure> {
483 let step = super::Steps(progress);
484 let run: &isothrum_runner::Running<'a> = self.run.insert(open(self.runner, self.project)?.sharing_elevation());
485 let opts = RunOptions::new().with_provider(provider);
486 let boot_line = |e: &isothrum_runner::Event| {
487 if let isothrum_runner::EventKind::Log { line, .. } = &e.kind {
488 progress(Progress::Passed(Step::Boot, Found::Line(line.clone())));
489 }
490 };
491 let up = Box::pin(async {
492 run.up(&opts, &boot_line)
493 .await
494 .map(|_| Found::Booted { name, provider })
495 .map_err(|e| Failure::Runner(Box::new(e.report())))
496 });
497 step.run(Step::Boot, up).await?;
498 step.run(Step::Exec, async {
499 let argv = ["uname", "-srm"].map(str::to_owned);
500 let ran = run
501 .exec("default", &argv, &opts, &super::quiet)
502 .await
503 .map_err(|e| Failure::Runner(Box::new(e.report())))?;
504 Ok(Found::Uname(uname_line(&ran.stdout)))
505 })
506 .await
507 }
508}
509
510async fn network(cx: &Context, provider: Provider, address: Option<&'static str>, progress: &(dyn Fn(StepProgress) + Send + Sync)) -> Result<(), Failure> {
512 let Some(address) = address else {
513 let why = if has_private_network(provider) {
514 Found::AddressesTaken
515 } else {
516 Found::NoPrivateNetwork(provider)
517 };
518 progress(Progress::Skipped(Step::Network, why));
519 return Ok(());
520 };
521 super::Steps(progress)
522 .run(Step::Network, async {
523 let mut last = String::new();
524 for _ in 0..PING_TRIES {
525 match ping_once(cx, address).await {
526 Ok(out) if ping::replied(&out) => return Ok(Found::Reached { address }),
527 Ok(out) => out
528 .lines()
529 .map(str::trim)
530 .filter(|l| !l.is_empty())
531 .nth(1)
532 .unwrap_or("no reply")
533 .clone_into(&mut last),
534 Err(e) => last = e,
535 }
536 tokio::time::sleep(PING_GAP).await;
537 }
538 Err(Failure::NoReply { address, last })
539 })
540 .await
541}
542
543fn uname_line(out: &str) -> String {
545 out.lines().map(str::trim).find(|l| !l.is_empty()).unwrap_or_default().to_owned()
546}
547
548#[cfg(test)]
549mod tests;