isothrum-runner 3.0.3

The Isothrum runner: runs a Compose project, a Vagrantfile or a Terraform module through its own tool (lifecycle, state and locks, the format drivers, events).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
//! The Compose driver: a Compose project's lifecycle, through `docker compose` on the project named
//! after the run (`-p <run>`, so two copies of one project never share a container, network or
//! volume) and `docker` for the objects Compose's own label marks as the project's.
//!
//! | Operation | Compose |
//! |---|---|
//! | up, update | `pull --ignore-buildable` ([`pull`]: stopped as stalled, tried again when cut short), then `up --detach --wait --remove-orphans --build` (each image built from the files as they are now, Compose's cache keeping it quick): ready once every service runs healthy and every one-shot service it waits on exited 0; an update then removes (`rm --stop --force --volumes`) the containers of services the files declare but no longer start (moved under a profile) and the run hasn't attached |
//! | down | `down --volumes --remove-orphans`, then whatever still carries the project's label, by id |
//! | park | `pause` (Pause), `stop` (Shutdown) |
//! | resume | `unpause` of the paused services (then `ps` until none reads unhealthy, at most a minute: Docker reads a paused container unhealthy until its check runs again), `stop` of those left in the network namespace of one that stopped, then `up --detach --wait --no-recreate` |
//! | attach, retire | `up --detach --wait --build <service>` (a service under a profile starts when named), `rm --stop --force --volumes <service>` |
//! | exec, console | `exec -T`, or `run --rm` for a service with no container (a profile's one-off); a console is `exec` with a terminal |
//! | observe | `ps --all --format json` |
//! | found | the containers, networks and volumes labelled `com.docker.compose.project=<run>` |
//! | usage | `ps`, then `docker stats --no-stream`: each running service's containers, summed |
//! | reapply | `up --detach --wait --remove-orphans --build` on the files: Compose makes or remakes only what changed |
//!
//! Recovery: an `up` refused because a name of the project is taken (a container or network an
//! earlier start left) removes the project's labelled leftovers by id and starts once more. A
//! host port taken is `port_in_use`. A first start claims the host ports the project fixes before
//! anything is made (one another run holds or something on this computer binds is refused there);
//! one refused by Docker anyway (taken since, or seen only by Docker) removes what the start made
//! (`down`), so the next start, the port free, finds nothing in its way. Compose has no set-up to run again:
//! `provision` is refused.

mod failures;
mod fetched;
mod namespaces;
mod pins;
mod progress;
mod pull;
mod reading;
mod unpaused;
mod usage;

use std::time::Duration;

use self::failures::{checked, engine_error, up_error};
use self::reading::{object_word, one_service, ran, run_state};
use super::{Change, FormatDriver, Found, Ran, Seen, SeenMachine, SeenPort, ToolCx, tool_error};
use crate::Result;
use crate::cli::CliError;
use crate::cli::compose::{self, Exec, Existing, Failure, Project, Up, Verb};
use crate::cli::docker::{self, Object};
use crate::console::ShellCommand;
use crate::console::shells;
use crate::error::Error;
use crate::events::Stream;
use crate::state::{Park, RunState};
use crate::status::MachineState;
use crate::store::{Lifetime, ResourceKind};

/// The label Compose puts on every object of a project, with the project's name.
pub(crate) const PROJECT_LABEL: &str = "com.docker.compose.project";

/// How long a start may take: images pulled, built and every service healthy.
const UP_LIMIT: Duration = Duration::from_secs(1800);

/// How long a lifecycle call that makes nothing may take (stop, start, down, rm).
const CALL_LIMIT: Duration = Duration::from_secs(600);

/// How long a read may take (`ps`, `config`, a version, a label listing).
const READ_LIMIT: Duration = Duration::from_secs(30);

/// The Compose driver.
#[derive(Debug, Clone, Copy, Default)]
pub(crate) struct Compose;

impl Compose {
    /// The project a call is on: the run's name and the project's own file.
    fn project<'a>(cx: &'a ToolCx<'_>) -> Project<'a> {
        Project {
            name: cx.run.as_str(),
            files: &cx.project.files,
            pins: pins::file(cx),
            profiles: &[],
        }
    }

    /// The `label=` filter that finds the project's objects.
    fn label(cx: &ToolCx<'_>) -> String {
        format!("{PROJECT_LABEL}={}", cx.run.as_str())
    }

    /// [`Compose::prepare`], then [`Compose::launch`]: an update, a reapply.
    async fn start(&self, cx: &ToolCx<'_>) -> Result<()> {
        fetched::recording(cx, &[], async {
            self.prepare(cx, false).await?;
            self.launch(cx).await
        })
        .await
    }

    /// What a start does before it makes anything: the project's ports pinned (its fixed host
    /// ports claimed first, at a `first` start), its images pulled.
    async fn prepare(&self, cx: &ToolCx<'_>, first: bool) -> Result<()> {
        pins::pin(cx, first).await?;
        self.pull(cx).await
    }

    /// `up`, which builds the project's images from its files as they are now, then makes and
    /// starts its containers.
    async fn launch(&self, cx: &ToolCx<'_>) -> Result<()> {
        let how = Up {
            wait: true,
            remove_orphans: true,
            existing: Existing::Rebuilt,
            ..Up::default()
        };
        self.up_recovering(cx, "up", &how).await
    }

    /// `up` as `how`, with one recovery: a name the project's leftovers hold is cleared by id, then
    /// the start is made once more. A taken host port is `port_in_use`. Its lines say its steps
    /// ([`progress`]), done once it went through.
    async fn up_recovering(&self, cx: &ToolCx<'_>, step: &str, how: &Up<'_>) -> Result<()> {
        let watch = progress::Watch::new(&cx.steps);
        let sink = |stream: Stream, line: &str| {
            watch.see(line);
            (cx.sink)(stream, line);
        };
        let mut call = cx.call(UP_LIMIT);
        call.sink = &sink;
        self.up_watched(cx, &call, step, how).await?;
        cx.steps.end(true);
        Ok(())
    }

    /// [`Compose::up_recovering`]'s calls, through `call`.
    async fn up_watched(&self, cx: &ToolCx<'_>, call: &crate::cli::Call<'_>, step: &str, how: &Up<'_>) -> Result<()> {
        let first = compose::up(call, &Self::project(cx), how).await;
        let retry = match first {
            Ok(()) => return Ok(()),
            Err(CliError::Failed {
                failure: Failure::NameInUse | Failure::NetworkExists,
                ..
            }) => true,
            Err(e) => return checked(cx, Err(e), |e| up_error(step, e)).await,
        };
        if retry {
            tracing::info!(run = %cx.run, "a name of the project is taken by what an earlier start left: removing it, then starting again");
            self.remove_labelled(cx).await?;
        }
        checked(cx, compose::up(call, &Self::project(cx), how).await, |e| up_error(step, e)).await
    }

    /// Removes every object the project's label marks, containers first (a network or volume a
    /// container holds can't go before it). A volume a container the label doesn't mark still
    /// holds (one a stopped start made under the same project) goes after that container.
    async fn remove_labelled(&self, cx: &ToolCx<'_>) -> Result<()> {
        let call = cx.call(CALL_LIMIT);
        for kind in [Object::Container, Object::Network, Object::Volume] {
            let ids = docker::labelled(&call, kind, &Self::label(cx)).await.map_err(|e| tool_error("leftovers", e))?;
            let removed = match docker::remove(&call, kind, &ids).await {
                Err(CliError::Failed {
                    failure: docker::Failure::InUse(_),
                    ..
                }) if kind == Object::Volume => Self::remove_held(&call, &ids).await,
                other => other,
            };
            removed.map_err(|e| tool_error("leftovers", e))?;
        }
        Ok(())
    }

    /// Removes the containers holding `volumes`, then the volumes once more.
    async fn remove_held(call: &crate::cli::Call<'_>, volumes: &[String]) -> std::result::Result<(), CliError<docker::Failure>> {
        for volume in volumes {
            let holders = docker::holding(call, volume).await?;
            tracing::info!(volume = %volume, containers = ?holders, "removing the containers that still hold a leftover volume");
            docker::remove(call, Object::Container, &holders).await?;
        }
        docker::remove(call, Object::Volume, volumes).await
    }

    /// The services the project's files start at `up` (`config --services`: a service under a
    /// profile isn't one), and those of them with no container: gone (removed outside the run,
    /// or never made). Files Compose can't read leave none gone: the status stands on `ps`.
    async fn gone(&self, cx: &ToolCx<'_>, containers: &[compose::Container]) -> Vec<String> {
        let declared = match compose::services(&cx.read(READ_LIMIT), &Self::project(cx)).await {
            Ok(services) => services,
            Err(e) => {
                tracing::warn!(run = %cx.run, error = %e, "the project's services couldn't be read; the status is the containers'");
                return Vec::new();
            }
        };
        declared.into_iter().filter(|s| !containers.iter().any(|c| c.service() == s)).collect()
    }

    /// After an update: the containers of services the files still declare but no longer start
    /// (moved under a profile, as an access machine's route keeper is when the machine that stood
    /// in its place goes back to its own) and the run hasn't attached, removed. `--remove-orphans`
    /// leaves them, a declared service being no orphan: stale, a namespace they shared gone, they
    /// read as failed and the run never ready again.
    async fn retire_unstarted(&self, cx: &ToolCx<'_>) -> Result<()> {
        let started = checked(cx, compose::services(&cx.read(READ_LIMIT), &Self::project(cx)).await, |e| {
            engine_error("services", e)
        })
        .await?;
        let attached = pins::attached(cx)?;
        let mut stale: Vec<String> = Vec::new();
        for c in self.containers(cx).await? {
            let service = c.service();
            if !started.iter().any(|s| s == service) && !attached.iter().any(|s| s == service) && !stale.iter().any(|s| s == service) {
                stale.push(service.to_owned());
            }
        }
        if stale.is_empty() {
            return Ok(());
        }
        tracing::info!(run = %cx.run, services = ?stale, "removing the containers of services the files no longer start");
        checked(cx, compose::rm_stop_force(&cx.call(CALL_LIMIT), &Self::project(cx), &stale).await, |e| {
            engine_error("update", e)
        })
        .await
    }

    /// Every container of the project, one-offs (`run`) left out.
    async fn containers(&self, cx: &ToolCx<'_>) -> Result<Vec<compose::Container>> {
        let all = checked(cx, compose::ps(&cx.read(READ_LIMIT), &Self::project(cx)).await, |e| engine_error("status", e)).await?;
        Ok(all.into_iter().filter(|c| !c.one_off()).collect())
    }
}

impl FormatDriver for Compose {
    async fn probe(&self, cx: &ToolCx<'_>) -> Result<()> {
        let found = compose::version(&cx.read(READ_LIMIT)).await.map_err(|e| engine_error("tools", e))?;
        super::unknown_version(cx, found.as_ref(), "docker compose", compose::MIN_VERSION);
        Ok(())
    }

    async fn up(&self, cx: &ToolCx<'_>) -> Result<()> {
        // A first start (nothing of the run recorded as made) refused for a taken host port is
        // undone: Compose makes the project's network and containers, and starts some, before
        // Docker refuses the bind; left there, they hold the run's names and namespaces, and the
        // next start, the port free, fails on them. A run with machines keeps them.
        // A first start claims the host ports the project fixes before anything is made: one
        // another run holds, or something on this computer binds, is refused with nothing to undo.
        let first = (cx.made)()?.is_empty();
        let started = fetched::recording(cx, &[], async {
            self.prepare(cx, first).await?;
            Ok::<_, crate::Error>(self.launch(cx).await)
        })
        .await?;
        if let Err(e) = &started
            && first
            && e.code() == crate::ErrorCode::PortInUse
        {
            tracing::info!(run = %cx.run, "the start was refused for a taken host port: removing what it made");
            if let Err(undo) = self.down(cx).await {
                let said = format!("what the refused start made wasn't all removed (the next start clears it): {undo}");
                (cx.warn)(crate::events::WarningCode::CleanupFailed, &said);
            }
        }
        started
    }

    async fn down(&self, cx: &ToolCx<'_>) -> Result<()> {
        checked(cx, compose::down(&cx.call(CALL_LIMIT), &Self::project(cx), true, true).await, |e| {
            engine_error("down", e)
        })
        .await?;
        // What `down` doesn't take (a container a killed client left unnamed, a volume another
        // file's service made), by the project's label.
        self.remove_labelled(cx).await?;
        pins::forget(cx)
    }

    async fn park(&self, cx: &ToolCx<'_>, mode: Park) -> Result<()> {
        let verb = match mode {
            Park::Pause => Verb::Pause,
            Park::Shutdown => Verb::Stop,
        };
        checked(cx, compose::act(&cx.call(CALL_LIMIT), &Self::project(cx), verb, &[]).await, |e| {
            engine_error("park", e)
        })
        .await
    }

    async fn resume(&self, cx: &ToolCx<'_>) -> Result<()> {
        let containers = self.containers(cx).await?;
        let gone = self.gone(cx, &containers).await;
        if !gone.is_empty() && !containers.is_empty() {
            // A service removed outside the run (its container gone) can't come back as it was,
            // and what joins its namespace can't start: the run is started again with `up`.
            return Err(Error::PartlyGone {
                run: cx.run.to_string(),
                machines: gone,
            });
        }
        let paused: Vec<String> = containers.iter().filter(|c| c.is_paused()).map(|c| c.service().to_owned()).collect();
        if !paused.is_empty() {
            checked(cx, compose::act(&cx.call(CALL_LIMIT), &Self::project(cx), Verb::Unpause, &paused).await, |e| {
                engine_error("resume", e)
            })
            .await?;
            unpaused::health_back(cx, &Self::project(cx), &paused).await?;
        }
        let stranded = namespaces::stranded(cx, &Self::project(cx), &containers).await;
        if !stranded.is_empty() {
            tracing::info!(run = %cx.run, services = ?stranded, "stopping the services left in the network namespace of one that stopped, so the start joins them to its new one");
            checked(cx, compose::act(&cx.call(CALL_LIMIT), &Self::project(cx), Verb::Stop, &stranded).await, |e| {
                engine_error("resume", e)
            })
            .await?;
        }
        let how = Up {
            wait: true,
            existing: Existing::Kept,
            ..Up::default()
        };
        self.up_recovering(cx, "resume", &how).await?;
        // The services under a profile the run attached: a plain `up` leaves them stopped.
        let attached = pins::attached(cx)?;
        if attached.is_empty() {
            return Ok(());
        }
        let theirs = Up { services: &attached, ..how };
        self.up_recovering(cx, "resume", &theirs).await
    }

    async fn update(&self, cx: &ToolCx<'_>) -> Result<()> {
        self.start(cx).await?;
        self.retire_unstarted(cx).await
    }

    async fn machines(&self, cx: &ToolCx<'_>) -> Result<Vec<String>> {
        checked(cx, compose::services(&cx.read(READ_LIMIT), &Self::project(cx)).await, |e| {
            engine_error("services", e)
        })
        .await
    }

    async fn reapply(&self, cx: &ToolCx<'_>, _change: &Change) -> Result<()> {
        // Compose diffs the files against the project's containers itself: one `up` makes what was
        // added, remakes what changed and (with --remove-orphans) removes what went.
        self.start(cx).await
    }

    #[expect(
        clippy::unused_async_trait_impl,
        reason = "the trait's operations are async; Compose refuses this one before calling anything"
    )]
    async fn provision(&self, _cx: &ToolCx<'_>, _machine: Option<&str>, _with: Option<&str>) -> Result<()> {
        Err(Error::Declined {
            what: "provisioning a Compose project again (its services set themselves up when they start: update it instead)".to_owned(),
        })
    }

    async fn attach(&self, cx: &ToolCx<'_>, machine: &str) -> Result<()> {
        let services = one_service(machine);
        let how = Up {
            services: &services,
            wait: true,
            existing: Existing::Rebuilt,
            ..Up::default()
        };
        pins::attach(cx, machine).await?;
        fetched::recording(cx, &services, self.up_recovering(cx, "attach", &how)).await
    }

    async fn retire(&self, cx: &ToolCx<'_>, machine: &str) -> Result<()> {
        checked(
            cx,
            compose::rm_stop_force(&cx.call(CALL_LIMIT), &Self::project(cx), &one_service(machine)).await,
            |e| engine_error("retire", e),
        )
        .await?;
        pins::retire(cx, machine)
    }

    async fn exec(&self, cx: &ToolCx<'_>, machine: &str, argv: &[String]) -> Result<Ran> {
        let call = cx.call(super::CHECK_LIMIT);
        let running = self.containers(cx).await?.iter().any(|c| c.service() == machine && c.machine_state().runs());
        let out = if running {
            let what = Exec {
                service: machine,
                user: None,
                argv,
                tty: false,
            };
            compose::exec(&call, &Self::project(cx), &what).await
        } else {
            compose::run_rm(&call, &Self::project(cx), machine, argv).await
        };
        Ok(ran(&checked(cx, out, |e| engine_error("exec", e)).await?))
    }

    fn console(&self, cx: &ToolCx<'_>, machine: &str, user: Option<&str>) -> impl Future<Output = Result<ShellCommand>> {
        let shell = user.map_or_else(|| shells::CONTAINER_SHELL.to_owned(), |_| shells::container_shell_as());
        let argv = vec!["sh".to_owned(), "-c".to_owned(), shell];
        let what = Exec {
            service: machine,
            user,
            argv: &argv,
            tty: true,
        };
        let spec = compose::exec_spec(&cx.call(READ_LIMIT), &Self::project(cx), &what);
        std::future::ready(Ok(ShellCommand::of_spec(spec, &cx.project.dir)))
    }

    async fn observe(&self, cx: &ToolCx<'_>) -> Result<(Seen, RunState)> {
        let containers = self.containers(cx).await?;
        let gone = self.gone(cx, &containers).await;
        let mut machines: Vec<SeenMachine> = containers
            .iter()
            .filter(|c| !c.one_off())
            .map(|c| SeenMachine {
                name: c.service().to_owned(),
                state: c.machine_state(),
                published: c
                    .published()
                    .into_iter()
                    .map(|p| SeenPort {
                        guest: p.guest,
                        host: p.host,
                        protocol: p.protocol,
                    })
                    .collect(),
                kind: None,
                address: None,
                windows: false,
            })
            .collect();
        // A service the project starts with no container reads absent: gone, never just left out.
        machines.extend(gone.into_iter().map(|name| SeenMachine {
            name,
            state: MachineState::Absent,
            published: Vec::new(),
            kind: None,
            address: None,
            windows: false,
        }));
        let state = run_state(&machines);
        Ok((Seen { machines, ..Seen::default() }, state))
    }

    async fn usage(&self, cx: &ToolCx<'_>) -> Result<Vec<crate::MachineUsage>> {
        let running: Vec<compose::Container> = self.containers(cx).await?.into_iter().filter(compose::Container::runs).collect();
        usage::of(cx, &running).await
    }

    async fn found(&self, cx: &ToolCx<'_>) -> Result<Vec<Found>> {
        let call = cx.read(READ_LIMIT);
        let mut found = Vec::new();
        for (object, kind, lifetime) in [
            (Object::Container, ResourceKind::Container, Lifetime::Machines),
            (Object::Network, ResourceKind::Network, Lifetime::Run),
            (Object::Volume, ResourceKind::Volume, Lifetime::Run),
        ] {
            for id in docker::labelled(&call, object, &Self::label(cx))
                .await
                .map_err(|e| tool_error("resources", e))?
            {
                found.push(Found {
                    key: format!("{}:{id}", object_word(object)),
                    kind,
                    native_id: id,
                    lifetime,
                });
            }
        }
        Ok(found)
    }

    async fn destroy_by_id(&self, cx: &ToolCx<'_>, _key: &str, kind: ResourceKind, native_id: &str) -> Result<()> {
        let object = match kind {
            ResourceKind::Container => Object::Container,
            ResourceKind::Network => Object::Network,
            ResourceKind::Volume => Object::Volume,
            other => {
                return Err(Error::Unsupported {
                    what: format!("removing a {other:?} resource through Compose"),
                });
            }
        };
        // An object already gone is fine: the adapter reads Docker's "no such" as done.
        docker::remove(&cx.call(CALL_LIMIT), object, &[native_id.to_owned()])
            .await
            .map_err(|e| tool_error("remove", e))
    }
}

#[cfg(test)]
mod tests;