isothrum-runner 2.0.0

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
//! One manifest opened under one run name: the operations an embedder calls, and the read-only
//! query `status` here (`console_command`, the other one, is in `console`). `operation` is what every operation does around its own work,
//! `up` starts a run, `existing` holds the operations on a run that exists (down, park, resume,
//! check, provision), `update` brings a running run up to date with its manifest, `boot` restarts
//! the VMs whose boot-time settings it changed, `retire` takes a machine out ahead of it, `attach`
//! hot-adds and removes the run's on-demand access machine (attach, detach), `console` builds the
//! command that opens a console into a machine, and `seal` seals a run once it is ready.

mod attach;
mod boot;
mod console;
mod existing;
mod graphical;
mod operation;
mod retire;
mod seal;
#[cfg(test)]
mod tests;
mod up;
mod update;

pub use attach::{AccessPick, AttachReport};

use std::collections::BTreeMap;
use std::path::Path;

use isoloom_manifest::{Manifest, Provider, RunVar};

use crate::Result;
use crate::driver::AnyDriver;
use crate::encoding::wire_name;
use crate::error::Error;
use crate::events::Emitter;
use crate::executor::{Cx, LineWatch};
use crate::manifest::LoadedManifest;
use crate::name::RunName;
use crate::options::RunOptions;
use crate::outputs;
use crate::params::params_for_existing;
use crate::runner::Runner;
use crate::scope::Scope;
use crate::secrets::Secrets;
use crate::status::{self, Status};

/// A run: a manifest under a name, on a runner.
pub struct Running<'r> {
    pub(crate) runner: &'r Runner,
    loaded: LoadedManifest,
    name: RunName,
    pub(crate) driver: AnyDriver,
    /// Values of the manifest's connection slots, given once ([`Running::with_connection`]).
    connection: Secrets,
}

impl std::fmt::Debug for Running<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Running")
            .field("name", &self.name)
            .field("manifest", &self.loaded.path)
            .finish_non_exhaustive()
    }
}

/// Makes the run's state folder of `cx`, owner-only, for what an operation (or a status read)
/// writes there; a query that writes nothing leaves no folder behind.
fn made(cx: &Cx<'_>) -> Result<()> {
    crate::store::create_dir(cx.state_dir())
}

impl<'r> Running<'r> {
    pub(crate) fn new(runner: &'r Runner, loaded: LoadedManifest, name: RunName) -> Result<Running<'r>> {
        if !loaded.manifest.hosts.contains(&runner.config.host) {
            return Err(Error::Unsupported {
                what: format!("target `{}` on this host", wire_name(&loaded.manifest.target)),
            });
        }
        let driver = AnyDriver::for_manifest(&loaded.manifest)?;
        Ok(Running {
            runner,
            loaded,
            name,
            driver,
            connection: Secrets::new(),
        })
    }

    /// The run with `secrets`, the values of its connection slots (an ESXi host's password),
    /// delivered to every operation, status (which takes no options) too. Kept in memory only,
    /// never stored; a value an operation's options give wins.
    #[must_use]
    pub fn with_connection(mut self, secrets: Secrets) -> Running<'r> {
        self.connection = secrets;
        self
    }

    /// `opts` with the connection's values its secrets lack.
    pub(crate) fn connected(&self, opts: &RunOptions) -> RunOptions {
        let mut out = opts.clone();
        for (name, value) in self.connection.iter() {
            if out.secrets.get(name).is_none() {
                out.secrets.insert(name, value.clone());
            }
        }
        out
    }

    /// The manifest.
    #[must_use]
    pub fn manifest(&self) -> &Manifest {
        &self.loaded.manifest
    }

    /// The run's name.
    #[must_use]
    pub fn name(&self) -> &RunName {
        &self.name
    }

    /// The manifest's file.
    pub(crate) fn path(&self) -> &Path {
        &self.loaded.path
    }

    /// The manifest's folder (`${run.dir}`).
    pub(crate) fn dir(&self) -> &Path {
        &self.loaded.dir
    }

    /// A silent context of the run, with `events` and what its start kept (its record bound: its
    /// SSH jump, its slot, its forwards; its provider; its params replayed, a fresh run's
    /// defaults otherwise), so a way in is the run's: for the read-only queries. No lock.
    fn silent_cx<'a>(&'a self, events: &'a Emitter<'a>) -> Result<(Option<crate::store::RunRecord>, Cx<'a>)> {
        let record = self.runner.store.record(&self.name)?;
        let provider = record.as_ref().and_then(|r| r.provider);
        let params = params_for_existing(
            self.manifest(),
            record.as_ref().and_then(crate::store::RunRecord::replayed_params),
            &BTreeMap::new(),
            &self.scope(provider),
        )?;
        let mut cx = self.cx(params, &self.connection, events, provider)?;
        cx.query = true;
        if let Some(r) = &record {
            Self::bind_record(&mut cx, r);
        }
        Ok((record, cx))
    }

    /// Runs `f` on a silent context of the run ([`Running::silent_cx`]), emitting nothing, its state
    /// folder not made: for the queries that run no step.
    pub(crate) fn query<T>(&self, f: impl FnOnce(&Cx<'_>) -> Result<T>) -> Result<T> {
        let events = self.silent();
        let (_, cx) = self.silent_cx(&events)?;
        f(&cx)
    }

    /// An emitter of the run that says nothing.
    fn silent(&self) -> Emitter<'_> {
        Emitter::silent(self.name.as_str(), self.runner.config.clock.as_ref())
    }

    /// The run as it stands: never locked, and never an event. It changes nothing of the run, but
    /// readies its state folder as an operation does for the tools it asks (the folder; Compose's
    /// empty pinned-ports file, which every Compose call names; Terraform's plugin cache); it
    /// never writes a secret (the consoles the runner chooses are an operation's to choose). While an operation holds the run
    /// (this runner's, or another process's), the engine isn't asked: that operation acts on the
    /// run with the same tools, which may refuse a read until it is done (Vagrant locks each VM
    /// for the whole of a `vagrant up`, provisioning included). The status is then the
    /// operation's state, with the machines as last read ([`Status::live`] false).
    ///
    /// # Errors
    ///
    /// Fails when the engine can't be asked (the status step fails or runs out of time) or the
    /// run's record can't be read. Another process acting on a machine (Vagrant's lock on it,
    /// past a short wait) is no failure: that machine is [`MachineState::Busy`](crate::MachineState::Busy),
    /// the others as last read, and the status isn't live.
    pub async fn status(&self) -> Result<Status> {
        let events = self.silent();
        let (record, mut cx) = self.silent_cx(&events)?;
        let provider = cx.scope.provider;
        let (state, mut observed, live) = self.read_for_query(&mut cx, record.as_ref()).await?;
        let mut machines = std::mem::take(&mut observed.machines);
        let known = cx.scope.provider;
        for m in &mut machines {
            let Some(declared) = self.manifest().machines.iter().find(|x| x.name.as_str() == m.name) else {
                continue;
            };
            m.console = crate::graphical::ConsoleOffer::of(declared, known);
            // A running machine's console is offered as it stands now: there, and answering.
            if m.state.runs()
                && let Some(offer) = m.console.as_mut()
                && let Some(console) = declared.console(known).filter(|c| c.source.is_some())
            {
                offer.unavailable = crate::graphical::unavailable(&cx, declared, console).await;
            }
        }
        let outputs = self.bind_observed(&mut cx, observed).values;
        let message = (state == crate::RunState::Ready)
            .then(|| outputs::message(self.manifest(), &cx.vars, &outputs))
            .flatten();
        Ok(Status {
            state,
            live,
            provider,
            machines,
            networks: self.networks(&cx),
            outputs,
            message,
            native: crate::graphical::native::app(self.manifest(), provider, cx.scope.host),
        })
    }

    /// Where the run stands, its machines and whether they were read now, for a query (`cx`, a
    /// silent context, `record` its run's record): while an operation holds the run, its state
    /// and the machines as last read; else as the engine reads them, unless another process
    /// acting on some of them refuses the read ([`crate::driver::Observed::busy`]): then those
    /// are busy, the others as last read, and the run where an operation holding it now, or its
    /// record, says.
    pub(crate) async fn read_for_query(
        &self,
        cx: &mut Cx<'_>,
        record: Option<&crate::store::RunRecord>,
    ) -> Result<(crate::RunState, crate::driver::Observed, bool)> {
        if let Some(state) = self.while_held(record)? {
            return Ok((state, self.last_seen(), false));
        }
        made(cx)?;
        self.driver.prepare(cx)?;
        self.relay(cx).await?;
        let observed = self.observe(cx).await?;
        let Some(busy) = &observed.busy else {
            return Ok((status::derive_state(&observed.machines, record), observed, true));
        };
        let recorded = record.map_or(crate::RunState::Absent, |r| r.state);
        let state = self.while_held(record)?.unwrap_or(recorded);
        let mut seen = self.last_seen();
        for m in seen.machines.iter_mut().filter(|m| busy.contains(&m.name)) {
            m.state = crate::MachineState::Busy;
        }
        Ok((state, seen, false))
    }

    /// Where the run stands while an operation holds it, if one does: the moving state of this
    /// runner's operation on it (`starting` from the first instant of an `up`), else what its
    /// record says (another process's operation records its moving state once it begins acting;
    /// an update leaves the run `ready`).
    fn while_held(&self, record: Option<&crate::store::RunRecord>) -> Result<Option<crate::RunState>> {
        let recorded = record.map_or(crate::RunState::Absent, |r| r.state);
        if let Some(op) = self.runner.op_of(&self.name) {
            return Ok(Some(op.during().unwrap_or(recorded)));
        }
        Ok(self.runner.store.held(&self.name)?.then_some(recorded))
    }

    /// The run as the runner last read it ([`crate::store::Seen`]); nothing before it ever did,
    /// or when what it kept can't be read (traced).
    fn last_seen(&self) -> crate::driver::Observed {
        match self.runner.store.seen(&self.name) {
            Ok(seen) => crate::driver::Observed::from_seen(seen.unwrap_or_default()),
            Err(e) => {
                tracing::warn!(error = %e, "what the runner last saw of the run can't be read: no machine is shown");
                crate::driver::Observed::default()
            }
        }
    }

    /// What `params`, `secrets` and `events` give this run's steps.
    pub(crate) fn cx<'a>(
        &'a self,
        params: BTreeMap<String, String>,
        secrets: &'a Secrets,
        events: &'a Emitter<'a>,
        provider: Option<Provider>,
    ) -> Result<Cx<'a>> {
        let state_dir = self.runner.store.run_dir_path(&self.name);
        let mut vars = crate::vars::Vars::default();
        vars.set_run(RunVar::Name, self.name.as_str());
        vars.set_run(RunVar::Dir, self.dir().display().to_string());
        vars.set_run(RunVar::StateDir, state_dir.display().to_string());
        vars.set_run(RunVar::KnownHosts, state_dir.join(crate::ssh::KNOWN_HOSTS).display().to_string());
        vars.set_run(RunVar::SshKey, crate::ssh::key_path(&self.runner.config.home).display().to_string());
        if let Some(key) = crate::ssh::public_key(&self.runner.config.home)? {
            vars.set_run(RunVar::SshPublicKey, key);
        }
        if let Some(p) = &provider {
            vars.set_run(RunVar::Provider, crate::wire_name(p));
        }
        vars.set_params(params);
        let stale = self
            .manifest()
            .recovery
            .as_ref()
            .map(|r| LineWatch::any_case(&r.stale_markers))
            .unwrap_or_default();
        Ok(Cx {
            run: self,
            state_dir,
            vars,
            secrets,
            events,
            scope: self.scope(provider),
            stale,
            gone: LineWatch::default(),
            processes: std::sync::Arc::clone(&self.runner.config.processes),
            ssh_jump: None,
            expires_at: None,
            relayed: None,
            set_up: std::collections::BTreeSet::new(),
            query: false,
        })
    }

    /// `cx` for an operation that acts on the run (never a status read): on a provider whose
    /// management commands need elevation (Hyper-V on Windows), its tools run through one
    /// elevated session, kept in the run's state folder.
    pub(crate) fn acting<'a>(&'a self, mut cx: Cx<'a>) -> Result<Cx<'a>> {
        made(&cx)?;
        if cx.scope.host == isoloom_manifest::HostOs::Windows && self.driver.elevates(&cx.scope) {
            let dir = cx.state_dir().join("elevated");
            let inner = std::sync::Arc::clone(&self.runner.config.processes);
            cx.processes = std::sync::Arc::new(crate::process::Elevated::new(inner, dir, self.elevated_env()));
        }
        Ok(cx)
    }

    /// What an elevated session is handed of the environment the runner read when it was
    /// configured ([`RunnerConfig::host_env`](crate::RunnerConfig) and its `PATH`).
    pub(crate) fn elevated_env(&self) -> Vec<(String, String)> {
        let config = &self.runner.config;
        config.host_env.for_elevation(config.path.as_deref())
    }

    /// Makes the runner's SSH key when the manifest reaches a machine over SSH and it has none yet
    /// (an adopted run, or one acted on from another home, may need it).
    pub(crate) async fn ensure_ssh_key(&self) -> Result<()> {
        if crate::ssh::needed(self.manifest()) {
            crate::ssh::ensure_key(self.runner.config.processes.as_ref(), &self.runner.config.home).await?;
        }
        Ok(())
    }

    /// Starts the macOS relays `cx`'s run needs (Vagrant on an ESXi host), for the operation.
    pub(crate) async fn relay(&self, cx: &mut Cx<'_>) -> Result<()> {
        let config = &self.runner.config;
        let vagrant = self.manifest().driver == isoloom_manifest::Driver::Vagrant;
        let params = cx.vars.params();
        let Some((host, port)) = crate::relay::esxi_host(&cx.scope, vagrant, params)? else {
            return Ok(());
        };
        let no_proxy = config.host_env.text("no_proxy").or_else(|| config.host_env.text("NO_PROXY"));
        let relayed = crate::relay::prepare(host, port, &config.home, config.path.as_deref(), no_proxy).await;
        cx.relayed = Some(relayed?);
        Ok(())
    }

    /// Binds what `record` keeps of the run into `cx`: its slot (`${run.slot}`), its SSH jump and
    /// its expiry.
    pub(crate) fn bind_record(cx: &mut Cx<'_>, record: &crate::store::RunRecord) {
        if let Some(slot) = record.slot {
            cx.vars.set_run(RunVar::Slot, slot.to_string());
        }
        cx.ssh_jump.clone_from(&record.ssh_jump);
        cx.expires_at = record.expires_at;
        // The host ports a fresh start pinned: a resume forwards the same ones, and status reads
        // them back (the Vagrant driver reports its forwards from here, not the manifest's number).
        cx.vars.set_vm_pins(record.vm_host_ports.clone());
    }

    /// This host, with `provider`.
    pub(crate) fn scope(&self, provider: Option<Provider>) -> Scope {
        Scope::new(self.runner.config.host, provider)
    }

    /// Reads what the engine gives back (published ports, outputs) and binds it, so a template
    /// can name it (`${outputs.ip}`): the run's outputs.
    pub(crate) async fn read_outputs(&self, cx: &mut Cx<'_>) -> Result<outputs::Read> {
        let observed = self.observe(cx).await?;
        Ok(self.bind_observed(cx, observed))
    }

    /// The run as its engine reports it: the driver's machines, then, when the run's containers
    /// run inside one of its VMs (`docker-vm`'s guest), those containers as read in the VM.
    /// What it read is kept as what the runner last saw of the run ([`crate::store::Seen`]).
    pub(crate) async fn observe(&self, cx: &mut Cx<'_>) -> Result<crate::driver::Observed> {
        let mut observed = self.driver.observe(cx).await?;
        if observed.busy.is_some() {
            // Nothing was read: what the runner last saw stands.
            return Ok(observed);
        }
        if let Some(guest) = &self.manifest().guest {
            crate::in_vm::observe(cx, guest, &mut observed).await;
        }
        if let Err(e) = self.runner.store.keep_seen(&self.name, &observed.seen()) {
            tracing::warn!(error = %e, "what the runner saw of the run wasn't kept");
        }
        Ok(observed)
    }

    /// [`Running::observe`], refused with `not_running` when no member machine runs.
    pub(crate) async fn observe_running(&self, cx: &mut Cx<'_>) -> Result<crate::driver::Observed> {
        let observed = self.observe(cx).await?;
        if !status::any_member_running(&observed.machines) {
            return Err(Error::NotRunning { run: self.name().to_string() });
        }
        Ok(observed)
    }

    /// The manifest's machine `name`, refused with `machine_unknown` when the run has none.
    pub(crate) fn machine_named(&self, name: &str) -> Result<&isoloom_manifest::Machine> {
        self.manifest()
            .machines
            .iter()
            .find(|m| m.name.as_str() == name)
            .ok_or_else(|| Error::MachineUnknown {
                run: self.name().to_string(),
                machine: name.to_owned(),
            })
    }

    /// Binds what `observed` gives back (published ports, outputs) into `cx`: the run's outputs.
    pub(crate) fn bind_observed(&self, cx: &mut Cx<'_>, observed: crate::driver::Observed) -> outputs::Read {
        cx.vars.set_published(observed.published);
        cx.vars.set_hosts(observed.hosts);
        let read = outputs::read(self.manifest(), &cx.vars, &observed.outputs, &observed.sensitive);
        // A value the engine or the manifest keeps secret is masked in every later event.
        cx.events
            .hide(read.values.iter().filter(|o| o.sensitive).filter_map(|o| o.revealed().map(str::to_owned)));
        outputs::bind(&mut cx.vars, &read.values);
        read
    }

    /// The run's networks, their native names filled; one that can't be is left out, and traced.
    fn networks(&self, cx: &Cx<'_>) -> Vec<status::NetworkView> {
        status::networks(self.manifest(), |t| {
            cx.vars
                .render(t, "networks.native")
                .inspect_err(|e| tracing::warn!(error = %e, "a network's native name couldn't be filled: it is left out"))
                .ok()
        })
    }
}