isothrum_machine/selftest/server.rs
1//! The server self-test: a throwaway VM on a server, run through a runner of its own. It checks
2//! the server answers, writes the test's own project (a Terraform module on Proxmox VE, a
3//! Vagrantfile for Vagrant's `vmware_esxi` on ESXi), takes down what an earlier test left, brings
4//! the VM up step by step as the tool's lines end each, waits for it to accept SSH, runs a command
5//! inside, and always takes it down.
6//!
7//! The runner's home and the project are in the test's folder, which the caller keeps from one
8//! test to the next: the runner's record of the run is how a VM an interrupted test left is found
9//! and removed first, and its Terraform plugin cache is reused.
10//!
11//! - [`Proxmox`]: the VM on the server's bridge (DHCP), a second card on a network of the test's
12//! own, the guest agent reporting its address; signed in to over SSH with the caller's key or
13//! the test runner's own, through the caller's jump host when only it reaches the bridge.
14//! - [`Esxi`]: the VM uploaded from a Vagrant box by the `vagrant-vmware-esxi` plugin and the OVF
15//! Tool, on the host's port group.
16
17mod course;
18mod esxi;
19mod proxmox;
20
21use std::path::Path;
22use std::time::Duration;
23
24use isothrum_runner::{ErrorReport, RunName, RunOptions, RunState, Runner};
25
26#[cfg(test)]
27use course::Deployment;
28use course::{Course, OnRunner, test};
29#[cfg(test)]
30use isothrum_runner::BoxFuture;
31
32pub use esxi::Esxi;
33pub use proxmox::{Key, Proxmox, SignIn};
34
35use super::hypervisor::TestVm;
36use super::{Progress, throwaway};
37use crate::Context;
38
39/// The run's name in the test's own runner.
40const RUN: &str = "server-selftest";
41/// How long the server has to answer on its port.
42const HOST_WAIT: Duration = Duration::from_secs(30);
43/// How long the VM has, once up, to accept SSH.
44const SSH_WAIT: Duration = Duration::from_secs(300);
45/// The gap between two tries of a port or of SSH.
46const RETRY: Duration = Duration::from_secs(3);
47/// How long one try to open a port may take.
48const CONNECT_LIMIT: Duration = Duration::from_secs(4);
49
50/// The server the test runs on.
51#[derive(Debug, Clone)]
52#[non_exhaustive]
53pub enum Server {
54 /// A Proxmox VE server, through its API (Terraform's `bpg/proxmox`); boxed, being by far the
55 /// larger.
56 Proxmox(Box<Proxmox>),
57 /// An ESXi host, from this computer (Vagrant's `vmware_esxi`).
58 Esxi(Esxi),
59}
60
61impl Server {
62 /// Where the server answers (`host:port`): its API's port on Proxmox VE, its SSH port on ESXi.
63 #[must_use]
64 pub fn address(&self) -> String {
65 match self {
66 Server::Proxmox(p) => p.api_address(),
67 Server::Esxi(e) => e.ssh_address(),
68 }
69 }
70}
71
72/// A step of the server self-test.
73#[derive(Debug, Clone, Copy, PartialEq, Eq)]
74#[non_exhaustive]
75pub enum Step {
76 /// The server answers on its port.
77 Host,
78 /// The test's project is written, and what an earlier test left is taken down.
79 Prepare,
80 /// The VM's image is on the server (Proxmox VE: the cloud image downloaded there; ESXi: the
81 /// box uploaded to the datastore).
82 Image,
83 /// The test's own network is made (Proxmox VE only).
84 Network,
85 /// The VM is created and started.
86 Vm,
87 /// The VM has an address on the server's network.
88 Address,
89 /// The VM accepts SSH.
90 Ssh,
91 /// A command runs inside it.
92 Exec,
93 /// Everything the test made is taken down.
94 Down,
95}
96
97/// What a step that passed found, or a line it printed while it runs.
98#[derive(Debug, Clone, PartialEq, Eq)]
99#[non_exhaustive]
100pub enum Found {
101 /// Nothing to say.
102 Nothing,
103 /// The server answered at this address (`host:port`).
104 Answers(String),
105 /// What an earlier test left is being taken down (said while [`Step::Prepare`] runs).
106 Removing,
107 /// The box the VM is built from, as Vagrant named it, and the architecture of its build.
108 Box {
109 /// Its name.
110 name: String,
111 /// Its version, when said.
112 version: Option<String>,
113 /// The architecture of its build, when known (several, `or`-joined, when the box store
114 /// holds several and none was named).
115 arch: Option<String>,
116 },
117 /// A line the step's tool printed while it runs, with how many bytes the step moves when
118 /// known (the box the OVF Tool uploads).
119 Line {
120 /// The line.
121 text: String,
122 /// The step's size.
123 bytes: Option<u64>,
124 },
125 /// What `uname -sm` printed inside.
126 Uname(String),
127}
128
129/// Why a step failed.
130#[derive(Debug, Clone, PartialEq, Eq)]
131#[non_exhaustive]
132pub enum Failure {
133 /// The server gave no answer at this address (`host:port`).
134 Unreachable(String),
135 /// What went wrong outside the runner (the project couldn't be written).
136 Said(String),
137 /// What an earlier test left couldn't be taken down: the runner's report.
138 Leftover(Box<ErrorReport>),
139 /// The server couldn't download the VM's image (Proxmox VE).
140 ImageDownload(Box<ErrorReport>),
141 /// A bridge the VM needs isn't on the server's node (Proxmox VE: the test's own network,
142 /// when the node doesn't load its SDN configuration).
143 NoBridge(Box<ErrorReport>),
144 /// A VM of the test's name is on the host already, which the test didn't make (ESXi).
145 NameTaken,
146 /// The OVF Tool couldn't upload the VM (ESXi): its last error line, else the runner's message.
147 Upload(String),
148 /// Vagrant couldn't get the box for the server's hypervisor (ESXi).
149 NoBox(Box<ErrorReport>),
150 /// The server couldn't power the VM on (ESXi).
151 PowerOn(Box<ErrorReport>),
152 /// The VM got no address on the server's network in time.
153 NoAddress(Box<ErrorReport>),
154 /// The VM didn't accept SSH in time: the last try's report.
155 NoSsh(Box<ErrorReport>),
156 /// The command inside ran and failed: its exit status and what it printed.
157 Command {
158 /// Its exit status.
159 exit: i32,
160 /// Its output.
161 output: String,
162 },
163 /// The runner's refusal or failure, as it reports it.
164 Runner(Box<ErrorReport>),
165}
166
167impl Failure {
168 /// The runner's report it holds, when it holds one.
169 #[must_use]
170 pub fn report(&self) -> Option<&ErrorReport> {
171 match self {
172 Failure::Leftover(r)
173 | Failure::ImageDownload(r)
174 | Failure::NoBridge(r)
175 | Failure::NoBox(r)
176 | Failure::PowerOn(r)
177 | Failure::NoAddress(r)
178 | Failure::NoSsh(r)
179 | Failure::Runner(r) => Some(r),
180 Failure::Unreachable(_) | Failure::Said(_) | Failure::NameTaken | Failure::Upload(_) | Failure::Command { .. } => None,
181 }
182 }
183}
184
185impl std::fmt::Display for Failure {
186 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
187 match self {
188 Failure::Unreachable(address) => write!(f, "no answer on {address}"),
189 Failure::Said(said) | Failure::Upload(said) => f.write_str(said),
190 Failure::NameTaken => f.write_str("a VM of the test's name is on the host already"),
191 Failure::Command { exit, output } => write!(f, "the command inside exited with {exit}: {}", output.trim()),
192 other => other.report().map_or(Ok(()), |r| r.fmt(f)),
193 }
194 }
195}
196
197/// A step's progress, as the test says it. [`Progress::Passed`] with [`Found::Line`] or
198/// [`Found::Removing`] is said while the step still runs.
199pub type StepProgress = Progress<Step, Found, Failure>;
200
201/// How the test went.
202#[derive(Debug)]
203#[non_exhaustive]
204pub struct Ran {
205 /// Whether every step passed; why not.
206 pub passed: Result<(), Failure>,
207 /// Whether what the test made was taken down; why not. None: it made nothing (the server
208 /// didn't answer, the project couldn't be written, an earlier test's VM couldn't be removed,
209 /// or `up` was refused before it acted, a tool it needs missing).
210 pub cleaned_up: Option<Result<(), Failure>>,
211}
212
213/// Runs the test on `server`, its runner's home and project in `dir` (the test's own folder,
214/// kept from one test to the next), its VM named `vm`, each step's progress said to `progress`.
215pub async fn run(cx: &Context, dir: &Path, server: &Server, vm: &TestVm<'_>, progress: &(dyn Fn(StepProgress) + Send + Sync)) -> Ran {
216 let step = super::Steps(progress);
217 let address = server.address();
218 let reached = step.run(Step::Host, async {
219 if answers(&address, HOST_WAIT).await {
220 Ok(Found::Answers(address.clone()))
221 } else {
222 Err(Failure::Unreachable(address.clone()))
223 }
224 });
225 if let Err(why) = reached.await {
226 return Ran {
227 passed: Err(why),
228 cleaned_up: None,
229 };
230 }
231 match server {
232 Server::Proxmox(p) => {
233 let (file, text) = proxmox::project();
234 Box::pin(on_runner(cx, dir, (file, &text), progress, async |runner: &Runner| {
235 proxmox::prepared(p, vm, runner).await
236 }))
237 .await
238 }
239 Server::Esxi(e) => {
240 let (file, text) = e.project(vm);
241 Box::pin(on_runner(cx, dir, (file, &text), progress, async |_: &Runner| {
242 Ok((e.options(), esxi::course(e)))
243 }))
244 .await
245 }
246 }
247}
248
249/// The test through a runner of its own in `dir`, its project `file` holding `text`; `ready`
250/// gives the run's options and how it comes up, once the runner is there.
251async fn on_runner<C: Course>(
252 cx: &Context,
253 dir: &Path,
254 (file, text): (&str, &str),
255 progress: &(dyn Fn(StepProgress) + Send + Sync),
256 ready: impl AsyncFnOnce(&Runner) -> Result<(RunOptions, C), String>,
257) -> Ran {
258 progress(Progress::Running(Step::Prepare));
259 let opened = async {
260 let (runner, project) = throwaway(cx, dir, file, text)?;
261 let (opts, course) = ready(&runner).await?;
262 Ok::<_, String>((runner, project, opts, course))
263 };
264 // Nothing is made yet: the preparation's failure ends the test.
265 let unprepared = |why: String| {
266 let why = Failure::Said(why);
267 progress(Progress::Failed(Step::Prepare, why.clone()));
268 Ran {
269 passed: Err(why),
270 cleaned_up: None,
271 }
272 };
273 let (runner, project, opts, course) = match opened.await {
274 Ok(opened) => opened,
275 Err(why) => return unprepared(why),
276 };
277 let run = match super::open(&runner, &project, RUN) {
278 Ok(run) => run,
279 Err(why) => return unprepared(why),
280 };
281 let left = RunName::new(RUN)
282 .ok()
283 .and_then(|name| runner.run_record(&name).ok().flatten())
284 .is_some_and(|r| r.state != RunState::Absent);
285 let deployment = OnRunner {
286 run,
287 opts,
288 machine: course.machine(),
289 };
290 Box::pin(test(&deployment, left, course, progress, SSH_WAIT)).await
291}
292
293/// Whether `address` (`host:port`) accepts a TCP connection within `within`, tried every
294/// [`RETRY`].
295async fn answers(address: &str, within: Duration) -> bool {
296 let deadline = tokio::time::Instant::now() + within;
297 loop {
298 if matches!(tokio::time::timeout(CONNECT_LIMIT, tokio::net::TcpStream::connect(address)).await, Ok(Ok(_))) {
299 return true;
300 }
301 if tokio::time::Instant::now() >= deadline {
302 return false;
303 }
304 tokio::time::sleep(RETRY).await;
305 }
306}
307
308#[cfg(test)]
309mod tests;