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        // Nothing is emitted, but its errors say what a tool printed: the connection's secrets
142        // masked there, as an operation's are.
143        events.hide(crate::secrets::sensitive_values(self.manifest(), &self.connection));
144        let mut cx = self.cx(params, &self.connection, events, provider)?;
145        cx.query = true;
146        if let Some(r) = &record {
147            Self::bind_record(&mut cx, r);
148        }
149        Ok((record, cx))
150    }
151
152    /// Runs `f` on a silent context of the run ([`Running::silent_cx`]), emitting nothing, its state
153    /// folder not made: for the queries that run no step.
154    pub(crate) fn query<T>(&self, f: impl FnOnce(&Cx<'_>) -> Result<T>) -> Result<T> {
155        let events = self.silent();
156        let (_, cx) = self.silent_cx(&events)?;
157        f(&cx)
158    }
159
160    /// An emitter of the run that says nothing.
161    fn silent(&self) -> Emitter<'_> {
162        Emitter::silent(self.name.as_str(), self.runner.config.clock.as_ref())
163    }
164
165    /// The run as it stands: never locked, and never an event. It changes nothing of the run, but
166    /// readies its state folder as an operation does for the tools it asks (the folder; Compose's
167    /// empty pinned-ports file, which every Compose call names; Terraform's plugin cache); it
168    /// never writes a secret (the consoles the runner chooses are an operation's to choose). While an operation holds the run
169    /// (this runner's, or another process's), the engine isn't asked: that operation acts on the
170    /// run with the same tools, which may refuse a read until it is done (Vagrant locks each VM
171    /// for the whole of a `vagrant up`, provisioning included). The status is then the
172    /// operation's state, with the machines as last read ([`Status::live`] false).
173    ///
174    /// # Errors
175    ///
176    /// Fails when the engine can't be asked (the status step fails or runs out of time) or the
177    /// run's record can't be read. Another process acting on a machine (Vagrant's lock on it,
178    /// past a short wait) is no failure: that machine is [`MachineState::Busy`](crate::MachineState::Busy),
179    /// the others as last read, and the status isn't live.
180    pub async fn status(&self) -> Result<Status> {
181        let events = self.silent();
182        let (record, mut cx) = self.silent_cx(&events)?;
183        let provider = cx.scope.provider;
184        let read = self.read_for_query(&mut cx, record.as_ref()).await;
185        let (state, mut observed, live) = read.map_err(|e| self.refused_sign_in(e, &RunOptions::new().with_params(cx.vars.params().clone())))?;
186        let mut machines = std::mem::take(&mut observed.machines);
187        let known = cx.scope.provider;
188        for m in &mut machines {
189            let Some(declared) = self.manifest().machines.iter().find(|x| x.name.as_str() == m.name) else {
190                continue;
191            };
192            m.console = crate::graphical::ConsoleOffer::of(declared, known);
193            // A running machine's console is offered as it stands now: there, and answering.
194            if m.state.runs()
195                && let Some(offer) = m.console.as_mut()
196                && let Some(console) = declared.console(known).filter(|c| c.source.is_some())
197            {
198                offer.unavailable = crate::graphical::unavailable(&cx, declared, console).await;
199            }
200        }
201        let outputs = self.bind_observed(&mut cx, observed).values;
202        let message = (state == crate::RunState::Ready)
203            .then(|| outputs::message(self.manifest(), &cx.vars, &outputs))
204            .flatten();
205        Ok(Status {
206            state,
207            live,
208            provider,
209            machines,
210            networks: self.networks(&cx),
211            outputs,
212            message,
213            native: crate::graphical::native::app(self.manifest(), provider, cx.scope.host),
214        })
215    }
216
217    /// Where the run stands, its machines and whether they were read now, for a query (`cx`, a
218    /// silent context, `record` its run's record): while an operation holds the run, its state
219    /// and the machines as last read; else as the engine reads them, unless another process
220    /// acting on some of them refuses the read ([`crate::driver::Observed::busy`]): then those
221    /// are busy, the others as last read, and the run where an operation holding it now, or its
222    /// record, says.
223    pub(crate) async fn read_for_query(
224        &self,
225        cx: &mut Cx<'_>,
226        record: Option<&crate::store::RunRecord>,
227    ) -> Result<(crate::RunState, crate::driver::Observed, bool)> {
228        if let Some(state) = self.while_held(record)? {
229            return Ok((state, self.last_seen(), false));
230        }
231        made(cx)?;
232        self.driver.prepare(cx)?;
233        self.relay(cx).await?;
234        let observed = self.observe(cx).await?;
235        let Some(busy) = &observed.busy else {
236            return Ok((status::derive_state(&observed.machines, record), observed, true));
237        };
238        let recorded = record.map_or(crate::RunState::Absent, |r| r.state);
239        let state = self.while_held(record)?.unwrap_or(recorded);
240        let mut seen = self.last_seen();
241        for m in seen.machines.iter_mut().filter(|m| busy.contains(&m.name)) {
242            m.state = crate::MachineState::Busy;
243        }
244        Ok((state, seen, false))
245    }
246
247    /// Where the run stands while an operation holds it, if one does: the moving state of this
248    /// runner's operation on it (`starting` from the first instant of an `up`), else what its
249    /// record says (another process's operation records its moving state once it begins acting;
250    /// an update leaves the run `ready`).
251    fn while_held(&self, record: Option<&crate::store::RunRecord>) -> Result<Option<crate::RunState>> {
252        let recorded = record.map_or(crate::RunState::Absent, |r| r.state);
253        if let Some(op) = self.runner.op_of(&self.name) {
254            return Ok(Some(op.during().unwrap_or(recorded)));
255        }
256        Ok(self.runner.store.held(&self.name)?.then_some(recorded))
257    }
258
259    /// The run as the runner last read it ([`crate::store::Seen`]); nothing before it ever did,
260    /// or when what it kept can't be read (traced).
261    fn last_seen(&self) -> crate::driver::Observed {
262        match self.runner.store.seen(&self.name) {
263            Ok(seen) => crate::driver::Observed::from_seen(seen.unwrap_or_default()),
264            Err(e) => {
265                tracing::warn!(error = %e, "what the runner last saw of the run can't be read: no machine is shown");
266                crate::driver::Observed::default()
267            }
268        }
269    }
270
271    /// What `params`, `secrets` and `events` give this run's steps.
272    pub(crate) fn cx<'a>(
273        &'a self,
274        params: BTreeMap<String, String>,
275        secrets: &'a Secrets,
276        events: &'a Emitter<'a>,
277        provider: Option<Provider>,
278    ) -> Result<Cx<'a>> {
279        let state_dir = self.runner.store.run_dir_path(&self.name);
280        let mut vars = crate::vars::Vars::default();
281        vars.set_run(RunVar::Name, self.name.as_str());
282        vars.set_run(RunVar::Dir, self.dir().display().to_string());
283        vars.set_run(RunVar::StateDir, state_dir.display().to_string());
284        vars.set_run(RunVar::KnownHosts, state_dir.join(crate::ssh::KNOWN_HOSTS).display().to_string());
285        vars.set_run(RunVar::SshKey, crate::ssh::key_path(&self.runner.config.home).display().to_string());
286        if let Some(key) = crate::ssh::public_key(&self.runner.config.home)? {
287            vars.set_run(RunVar::SshPublicKey, key);
288        }
289        if let Some(p) = &provider {
290            vars.set_run(RunVar::Provider, crate::wire_name(p));
291        }
292        vars.set_params(params);
293        let stale = self
294            .manifest()
295            .recovery
296            .as_ref()
297            .map(|r| LineWatch::any_case(&r.stale_markers))
298            .unwrap_or_default();
299        Ok(Cx {
300            run: self,
301            state_dir,
302            vars,
303            secrets,
304            events,
305            scope: self.scope(provider),
306            stale,
307            gone: LineWatch::default(),
308            processes: std::sync::Arc::clone(&self.runner.config.processes),
309            ssh_jump: None,
310            expires_at: None,
311            relayed: None,
312            set_up: std::collections::BTreeSet::new(),
313            query: false,
314        })
315    }
316
317    /// `cx` for an operation that acts on the run (never a status read): on a provider whose
318    /// management commands need elevation (Hyper-V on Windows), its tools run through one
319    /// elevated session, kept in the run's state folder.
320    pub(crate) fn acting<'a>(&'a self, mut cx: Cx<'a>) -> Result<Cx<'a>> {
321        made(&cx)?;
322        // Its tools recorded in the run's state folder while they run: this process killed, the
323        // next operation ends them ([`crate::process::ledger`]).
324        let tools = cx.state_dir().join(crate::process::ledger::DIR);
325        let recorded: std::sync::Arc<dyn crate::ProcessRunner> =
326            std::sync::Arc::new(crate::process::Recording::new(std::sync::Arc::clone(&self.runner.config.processes), tools));
327        cx.processes = std::sync::Arc::clone(&recorded);
328        if cx.scope.host == isoloom_manifest::HostOs::Windows && self.driver.elevates(&cx.scope) {
329            let dir = cx.state_dir().join("elevated");
330            cx.processes = std::sync::Arc::new(crate::process::Elevated::new(recorded, dir, self.elevated_env()));
331        }
332        Ok(cx)
333    }
334
335    /// What an elevated session is handed of the environment the runner read when it was
336    /// configured ([`RunnerConfig::host_env`](crate::RunnerConfig) and its `PATH`).
337    pub(crate) fn elevated_env(&self) -> Vec<(String, String)> {
338        let config = &self.runner.config;
339        config.host_env.for_elevation(config.path.as_deref())
340    }
341
342    /// Makes the runner's SSH key when the manifest reaches a machine over SSH and it has none yet
343    /// (an adopted run, or one acted on from another home, may need it).
344    pub(crate) async fn ensure_ssh_key(&self) -> Result<()> {
345        if crate::ssh::needed(self.manifest()) {
346            crate::ssh::ensure_key(self.runner.config.processes.as_ref(), &self.runner.config.home).await?;
347        }
348        Ok(())
349    }
350
351    /// Starts the macOS relays `cx`'s run needs (Vagrant on an ESXi host), for the operation.
352    pub(crate) async fn relay(&self, cx: &mut Cx<'_>) -> Result<()> {
353        let config = &self.runner.config;
354        let vagrant = self.manifest().driver == isoloom_manifest::Driver::Vagrant;
355        let params = cx.vars.params();
356        let Some((host, port)) = crate::relay::esxi_host(&cx.scope, vagrant, params)? else {
357            return Ok(());
358        };
359        let no_proxy = config.host_env.text("no_proxy").or_else(|| config.host_env.text("NO_PROXY"));
360        let relayed = crate::relay::prepare(host, port, &config.home, config.path.as_deref(), no_proxy).await;
361        cx.relayed = Some(relayed?);
362        Ok(())
363    }
364
365    /// Binds what `record` keeps of the run into `cx`: its slot (`${run.slot}`), its SSH jump and
366    /// its expiry.
367    pub(crate) fn bind_record(cx: &mut Cx<'_>, record: &crate::store::RunRecord) {
368        if let Some(slot) = record.slot {
369            cx.vars.set_run(RunVar::Slot, slot.to_string());
370        }
371        cx.ssh_jump.clone_from(&record.ssh_jump);
372        cx.expires_at = record.expires_at;
373        // The host ports a fresh start pinned: a resume forwards the same ones, and status reads
374        // them back (the Vagrant driver reports its forwards from here, not the manifest's number).
375        cx.vars.set_vm_pins(record.vm_host_ports.clone());
376    }
377
378    /// This host, with `provider`.
379    pub(crate) fn scope(&self, provider: Option<Provider>) -> Scope {
380        Scope::new(self.runner.config.host, provider)
381    }
382
383    /// Reads what the engine gives back (published ports, outputs) and binds it, so a template
384    /// can name it (`${outputs.ip}`): the run's outputs.
385    pub(crate) async fn read_outputs(&self, cx: &mut Cx<'_>) -> Result<outputs::Read> {
386        let observed = self.observe(cx).await?;
387        Ok(self.bind_observed(cx, observed))
388    }
389
390    /// The run as its engine reports it: the driver's machines, then, when the run's containers
391    /// run inside one of its VMs (`docker-vm`'s guest), those containers as read in the VM.
392    /// What it read is kept as what the runner last saw of the run ([`crate::store::Seen`]).
393    pub(crate) async fn observe(&self, cx: &mut Cx<'_>) -> Result<crate::driver::Observed> {
394        let mut observed = self.driver.observe(cx).await?;
395        if observed.busy.is_some() {
396            // Nothing was read: what the runner last saw stands.
397            return Ok(observed);
398        }
399        if let Some(guest) = &self.manifest().guest {
400            crate::in_vm::observe(cx, guest, &mut observed).await;
401        }
402        if let Err(e) = self.runner.store.keep_seen(&self.name, &observed.seen()) {
403            tracing::warn!(error = %e, "what the runner saw of the run wasn't kept");
404        }
405        Ok(observed)
406    }
407
408    /// [`Running::observe`], refused with `not_running` when no member machine runs.
409    pub(crate) async fn observe_running(&self, cx: &mut Cx<'_>) -> Result<crate::driver::Observed> {
410        let observed = self.observe(cx).await?;
411        if !status::any_member_running(&observed.machines) {
412            return Err(Error::NotRunning { run: self.name().to_string() });
413        }
414        Ok(observed)
415    }
416
417    /// The manifest's machine `name`, refused with `machine_unknown` when the run has none.
418    pub(crate) fn machine_named(&self, name: &str) -> Result<&isoloom_manifest::Machine> {
419        self.manifest()
420            .machines
421            .iter()
422            .find(|m| m.name.as_str() == name)
423            .ok_or_else(|| Error::MachineUnknown {
424                run: self.name().to_string(),
425                machine: name.to_owned(),
426            })
427    }
428
429    /// Binds what `observed` gives back (published ports, outputs) into `cx`: the run's outputs.
430    pub(crate) fn bind_observed(&self, cx: &mut Cx<'_>, observed: crate::driver::Observed) -> outputs::Read {
431        cx.vars.set_published(observed.published);
432        cx.vars.set_hosts(observed.hosts);
433        let read = outputs::read(self.manifest(), &cx.vars, &observed.outputs, &observed.sensitive);
434        // A value the engine or the manifest keeps secret is masked in every later event.
435        cx.events
436            .hide(read.values.iter().filter(|o| o.sensitive).filter_map(|o| o.revealed().map(str::to_owned)));
437        outputs::bind(&mut cx.vars, &read.values);
438        read
439    }
440
441    /// The run's networks, their native names filled; one that can't be is left out, and traced.
442    fn networks(&self, cx: &Cx<'_>) -> Vec<status::NetworkView> {
443        status::networks(self.manifest(), |t| {
444            cx.vars
445                .render(t, "networks.native")
446                .inspect_err(|e| tracing::warn!(error = %e, "a network's native name couldn't be filled: it is left out"))
447                .ok()
448        })
449    }
450}