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`]).
181async fn ask(cx: &Context, limit: Duration, spec: &ProcessSpec) -> Result<String, NoAnswer> {
182    let missing = |answer: &Result<Captured, Unanswered>| matches!(answer, Err(Unanswered::NotStarted(isothrum_runner::ProcessError::Missing { .. })));
183    let mut answer = cx.probe_within(limit, spec).await;
184    if missing(&answer)
185        && let Some(cli) = bundled_cli(cx)
186    {
187        let mut bundled = spec.clone();
188        bundled.program = cli;
189        answer = cx.probe_within(limit, &bundled).await;
190    }
191    match answer {
192        Ok(captured) => captured.output().map_err(|failed| failure(&captured, failed.reason)),
193        Err(Unanswered::NotStarted(isothrum_runner::ProcessError::Missing { .. })) => Err(NoAnswer::NoCli),
194        Err(e) => Err(NoAnswer::Down(e.to_string())),
195    }
196}
197
198/// A failed call's reason as a [`NoAnswer`]: refused to this account, else not answering.
199fn failure(captured: &Captured, reason: String) -> NoAnswer {
200    let said = captured.stdout.iter().chain(&captured.stderr_tail).cloned().collect::<Vec<_>>().join("\n");
201    if says_denied(&said) {
202        NoAnswer::Denied(reason)
203    } else {
204        NoAnswer::Down(reason)
205    }
206}
207
208/// A daemon's `docker info` answer, when it gave one: Docker 26 and older print an empty line
209/// (and exit 0) when the daemon doesn't answer.
210fn answered(info: &str) -> Option<&str> {
211    Some(info.trim()).filter(|out| !out.is_empty())
212}
213
214/// `docker info --format <field>` (`{{.ServerVersion}}`, say), of the daemon `context` reaches
215/// (the current one when `None`): the daemon answers this account. Docker 26 and older (Debian's
216/// `docker.io`) exit 0 from `docker info` when the daemon doesn't answer, saying so on standard
217/// error alone with an empty line on standard output: an empty answer is asked again of `docker
218/// version`, which fails with the reason (not running, or refused to this account).
219///
220/// # Errors
221///
222/// [`NoAnswer`]: why the daemon gave none.
223pub async fn daemon_info(cx: &Context, field: &str, context: Option<&str>) -> Result<String, NoAnswer> {
224    let out = ask(cx, cx.probe_timeout, &docker(context, &["info", "--format", field])).await?;
225    if answered(&out).is_some() {
226        return Ok(out);
227    }
228    ask(cx, cx.probe_timeout, &docker(context, &["version", "--format", "{{.Server.Os}}"])).await?;
229    Err(NoAnswer::Empty(field.to_owned()))
230}
231
232/// The current daemon's operating system line (`docker info`'s `{{.OperatingSystem}}`): it
233/// answers this account.
234///
235/// # Errors
236///
237/// [`NoAnswer`]: why the daemon gave none.
238pub async fn daemon_os(cx: &Context) -> Result<String, NoAnswer> {
239    daemon_info(cx, "{{.OperatingSystem}}", None).await
240}
241
242/// The engine running, from its daemon's operating system line (`daemon_os`) and the CLI's
243/// current context.
244pub async fn engine_in_use(cx: &Context, daemon_os: &str) -> Engine {
245    let context = ask(cx, cx.probe_timeout, &docker(None, &["context", "show"])).await.unwrap_or_default();
246    engine_named(daemon_os.trim(), &context)
247}
248
249/// The engine a daemon's operating system line and the CLI's current context point to.
250fn engine_named(os: &str, context: &str) -> Engine {
251    let (os, context) = (os.to_lowercase(), context.to_lowercase());
252    if os.contains("orbstack") || context.contains("orbstack") {
253        Engine::Orbstack
254    } else if context.contains("colima") {
255        Engine::Colima
256    } else if os.contains("rancher") || context.contains("rancher") {
257        Engine::RancherDesktop
258    } else if os.contains("podman") || context.contains("podman") {
259        Engine::Podman
260    } else if os.contains("docker desktop") || context.starts_with("desktop-") {
261        Engine::DockerDesktop
262    } else {
263        Engine::Native
264    }
265}
266
267/// The engine behind a Docker CLI context, by the names the engines give their contexts.
268/// `default` only counts on Linux, where it is the native daemon; elsewhere its socket is a link
269/// to whichever desktop app installed it, so it says nothing on its own.
270fn context_engine(name: &str, os: HostOs) -> Option<Engine> {
271    let n = name.to_lowercase();
272    if n == "orbstack" {
273        Some(Engine::Orbstack)
274    } else if n.starts_with("desktop-") {
275        Some(Engine::DockerDesktop)
276    } else if n == "colima" || n.starts_with("colima-") {
277        Some(Engine::Colima)
278    } else if n == "rancher-desktop" {
279        Some(Engine::RancherDesktop)
280    } else if n.starts_with("podman") {
281        Some(Engine::Podman)
282    } else if n == "default" && os == HostOs::Linux {
283        Some(Engine::Native)
284    } else {
285        None
286    }
287}
288
289/// The Docker CLI contexts: each name, and whether it is the current one.
290///
291/// # Errors
292///
293/// Why `docker context ls` failed.
294async fn contexts(cx: &Context) -> Result<Vec<(String, bool)>, NoAnswer> {
295    let listed = ask(cx, cx.probe_timeout, &docker(None, &["context", "ls", "--format", "{{.Name}}\t{{.Current}}"])).await?;
296    Ok(contexts_from(&listed))
297}
298
299/// `docker context ls` lines: the name, then whether it is current (`true`, or a trailing `*` as
300/// the table view marks it).
301fn contexts_from(listing: &str) -> Vec<(String, bool)> {
302    listing
303        .lines()
304        .filter_map(|l| {
305            let mut words = l.split_whitespace();
306            let name = words.next()?.to_owned();
307            let current = words.any(|w| w == "true" || w == "*");
308            Some((name, current))
309        })
310        .collect()
311}
312
313/// Every engine this computer has, one per context that names one or answers: probed one by one
314/// with `docker --context <c> info`, given as long as any probe ([`Context::probe_timeout`], as
315/// [`daemon_os`]): a stopped engine fails fast, and one waking up (Docker Desktop's Resource
316/// Saver, a cold CLI on Windows) answers within it. A context that answers names its engine from the daemon's operating system
317/// too, so `default` on a Mac reads as the desktop app behind it; one that doesn't is known by its
318/// name alone. Two contexts to one engine keep the first (the current one first of all). None
319/// when the contexts can't be listed (no Docker CLI).
320pub async fn engines(cx: &Context) -> Vec<EngineStatus> {
321    let mut listed = contexts(cx).await.unwrap_or_default();
322    listed.sort_by_key(|(_, current)| !current);
323    let mut found: Vec<EngineStatus> = Vec::new();
324    for (name, current) in listed {
325        let info = docker(Some(&name), &["info", "--format", "{{.OperatingSystem}}"]);
326        let answer = ask(cx, cx.probe_timeout, &info).await.ok().and_then(|os| answered(&os).map(str::to_owned));
327        let engine = match &answer {
328            Some(daemon_os) => engine_named(daemon_os, &name),
329            None => match context_engine(&name, cx.host.os) {
330                Some(engine) => engine,
331                None => continue,
332            },
333        };
334        if !found.iter().any(|f| f.engine == engine) {
335            found.push(EngineStatus {
336                engine,
337                context: name,
338                running: answer.is_some(),
339                current,
340            });
341        }
342    }
343    found
344}
345
346/// The engines whose daemon answers.
347#[must_use]
348pub fn running_of(engines: &[EngineStatus]) -> Vec<Engine> {
349    engines.iter().filter(|e| e.running).map(|e| e.engine).collect()
350}
351
352/// Why an engine's context couldn't be found or used.
353#[derive(Clone, Debug, PartialEq, Eq)]
354#[non_exhaustive]
355pub enum ContextError {
356    /// The contexts couldn't be listed: why.
357    Unlisted(NoAnswer),
358    /// No context on this computer names the engine.
359    None(Engine),
360    /// `docker context use` failed: why.
361    Unused(NoAnswer),
362}
363
364impl std::fmt::Display for ContextError {
365    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
366        match self {
367            ContextError::Unlisted(why) => write!(f, "the Docker contexts couldn't be listed: {why}"),
368            ContextError::None(engine) => write!(f, "no Docker context for {}", engine.id()),
369            ContextError::Unused(why) => write!(f, "docker context use failed: {why}"),
370        }
371    }
372}
373
374impl std::error::Error for ContextError {}
375
376/// The Docker context behind `engine` on this computer, to run on it (`docker --context <name>`).
377///
378/// # Errors
379///
380/// [`ContextError::Unlisted`] when the contexts can't be listed, [`ContextError::None`] when no
381/// context names `engine`.
382pub async fn engine_context(cx: &Context, engine: Engine) -> Result<String, ContextError> {
383    let listed = contexts(cx).await.map_err(ContextError::Unlisted)?;
384    let mut named = listed
385        .into_iter()
386        .filter_map(|(name, _)| (context_engine(&name, cx.host.os) == Some(engine)).then_some(name));
387    named.next().ok_or(ContextError::None(engine))
388}
389
390/// Points the Docker CLI at `engine` (`docker context use`), as its user would in a terminal.
391///
392/// # Errors
393///
394/// [`engine_context`]'s, or [`ContextError::Unused`] when `docker context use` fails.
395pub async fn use_engine(cx: &Context, engine: Engine) -> Result<(), ContextError> {
396    let name = engine_context(cx, engine).await?;
397    ask(cx, cx.probe_timeout, &docker(None, &["context", "use", &name]))
398        .await
399        .map_err(ContextError::Unused)?;
400    Ok(())
401}
402
403#[cfg(test)]
404mod tests;