isothrum-runner 2.1.6

The Isothrum runner: executes the run manifest Isoloom writes next to a target's files (lifecycle, state and locks, drivers, checks, 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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
//! Drivers: the manifest's closed set (`compose`, `vagrant`, `terraform`), dispatched through
//! [`AnyDriver`]. Steps are generic and run by the executor; a driver implements only its
//! actions (each one a run manifest's step names is one driver's, and [`foreign_action`] refuses
//! another driver's), how it reads status, and its run-state upkeep.

mod compose;
mod port_pick;
pub(crate) mod shells;
pub(crate) mod terraform;
mod vagrant;

pub(crate) use compose::{COMPOSE_SERVICE_LABEL, UNREADABLE_PS, read_ps};
pub(crate) use terraform::plugin_cache;

use std::collections::BTreeMap;

use isoloom_manifest::{Action, Delivery, Identity, Machine, Manifest, Native, Run, SnakeName, Step, Template};
use tracing::Instrument;

use crate::Result;
use crate::console::ShellCommand;
use crate::encoding::wire_name;
use crate::error::Error;
use crate::executor::Cx;
use crate::process::ProcessSpec;
use crate::status::MachineStatus;
use crate::vars::PortKey;

/// How long taking one machine out of a running run may go without progress (as every tool
/// call's limit counts): a VM destroyed, a service in the run's VM removed with its namespace.
pub(crate) const REMOVE_LIMIT: std::time::Duration = std::time::Duration::from_secs(300);

/// What the engine says about a run.
#[derive(Debug, Clone, Default)]
pub(crate) struct Observed {
    /// Every machine of the manifest.
    pub(crate) machines: Vec<MachineStatus>,
    /// The host port each published machine port got.
    pub(crate) published: BTreeMap<PortKey, u16>,
    /// Where each machine's published ports answer (`${host.<machine>}`).
    pub(crate) hosts: BTreeMap<String, String>,
    /// What the engine gives back, by output name (a Terraform state's outputs).
    pub(crate) outputs: BTreeMap<String, String>,
    /// The engine's outputs it marks sensitive itself (a Terraform output's `sensitive`).
    pub(crate) sensitive: std::collections::BTreeSet<String>,
    /// Not read, for a query: another process acts on these machines (by the manifest's names;
    /// none when the engine named none), and the engine refused the read for as long as a query
    /// waits ([`Cx::query`]). Nothing else is filled then.
    pub(crate) busy: Option<Vec<String>>,
}

impl Observed {
    /// What of it the runner keeps as what it last saw: everything but the engine's outputs.
    pub(crate) fn seen(&self) -> crate::store::Seen {
        crate::store::Seen {
            machines: self.machines.clone(),
            published: self
                .published
                .iter()
                .map(|((machine, port), host)| (machine.clone(), port.clone(), *host))
                .collect(),
            hosts: self.hosts.clone(),
        }
    }

    /// What the runner last saw, as an observation with no engine output.
    pub(crate) fn from_seen(seen: crate::store::Seen) -> Observed {
        Observed {
            machines: seen.machines,
            published: seen.published.into_iter().map(|(machine, port, host)| ((machine, port), host)).collect(),
            hosts: seen.hosts,
            ..Observed::default()
        }
    }
}

/// A driver. Internal and statically dispatched (`async fn`, not object safe by design).
pub(crate) trait Driver {
    /// Refuses a start this driver can see won't work, before anything is created (Vagrant: a
    /// provider the run refuses, or whose plugin is missing).
    async fn preflight(&self, cx: &Cx<'_>) -> Result<()>;
    /// Readies the run's state before any of its steps (Compose: the pinned-ports file exists).
    fn prepare(&self, cx: &Cx<'_>) -> Result<()>;
    /// What every process of the run gets in its environment, besides its step's (Vagrant: its
    /// state folder, `VAGRANT_DOTFILE_PATH`).
    fn env(&self, cx: &Cx<'_>) -> Result<Vec<(String, String)>>;
    /// Runs one of this driver's actions, step `step` of list `list` (`lifecycle.up`), which its
    /// errors name it by ([`crate::executor::plan::at`]), with its arguments ([`with_of`]).
    async fn action(&self, cx: &Cx<'_>, list: &str, step: &Step, action: Action) -> Result<()>;
    /// The run as the engine reports it, from the manifest's `lifecycle.status`.
    async fn observe(&self, cx: &Cx<'_>) -> Result<Observed>;
    /// Reads what a `down` must know before its steps run (Compose: the containers' anonymous
    /// volumes, which the steps leave once a recreate inherited them).
    async fn before_down(&self, cx: &Cx<'_>) -> Result<()>;
    /// Clears the run's state after a successful `down` (Compose: no pins left, the recorded
    /// anonymous volumes removed).
    async fn after_down(&self, cx: &Cx<'_>) -> Result<()>;
    /// Reads what a change of the running run (an update, a retire, a detach) must know before
    /// its steps run (Compose: the containers' anonymous volumes, which a recreate orphans and a
    /// removal can leave).
    async fn before_change(&self, cx: &Cx<'_>) -> Result<()>;
    /// Clears what the change's steps left (Compose: the recorded anonymous volumes no container
    /// holds any more).
    async fn after_change(&self, cx: &Cx<'_>) -> Result<()>;
    /// Restarts `machine`, running, as step `id`, so it boots with the settings its engine
    /// applies only at boot (an update, when its boot digest changed: [`Native::Vagrant`]'s
    /// `boot_digest`). Nothing for a driver whose machines carry no boot digest.
    async fn restart(&self, cx: &Cx<'_>, machine: &Machine, id: &str) -> Result<()>;
    /// Hot-adds `machine`, an on-demand access machine the initial `up` left down, into the
    /// running run: brought up with the picked `image`, else its baked default, and joined to the
    /// network whose native name is `network` when one is given. Refused where the driver can't.
    async fn attach(&self, cx: &Cx<'_>, machine: &Machine, image: Option<&str>, network: Option<&str>) -> Result<()>;
    /// Takes `machine` out of the running run (a retire ahead of its removal from the manifest,
    /// or its move out of the default start; a detach of an on-demand access machine), where the
    /// next update wouldn't remove it itself. The operation's step is named after the emitter's
    /// op. Refused where the driver does nothing for it, except for a machine a Terraform module
    /// makes, which the update's apply removes. A Compose service in the run's VM never reaches
    /// here: [`crate::in_vm::retire`] takes it.
    async fn retire(&self, cx: &Cx<'_>, machine: &Machine) -> Result<()>;
    /// The argv that opens an interactive console into `machine`, any machine of the run, as
    /// account `user` when given (a checked name, [`crate::console::check_user`]). A pure query:
    /// no process runs here, the embedder runs what it returns in its own terminal. Refused where
    /// the driver has no way in. A Compose service in the run's VM never reaches here:
    /// [`crate::in_vm::console`] opens it.
    fn console_command(&self, cx: &Cx<'_>, machine: &Machine, user: Option<&str>) -> Result<ShellCommand>;
    /// The process that runs `script` inside `vm`, the VM the run's containers run in
    /// (`docker-vm`'s guest), through the VM's way in, as `use_` says. Refused by a driver whose
    /// runs have no such VM.
    fn in_guest(&self, cx: &Cx<'_>, vm: &Machine, script: &str, use_: GuestUse) -> Result<ProcessSpec>;
}

/// What a script run in the run's VM ([`Driver::in_guest`]) is for, which decides how it runs.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum GuestUse {
    /// A console the embedder runs in its own terminal: with a terminal, and with the run's own
    /// variables only. Nothing the manifest delivers to a step goes in: the embedder is handed
    /// the command, its variables included, so a secret delivered there would show.
    Console,
    /// Part of the operation, run by the runner itself: no terminal, with what the manifest
    /// delivers to the operation's step (the values reach only the process).
    Step,
}

/// The driver a manifest names.
#[derive(Debug, Clone)]
pub(crate) enum AnyDriver {
    Compose(compose::Compose),
    Vagrant(vagrant::Vagrant),
    Terraform(terraform::Terraform),
}

impl AnyDriver {
    /// The driver for `manifest`, refusing what this runner doesn't run yet.
    pub(crate) fn for_manifest(manifest: &Manifest) -> Result<AnyDriver> {
        let unsupported = |what: String| Err(Error::Unsupported { what });
        let driver = match &manifest.identity {
            Identity::Compose(identity) => AnyDriver::Compose(compose::Compose::new(identity.clone())),
            Identity::Vagrant(identity) => AnyDriver::Vagrant(vagrant::Vagrant::new(identity.clone())),
            Identity::Terraform(identity) => AnyDriver::Terraform(terraform::Terraform::new(identity.clone())),
        };
        let terraform = matches!(driver, AnyDriver::Terraform(_));
        for delivery in crate::executor::every_delivery(manifest) {
            let ok = match delivery {
                Delivery::Env { .. } | Delivery::StateFile { .. } | Delivery::Guest { .. } => true,
                Delivery::TfVar { .. } => terraform,
            };
            if !ok {
                return unsupported(format!("a `{}` delivery", delivery_kind(delivery)));
            }
        }
        Ok(driver)
    }

    /// The driver's name, as the manifest writes it, for tracing.
    fn name(&self) -> &'static str {
        isoloom_manifest::Driver::from(self).id()
    }

    pub(crate) async fn preflight(&self, cx: &Cx<'_>) -> Result<()> {
        let span = tracing::debug_span!("driver", driver = self.name(), check = "preflight");
        match self {
            AnyDriver::Compose(d) => d.preflight(cx).instrument(span).await,
            AnyDriver::Vagrant(d) => d.preflight(cx).instrument(span).await,
            AnyDriver::Terraform(d) => d.preflight(cx).instrument(span).await,
        }
    }

    /// Whether the run's management commands need elevation in `scope` (Hyper-V's provider).
    pub(crate) fn elevates(&self, scope: &crate::scope::Scope) -> bool {
        match self {
            AnyDriver::Compose(_) | AnyDriver::Terraform(_) => false,
            AnyDriver::Vagrant(d) => d.elevates(scope),
        }
    }

    pub(crate) fn prepare(&self, cx: &Cx<'_>) -> Result<()> {
        match self {
            AnyDriver::Compose(d) => d.prepare(cx),
            AnyDriver::Vagrant(d) => d.prepare(cx),
            AnyDriver::Terraform(d) => d.prepare(cx),
        }
    }

    pub(crate) fn env(&self, cx: &Cx<'_>) -> Result<Vec<(String, String)>> {
        match self {
            AnyDriver::Compose(d) => d.env(cx),
            AnyDriver::Vagrant(d) => d.env(cx),
            AnyDriver::Terraform(d) => d.env(cx),
        }
    }

    /// The host ports a fresh start pins for a driver that chooses its own (Vagrant, locally: a
    /// free loopback port per ephemeral published port, by `"<machine>/<port>"`), empty for the
    /// others. Recorded so a resume forwards the same ports; Compose pins its own through its
    /// `pin_ports` action, and a Terraform (server/cloud) run forwards nothing to this computer.
    ///
    /// # Errors
    ///
    /// `tool_failed` when no free host port is found for one, `io` when the loopback can't be
    /// bound to look for one ([`port_pick::PortPick::pin`]).
    pub(crate) fn pin_vm_ports(&self, cx: &Cx<'_>) -> Result<BTreeMap<String, u16>> {
        match self {
            AnyDriver::Vagrant(_) => vagrant::forwarded::pin(cx),
            AnyDriver::Compose(_) | AnyDriver::Terraform(_) => Ok(BTreeMap::new()),
        }
    }

    pub(crate) async fn action(&self, cx: &Cx<'_>, list: &str, step: &Step, action: Action) -> Result<()> {
        let span = tracing::debug_span!("driver", driver = self.name(), action = ?action);
        match self {
            AnyDriver::Compose(d) => d.action(cx, list, step, action).instrument(span).await,
            AnyDriver::Vagrant(d) => d.action(cx, list, step, action).instrument(span).await,
            AnyDriver::Terraform(d) => d.action(cx, list, step, action).instrument(span).await,
        }
    }

    /// What step `step` of list `list` needs before it runs, in a phase of its own with its own
    /// step events and limit: the images a Compose `up` starts, pulled; the boxes a `vagrant up`
    /// boots, downloaded. Nothing for another step, nor for another driver.
    pub(crate) async fn before_step(&self, cx: &Cx<'_>, list: &str, step: &Step) -> Result<()> {
        match self {
            AnyDriver::Compose(_) => compose::pull_before_step(cx, list, step).await,
            AnyDriver::Vagrant(d) => vagrant::boxes_before_step(d, cx, list, step).await,
            AnyDriver::Terraform(_) => Ok(()),
        }
    }

    /// Runs argv step `step` of list `list` once ([`crate::executor::once`]), `observe` seeing
    /// each line; the Vagrant driver runs a `vagrant` command another Vagrant process's lock
    /// refused again, while that is safe ([`vagrant::run_step`]).
    pub(crate) async fn run_argv(&self, cx: &Cx<'_>, list: &str, step: &Step, observe: &mut (dyn FnMut(&str) + Send)) -> Result<()> {
        match self {
            AnyDriver::Vagrant(_) => vagrant::run_step(cx, list, step, observe).await,
            AnyDriver::Compose(_) | AnyDriver::Terraform(_) => crate::executor::once(cx, list, step, observe, crate::executor::Hold::No)
                .await?
                .result(cx, step),
        }
    }

    pub(crate) async fn observe(&self, cx: &Cx<'_>) -> Result<Observed> {
        let span = tracing::debug_span!("driver", driver = self.name(), read = "status");
        match self {
            AnyDriver::Compose(d) => d.observe(cx).instrument(span).await,
            AnyDriver::Vagrant(d) => d.observe(cx).instrument(span).await,
            AnyDriver::Terraform(d) => d.observe(cx).instrument(span).await,
        }
    }

    /// What a failed `down` may print for each resource of the run that is already gone, and the
    /// resource: Terraform's `identity.terraform.gone`, filled for each instance its state holds
    /// ([`terraform::gone`]). None for the other drivers.
    pub(crate) fn gone(&self, cx: &Cx<'_>) -> Result<Vec<terraform::gone::Gone>> {
        match self {
            AnyDriver::Terraform(d) => d.gone(cx),
            AnyDriver::Compose(_) | AnyDriver::Vagrant(_) => Ok(Vec::new()),
        }
    }

    /// Drops from the run's state each resource [`AnyDriver::gone`] names whose text, among
    /// `seen`, step `step` of list `list` printed before it failed, through that step's own tool;
    /// whether it dropped any (so the list may run again). Nothing for a step that isn't a
    /// Terraform destroy, nor for another driver.
    pub(crate) async fn forget_gone(&self, cx: &Cx<'_>, list: &str, step: &Step, seen: &std::collections::BTreeSet<String>) -> Result<bool> {
        match self {
            AnyDriver::Terraform(d) => d.forget_gone(cx, list, step, seen).await,
            AnyDriver::Compose(_) | AnyDriver::Vagrant(_) => Ok(false),
        }
    }

    /// Whether `e`, a failure of the start's steps `up`, is one a later apply may get past (a
    /// cloud's eventual consistency): a step that runs `terraform apply` failing. Never for another
    /// driver.
    pub(crate) fn reapplies(&self, up: &[Step], e: &Error) -> bool {
        match self {
            AnyDriver::Terraform(_) => terraform::argv::applied(up, e),
            AnyDriver::Compose(_) | AnyDriver::Vagrant(_) => false,
        }
    }

    pub(crate) async fn before_down(&self, cx: &Cx<'_>) -> Result<()> {
        let span = tracing::debug_span!("driver", driver = self.name(), op = "before_down");
        match self {
            AnyDriver::Compose(d) => d.before_down(cx).instrument(span).await,
            AnyDriver::Vagrant(d) => d.before_down(cx).instrument(span).await,
            AnyDriver::Terraform(d) => d.before_down(cx).instrument(span).await,
        }
    }

    pub(crate) async fn before_change(&self, cx: &Cx<'_>) -> Result<()> {
        let span = tracing::debug_span!("driver", driver = self.name(), op = "before_change");
        match self {
            AnyDriver::Compose(d) => d.before_change(cx).instrument(span).await,
            AnyDriver::Vagrant(d) => d.before_change(cx).instrument(span).await,
            AnyDriver::Terraform(d) => d.before_change(cx).instrument(span).await,
        }
    }

    pub(crate) async fn after_change(&self, cx: &Cx<'_>) -> Result<()> {
        let span = tracing::debug_span!("driver", driver = self.name(), op = "after_change");
        match self {
            AnyDriver::Compose(d) => d.after_change(cx).instrument(span).await,
            AnyDriver::Vagrant(d) => d.after_change(cx).instrument(span).await,
            AnyDriver::Terraform(d) => d.after_change(cx).instrument(span).await,
        }
    }

    pub(crate) async fn after_down(&self, cx: &Cx<'_>) -> Result<()> {
        let span = tracing::debug_span!("driver", driver = self.name(), op = "after_down");
        match self {
            AnyDriver::Compose(d) => d.after_down(cx).instrument(span).await,
            AnyDriver::Vagrant(d) => d.after_down(cx).instrument(span).await,
            AnyDriver::Terraform(d) => d.after_down(cx).instrument(span).await,
        }
    }

    pub(crate) async fn restart(&self, cx: &Cx<'_>, machine: &Machine, id: &str) -> Result<()> {
        let span = tracing::debug_span!("driver", driver = self.name(), op = cx.events.call_id(), machine = %machine.name);
        match self {
            AnyDriver::Compose(d) => d.restart(cx, machine, id).instrument(span).await,
            AnyDriver::Vagrant(d) => d.restart(cx, machine, id).instrument(span).await,
            AnyDriver::Terraform(d) => d.restart(cx, machine, id).instrument(span).await,
        }
    }

    pub(crate) async fn attach(&self, cx: &Cx<'_>, machine: &Machine, image: Option<&str>, network: Option<&str>) -> Result<()> {
        let span = tracing::debug_span!("driver", driver = self.name(), op = "attach", machine = %machine.name);
        match self {
            AnyDriver::Compose(d) => d.attach(cx, machine, image, network).instrument(span).await,
            AnyDriver::Vagrant(d) => d.attach(cx, machine, image, network).instrument(span).await,
            AnyDriver::Terraform(d) => d.attach(cx, machine, image, network).instrument(span).await,
        }
    }

    pub(crate) async fn retire(&self, cx: &Cx<'_>, machine: &Machine) -> Result<()> {
        let span = tracing::debug_span!("driver", driver = self.name(), op = cx.events.call_id(), machine = %machine.name);
        match self {
            AnyDriver::Compose(d) => d.retire(cx, machine).instrument(span).await,
            AnyDriver::Vagrant(d) => d.retire(cx, machine).instrument(span).await,
            AnyDriver::Terraform(d) => d.retire(cx, machine).instrument(span).await,
        }
    }

    pub(crate) fn console_command(&self, cx: &Cx<'_>, machine: &Machine, user: Option<&str>) -> Result<ShellCommand> {
        let _span = tracing::debug_span!("driver", driver = self.name(), query = "console", machine = %machine.name).entered();
        match self {
            AnyDriver::Compose(d) => d.console_command(cx, machine, user),
            AnyDriver::Vagrant(d) => d.console_command(cx, machine, user),
            AnyDriver::Terraform(d) => d.console_command(cx, machine, user),
        }
    }

    pub(crate) fn in_guest(&self, cx: &Cx<'_>, vm: &Machine, script: &str, use_: GuestUse) -> Result<ProcessSpec> {
        match self {
            AnyDriver::Compose(d) => d.in_guest(cx, vm, script, use_),
            AnyDriver::Vagrant(d) => d.in_guest(cx, vm, script, use_),
            AnyDriver::Terraform(d) => d.in_guest(cx, vm, script, use_),
        }
    }
}

/// The arguments (`with`) of action step `step`; none for a command step.
pub(crate) fn with_of(step: &Step) -> &BTreeMap<SnakeName, Template> {
    static NONE: BTreeMap<SnakeName, Template> = BTreeMap::new();
    match &step.run {
        Run::Action { with, .. } => with,
        Run::Argv(_) => &NONE,
    }
}

/// The loopback: where a port published on every interface of this computer answers.
const LOOPBACK: &str = "127.0.0.1";

/// Where `machine`'s ports published on this computer answer (`${host.<machine>}`): the address
/// its published ports listen on (the first one's `publish.address`, filled), the loopback for one
/// on every interface (an unspecified address, `0.0.0.0` or `::` however it is written) or none
/// said.
///
/// # Errors
///
/// As [`crate::vars::Vars::render`]: an address naming a value the run doesn't have.
pub(crate) fn publish_host(cx: &Cx<'_>, machine: &Machine) -> Result<String> {
    let at = cx.run.manifest().machines.iter().position(|m| m.name == machine.name).unwrap_or_default();
    let address = machine
        .ports
        .iter()
        .enumerate()
        .find_map(|(j, p)| Some((j, p.publish.as_ref()?.address.as_ref()?)));
    let Some((j, address)) = address else {
        return Ok(LOOPBACK.to_owned());
    };
    let address = cx.vars.render(address, &format!("machines[{at}].ports[{j}].publish.address"))?;
    let bound = address.trim();
    let every_interface = crate::relay::bare_host(bound).parse::<std::net::IpAddr>().is_ok_and(|ip| ip.is_unspecified());
    Ok(if bound.is_empty() || every_interface {
        LOOPBACK.to_owned()
    } else {
        bound.to_owned()
    })
}

/// The console `spec` builds, run in its own folder (`ssh`'s: the run's state folder, which its
/// config is named relative to), else in the run's folder.
pub(crate) fn console_in_run(cx: &Cx<'_>, spec: ProcessSpec) -> ShellCommand {
    let cwd = spec.cwd.unwrap_or_else(|| cx.run.dir().to_path_buf());
    ShellCommand::new(spec.program, spec.args, cwd).with_env(spec.env)
}

/// Refuses an action of another driver's (the manifest's actions are each one driver's): step
/// `step` of a `driver` run.
pub(crate) fn foreign_action(driver: isoloom_manifest::Driver, step: &Step, action: Action) -> Error {
    Error::Unsupported {
        what: format!("step `{}`: the action `{}` on a `{}` run", step.id, wire_name(&action), driver.id()),
    }
}

impl From<&AnyDriver> for isoloom_manifest::Driver {
    fn from(driver: &AnyDriver) -> isoloom_manifest::Driver {
        match driver {
            AnyDriver::Compose(_) => isoloom_manifest::Driver::Compose,
            AnyDriver::Vagrant(_) => isoloom_manifest::Driver::Vagrant,
            AnyDriver::Terraform(_) => isoloom_manifest::Driver::Terraform,
        }
    }
}

/// The manifest's `lifecycle.status`, as messages name it.
pub(crate) const STATUS: &str = "lifecycle.status";

/// What the manifest's `lifecycle.status` prints: the engine's own report of the run.
pub(crate) async fn status_report(cx: &Cx<'_>) -> Result<String> {
    crate::executor::capture_step(cx, STATUS, &cx.run.manifest().lifecycle.status).await
}

/// A machine's static addresses as the status shows them: each of the run's networks, by name, to the address
/// the manifest fixes on it.
pub(crate) fn static_addresses(m: &Machine) -> BTreeMap<String, String> {
    m.addresses.iter().map(|(n, a)| (n.to_string(), a.to_string())).collect()
}

/// The name the machine's engine addresses it by: its Compose service, its Vagrant define, else
/// its manifest name.
pub(crate) fn native_name(m: &Machine) -> &str {
    match &m.native {
        Some(Native::Compose { service }) => service.as_str(),
        Some(Native::Vagrant { vagrant, .. }) => vagrant.as_str(),
        None => m.name.as_str(),
    }
}

/// Whether `m` is a Compose service.
pub(crate) fn is_compose_service(m: &Machine) -> bool {
    matches!(m.native, Some(Native::Compose { .. }))
}

/// The refusal of `what` (`taking out`, `a console into`) on `machine`, a Compose service on a
/// run with no VM for it to run in.
pub(crate) fn no_vm_for(what: &str, machine: &Machine) -> Error {
    Error::Unsupported {
        what: format!("{what} `{}`: a Compose service with no VM to run in", machine.name),
    }
}

fn delivery_kind(d: &Delivery) -> &'static str {
    match d {
        Delivery::Env { .. } => "env",
        Delivery::TfVar { .. } => "tf_var",
        Delivery::StateFile { .. } => "state_file",
        Delivery::Guest { .. } => "guest",
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn only_what_this_runner_runs_is_accepted() {
        assert!(matches!(AnyDriver::for_manifest(&crate::testing::docker_manifest()), Ok(AnyDriver::Compose(_))));
        assert!(matches!(
            AnyDriver::for_manifest(&crate::testing::vagrant_manifest()),
            Ok(AnyDriver::Vagrant(_))
        ));
        assert!(matches!(
            AnyDriver::for_manifest(&crate::testing::proxmox_manifest()),
            Ok(AnyDriver::Terraform(_))
        ));
        let mut m = crate::testing::docker_manifest();
        let tf: Delivery = serde_json::from_str(r#"{"via": "tf_var", "var": "inputs"}"#).unwrap();
        m.secrets[0].deliver = isoloom_manifest::NonEmpty::one(tf);
        assert_eq!(AnyDriver::for_manifest(&m).unwrap_err().to_string(), "a `tf_var` delivery isn't supported");
        let mut cloud = crate::testing::proxmox_manifest();
        let file: Delivery = serde_json::from_str(r#"{"via": "state_file", "path": "inputs.tfvars.json", "format": "tfvars_json"}"#).unwrap();
        cloud.secrets[0].deliver = isoloom_manifest::NonEmpty::one(file);
        assert!(AnyDriver::for_manifest(&cloud).is_ok(), "a state file");
    }
}