Skip to main content

isothrum_machine/selftest/
engine.rs

1//! The engine self-test: a throwaway two-container deployment, run through a runner of its own.
2//! It checks the engine answers, its test image is here (pulled when it isn't), the deployment
3//! starts, its containers reach each other by name on their network, and a port it publishes
4//! answers on this computer. The deployment is always taken down.
5
6use std::path::Path;
7use std::time::Duration;
8
9use isothrum_runner::{DownloadToAdopt, RunOptions, Runner};
10use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
11
12use super::{Progress, throwaway};
13use crate::Context;
14use crate::docker::{NoAnswer, daemon_info, docker};
15
16/// The test's image: small, with a shell, `wget` and `httpd`.
17pub const IMAGE: &str = "busybox:1.36";
18/// What the test's web server serves, so a reply is known to come from it.
19const MARKER: &str = "isothrum-selftest-ok";
20/// The run's name in the test's own runner.
21const RUN: &str = "engine-selftest";
22/// Tries, [`RETRY`] apart, for the web server to answer: `httpd` needs a moment.
23const ANSWER_TRIES: u32 = 10;
24const RETRY: Duration = Duration::from_millis(500);
25/// How long the test image's pull may take.
26const PULL_LIMIT: Duration = Duration::from_secs(300);
27/// How long a reply to the port's request may take.
28const REPLY_LIMIT: Duration = Duration::from_secs(3);
29
30/// A step of the engine self-test.
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32#[non_exhaustive]
33pub enum Step {
34    /// The engine answers.
35    Engine,
36    /// The test image is here, pulled when it wasn't.
37    Pull,
38    /// The test deployment starts.
39    Start,
40    /// Its containers reach each other by name.
41    Network,
42    /// A port it publishes answers on this computer.
43    Port,
44}
45
46/// What a step that passed found.
47#[derive(Debug, Clone, PartialEq, Eq)]
48#[non_exhaustive]
49pub enum Found {
50    /// The engine's version.
51    Version(String),
52    /// The test image: whether it was here already.
53    Image {
54        /// Here before the test (nothing pulled).
55        held: bool,
56    },
57    /// Nothing to say.
58    Nothing,
59    /// One container reached the other by name.
60    Reached,
61    /// Where the published port answered (`host:port`).
62    Address(String),
63}
64
65/// Why a step failed.
66#[derive(Debug, Clone, PartialEq, Eq)]
67#[non_exhaustive]
68pub enum Failure {
69    /// The engine gave no answer.
70    Engine(NoAnswer),
71    /// What the tool or the runner said.
72    Said(String),
73}
74
75impl std::fmt::Display for Failure {
76    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
77        match self {
78            Failure::Engine(why) => why.fmt(f),
79            Failure::Said(said) => f.write_str(said),
80        }
81    }
82}
83
84/// A step's progress, as the test says it.
85pub type StepProgress = Progress<Step, Found, Failure>;
86
87/// How the test went.
88#[derive(Debug)]
89#[non_exhaustive]
90pub struct Ran {
91    /// Whether every step passed; why not (the failed step's reason, or what kept the test from
92    /// starting).
93    pub passed: Result<(), Failure>,
94    /// Whether the test deployment was taken down; why not.
95    pub cleaned_up: Result<(), String>,
96    /// The test image as this test pulled it, when it did: for a caller that keeps a record of
97    /// its downloads.
98    pub pulled: Option<DownloadToAdopt>,
99}
100
101/// The test deployment: a web server on a loopback port serving its own host name, [`MARKER`]
102/// (`/hostname`), and a prober.
103fn compose_file() -> String {
104    format!(
105        r#"services:
106  web:
107    image: {IMAGE}
108    hostname: {MARKER}
109    command: ["httpd", "-f", "-p", "80", "-h", "/etc"]
110    ports: ["127.0.0.1::80"]
111  probe:
112    image: {IMAGE}
113    command: ["sleep", "300"]
114"#
115    )
116}
117
118/// The id `IMAGE` names on the engine `context` reaches; none when it holds no such image.
119async fn image_id(cx: &Context, context: Option<&str>) -> Option<String> {
120    let spec = docker(context, &["image", "inspect", "--format", "{{.Id}}", IMAGE]);
121    let out = cx.probe_within(cx.probe_timeout, &spec).await.ok()?.output().ok()?;
122    Some(out.trim().to_owned()).filter(|id| !id.is_empty())
123}
124
125/// Pulls the test image on the engine `context` reaches unless it is there: whether it was, and
126/// the image as pulled when it wasn't. Setup may call it ahead of the test, so the test finds the
127/// image there.
128///
129/// # Errors
130///
131/// The pull failed: what the engine said.
132pub async fn pull(cx: &Context, context: Option<&str>) -> Result<(bool, Option<DownloadToAdopt>), String> {
133    if image_id(cx, context).await.is_some() {
134        return Ok((true, None));
135    }
136    let spec = docker(context, &["pull", "--quiet", IMAGE]);
137    let pulled = cx.probe_within(PULL_LIMIT, &spec).await.map_err(|e| e.to_string())?;
138    pulled.output().map_err(|e| e.reason)?;
139    let image_id = image_id(cx, context).await;
140    Ok((
141        false,
142        Some(DownloadToAdopt::Image {
143            reference: IMAGE.to_owned(),
144            image_id,
145        }),
146    ))
147}
148
149/// Runs the test on the engine Docker context `context` reaches (the current one when none is
150/// named), its deployment in `dir` (the test's own folder: its runner's home and project are
151/// there), each step's progress said to `progress`.
152pub async fn run(cx: &Context, dir: &Path, context: Option<&str>, progress: &(dyn Fn(StepProgress) + Send + Sync)) -> Ran {
153    let mut pulled = None;
154    let made = throwaway(cx, dir, "compose.yaml", &compose_file());
155    let (runner, project) = match made {
156        Ok(test) => test,
157        Err(e) => {
158            return Ran {
159                passed: Err(Failure::Said(e)),
160                cleaned_up: Ok(()),
161                pulled,
162            };
163        }
164    };
165    let opts = context.map_or_else(RunOptions::new, |c| RunOptions::new().with_docker_context(c));
166    let test = Test {
167        cx,
168        runner: &runner,
169        project: &project,
170        context,
171        opts: &opts,
172    };
173    let passed = Box::pin(steps(&test, &mut pulled, progress)).await;
174    let cleaned_up = match super::open(&runner, &project, RUN) {
175        Ok(run) => run.down(&opts, &super::quiet).await.map_err(|e| e.to_string()),
176        Err(e) => Err(e),
177    };
178    Ran { passed, cleaned_up, pulled }
179}
180
181/// What the steps work on: the engine, the test's runner, its project and options.
182struct Test<'a> {
183    cx: &'a Context,
184    runner: &'a Runner,
185    project: &'a Path,
186    context: Option<&'a str>,
187    opts: &'a RunOptions,
188}
189
190/// The steps, in order: the first that fails ends the test.
191async fn steps(test: &Test<'_>, pulled: &mut Option<DownloadToAdopt>, progress: &(dyn Fn(StepProgress) + Send + Sync)) -> Result<(), Failure> {
192    let Test {
193        cx,
194        runner,
195        project,
196        context,
197        opts,
198    } = *test;
199    let step = super::Steps(progress);
200    step.run(Step::Engine, async {
201        daemon_info(cx, "{{.ServerVersion}}", context)
202            .await
203            .map(|v| Found::Version(v.trim().to_owned()))
204            .map_err(Failure::Engine)
205    })
206    .await?;
207    step.run(Step::Pull, async {
208        let (held, image) = pull(cx, context).await.map_err(Failure::Said)?;
209        *pulled = image;
210        Ok(Found::Image { held })
211    })
212    .await?;
213    let run = super::open(runner, project, RUN).map_err(Failure::Said)?;
214    let up = Box::pin(async {
215        run.up(opts, &super::quiet)
216            .await
217            .map(|_| Found::Nothing)
218            .map_err(|e| Failure::Said(e.to_string()))
219    });
220    step.run(Step::Start, up).await?;
221    step.run(Step::Network, async { reach_by_name(&run, opts).await.map_err(Failure::Said) })
222        .await?;
223    step.run(Step::Port, async { reach_port(&run, opts).await.map_err(Failure::Said) }).await?;
224    Ok(())
225}
226
227/// The prober reaches the web server by name, on the deployment's network.
228async fn reach_by_name(run: &isothrum_runner::Running<'_>, opts: &RunOptions) -> Result<Found, String> {
229    let argv = ["wget", "-qO-", "-T", "2", "http://web/hostname"].map(str::to_owned);
230    let mut last = String::new();
231    for _ in 0..ANSWER_TRIES {
232        match run.exec("probe", &argv, opts, &super::quiet).await {
233            Ok(ran) if ran.stdout.contains(MARKER) => return Ok(Found::Reached),
234            Ok(ran) => format!("{} {}", ran.stdout.trim(), ran.stderr.trim()).trim().clone_into(&mut last),
235            Err(e) => last = e.to_string(),
236        }
237        tokio::time::sleep(RETRY).await;
238    }
239    Err(format!("probe could not reach web: {last}"))
240}
241
242/// The web server's published port answers on this computer's loopback.
243async fn reach_port(run: &isothrum_runner::Running<'_>, opts: &RunOptions) -> Result<Found, String> {
244    let status = run.status_with(opts).await.map_err(|e| e.to_string())?;
245    let port = status
246        .machines
247        .iter()
248        .find(|m| m.name == "web")
249        .and_then(|m| m.published.first())
250        .map(|p| p.host_port.get());
251    let address = format!("127.0.0.1:{}", port.ok_or("web publishes no port")?);
252    let mut last = String::new();
253    for _ in 0..ANSWER_TRIES {
254        match get(&address).await {
255            Ok(body) if body.contains(MARKER) => return Ok(Found::Address(address)),
256            Ok(body) => last = body,
257            Err(e) => last = e,
258        }
259        tokio::time::sleep(RETRY).await;
260    }
261    Err(format!("http://{address} did not answer: {last}"))
262}
263
264/// What `GET /hostname` on `address` answers, within [`REPLY_LIMIT`].
265async fn get(address: &str) -> Result<String, String> {
266    let ask = async {
267        let mut stream = tokio::net::TcpStream::connect(address).await?;
268        stream.write_all(b"GET /hostname HTTP/1.0\r\nHost: localhost\r\n\r\n").await?;
269        let mut reply = Vec::new();
270        stream.read_to_end(&mut reply).await?;
271        Ok::<_, std::io::Error>(String::from_utf8_lossy(&reply).into_owned())
272    };
273    match tokio::time::timeout(REPLY_LIMIT, ask).await {
274        Ok(Ok(reply)) => Ok(reply),
275        Ok(Err(e)) => Err(e.to_string()),
276        Err(_) => Err(format!("no reply within {}s", REPLY_LIMIT.as_secs())),
277    }
278}
279
280#[cfg(test)]
281mod tests;