Skip to main content

isothrum_machine/docker/
start.rs

1//! Starting an installed engine that doesn't answer ([`crate::setup::Action::StartEngine`]), the
2//! way its user would: its app opened (`open -a`, Docker Desktop's program on Windows), its CLI
3//! run (`colima start`), or Docker Engine's service started as root (`systemctl start docker`,
4//! through pkexec's prompt or unattended). Then the CLI is pointed at it and its daemon asked
5//! until it answers: Docker Desktop and OrbStack take a while on a first start.
6//!
7//! Docker Desktop shows Docker's Subscription Service Agreement at its first start, and its engine
8//! starts only once its user has accepted it there: nothing accepts it for them. Its settings
9//! saying it isn't accepted is said as soon as its window has had time to show
10//! ([`StartFailed::AgreementNotAccepted`], after [`AGREEMENT_GRACE`]); a Docker Desktop whose
11//! backend never comes up otherwise waits for its user in its window too (its first start's setup
12//! to finish: [`StartFailed::WaitingForUser`]). Either is said as soon as it is clear, not after
13//! the whole wait.
14
15use std::time::Duration;
16
17use super::{Engine, NoAnswer, daemon_info, daemon_os, engine_context, use_engine};
18use crate::context::Context;
19use crate::host::HostOs;
20use crate::install::Elevation;
21use crate::install::{Step, StepFailed, run_steps, step};
22
23/// How many times a started engine is asked whether it answers, [`START_POLL`] apart: three
24/// minutes in all.
25pub const START_TRIES: u32 = 90;
26
27/// How long between two of those asks.
28pub const START_POLL: Duration = Duration::from_secs(2);
29
30/// How long Docker Desktop, opened, is given to show its window before its agreement, not
31/// accepted yet, is said to wait for its user ([`StartFailed::AgreementNotAccepted`]).
32pub const AGREEMENT_GRACE: Duration = Duration::from_secs(10);
33
34/// How long Docker Desktop, opened, is given to start its backend (its socket listening:
35/// [`crate::host::Devices::docker_desktop_socket`]) before it is taken to wait for its user.
36pub const DESKTOP_BACKEND_GRACE: Duration = Duration::from_secs(40);
37
38/// Docker Desktop's program on Windows, under Program Files, opened by PowerShell's
39/// `Start-Process` (the shell's own launch): the app inherits none of the runner's pipes, so the
40/// step ends once the app is opened, not when it quits.
41const DOCKER_DESKTOP_WINDOWS: &str = "Start-Process -FilePath (Join-Path $env:ProgramFiles 'Docker\\Docker\\Docker Desktop.exe')";
42
43/// The steps that start `engine` on `os`, root steps elevated by `elevation` (Linux): `None` when
44/// it isn't one a setup starts there (its user starts it).
45#[must_use]
46pub fn start_steps(os: HostOs, engine: Engine, elevation: Elevation) -> Option<Vec<Step>> {
47    let one = match (os, engine) {
48        (HostOs::Macos, Engine::DockerDesktop) => step("open", &["-a", "Docker"]),
49        (HostOs::Macos, Engine::Orbstack) => step("open", &["-a", "OrbStack"]),
50        (HostOs::Windows, Engine::DockerDesktop) => step("powershell", &["-NoProfile", "-NonInteractive", "-Command", DOCKER_DESKTOP_WINDOWS]),
51        (HostOs::Linux, Engine::Native) => {
52            let (program, args) = elevation.as_root("systemctl", &["start".to_owned(), "docker".to_owned()]);
53            step(program, &args.iter().map(String::as_str).collect::<Vec<_>>())
54        }
55        (HostOs::Macos | HostOs::Linux, Engine::Colima) => step("colima", &["start"]),
56        _ => return None,
57    };
58    Some(vec![one])
59}
60
61/// Why an engine wasn't started.
62#[derive(Debug, Clone, PartialEq, Eq)]
63#[non_exhaustive]
64pub enum StartFailed {
65    /// It isn't one a setup starts on this OS: its user starts it.
66    NotHere(Engine),
67    /// The daemon runs, but refuses this account (its socket's or pipe's permission): starting
68    /// it can't help, joining its group (and a new login) does. What the CLI said.
69    Denied(String),
70    /// A start step failed.
71    Step(StepFailed),
72    /// Docker Desktop, opened, shows Docker's Subscription Service Agreement in its own window,
73    /// which its user hasn't accepted (its settings say so, [`super::agreement_accepted`]): they
74    /// accept it there themselves, and its engine answers once they have. Nothing accepts it for
75    /// them.
76    AgreementNotAccepted(Engine),
77    /// Docker Desktop, opened, waits for its user in its own window: its first start's setup to
78    /// finish (its backend never started within [`DESKTOP_BACKEND_GRACE`], or, on Windows, it
79    /// wrote no settings by then). It answers once they have.
80    WaitingForUser(Engine),
81    /// Started, it gave no answer within [`START_TRIES`] asks: why the last one failed.
82    NoAnswer {
83        /// The engine.
84        engine: Engine,
85        /// How long it was waited for.
86        waited: Duration,
87        /// The last ask's reason.
88        last: String,
89    },
90}
91
92impl std::fmt::Display for StartFailed {
93    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
94        match self {
95            StartFailed::NotHere(engine) => write!(f, "{} isn't started by a setup here; start it yourself", engine.label()),
96            StartFailed::Denied(said) => write!(f, "the Docker daemon refuses this account: {said}"),
97            StartFailed::Step(failed) => failed.fmt(f),
98            StartFailed::AgreementNotAccepted(engine) => write!(
99                f,
100                "{} waits for you to accept the Docker Subscription Service Agreement in its window; nothing accepts it for you",
101                engine.label()
102            ),
103            StartFailed::WaitingForUser(engine) => write!(
104                f,
105                "{} waits for you in its window: accept its agreement or finish its setup there",
106                engine.label()
107            ),
108            StartFailed::NoAnswer { engine, waited, last } => {
109                write!(f, "{} gave no answer within {} s of its start: {last}", engine.label(), waited.as_secs())
110            }
111        }
112    }
113}
114
115impl std::error::Error for StartFailed {}
116
117/// Starts `engine` ([`start_steps`], each line its steps print handed to `on_line`), points the
118/// Docker CLI at it once its context appears, and waits until its daemon answers this account.
119/// An engine that runs already (its own context answers) is only pointed at: no step runs.
120///
121/// # Errors
122///
123/// [`StartFailed`]: why it wasn't started, or gave no answer.
124pub async fn start_engine(cx: &Context, engine: Engine, elevation: Elevation, on_line: &mut (dyn FnMut(&str) + Send)) -> Result<(), StartFailed> {
125    let steps = start_steps(cx.host.os, engine, elevation).ok_or(StartFailed::NotHere(engine))?;
126    // Running already, but not for this account: starting it again can't help.
127    if let Err(NoAnswer::Denied(said)) = daemon_os(cx).await {
128        return Err(StartFailed::Denied(said));
129    }
130    // Running already: nothing is started again (its app isn't brought up, its service isn't
131    // asked to start as root); the CLI is pointed at it, as after a start.
132    if answers(cx, engine).await {
133        drop(use_engine(cx, engine).await);
134        return Ok(());
135    }
136    run_steps(cx, &steps, on_line).await.map_err(StartFailed::Step)?;
137    let mut last = String::new();
138    for tried in 1..=START_TRIES {
139        // Its context appears once it is up: Docker is pointed at it, then its daemon asked.
140        // Not up yet, it has no context to use: its daemon's answer below says how it is.
141        drop(use_engine(cx, engine).await);
142        match daemon_os(cx).await {
143            Ok(_) => return Ok(()),
144            Err(NoAnswer::Denied(said)) => return Err(StartFailed::Denied(said)),
145            Err(why) => last = why.to_string(),
146        }
147        if let Some(waiting) = waits_for_user(cx, engine, START_POLL * tried) {
148            return Err(waiting);
149        }
150        tokio::time::sleep(START_POLL).await;
151    }
152    Err(StartFailed::NoAnswer {
153        engine,
154        waited: START_POLL * START_TRIES,
155        last,
156    })
157}
158
159/// How `engine`, opened `waited` ago, waits for its user, when it does: Docker Desktop (macOS,
160/// Windows) whose settings say its agreement isn't accepted, once [`AGREEMENT_GRACE`] is over;
161/// else, once [`DESKTOP_BACKEND_GRACE`] is, Docker Desktop on macOS whose backend hasn't started
162/// (its socket doesn't listen), or on Windows that has written no settings (its first start's
163/// window, which nothing reads on Windows).
164fn waits_for_user(cx: &Context, engine: Engine, waited: Duration) -> Option<StartFailed> {
165    if engine != Engine::DockerDesktop || cx.host.os == HostOs::Linux {
166        return None;
167    }
168    let accepted = super::agreement_accepted(cx);
169    if waited >= AGREEMENT_GRACE && accepted == Some(false) {
170        return Some(StartFailed::AgreementNotAccepted(engine));
171    }
172    let first_start = match cx.host.os {
173        HostOs::Macos => !listens(&cx.host.devices.docker_desktop_socket),
174        _ => accepted.is_none(),
175    };
176    (waited >= DESKTOP_BACKEND_GRACE && first_start).then_some(StartFailed::WaitingForUser(engine))
177}
178
179/// Whether something listens on the unix socket `socket` (a file left behind refuses).
180#[cfg(unix)]
181fn listens(socket: &std::path::Path) -> bool {
182    std::os::unix::net::UnixStream::connect(socket).is_ok()
183}
184
185/// Docker Desktop's socket is a unix one, on macOS only.
186#[cfg(not(unix))]
187fn listens(_socket: &std::path::Path) -> bool {
188    true
189}
190
191/// Whether `engine`'s own Docker context answers: it runs already.
192async fn answers(cx: &Context, engine: Engine) -> bool {
193    match engine_context(cx, engine).await {
194        Ok(context) => daemon_info(cx, "{{.OperatingSystem}}", Some(&context)).await.is_ok(),
195        Err(_) => false,
196    }
197}
198
199#[cfg(test)]
200mod tests {
201    use std::sync::Arc;
202
203    use isothrum_runner::fake::{FakeProcesses, Reply};
204
205    use super::*;
206    use crate::testing::linux_host;
207
208    fn cx(os: HostOs, fake: FakeProcesses) -> Context {
209        let mut host = linux_host(std::path::Path::new("/nonexistent/isothrum-machine-test"));
210        host.os = os;
211        Context::new(Arc::new(fake), host)
212    }
213
214    fn lines(steps: &[Step]) -> Vec<String> {
215        steps.iter().map(crate::install::command_line).collect()
216    }
217
218    #[test]
219    fn each_engine_starts_the_way_its_user_would_on_its_os() {
220        let prompt = Elevation::Prompt;
221        let started = |os, engine| start_steps(os, engine, prompt).map(|s| lines(&s));
222        assert_eq!(started(HostOs::Macos, Engine::DockerDesktop), Some(vec!["$ open -a Docker".to_owned()]));
223        assert_eq!(started(HostOs::Macos, Engine::Orbstack), Some(vec!["$ open -a OrbStack".to_owned()]));
224        assert_eq!(started(HostOs::Linux, Engine::Colima), Some(vec!["$ colima start".to_owned()]));
225        assert_eq!(started(HostOs::Linux, Engine::Native), Some(vec!["$ pkexec systemctl start docker".to_owned()]));
226        let windows = started(HostOs::Windows, Engine::DockerDesktop).unwrap();
227        assert!(
228            windows[0].starts_with("$ powershell -NoProfile -NonInteractive -Command Start-Process -FilePath"),
229            "{windows:?}"
230        );
231        assert!(windows[0].contains("Docker Desktop.exe"), "{windows:?}");
232        assert_eq!(started(HostOs::Windows, Engine::Colima), None);
233        assert_eq!(started(HostOs::Macos, Engine::Native), None);
234        assert_eq!(started(HostOs::Linux, Engine::Podman), None);
235    }
236
237    #[test]
238    fn docker_engine_starts_unattended_as_root_or_through_sudo() {
239        let root = start_steps(HostOs::Linux, Engine::Native, Elevation::Unattended { root: true }).unwrap();
240        assert_eq!(lines(&root), ["$ systemctl start docker"]);
241        let sudo = start_steps(HostOs::Linux, Engine::Native, Elevation::Unattended { root: false }).unwrap();
242        assert_eq!(lines(&sudo), ["$ sudo -n systemctl start docker"]);
243    }
244
245    #[tokio::test(start_paused = true)]
246    async fn a_started_engine_is_used_and_waited_for_until_it_answers() {
247        use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
248        // OrbStack answers from its third ask on, its context listed once it is up.
249        let (asked, opened) = (Arc::new(AtomicU32::new(0)), Arc::new(AtomicBool::new(false)));
250        let (asks, open) = (Arc::clone(&asked), Arc::clone(&opened));
251        let fake = Arc::new(FakeProcesses::model(move |call| match call.line().as_str() {
252            "open -a OrbStack" => {
253                open.store(true, Ordering::SeqCst);
254                Reply::ok("")
255            }
256            "docker info --format '{{.OperatingSystem}}'" if asks.fetch_add(1, Ordering::SeqCst) >= 2 => Reply::ok("OrbStack"),
257            "docker info --format '{{.OperatingSystem}}'" => Reply::fail(1, "Cannot connect to the Docker daemon"),
258            line if line.starts_with("docker context ls") => Reply::ok("default\ttrue\norbstack\tfalse"),
259            "docker context use orbstack" => Reply::ok("orbstack"),
260            other => Reply::fail(1, &format!("unexpected {other}")),
261        }));
262        let mut host = linux_host(std::path::Path::new("/nonexistent/isothrum-machine-test"));
263        host.os = HostOs::Macos;
264        let runner: Arc<dyn isothrum_runner::ProcessRunner> = Arc::<FakeProcesses>::clone(&fake);
265        let mut said = Vec::new();
266        start_engine(&Context::new(runner, host), Engine::Orbstack, Elevation::Prompt, &mut |l| {
267            said.push(l.to_owned());
268        })
269        .await
270        .unwrap();
271        assert_eq!(said, ["$ open -a OrbStack"]);
272        assert!(opened.load(Ordering::SeqCst));
273        assert_eq!(asked.load(Ordering::SeqCst), 3);
274        assert_eq!(fake.made("docker context use orbstack").len(), 2);
275    }
276
277    #[tokio::test(start_paused = true)]
278    async fn an_engine_that_runs_already_is_used_and_not_started_again() {
279        // Docker Desktop answers on its own context, the CLI pointed at another: no `open`.
280        let fake = FakeProcesses::script()
281            .expect("docker info --format {{.OperatingSystem}}", Reply::ok("OrbStack"))
282            .expect("docker context ls", Reply::ok("orbstack\ttrue\ndesktop-linux\tfalse"))
283            .expect("docker --context desktop-linux info --format {{.OperatingSystem}}", Reply::ok("Docker Desktop"))
284            .expect("docker context use desktop-linux", Reply::ok("desktop-linux"))
285            .build();
286        let mut said = Vec::new();
287        let started = start_engine(&cx(HostOs::Macos, fake), Engine::DockerDesktop, Elevation::Prompt, &mut |l| {
288            said.push(l.to_owned());
289        })
290        .await;
291        assert_eq!((started, said), (Ok(()), Vec::<String>::new()));
292    }
293
294    #[tokio::test(start_paused = true)]
295    async fn a_daemon_refusing_this_account_is_not_started_again() {
296        let fake = FakeProcesses::script()
297            .expect(
298                "docker info --format {{.OperatingSystem}}",
299                Reply::fail(
300                    1,
301                    "permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock",
302                ),
303            )
304            .build();
305        let err = start_engine(&cx(HostOs::Linux, fake), Engine::Native, Elevation::Prompt, &mut |_| {})
306            .await
307            .unwrap_err();
308        assert!(matches!(err, StartFailed::Denied(_)), "{err:?}");
309    }
310
311    #[tokio::test(start_paused = true)]
312    async fn an_engine_not_started_here_and_a_failed_step_say_so() {
313        let none = start_engine(
314            &cx(HostOs::Windows, FakeProcesses::script().build()),
315            Engine::Podman,
316            Elevation::Prompt,
317            &mut |_| {},
318        )
319        .await;
320        assert_eq!(none, Err(StartFailed::NotHere(Engine::Podman)));
321
322        let fake = FakeProcesses::script()
323            .expect(
324                "docker info --format {{.OperatingSystem}}",
325                Reply::fail(1, "Cannot connect to the Docker daemon"),
326            )
327            .expect("docker context ls", Reply::ok("default\ttrue"))
328            .expect(
329                "docker --context default info --format {{.OperatingSystem}}",
330                Reply::fail(1, "Cannot connect to the Docker daemon"),
331            )
332            .expect("pkexec systemctl start docker", Reply::missing())
333            .build();
334        let err = start_engine(&cx(HostOs::Linux, fake), Engine::Native, Elevation::Prompt, &mut |_| {}).await;
335        assert_eq!(err, Err(StartFailed::Step(StepFailed::NoPkexec)));
336    }
337
338    /// Docker Desktop on a Mac whose devices are under `root`, its CLI never answering.
339    fn desktop_never_answering(root: &std::path::Path) -> (Context, Arc<FakeProcesses>) {
340        desktop_never_answering_on(root, HostOs::Macos)
341    }
342
343    /// Docker Desktop on `os` whose devices are under `root`, opened, its CLI never answering.
344    fn desktop_never_answering_on(root: &std::path::Path, os: HostOs) -> (Context, Arc<FakeProcesses>) {
345        let fake = Arc::new(FakeProcesses::model(|call| match call.line().as_str() {
346            "open -a Docker" => Reply::ok(""),
347            line if line.starts_with("powershell") => Reply::ok(""),
348            line if line.starts_with("docker context ls") => Reply::ok("default\ttrue"),
349            _ => Reply::fail(1, "Cannot connect to the Docker daemon at unix:///Users/ada/.docker/run/docker.sock"),
350        }));
351        let mut host = linux_host(root);
352        host.os = os;
353        let runner: Arc<dyn isothrum_runner::ProcessRunner> = Arc::<FakeProcesses>::clone(&fake);
354        (Context::new(runner, host), fake)
355    }
356
357    /// Regression (a Mac installed from scratch): Docker Desktop, opened for the first time, waited
358    /// in its window for its terms to be accepted, and its start gave up 180 s later with "no
359    /// answer". Its backend never listening says it waits for its user, once its grace is over.
360    #[tokio::test(start_paused = true)]
361    #[cfg_attr(not(unix), ignore = "macOS's Docker Desktop socket is a unix one, which only a unix host can find not listening")]
362    async fn docker_desktop_waiting_for_its_user_says_so_instead_of_timing_out() {
363        let root = tempfile::tempdir().unwrap();
364        let (cx, fake) = desktop_never_answering(root.path());
365        let started = tokio::time::Instant::now();
366        let err = start_engine(&cx, Engine::DockerDesktop, Elevation::Prompt, &mut |_| {}).await;
367        assert_eq!(err, Err(StartFailed::WaitingForUser(Engine::DockerDesktop)));
368        assert!(started.elapsed() < DESKTOP_BACKEND_GRACE + START_POLL, "{:?}", started.elapsed());
369        assert_eq!(fake.made("open -a Docker").len(), 1);
370        assert!(err.unwrap_err().to_string().contains("accept its agreement"));
371    }
372
373    /// Docker Desktop installed without `--accept-license` shows Docker's agreement at its first
374    /// start: its settings say it isn't accepted, which is said once its window has had time to
375    /// show, on macOS and Windows alike, not as a start that timed out. Accepted, it is waited for.
376    #[tokio::test(start_paused = true)]
377    async fn docker_desktop_whose_agreement_isnt_accepted_waits_for_its_user_to_accept_it() {
378        for os in [HostOs::Macos, HostOs::Windows] {
379            let root = tempfile::tempdir().unwrap();
380            let (cx, _) = desktop_never_answering_on(root.path(), os);
381            let settings = &cx.host.devices.docker_desktop_settings[0];
382            std::fs::create_dir_all(settings.parent().unwrap()).unwrap();
383            std::fs::write(settings, r#"{"AutoStart": false}"#).unwrap();
384            let started = tokio::time::Instant::now();
385            let err = start_engine(&cx, Engine::DockerDesktop, Elevation::Prompt, &mut |_| {}).await;
386            assert_eq!(err, Err(StartFailed::AgreementNotAccepted(Engine::DockerDesktop)), "{os:?}");
387            assert!(started.elapsed() < AGREEMENT_GRACE + START_POLL, "{os:?}: {:?}", started.elapsed());
388            let said = err.unwrap_err().to_string();
389            assert!(said.contains("accept the Docker Subscription Service Agreement in its window"), "{said}");
390            // Accepted in Docker's window: no longer said; on Windows, nothing else to read, it is
391            // waited for in full.
392            std::fs::write(settings, r#"{"AutoStart": false, "LicenseTermsVersion": 2}"#).unwrap();
393            let after = start_engine(&cx, Engine::DockerDesktop, Elevation::Prompt, &mut |_| {}).await;
394            assert!(!matches!(after, Err(StartFailed::AgreementNotAccepted(_))), "{os:?}: {after:?}");
395            if os == HostOs::Windows {
396                assert!(matches!(after, Err(StartFailed::NoAnswer { .. })), "{after:?}");
397            }
398        }
399    }
400
401    /// Docker Desktop on Windows that wrote no settings within its backend's grace waits in its
402    /// first start's window.
403    #[tokio::test(start_paused = true)]
404    async fn docker_desktop_on_windows_without_settings_waits_for_its_user() {
405        let root = tempfile::tempdir().unwrap();
406        let (cx, _) = desktop_never_answering_on(root.path(), HostOs::Windows);
407        let err = start_engine(&cx, Engine::DockerDesktop, Elevation::Prompt, &mut |_| {}).await;
408        assert_eq!(err, Err(StartFailed::WaitingForUser(Engine::DockerDesktop)));
409    }
410
411    /// Docker Desktop whose backend listens is starting, not waiting: it is given its whole time.
412    #[cfg(unix)]
413    #[tokio::test(start_paused = true)]
414    async fn docker_desktop_whose_backend_listens_is_waited_for_in_full() {
415        // A short path: a unix socket's is limited to about a hundred bytes.
416        let root = tempfile::Builder::new().prefix("dd").tempdir_in("/tmp").unwrap();
417        let (cx, _) = desktop_never_answering(root.path());
418        let socket = &cx.host.devices.docker_desktop_socket;
419        std::fs::create_dir_all(socket.parent().unwrap()).unwrap();
420        let _backend = std::os::unix::net::UnixListener::bind(socket).unwrap();
421        let err = start_engine(&cx, Engine::DockerDesktop, Elevation::Prompt, &mut |_| {}).await;
422        assert!(
423            matches!(err, Err(StartFailed::NoAnswer { waited, .. }) if waited == Duration::from_secs(180)),
424            "{err:?}"
425        );
426    }
427
428    #[tokio::test(start_paused = true)]
429    async fn an_engine_that_never_answers_is_given_up_on_with_the_last_reason() {
430        let fake = FakeProcesses::model(|call| {
431            if call.program == "colima" {
432                Reply::ok("")
433            } else {
434                Reply::fail(1, "Cannot connect to the Docker daemon")
435            }
436        });
437        let err = start_engine(&cx(HostOs::Macos, fake), Engine::Colima, Elevation::Prompt, &mut |_| {})
438            .await
439            .unwrap_err();
440        let StartFailed::NoAnswer { engine, waited, last } = err else {
441            panic!("{err:?}")
442        };
443        assert_eq!((engine, waited), (Engine::Colima, Duration::from_secs(180)));
444        assert!(last.contains("Cannot connect"), "{last}");
445    }
446}