use std::time::Duration;
use isothrum_runner::{Captured, ProcessSpec};
use serde::{Deserialize, Serialize};
use crate::context::Context;
use crate::exec::Unanswered;
use crate::host::HostOs;
mod agreement;
mod start;
pub use agreement::agreement_accepted;
pub use start::{AGREEMENT_GRACE, DESKTOP_BACKEND_GRACE, START_POLL, START_TRIES, StartFailed, start_engine, start_steps};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(any(test, feature = "ts-rs"), derive(ts_rs::TS), ts(rename = "DockerEngine"))]
#[serde(rename_all = "kebab-case")]
pub enum Engine {
DockerDesktop,
Orbstack,
Colima,
RancherDesktop,
Podman,
#[serde(rename = "docker-engine")]
Native,
}
impl Engine {
pub const ALL: [Engine; 6] = [
Engine::DockerDesktop,
Engine::Orbstack,
Engine::Colima,
Engine::RancherDesktop,
Engine::Podman,
Engine::Native,
];
#[must_use]
pub fn id(self) -> &'static str {
match self {
Engine::DockerDesktop => "docker-desktop",
Engine::Orbstack => "orbstack",
Engine::Colima => "colima",
Engine::RancherDesktop => "rancher-desktop",
Engine::Podman => "podman",
Engine::Native => "docker-engine",
}
}
#[must_use]
pub fn from_id(id: &str) -> Option<Engine> {
Engine::ALL.into_iter().find(|e| e.id() == id)
}
#[must_use]
pub fn label(self) -> &'static str {
match self {
Engine::DockerDesktop => "Docker Desktop",
Engine::Orbstack => "OrbStack",
Engine::Colima => "Colima",
Engine::RancherDesktop => "Rancher Desktop",
Engine::Podman => "Podman",
Engine::Native => "Docker Engine",
}
}
#[must_use]
pub fn url(self) -> &'static str {
match self {
Engine::DockerDesktop => "https://www.docker.com/products/docker-desktop/",
Engine::Orbstack => "https://orbstack.dev/",
Engine::Colima => "https://github.com/abiosoft/colima",
Engine::RancherDesktop => "https://rancherdesktop.io/",
Engine::Podman => "https://podman.io/",
Engine::Native => "https://docs.docker.com/engine/install/",
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(any(test, feature = "ts-rs"), derive(ts_rs::TS))]
#[serde(rename_all = "camelCase")]
pub struct EngineStatus {
pub engine: Engine,
pub context: String,
pub running: bool,
pub current: bool,
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum NoAnswer {
NoCli,
Denied(String),
Down(String),
Empty(String),
}
impl NoAnswer {
#[must_use]
pub fn denied(&self) -> bool {
matches!(self, NoAnswer::Denied(_))
}
}
impl std::fmt::Display for NoAnswer {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
NoAnswer::NoCli => f.write_str("the Docker CLI isn't installed"),
NoAnswer::Denied(said) | NoAnswer::Down(said) => f.write_str(said),
NoAnswer::Empty(field) => write!(f, "docker info --format {field} answered nothing, though the Docker daemon answers"),
}
}
}
impl std::error::Error for NoAnswer {}
#[must_use]
pub fn says_denied(said: &str) -> bool {
let s = said.to_lowercase();
let socket = s.contains("permission denied") && ["docker.sock", "docker api", "docker daemon"].iter().any(|w| s.contains(w));
let pipe = s.contains("access is denied") && s.contains("pipe");
socket || pipe
}
pub(crate) fn docker(context: Option<&str>, args: &[&str]) -> ProcessSpec {
let on = context.map(|c| ["--context", c]).into_iter().flatten();
ProcessSpec::new("docker", on.chain(args.iter().copied()))
}
fn bundled_cli(cx: &Context) -> Option<String> {
let cli = cx.host.devices.applications.join("Docker.app/Contents/Resources/bin/docker");
(cx.host.os == HostOs::Macos && cli.is_file()).then(|| cli.display().to_string())
}
async fn ask(cx: &Context, limit: Duration, spec: &ProcessSpec) -> Result<String, NoAnswer> {
let missing = |answer: &Result<Captured, Unanswered>| matches!(answer, Err(Unanswered::NotStarted(isothrum_runner::ProcessError::Missing { .. })));
let mut spec = spec.clone();
let mut answer = cx.probe_within(limit, &spec).await;
if missing(&answer)
&& let Some(cli) = bundled_cli(cx)
{
spec.program = cli;
answer = cx.probe_within(limit, &spec).await;
}
if matches!(answer, Err(Unanswered::TimedOut(_))) {
answer = cx.probe_within(limit, &spec).await;
}
match answer {
Ok(captured) => captured.output().map_err(|failed| failure(&captured, failed.reason)),
Err(Unanswered::NotStarted(isothrum_runner::ProcessError::Missing { .. })) => Err(NoAnswer::NoCli),
Err(e) => Err(NoAnswer::Down(e.to_string())),
}
}
fn failure(captured: &Captured, reason: String) -> NoAnswer {
let said = captured.stdout.iter().chain(&captured.stderr_tail).cloned().collect::<Vec<_>>().join("\n");
if says_denied(&said) {
NoAnswer::Denied(reason)
} else {
NoAnswer::Down(reason)
}
}
fn answered(info: &str) -> Option<&str> {
Some(info.trim()).filter(|out| !out.is_empty())
}
pub async fn daemon_info(cx: &Context, field: &str, context: Option<&str>) -> Result<String, NoAnswer> {
let out = ask(cx, cx.probe_timeout, &docker(context, &["info", "--format", field])).await?;
if answered(&out).is_some() {
return Ok(out);
}
ask(cx, cx.probe_timeout, &docker(context, &["version", "--format", "{{.Server.Os}}"])).await?;
Err(NoAnswer::Empty(field.to_owned()))
}
pub async fn daemon_os(cx: &Context) -> Result<String, NoAnswer> {
daemon_info(cx, "{{.OperatingSystem}}", None).await
}
pub async fn engine_in_use(cx: &Context, daemon_os: &str) -> Engine {
let context = ask(cx, cx.probe_timeout, &docker(None, &["context", "show"])).await.unwrap_or_default();
engine_named(daemon_os.trim(), &context)
}
fn engine_named(os: &str, context: &str) -> Engine {
let (os, context) = (os.to_lowercase(), context.to_lowercase());
if os.contains("orbstack") || context.contains("orbstack") {
Engine::Orbstack
} else if context.contains("colima") {
Engine::Colima
} else if os.contains("rancher") || context.contains("rancher") {
Engine::RancherDesktop
} else if os.contains("podman") || context.contains("podman") {
Engine::Podman
} else if os.contains("docker desktop") || context.starts_with("desktop-") {
Engine::DockerDesktop
} else {
Engine::Native
}
}
fn context_engine(name: &str, os: HostOs) -> Option<Engine> {
let n = name.to_lowercase();
if n == "orbstack" {
Some(Engine::Orbstack)
} else if n.starts_with("desktop-") {
Some(Engine::DockerDesktop)
} else if n == "colima" || n.starts_with("colima-") {
Some(Engine::Colima)
} else if n == "rancher-desktop" {
Some(Engine::RancherDesktop)
} else if n.starts_with("podman") {
Some(Engine::Podman)
} else if n == "default" && os == HostOs::Linux {
Some(Engine::Native)
} else {
None
}
}
async fn contexts(cx: &Context) -> Result<Vec<(String, bool)>, NoAnswer> {
let listed = ask(cx, cx.probe_timeout, &docker(None, &["context", "ls", "--format", "{{.Name}}\t{{.Current}}"])).await?;
Ok(contexts_from(&listed))
}
fn contexts_from(listing: &str) -> Vec<(String, bool)> {
listing
.lines()
.filter_map(|l| {
let mut words = l.split_whitespace();
let name = words.next()?.to_owned();
let current = words.any(|w| w == "true" || w == "*");
Some((name, current))
})
.collect()
}
pub async fn engines(cx: &Context) -> Vec<EngineStatus> {
let mut listed = contexts(cx).await.unwrap_or_default();
listed.sort_by_key(|(_, current)| !current);
let mut found: Vec<EngineStatus> = Vec::new();
for (name, current) in listed {
let info = docker(Some(&name), &["info", "--format", "{{.OperatingSystem}}"]);
let answer = ask(cx, cx.probe_timeout, &info).await.ok().and_then(|os| answered(&os).map(str::to_owned));
let engine = match &answer {
Some(daemon_os) => engine_named(daemon_os, &name),
None => match context_engine(&name, cx.host.os) {
Some(engine) => engine,
None => continue,
},
};
if !found.iter().any(|f| f.engine == engine) {
found.push(EngineStatus {
engine,
context: name,
running: answer.is_some(),
current,
});
}
}
found
}
#[must_use]
pub fn running_of(engines: &[EngineStatus]) -> Vec<Engine> {
engines.iter().filter(|e| e.running).map(|e| e.engine).collect()
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ContextError {
Unlisted(NoAnswer),
None(Engine),
Unused(NoAnswer),
}
impl std::fmt::Display for ContextError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ContextError::Unlisted(why) => write!(f, "the Docker contexts couldn't be listed: {why}"),
ContextError::None(engine) => write!(f, "no Docker context for {}", engine.id()),
ContextError::Unused(why) => write!(f, "docker context use failed: {why}"),
}
}
}
impl std::error::Error for ContextError {}
pub async fn engine_context(cx: &Context, engine: Engine) -> Result<String, ContextError> {
let listed = contexts(cx).await.map_err(ContextError::Unlisted)?;
let mut named = listed
.into_iter()
.filter_map(|(name, _)| (context_engine(&name, cx.host.os) == Some(engine)).then_some(name));
named.next().ok_or(ContextError::None(engine))
}
pub async fn use_engine(cx: &Context, engine: Engine) -> Result<(), ContextError> {
let name = engine_context(cx, engine).await?;
ask(cx, cx.probe_timeout, &docker(None, &["context", "use", &name]))
.await
.map_err(ContextError::Unused)?;
Ok(())
}
#[cfg(test)]
mod tests;