isothrum_machine/selftest/
engine.rs1use 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
16pub const IMAGE: &str = "busybox:1.36";
18const MARKER: &str = "isothrum-selftest-ok";
20const RUN: &str = "engine-selftest";
22const ANSWER_TRIES: u32 = 10;
24const RETRY: Duration = Duration::from_millis(500);
25const PULL_LIMIT: Duration = Duration::from_secs(300);
27const REPLY_LIMIT: Duration = Duration::from_secs(3);
29
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32#[non_exhaustive]
33pub enum Step {
34 Engine,
36 Pull,
38 Start,
40 Network,
42 Port,
44}
45
46#[derive(Debug, Clone, PartialEq, Eq)]
48#[non_exhaustive]
49pub enum Found {
50 Version(String),
52 Image {
54 held: bool,
56 },
57 Nothing,
59 Reached,
61 Address(String),
63}
64
65#[derive(Debug, Clone, PartialEq, Eq)]
67#[non_exhaustive]
68pub enum Failure {
69 Engine(NoAnswer),
71 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
84pub type StepProgress = Progress<Step, Found, Failure>;
86
87#[derive(Debug)]
89#[non_exhaustive]
90pub struct Ran {
91 pub passed: Result<(), Failure>,
94 pub cleaned_up: Result<(), String>,
96 pub pulled: Option<DownloadToAdopt>,
99}
100
101fn 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
118async 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
125pub 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
149pub 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
181struct 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
190async 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
227async 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
242async 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
264async 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;