Skip to main content

isothrum_machine/
docker.rs

1//! The Docker-compatible engines this computer has: each CLI context with an engine behind it,
2//! whether its daemon answers, which one the CLI uses, and pointing the CLI at another
3//! (`docker context use`). Every call is the Docker CLI's, through the [`Context`]'s runner.
4//!
5//! A daemon that gives no answer says why ([`NoAnswer`]): no CLI, refused to this account (its
6//! socket's or named pipe's permission: joining a group helps, starting the engine doesn't),
7//! stopped, or an empty answer. An installed engine that doesn't answer is started as its user
8//! would start it ([`start_engine`]).
9
10use std::time::Duration;
11
12use isothrum_runner::{Captured, ProcessSpec};
13use serde::{Deserialize, Serialize};
14
15use crate::context::Context;
16use crate::exec::Unanswered;
17use crate::host::HostOs;
18
19mod agreement;
20mod start;
21
22pub use agreement::agreement_accepted;
23pub use start::{AGREEMENT_GRACE, DESKTOP_BACKEND_GRACE, START_POLL, START_TRIES, StartFailed, start_engine, start_steps};
24
25/// A Docker-compatible engine.
26#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
27#[cfg_attr(any(test, feature = "ts-rs"), derive(ts_rs::TS), ts(rename = "DockerEngine"))]
28#[serde(rename_all = "kebab-case")]
29pub enum Engine {
30    /// Docker Desktop.
31    DockerDesktop,
32    /// OrbStack.
33    Orbstack,
34    /// Colima.
35    Colima,
36    /// Rancher Desktop.
37    RancherDesktop,
38    /// Podman.
39    Podman,
40    /// Docker Engine, the native daemon on Linux.
41    #[serde(rename = "docker-engine")]
42    Native,
43}
44
45impl Engine {
46    /// Every engine.
47    pub const ALL: [Engine; 6] = [
48        Engine::DockerDesktop,
49        Engine::Orbstack,
50        Engine::Colima,
51        Engine::RancherDesktop,
52        Engine::Podman,
53        Engine::Native,
54    ];
55
56    /// Its id, its serde name (`docker-desktop`).
57    #[must_use]
58    pub fn id(self) -> &'static str {
59        match self {
60            Engine::DockerDesktop => "docker-desktop",
61            Engine::Orbstack => "orbstack",
62            Engine::Colima => "colima",
63            Engine::RancherDesktop => "rancher-desktop",
64            Engine::Podman => "podman",
65            Engine::Native => "docker-engine",
66        }
67    }
68
69    /// The engine with id `id` ([`Engine::id`]).
70    #[must_use]
71    pub fn from_id(id: &str) -> Option<Engine> {
72        Engine::ALL.into_iter().find(|e| e.id() == id)
73    }
74
75    /// Its name as its vendor writes it (`Docker Desktop`).
76    #[must_use]
77    pub fn label(self) -> &'static str {
78        match self {
79            Engine::DockerDesktop => "Docker Desktop",
80            Engine::Orbstack => "OrbStack",
81            Engine::Colima => "Colima",
82            Engine::RancherDesktop => "Rancher Desktop",
83            Engine::Podman => "Podman",
84            Engine::Native => "Docker Engine",
85        }
86    }
87
88    /// Where its vendor offers it.
89    #[must_use]
90    pub fn url(self) -> &'static str {
91        match self {
92            Engine::DockerDesktop => "https://www.docker.com/products/docker-desktop/",
93            Engine::Orbstack => "https://orbstack.dev/",
94            Engine::Colima => "https://github.com/abiosoft/colima",
95            Engine::RancherDesktop => "https://rancherdesktop.io/",
96            Engine::Podman => "https://podman.io/",
97            Engine::Native => "https://docs.docker.com/engine/install/",
98        }
99    }
100}
101
102/// One Docker-compatible engine found on this computer: the CLI context that reaches it, whether
103/// its daemon answers, and whether it is the CLI's current context.
104#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
105#[cfg_attr(any(test, feature = "ts-rs"), derive(ts_rs::TS))]
106#[serde(rename_all = "camelCase")]
107pub struct EngineStatus {
108    /// Which engine it is.
109    pub engine: Engine,
110    /// The CLI context that reaches it.
111    pub context: String,
112    /// Whether its daemon answers.
113    pub running: bool,
114    /// Whether its context is the CLI's current one.
115    pub current: bool,
116}
117
118/// Why the Docker daemon gave no answer.
119#[derive(Clone, Debug, PartialEq, Eq)]
120#[non_exhaustive]
121pub enum NoAnswer {
122    /// The Docker CLI isn't installed.
123    NoCli,
124    /// The daemon runs but refused this account: its socket (`permission denied … docker.sock`)
125    /// or its named pipe (`Access is denied`). What the CLI said.
126    Denied(String),
127    /// It doesn't answer (stopped, or ran out of the probe's time): why.
128    Down(String),
129    /// `docker info --format <field>` answered nothing, though the daemon answers.
130    Empty(String),
131}
132
133impl NoAnswer {
134    /// Whether the daemon refused this account ([`NoAnswer::Denied`]).
135    #[must_use]
136    pub fn denied(&self) -> bool {
137        matches!(self, NoAnswer::Denied(_))
138    }
139}
140
141impl std::fmt::Display for NoAnswer {
142    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
143        match self {
144            NoAnswer::NoCli => f.write_str("the Docker CLI isn't installed"),
145            NoAnswer::Denied(said) | NoAnswer::Down(said) => f.write_str(said),
146            NoAnswer::Empty(field) => write!(f, "docker info --format {field} answered nothing, though the Docker daemon answers"),
147        }
148    }
149}
150
151impl std::error::Error for NoAnswer {}
152
153/// Whether `said` (a failed `docker` call's) says the daemon refused this account: the socket's
154/// refusal on unix (`permission denied … docker.sock`, `… the docker API`, `… the Docker daemon
155/// socket`), or the named pipe's on Windows (`open //./pipe/dockerDesktopLinuxEngine: Access is
156/// denied.`).
157#[must_use]
158pub fn says_denied(said: &str) -> bool {
159    let s = said.to_lowercase();
160    let socket = s.contains("permission denied") && ["docker.sock", "docker api", "docker daemon"].iter().any(|w| s.contains(w));
161    let pipe = s.contains("access is denied") && s.contains("pipe");
162    socket || pipe
163}
164
165/// `docker [--context <context>] <args>`.
166pub(crate) fn docker(context: Option<&str>, args: &[&str]) -> ProcessSpec {
167    let on = context.map(|c| ["--context", c]).into_iter().flatten();
168    ProcessSpec::new("docker", on.chain(args.iter().copied()))
169}
170
171/// Docker Desktop's own `docker` CLI, inside its app bundle (macOS), when it is there: the one a
172/// call falls back on while `PATH` has none. Docker Desktop links it onto `PATH` only once its
173/// first start's setup is done, and until then its engine, started, is asked through this one.
174fn bundled_cli(cx: &Context) -> Option<String> {
175    let cli = cx.host.devices.applications.join("Docker.app/Contents/Resources/bin/docker");
176    (cx.host.os == HostOs::Macos && cli.is_file()).then(|| cli.display().to_string())
177}
178
179/// What `docker args` printed when it exited 0, else why the daemon gave no answer. With no
180/// `docker` on `PATH`, Docker Desktop's own CLI is asked, where it is ([`bundled_cli`]). A call
181/// that runs out of time is made once more: the first call of a cold CLI and daemon (a Windows
182/// Server's Docker Engine just after boot) can take longer than a probe, and warms them for the
183/// next.
184async fn ask(cx: &Context, limit: Duration, spec: &ProcessSpec) -> Result<String, NoAnswer> {
185    let missing = |answer: &Result<Captured, Unanswered>| matches!(answer, Err(Unanswered::NotStarted(isothrum_runner::ProcessError::Missing { .. })));
186    let mut spec = spec.clone();
187    let mut answer = cx.probe_within(limit, &spec).await;
188    if missing(&answer)
189        && let Some(cli) = bundled_cli(cx)
190    {
191        spec.program = cli;
192        answer = cx.probe_within(limit, &spec).await;
193    }
194    if matches!(answer, Err(Unanswered::TimedOut(_))) {
195        answer = cx.probe_within(limit, &spec).await;
196    }
197    match answer {
198        Ok(captured) => captured.output().map_err(|failed| failure(&captured, failed.reason)),
199        Err(Unanswered::NotStarted(isothrum_runner::ProcessError::Missing { .. })) => Err(NoAnswer::NoCli),
200        Err(e) => Err(NoAnswer::Down(e.to_string())),
201    }
202}
203
204/// A failed call's reason as a [`NoAnswer`]: refused to this account, else not answering.
205fn failure(captured: &Captured, reason: String) -> NoAnswer {
206    let said = captured.stdout.iter().chain(&captured.stderr_tail).cloned().collect::<Vec<_>>().join("\n");
207    if says_denied(&said) {
208        NoAnswer::Denied(reason)
209    } else {
210        NoAnswer::Down(reason)
211    }
212}
213
214/// A daemon's `docker info` answer, when it gave one: Docker 26 and older print an empty line
215/// (and exit 0) when the daemon doesn't answer.
216fn answered(info: &str) -> Option<&str> {
217    Some(info.trim()).filter(|out| !out.is_empty())
218}
219
220/// `docker info --format <field>` (`{{.ServerVersion}}`, say), of the daemon `context` reaches
221/// (the current one when `None`): the daemon answers this account. Docker 26 and older (Debian's
222/// `docker.io`) exit 0 from `docker info` when the daemon doesn't answer, saying so on standard
223/// error alone with an empty line on standard output: an empty answer is asked again of `docker
224/// version`, which fails with the reason (not running, or refused to this account).
225///
226/// # Errors
227///
228/// [`NoAnswer`]: why the daemon gave none.
229pub async fn daemon_info(cx: &Context, field: &str, context: Option<&str>) -> Result<String, NoAnswer> {
230    let out = ask(cx, cx.probe_timeout, &docker(context, &["info", "--format", field])).await?;
231    if answered(&out).is_some() {
232        return Ok(out);
233    }
234    ask(cx, cx.probe_timeout, &docker(context, &["version", "--format", "{{.Server.Os}}"])).await?;
235    Err(NoAnswer::Empty(field.to_owned()))
236}
237
238/// The current daemon's operating system line (`docker info`'s `{{.OperatingSystem}}`): it
239/// answers this account.
240///
241/// # Errors
242///
243/// [`NoAnswer`]: why the daemon gave none.
244pub async fn daemon_os(cx: &Context) -> Result<String, NoAnswer> {
245    daemon_info(cx, "{{.OperatingSystem}}", None).await
246}
247
248/// The engine running, from its daemon's operating system line (`daemon_os`) and the CLI's
249/// current context.
250pub async fn engine_in_use(cx: &Context, daemon_os: &str) -> Engine {
251    let context = ask(cx, cx.probe_timeout, &docker(None, &["context", "show"])).await.unwrap_or_default();
252    engine_named(daemon_os.trim(), &context)
253}
254
255/// The engine a daemon's operating system line and the CLI's current context point to.
256fn engine_named(os: &str, context: &str) -> Engine {
257    let (os, context) = (os.to_lowercase(), context.to_lowercase());
258    if os.contains("orbstack") || context.contains("orbstack") {
259        Engine::Orbstack
260    } else if context.contains("colima") {
261        Engine::Colima
262    } else if os.contains("rancher") || context.contains("rancher") {
263        Engine::RancherDesktop
264    } else if os.contains("podman") || context.contains("podman") {
265        Engine::Podman
266    } else if os.contains("docker desktop") || context.starts_with("desktop-") {
267        Engine::DockerDesktop
268    } else {
269        Engine::Native
270    }
271}
272
273/// The engine behind a Docker CLI context, by the names the engines give their contexts.
274/// `default` only counts on Linux, where it is the native daemon; elsewhere its socket is a link
275/// to whichever desktop app installed it, so it says nothing on its own.
276fn context_engine(name: &str, os: HostOs) -> Option<Engine> {
277    let n = name.to_lowercase();
278    if n == "orbstack" {
279        Some(Engine::Orbstack)
280    } else if n.starts_with("desktop-") {
281        Some(Engine::DockerDesktop)
282    } else if n == "colima" || n.starts_with("colima-") {
283        Some(Engine::Colima)
284    } else if n == "rancher-desktop" {
285        Some(Engine::RancherDesktop)
286    } else if n.starts_with("podman") {
287        Some(Engine::Podman)
288    } else if n == "default" && os == HostOs::Linux {
289        Some(Engine::Native)
290    } else {
291        None
292    }
293}
294
295/// The Docker CLI contexts: each name, and whether it is the current one.
296///
297/// # Errors
298///
299/// Why `docker context ls` failed.
300async fn contexts(cx: &Context) -> Result<Vec<(String, bool)>, NoAnswer> {
301    let listed = ask(cx, cx.probe_timeout, &docker(None, &["context", "ls", "--format", "{{.Name}}\t{{.Current}}"])).await?;
302    Ok(contexts_from(&listed))
303}
304
305/// `docker context ls` lines: the name, then whether it is current (`true`, or a trailing `*` as
306/// the table view marks it).
307fn contexts_from(listing: &str) -> Vec<(String, bool)> {
308    listing
309        .lines()
310        .filter_map(|l| {
311            let mut words = l.split_whitespace();
312            let name = words.next()?.to_owned();
313            let current = words.any(|w| w == "true" || w == "*");
314            Some((name, current))
315        })
316        .collect()
317}
318
319/// Every engine this computer has, one per context that names one or answers: probed one by one
320/// with `docker --context <c> info`, given as long as any probe ([`Context::probe_timeout`], as
321/// [`daemon_os`]): a stopped engine fails fast, and one waking up (Docker Desktop's Resource
322/// Saver, a cold CLI on Windows) answers within it. A context that answers names its engine from the daemon's operating system
323/// too, so `default` on a Mac reads as the desktop app behind it; one that doesn't is known by its
324/// name alone. Two contexts to one engine keep the first (the current one first of all). None
325/// when the contexts can't be listed (no Docker CLI).
326pub async fn engines(cx: &Context) -> Vec<EngineStatus> {
327    let mut listed = contexts(cx).await.unwrap_or_default();
328    listed.sort_by_key(|(_, current)| !current);
329    let mut found: Vec<EngineStatus> = Vec::new();
330    for (name, current) in listed {
331        let info = docker(Some(&name), &["info", "--format", "{{.OperatingSystem}}"]);
332        let answer = ask(cx, cx.probe_timeout, &info).await.ok().and_then(|os| answered(&os).map(str::to_owned));
333        let engine = match &answer {
334            Some(daemon_os) => engine_named(daemon_os, &name),
335            None => match context_engine(&name, cx.host.os) {
336                Some(engine) => engine,
337                None => continue,
338            },
339        };
340        if !found.iter().any(|f| f.engine == engine) {
341            found.push(EngineStatus {
342                engine,
343                context: name,
344                running: answer.is_some(),
345                current,
346            });
347        }
348    }
349    found
350}
351
352/// The engines whose daemon answers.
353#[must_use]
354pub fn running_of(engines: &[EngineStatus]) -> Vec<Engine> {
355    engines.iter().filter(|e| e.running).map(|e| e.engine).collect()
356}
357
358/// Why an engine's context couldn't be found or used.
359#[derive(Clone, Debug, PartialEq, Eq)]
360#[non_exhaustive]
361pub enum ContextError {
362    /// The contexts couldn't be listed: why.
363    Unlisted(NoAnswer),
364    /// No context on this computer names the engine.
365    None(Engine),
366    /// `docker context use` failed: why.
367    Unused(NoAnswer),
368}
369
370impl std::fmt::Display for ContextError {
371    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
372        match self {
373            ContextError::Unlisted(why) => write!(f, "the Docker contexts couldn't be listed: {why}"),
374            ContextError::None(engine) => write!(f, "no Docker context for {}", engine.id()),
375            ContextError::Unused(why) => write!(f, "docker context use failed: {why}"),
376        }
377    }
378}
379
380impl std::error::Error for ContextError {}
381
382/// The Docker context behind `engine` on this computer, to run on it (`docker --context <name>`).
383///
384/// # Errors
385///
386/// [`ContextError::Unlisted`] when the contexts can't be listed, [`ContextError::None`] when no
387/// context names `engine`.
388pub async fn engine_context(cx: &Context, engine: Engine) -> Result<String, ContextError> {
389    let listed = contexts(cx).await.map_err(ContextError::Unlisted)?;
390    let mut named = listed
391        .into_iter()
392        .filter_map(|(name, _)| (context_engine(&name, cx.host.os) == Some(engine)).then_some(name));
393    named.next().ok_or(ContextError::None(engine))
394}
395
396/// Points the Docker CLI at `engine` (`docker context use`), as its user would in a terminal.
397///
398/// # Errors
399///
400/// [`engine_context`]'s, or [`ContextError::Unused`] when `docker context use` fails.
401pub async fn use_engine(cx: &Context, engine: Engine) -> Result<(), ContextError> {
402    let name = engine_context(cx, engine).await?;
403    ask(cx, cx.probe_timeout, &docker(None, &["context", "use", &name]))
404        .await
405        .map_err(ContextError::Unused)?;
406    Ok(())
407}
408
409#[cfg(test)]
410mod tests;