Skip to main content

isothrum_runner/
run.rs

1//! One manifest opened under one run name: the operations an embedder calls, and the read-only
2//! query `status` here (`console_command`, the other one, is in `console`). `operation` is what every operation does around its own work,
3//! `up` starts a run, `existing` holds the operations on a run that exists (down, park, resume,
4//! check, provision), `update` brings a running run up to date with its manifest, `boot` restarts
5//! the VMs whose boot-time settings it changed, `retire` takes a machine out ahead of it, `attach`
6//! hot-adds and removes the run's on-demand access machine (attach, detach), `console` builds the
7//! command that opens a console into a machine, and `seal` seals a run once it is ready.
8
9mod attach;
10mod boot;
11mod console;
12mod existing;
13mod graphical;
14mod operation;
15mod retire;
16mod seal;
17#[cfg(test)]
18mod tests;
19mod up;
20mod update;
21
22pub use attach::{AccessPick, AttachReport};
23
24use std::collections::BTreeMap;
25use std::path::Path;
26
27use isoloom_manifest::{Manifest, Provider, RunVar};
28
29use crate::Result;
30use crate::driver::AnyDriver;
31use crate::encoding::wire_name;
32use crate::error::Error;
33use crate::events::Emitter;
34use crate::executor::{Cx, LineWatch};
35use crate::manifest::LoadedManifest;
36use crate::name::RunName;
37use crate::options::RunOptions;
38use crate::outputs;
39use crate::params::params_for_existing;
40use crate::runner::Runner;
41use crate::scope::Scope;
42use crate::secrets::Secrets;
43use crate::status::{self, Status};
44
45/// A run: a manifest under a name, on a runner.
46pub struct Running<'r> {
47    pub(crate) runner: &'r Runner,
48    loaded: LoadedManifest,
49    name: RunName,
50    pub(crate) driver: AnyDriver,
51    /// Values of the manifest's connection slots, given once ([`Running::with_connection`]).
52    connection: Secrets,
53}
54
55impl std::fmt::Debug for Running<'_> {
56    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
57        f.debug_struct("Running")
58            .field("name", &self.name)
59            .field("manifest", &self.loaded.path)
60            .finish_non_exhaustive()
61    }
62}
63
64/// Makes the run's state folder of `cx`, owner-only, for what an operation (or a status read)
65/// writes there; a query that writes nothing leaves no folder behind.
66fn made(cx: &Cx<'_>) -> Result<()> {
67    crate::store::create_dir(cx.state_dir())
68}
69
70impl<'r> Running<'r> {
71    pub(crate) fn new(runner: &'r Runner, loaded: LoadedManifest, name: RunName) -> Result<Running<'r>> {
72        if !loaded.manifest.hosts.contains(&runner.config.host) {
73            return Err(Error::Unsupported {
74                what: format!("target `{}` on this host", wire_name(&loaded.manifest.target)),
75            });
76        }
77        let driver = AnyDriver::for_manifest(&loaded.manifest)?;
78        Ok(Running {
79            runner,
80            loaded,
81            name,
82            driver,
83            connection: Secrets::new(),
84        })
85    }
86
87    /// The run with `secrets`, the values of its connection slots (an ESXi host's password),
88    /// delivered to every operation, status (which takes no options) too. Kept in memory only,
89    /// never stored; a value an operation's options give wins.
90    #[must_use]
91    pub fn with_connection(mut self, secrets: Secrets) -> Running<'r> {
92        self.connection = secrets;
93        self
94    }
95
96    /// `opts` with the connection's values its secrets lack.
97    pub(crate) fn connected(&self, opts: &RunOptions) -> RunOptions {
98        let mut out = opts.clone();
99        for (name, value) in self.connection.iter() {
100            if out.secrets.get(name).is_none() {
101                out.secrets.insert(name, value.clone());
102            }
103        }
104        out
105    }
106
107    /// The manifest.
108    #[must_use]
109    pub fn manifest(&self) -> &Manifest {
110        &self.loaded.manifest
111    }
112
113    /// The run's name.
114    #[must_use]
115    pub fn name(&self) -> &RunName {
116        &self.name
117    }
118
119    /// The manifest's file.
120    pub(crate) fn path(&self) -> &Path {
121        &self.loaded.path
122    }
123
124    /// The manifest's folder (`${run.dir}`).
125    pub(crate) fn dir(&self) -> &Path {
126        &self.loaded.dir
127    }
128
129    /// A silent context of the run, with `events` and what its start kept (its record bound: its
130    /// SSH jump, its slot, its forwards; its provider; its params replayed, a fresh run's
131    /// defaults otherwise), so a way in is the run's: for the read-only queries. No lock.
132    fn silent_cx<'a>(&'a self, events: &'a Emitter<'a>) -> Result<(Option<crate::store::RunRecord>, Cx<'a>)> {
133        let record = self.runner.store.record(&self.name)?;
134        let provider = record.as_ref().and_then(|r| r.provider);
135        let params = params_for_existing(
136            self.manifest(),
137            record.as_ref().and_then(crate::store::RunRecord::replayed_params),
138            &BTreeMap::new(),
139            &self.scope(provider),
140        )?;
141        let mut cx = self.cx(params, &self.connection, events, provider)?;
142        cx.query = true;
143        if let Some(r) = &record {
144            Self::bind_record(&mut cx, r);
145        }
146        Ok((record, cx))
147    }
148
149    /// Runs `f` on a silent context of the run ([`Running::silent_cx`]), emitting nothing, its state
150    /// folder not made: for the queries that run no step.
151    pub(crate) fn query<T>(&self, f: impl FnOnce(&Cx<'_>) -> Result<T>) -> Result<T> {
152        let events = self.silent();
153        let (_, cx) = self.silent_cx(&events)?;
154        f(&cx)
155    }
156
157    /// An emitter of the run that says nothing.
158    fn silent(&self) -> Emitter<'_> {
159        Emitter::silent(self.name.as_str(), self.runner.config.clock.as_ref())
160    }
161
162    /// The run as it stands: never locked, and never an event. It changes nothing of the run, but
163    /// readies its state folder as an operation does for the tools it asks (the folder; Compose's
164    /// empty pinned-ports file, which every Compose call names; Terraform's plugin cache); it
165    /// never writes a secret (the consoles the runner chooses are an operation's to choose). While an operation holds the run
166    /// (this runner's, or another process's), the engine isn't asked: that operation acts on the
167    /// run with the same tools, which may refuse a read until it is done (Vagrant locks each VM
168    /// for the whole of a `vagrant up`, provisioning included). The status is then the
169    /// operation's state, with the machines as last read ([`Status::live`] false).
170    ///
171    /// # Errors
172    ///
173    /// Fails when the engine can't be asked (the status step fails or runs out of time) or the
174    /// run's record can't be read. Another process acting on a machine (Vagrant's lock on it,
175    /// past a short wait) is no failure: that machine is [`MachineState::Busy`](crate::MachineState::Busy),
176    /// the others as last read, and the status isn't live.
177    pub async fn status(&self) -> Result<Status> {
178        let events = self.silent();
179        let (record, mut cx) = self.silent_cx(&events)?;
180        let provider = cx.scope.provider;
181        let (state, mut observed, live) = self.read_for_query(&mut cx, record.as_ref()).await?;
182        let mut machines = std::mem::take(&mut observed.machines);
183        let known = cx.scope.provider;
184        for m in &mut machines {
185            let Some(declared) = self.manifest().machines.iter().find(|x| x.name.as_str() == m.name) else {
186                continue;
187            };
188            m.console = crate::graphical::ConsoleOffer::of(declared, known);
189            // A running machine's console is offered as it stands now: there, and answering.
190            if m.state.runs()
191                && let Some(offer) = m.console.as_mut()
192                && let Some(console) = declared.console(known).filter(|c| c.source.is_some())
193            {
194                offer.unavailable = crate::graphical::unavailable(&cx, declared, console).await;
195            }
196        }
197        let outputs = self.bind_observed(&mut cx, observed).values;
198        let message = (state == crate::RunState::Ready)
199            .then(|| outputs::message(self.manifest(), &cx.vars, &outputs))
200            .flatten();
201        Ok(Status {
202            state,
203            live,
204            provider,
205            machines,
206            networks: self.networks(&cx),
207            outputs,
208            message,
209            native: crate::graphical::native::app(self.manifest(), provider, cx.scope.host),
210        })
211    }
212
213    /// Where the run stands, its machines and whether they were read now, for a query (`cx`, a
214    /// silent context, `record` its run's record): while an operation holds the run, its state
215    /// and the machines as last read; else as the engine reads them, unless another process
216    /// acting on some of them refuses the read ([`crate::driver::Observed::busy`]): then those
217    /// are busy, the others as last read, and the run where an operation holding it now, or its
218    /// record, says.
219    pub(crate) async fn read_for_query(
220        &self,
221        cx: &mut Cx<'_>,
222        record: Option<&crate::store::RunRecord>,
223    ) -> Result<(crate::RunState, crate::driver::Observed, bool)> {
224        if let Some(state) = self.while_held(record)? {
225            return Ok((state, self.last_seen(), false));
226        }
227        made(cx)?;
228        self.driver.prepare(cx)?;
229        self.relay(cx).await?;
230        let observed = self.observe(cx).await?;
231        let Some(busy) = &observed.busy else {
232            return Ok((status::derive_state(&observed.machines, record), observed, true));
233        };
234        let recorded = record.map_or(crate::RunState::Absent, |r| r.state);
235        let state = self.while_held(record)?.unwrap_or(recorded);
236        let mut seen = self.last_seen();
237        for m in seen.machines.iter_mut().filter(|m| busy.contains(&m.name)) {
238            m.state = crate::MachineState::Busy;
239        }
240        Ok((state, seen, false))
241    }
242
243    /// Where the run stands while an operation holds it, if one does: the moving state of this
244    /// runner's operation on it (`starting` from the first instant of an `up`), else what its
245    /// record says (another process's operation records its moving state once it begins acting;
246    /// an update leaves the run `ready`).
247    fn while_held(&self, record: Option<&crate::store::RunRecord>) -> Result<Option<crate::RunState>> {
248        let recorded = record.map_or(crate::RunState::Absent, |r| r.state);
249        if let Some(op) = self.runner.op_of(&self.name) {
250            return Ok(Some(op.during().unwrap_or(recorded)));
251        }
252        Ok(self.runner.store.held(&self.name)?.then_some(recorded))
253    }
254
255    /// The run as the runner last read it ([`crate::store::Seen`]); nothing before it ever did,
256    /// or when what it kept can't be read (traced).
257    fn last_seen(&self) -> crate::driver::Observed {
258        match self.runner.store.seen(&self.name) {
259            Ok(seen) => crate::driver::Observed::from_seen(seen.unwrap_or_default()),
260            Err(e) => {
261                tracing::warn!(error = %e, "what the runner last saw of the run can't be read: no machine is shown");
262                crate::driver::Observed::default()
263            }
264        }
265    }
266
267    /// What `params`, `secrets` and `events` give this run's steps.
268    pub(crate) fn cx<'a>(
269        &'a self,
270        params: BTreeMap<String, String>,
271        secrets: &'a Secrets,
272        events: &'a Emitter<'a>,
273        provider: Option<Provider>,
274    ) -> Result<Cx<'a>> {
275        let state_dir = self.runner.store.run_dir_path(&self.name);
276        let mut vars = crate::vars::Vars::default();
277        vars.set_run(RunVar::Name, self.name.as_str());
278        vars.set_run(RunVar::Dir, self.dir().display().to_string());
279        vars.set_run(RunVar::StateDir, state_dir.display().to_string());
280        vars.set_run(RunVar::KnownHosts, state_dir.join(crate::ssh::KNOWN_HOSTS).display().to_string());
281        vars.set_run(RunVar::SshKey, crate::ssh::key_path(&self.runner.config.home).display().to_string());
282        if let Some(key) = crate::ssh::public_key(&self.runner.config.home)? {
283            vars.set_run(RunVar::SshPublicKey, key);
284        }
285        if let Some(p) = &provider {
286            vars.set_run(RunVar::Provider, crate::wire_name(p));
287        }
288        vars.set_params(params);
289        let stale = self
290            .manifest()
291            .recovery
292            .as_ref()
293            .map(|r| LineWatch::any_case(&r.stale_markers))
294            .unwrap_or_default();
295        Ok(Cx {
296            run: self,
297            state_dir,
298            vars,
299            secrets,
300            events,
301            scope: self.scope(provider),
302            stale,
303            gone: LineWatch::default(),
304            processes: std::sync::Arc::clone(&self.runner.config.processes),
305            ssh_jump: None,
306            expires_at: None,
307            relayed: None,
308            set_up: std::collections::BTreeSet::new(),
309            query: false,
310        })
311    }
312
313    /// `cx` for an operation that acts on the run (never a status read): on a provider whose
314    /// management commands need elevation (Hyper-V on Windows), its tools run through one
315    /// elevated session, kept in the run's state folder.
316    pub(crate) fn acting<'a>(&'a self, mut cx: Cx<'a>) -> Result<Cx<'a>> {
317        made(&cx)?;
318        if cx.scope.host == isoloom_manifest::HostOs::Windows && self.driver.elevates(&cx.scope) {
319            let dir = cx.state_dir().join("elevated");
320            let inner = std::sync::Arc::clone(&self.runner.config.processes);
321            cx.processes = std::sync::Arc::new(crate::process::Elevated::new(inner, dir, self.elevated_env()));
322        }
323        Ok(cx)
324    }
325
326    /// What an elevated session is handed of the environment the runner read when it was
327    /// configured ([`RunnerConfig::host_env`](crate::RunnerConfig) and its `PATH`).
328    pub(crate) fn elevated_env(&self) -> Vec<(String, String)> {
329        let config = &self.runner.config;
330        config.host_env.for_elevation(config.path.as_deref())
331    }
332
333    /// Makes the runner's SSH key when the manifest reaches a machine over SSH and it has none yet
334    /// (an adopted run, or one acted on from another home, may need it).
335    pub(crate) async fn ensure_ssh_key(&self) -> Result<()> {
336        if crate::ssh::needed(self.manifest()) {
337            crate::ssh::ensure_key(self.runner.config.processes.as_ref(), &self.runner.config.home).await?;
338        }
339        Ok(())
340    }
341
342    /// Starts the macOS relays `cx`'s run needs (Vagrant on an ESXi host), for the operation.
343    pub(crate) async fn relay(&self, cx: &mut Cx<'_>) -> Result<()> {
344        let config = &self.runner.config;
345        let vagrant = self.manifest().driver == isoloom_manifest::Driver::Vagrant;
346        let params = cx.vars.params();
347        let Some((host, port)) = crate::relay::esxi_host(&cx.scope, vagrant, params)? else {
348            return Ok(());
349        };
350        let no_proxy = config.host_env.text("no_proxy").or_else(|| config.host_env.text("NO_PROXY"));
351        let relayed = crate::relay::prepare(host, port, &config.home, config.path.as_deref(), no_proxy).await;
352        cx.relayed = Some(relayed?);
353        Ok(())
354    }
355
356    /// Binds what `record` keeps of the run into `cx`: its slot (`${run.slot}`), its SSH jump and
357    /// its expiry.
358    pub(crate) fn bind_record(cx: &mut Cx<'_>, record: &crate::store::RunRecord) {
359        if let Some(slot) = record.slot {
360            cx.vars.set_run(RunVar::Slot, slot.to_string());
361        }
362        cx.ssh_jump.clone_from(&record.ssh_jump);
363        cx.expires_at = record.expires_at;
364        // The host ports a fresh start pinned: a resume forwards the same ones, and status reads
365        // them back (the Vagrant driver reports its forwards from here, not the manifest's number).
366        cx.vars.set_vm_pins(record.vm_host_ports.clone());
367    }
368
369    /// This host, with `provider`.
370    pub(crate) fn scope(&self, provider: Option<Provider>) -> Scope {
371        Scope::new(self.runner.config.host, provider)
372    }
373
374    /// Reads what the engine gives back (published ports, outputs) and binds it, so a template
375    /// can name it (`${outputs.ip}`): the run's outputs.
376    pub(crate) async fn read_outputs(&self, cx: &mut Cx<'_>) -> Result<outputs::Read> {
377        let observed = self.observe(cx).await?;
378        Ok(self.bind_observed(cx, observed))
379    }
380
381    /// The run as its engine reports it: the driver's machines, then, when the run's containers
382    /// run inside one of its VMs (`docker-vm`'s guest), those containers as read in the VM.
383    /// What it read is kept as what the runner last saw of the run ([`crate::store::Seen`]).
384    pub(crate) async fn observe(&self, cx: &mut Cx<'_>) -> Result<crate::driver::Observed> {
385        let mut observed = self.driver.observe(cx).await?;
386        if observed.busy.is_some() {
387            // Nothing was read: what the runner last saw stands.
388            return Ok(observed);
389        }
390        if let Some(guest) = &self.manifest().guest {
391            crate::in_vm::observe(cx, guest, &mut observed).await;
392        }
393        if let Err(e) = self.runner.store.keep_seen(&self.name, &observed.seen()) {
394            tracing::warn!(error = %e, "what the runner saw of the run wasn't kept");
395        }
396        Ok(observed)
397    }
398
399    /// [`Running::observe`], refused with `not_running` when no member machine runs.
400    pub(crate) async fn observe_running(&self, cx: &mut Cx<'_>) -> Result<crate::driver::Observed> {
401        let observed = self.observe(cx).await?;
402        if !status::any_member_running(&observed.machines) {
403            return Err(Error::NotRunning { run: self.name().to_string() });
404        }
405        Ok(observed)
406    }
407
408    /// The manifest's machine `name`, refused with `machine_unknown` when the run has none.
409    pub(crate) fn machine_named(&self, name: &str) -> Result<&isoloom_manifest::Machine> {
410        self.manifest()
411            .machines
412            .iter()
413            .find(|m| m.name.as_str() == name)
414            .ok_or_else(|| Error::MachineUnknown {
415                run: self.name().to_string(),
416                machine: name.to_owned(),
417            })
418    }
419
420    /// Binds what `observed` gives back (published ports, outputs) into `cx`: the run's outputs.
421    pub(crate) fn bind_observed(&self, cx: &mut Cx<'_>, observed: crate::driver::Observed) -> outputs::Read {
422        cx.vars.set_published(observed.published);
423        cx.vars.set_hosts(observed.hosts);
424        let read = outputs::read(self.manifest(), &cx.vars, &observed.outputs, &observed.sensitive);
425        // A value the engine or the manifest keeps secret is masked in every later event.
426        cx.events
427            .hide(read.values.iter().filter(|o| o.sensitive).filter_map(|o| o.revealed().map(str::to_owned)));
428        outputs::bind(&mut cx.vars, &read.values);
429        read
430    }
431
432    /// The run's networks, their native names filled; one that can't be is left out, and traced.
433    fn networks(&self, cx: &Cx<'_>) -> Vec<status::NetworkView> {
434        status::networks(self.manifest(), |t| {
435            cx.vars
436                .render(t, "networks.native")
437                .inspect_err(|e| tracing::warn!(error = %e, "a network's native name couldn't be filled: it is left out"))
438                .ok()
439        })
440    }
441}