1use 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#[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 DockerDesktop,
32 Orbstack,
34 Colima,
36 RancherDesktop,
38 Podman,
40 #[serde(rename = "docker-engine")]
42 Native,
43}
44
45impl Engine {
46 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 #[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 #[must_use]
71 pub fn from_id(id: &str) -> Option<Engine> {
72 Engine::ALL.into_iter().find(|e| e.id() == id)
73 }
74
75 #[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 #[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#[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 pub engine: Engine,
110 pub context: String,
112 pub running: bool,
114 pub current: bool,
116}
117
118#[derive(Clone, Debug, PartialEq, Eq)]
120#[non_exhaustive]
121pub enum NoAnswer {
122 NoCli,
124 Denied(String),
127 Down(String),
129 Empty(String),
131}
132
133impl NoAnswer {
134 #[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#[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
165pub(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
171fn 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
179async 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
198fn 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
208fn answered(info: &str) -> Option<&str> {
211 Some(info.trim()).filter(|out| !out.is_empty())
212}
213
214pub 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
232pub async fn daemon_os(cx: &Context) -> Result<String, NoAnswer> {
239 daemon_info(cx, "{{.OperatingSystem}}", None).await
240}
241
242pub 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
249fn 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
267fn 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
289async 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
299fn 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
313pub 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#[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#[derive(Clone, Debug, PartialEq, Eq)]
354#[non_exhaustive]
355pub enum ContextError {
356 Unlisted(NoAnswer),
358 None(Engine),
360 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
376pub 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
390pub 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;