Skip to main content

isothrum_runner/
run.rs

1//! A run of a project folder: any Compose project, Vagrantfile or Terraform module, driven by its
2//! format's driver ([`crate::formats`]). Each operation is journaled, holds the run's lock, moves
3//! the run's state, records the resources the tool reports and says it all as events, the same
4//! way for every format; only the driver knows its tool. `operate` is what every operation does
5//! around its own work, `recovery` what it does about what dead operations left.
6
7mod endpoints;
8mod graphical;
9mod operate;
10mod ports;
11mod processes;
12mod quiet;
13pub(crate) mod recovery;
14pub use endpoints::ServiceEndpoint;
15mod status;
16use self::quiet::Quiet;
17use status::status_of;
18#[cfg(test)]
19mod tests;
20
21use std::path::{Path, PathBuf};
22
23use crate::Result;
24use crate::console::ShellCommand;
25use crate::error::Error;
26use crate::events::{Emitter, Events, ResultData, ShownOutput, Stream, WarningCode};
27use crate::formats::any::AnyFormat;
28use crate::formats::{Seen, ToolCx, ledger};
29use crate::name::RunName;
30use crate::options::RunOptions;
31use crate::process::ProcessRunner;
32use crate::project::{Format, Project};
33use crate::runner::Runner;
34use crate::state::{Op, Park, RunState};
35use crate::status::{OutputValue, Started, Status};
36use crate::store::{LastObserved, OperationId};
37
38use operate::Done;
39
40/// What a command run in a machine of the run said ([`Running::exec`]).
41#[derive(Debug, Clone, PartialEq, Eq)]
42#[non_exhaustive]
43pub struct ExecReport {
44    /// The machine it ran in.
45    pub machine: String,
46    /// Its exit status (`-1` when it was killed by a signal).
47    pub exit: i32,
48    /// Its standard output.
49    pub stdout: String,
50    /// The end of its standard error.
51    pub stderr: String,
52}
53
54/// What an operation that moves the run asks of its tool ([`Running::drive`]).
55#[derive(Debug, Clone, Copy)]
56enum Act<'a> {
57    /// Make and start everything.
58    Up,
59    /// Stop the machines and keep them.
60    Park(Park),
61    /// Start the parked machines again.
62    Resume,
63    /// Bring the run to the project's files.
64    Update,
65    /// Run the set-up again, on one machine or all.
66    Provision(Option<&'a str>, Option<&'a str>),
67    /// Start a machine the project leaves down.
68    Attach(&'a str),
69    /// Remove a machine.
70    Retire(&'a str),
71    /// Save a machine as a box file.
72    Package(&'a str, &'a Path),
73}
74
75impl Act<'_> {
76    /// The operation it is.
77    fn op(self) -> Op {
78        match self {
79            Act::Up => Op::Up,
80            Act::Park(_) => Op::Park,
81            Act::Resume => Op::Resume,
82            Act::Update => Op::Update,
83            Act::Provision(..) => Op::Provision,
84            Act::Attach(_) => Op::Attach,
85            Act::Retire(_) => Op::Retire,
86            Act::Package(..) => Op::Package,
87        }
88    }
89}
90
91/// The host ports run `run` pins, reserved through its runner for the operation.
92struct RunPorts<'a> {
93    runner: &'a Runner,
94    run: &'a RunName,
95}
96
97impl crate::formats::PickPorts for RunPorts<'_> {
98    fn pick(&self, protocol: crate::project::platform::Protocol) -> std::io::Result<Option<crate::net::HeldPort>> {
99        self.runner.pick_reserved(self.run, protocol)
100    }
101
102    fn claim(&self, ports: &[(crate::port::HostPort, crate::project::platform::Protocol)]) -> Result<()> {
103        self.runner.claim_ports(self.run, ports.iter().copied())
104    }
105}
106
107/// Removes a recorded resource through the run's driver, by the id its tool gave.
108struct ById<'a, 'c> {
109    driver: AnyFormat,
110    cx: &'a ToolCx<'c>,
111}
112
113impl recovery::Remover for ById<'_, '_> {
114    async fn remove(&mut self, row: &crate::store::ResourceRow) -> Result<()> {
115        let id = row.native_id.as_deref().unwrap_or_default();
116        self.driver.destroy_by_id(self.cx, &row.key, row.kind, id).await
117    }
118}
119
120/// A run of a project folder.
121pub struct Running<'r> {
122    runner: &'r Runner,
123    project: Project,
124    name: RunName,
125    driver: AnyFormat,
126    /// The elevated processes every operation of this handle shares, once
127    /// [`Running::sharing_elevation`] asked for it (none: one elevation per operation).
128    elevation: Option<std::sync::OnceLock<std::sync::Arc<dyn crate::process::ProcessRunner>>>,
129}
130
131impl<'r> Running<'r> {
132    /// Run `name` of `project` on `runner`.
133    pub(crate) fn new(runner: &'r Runner, project: Project, name: RunName) -> Running<'r> {
134        let driver = AnyFormat::of(project.format);
135        Running {
136            runner,
137            project,
138            name,
139            driver,
140            elevation: None,
141        }
142    }
143
144    /// The run's name.
145    #[must_use]
146    pub fn name(&self) -> &RunName {
147        &self.name
148    }
149
150    /// The project it runs.
151    #[must_use]
152    pub fn project(&self) -> &Project {
153        &self.project
154    }
155
156    /// The folder the runner keeps the run's own files in.
157    fn state_dir(&self) -> PathBuf {
158        self.runner.store.run_dir_path(&self.name)
159    }
160
161    /// Every variable the run's tools get: the run's key, then its values and secrets as the
162    /// format reads them ([`crate::project::inputs`]).
163    fn tool_env(&self, opts: &RunOptions) -> Result<Vec<(String, String)>> {
164        let mut env = vec![(crate::RUN_KEY_VAR.to_owned(), self.runner.copy_key(&self.name))];
165        // The values the run's record keeps, under those the caller gives now.
166        let mut values = self.runner.store.record(&self.name)?.map(|r| r.env).unwrap_or_default();
167        values.extend(opts.env.iter().map(|(k, v)| (k.clone(), v.clone())));
168        if self.project.format == Format::Terraform {
169            // Every run of the runner shares one provider cache, unless the user has their own.
170            let cache = crate::formats::terraform::plugin_cache(&self.runner.config);
171            std::fs::create_dir_all(&cache).map_err(Error::io(&cache, "create"))?;
172            env.push(("TF_PLUGIN_CACHE_DIR".to_owned(), cache.to_string_lossy().into_owned()));
173        }
174        env.extend(crate::project::inputs::environment(self.project.format, &values, &opts.secrets)?);
175        if self.project.format == Format::Vagrant {
176            // The ports the run kept, for a Vagrantfile that pins its forwards to them.
177            env.extend(ports::env(&ports::kept(&self.state_dir())?));
178        }
179        Ok(env)
180    }
181
182    /// The hypervisor the run takes: the one the caller names, else the one its start recorded (a
183    /// `down` names none, and must reach the VMs its start made on their provider).
184    fn provider(&self, opts: &RunOptions) -> Option<crate::Provider> {
185        opts.provider
186            .or_else(|| self.runner.store.record(&self.name).ok().flatten().and_then(|r| r.provider))
187    }
188
189    /// Runs `work` with a tool context for this run, whose tool lines, steps and warnings go to
190    /// `emitter` (the lines as the operation's own step). A step still open when `work` returns
191    /// ends as it ended ([`crate::steps::Steps::end`]).
192    async fn with_cx<T>(
193        &self,
194        opts: &RunOptions,
195        emitter: &Emitter<'_>,
196        processes: &dyn ProcessRunner,
197        work: impl AsyncFnOnce(&ToolCx<'_>) -> Result<T>,
198    ) -> Result<T> {
199        let state_dir = self.state_dir();
200        let key = self.runner.copy_key(&self.name);
201        let ssh_key = crate::ssh::key_path(&self.runner.config.home);
202        let step = emitter.operation_name();
203        let sink = |stream: Stream, line: &str| emitter.log(step, stream, line);
204        let warn = |code: WarningCode, message: &str| emitter.warning(code, message);
205        let say = |kind: crate::events::EventKind| emitter.emit(kind);
206        let ports = RunPorts {
207            runner: self.runner,
208            run: &self.name,
209        };
210        let made = || self.made();
211        let context = self.docker_context(opts);
212        let fetched = |item: crate::DownloadItem| self.record_fetched(item, context.as_deref());
213        let processes = &crate::process::DockerContext {
214            inner: processes,
215            context: context.as_deref(),
216        };
217        let cx = ToolCx {
218            project: &self.project,
219            run: &self.name,
220            key: &key,
221            state_dir: &state_dir,
222            provider: self.provider(opts),
223            env: self.tool_env(opts)?,
224            processes,
225            ssh_key: &ssh_key,
226            ports: &ports,
227            host_env: &self.runner.config.host_env,
228            sink: &sink,
229            warn: &warn,
230            steps: crate::steps::Steps::new(&say),
231            made: &made,
232            fetched: Some(&fetched),
233        };
234        let done = work(&cx).await;
235        cx.steps.end(done.is_ok());
236        done
237    }
238
239    /// Keeps `seen`, an operation's own read, as what the runner last saw of the run, its state
240    /// left to the operation: a status read after it compares with it.
241    fn keep_seen(&self, seen: &Seen) -> Result<()> {
242        let observed = LastObserved {
243            machines: status::machine_statuses(&seen.machines),
244        };
245        self.runner.store.db().write(|tx| tx.keep_observed(&self.name, &observed)).map(drop)
246    }
247
248    /// Records what the tool now reports of the run's resources against the store's rows, and
249    /// says each row that moved.
250    async fn record_found(&self, cx: &ToolCx<'_>, emitter: &Emitter<'_>, by: OperationId) -> Result<()> {
251        let found = self.driver.found(cx).await?;
252        let db = self.runner.store.db();
253        let recorded = db.write(|tx| ledger::record_found(tx, &self.name, by, &found))?;
254        let moved: Vec<_> = recorded.made.iter().chain(&recorded.gone).copied().collect();
255        crate::run::recovery::say(emitter, db, &moved);
256        // A machine made again (destroyed outside, recovered, re-made by an update) is a new VM,
257        // maybe at its old address, with new host keys: the pins go, and the next console pins
258        // the keys it meets (#110).
259        let machines = db.read(|tx| moved.iter().map(|id| tx.resource(*id)).collect::<Result<Vec<_>>>())?;
260        if machines.into_iter().flatten().any(|r| r.kind == crate::store::ResourceKind::Vm) {
261            crate::ssh::forget(&self.state_dir())?;
262        }
263        Ok(())
264    }
265
266    /// Removes, by recorded id, what dead operations of the run left, before this one acts.
267    async fn recover(&self, cx: &ToolCx<'_>, emitter: &Emitter<'_>, by: OperationId) -> Result<()> {
268        let db = self.runner.store.db();
269        let rows = db.read(|tx| tx.left_by_dead_operations(&self.name, by))?;
270        if rows.is_empty() {
271            return Ok(());
272        }
273        let left = recovery::destroy_recorded(db, emitter, by, &rows, ById { driver: self.driver, cx }).await?;
274        for not in &left {
275            emitter.warning(
276                WarningCode::CleanupFailed,
277                &format!("`{}` an earlier operation left wasn't removed: {}", not.row.key, not.error),
278            );
279        }
280        Ok(())
281    }
282
283    /// Drives the tool as `act` says.
284    async fn act(&self, cx: &ToolCx<'_>, act: Act<'_>) -> Result<()> {
285        match act {
286            Act::Up => self.driver.up(cx).await,
287            Act::Park(mode) => self.driver.park(cx, mode).await.and_then(|()| self.note_parked(mode)),
288            Act::Resume => self.driver.resume(cx).await,
289            Act::Update => {
290                self.driver.update(cx).await?;
291                if self.project.format == Format::Vagrant {
292                    // Compose's --remove-orphans and Terraform's apply take what the files no
293                    // longer declare themselves; a service under a profile the run attached isn't
294                    // in what Compose's files start, and is no orphan.
295                    self.retire_undeclared(cx).await?;
296                }
297                Ok(())
298            }
299            Act::Provision(machine, with) => self.driver.provision(cx, machine, with).await,
300            Act::Attach(machine) => self.driver.attach(cx, machine).await,
301            Act::Retire(machine) => self.driver.retire(cx, machine).await,
302            Act::Package(machine, output) => self.driver.package(cx, machine, output).await,
303        }
304    }
305
306    /// After an update: the running machines the project's files no longer declare, brought down
307    /// by the driver's re-apply (a Vagrant machine whose `define` left the Vagrantfile, which
308    /// `vagrant up` leaves running; Compose's `--remove-orphans` and Terraform's apply leave none).
309    async fn retire_undeclared(&self, cx: &ToolCx<'_>) -> Result<()> {
310        let declared = self.driver.machines(cx).await?;
311        let (seen, _) = self.driver.observe(cx).await?;
312        let removed: Vec<String> = seen.machines.into_iter().map(|m| m.name).filter(|m| !declared.contains(m)).collect();
313        if removed.is_empty() {
314            return Ok(());
315        }
316        let change = crate::formats::Change {
317            removed,
318            ..crate::formats::Change::default()
319        };
320        self.driver.reapply(cx, &change).await
321    }
322
323    /// Runs `act` as an operation: what dead operations left removed, the tool probed and driven,
324    /// then the resources it reports recorded and where the run stands read.
325    async fn drive(&self, act: Act<'_>, opts: &RunOptions, events: &dyn Events) -> Result<RunState> {
326        let op = act.op();
327        self.operate(op, opts, events, async |given: &RunOptions, emitter: &Emitter<'_>, by: OperationId| {
328            let processes = self.operation_processes(given);
329            self.with_cx(given, emitter, processes.as_ref(), async |cx: &ToolCx<'_>| {
330                self.recover(cx, emitter, by).await?;
331                self.driver.probe(cx).await?;
332                self.act(cx, act).await?;
333                self.record_found(cx, emitter, by).await?;
334                let (seen, state) = self.driver.observe(cx).await?;
335                self.keep_seen(&seen)?;
336                operate::not_whole(op, &seen, state)?;
337                if matches!(op, Op::Up | Op::Resume | Op::Update) {
338                    ports::keep(&self.state_dir(), &seen, cx.warn)?;
339                }
340                Ok((seen, state))
341            })
342            .await
343            .map(|(seen, state)| {
344                let goal = op_goal(op).unwrap_or(state);
345                let data = if op == Op::Up {
346                    // A start says what the project gives back (a module's outputs), masked.
347                    let outputs = status_of(&seen, goal, true, None).outputs;
348                    ResultData::Started {
349                        state: goal,
350                        outputs: outputs.into_iter().map(|o| ShownOutput::new(o.name, o.value)).collect(),
351                    }
352                } else {
353                    ResultData::Moved { state: goal }
354                };
355                Done::settled(goal, data)
356            })
357        })
358        .await
359    }
360
361    /// Starts the run: makes and starts everything, and returns once the project says it's ready.
362    ///
363    /// # Errors
364    ///
365    /// Fails, after its `error` event, as the run's tool does (missing, too old, failing, out of
366    /// time), with `port_in_use` for a host port taken, or as the run's state refuses an `up`:
367    /// `already_running` for a run that is ready and live (its tool says so now), before any tool
368    /// acts. A run recorded ready whose machines are gone or stopped meanwhile starts again.
369    pub async fn up(&self, opts: &RunOptions, events: &dyn Events) -> Result<Started> {
370        self.refresh_if(RunState::Ready, opts).await;
371        self.drive(Act::Up, opts, events).await?;
372        let record = self
373            .runner
374            .store
375            .record(&self.name)?
376            .ok_or_else(|| Error::NotRunning { run: self.name.to_string() })?;
377        let outputs = self.outputs(opts).await.unwrap_or_default();
378        Ok(Started { record, outputs })
379    }
380
381    /// Removes everything the run made, the tunnels of its consoles ended first (whichever
382    /// process holds them), and forgets its machines' pinned SSH host keys.
383    ///
384    /// # Errors
385    ///
386    /// As [`Running::up`]'s tool failures.
387    pub async fn down(&self, opts: &RunOptions, events: &dyn Events) -> Result<()> {
388        self.operate(Op::Down, opts, events, async |given: &RunOptions, emitter: &Emitter<'_>, by: OperationId| {
389            let processes = self.operation_processes(given);
390            self.with_cx(given, emitter, processes.as_ref(), async |cx: &ToolCx<'_>| {
391                // The consoles' tunnels to the machines that go, whichever process holds them.
392                crate::process::ledger::end_tunnels(&self.state_dir().join(crate::process::ledger::DIR)).await;
393                self.driver.probe(cx).await?;
394                self.driver.down(cx).await?;
395                // The machines' pinned host keys go with them, and the ports they kept.
396                crate::ssh::forget(&self.state_dir())?;
397                ports::forget(&self.state_dir())?;
398                // What the tool's own down left that the run made, by recorded id.
399                self.record_found(cx, emitter, by).await?;
400                let db = self.runner.store.db();
401                let left = db.read(|tx| ledger::left_to_remove(tx, &self.name))?;
402                recovery::destroy_recorded(db, emitter, by, &left, ById { driver: self.driver, cx }).await?;
403                // A status while the next start holds the run shows none of these machines.
404                db.write(|tx| tx.forget_observed(&self.name))?;
405                Ok(())
406            })
407            .await
408            .map(|()| Done::moved(RunState::Absent))
409        })
410        .await
411    }
412
413    /// Stops the machines and keeps them, as `mode` says.
414    ///
415    /// # Errors
416    ///
417    /// As the tool fails, or as the run's state refuses a park.
418    pub async fn park(&self, mode: Park, opts: &RunOptions, events: &dyn Events) -> Result<()> {
419        self.drive(Act::Park(mode), opts, events).await.map(drop)
420    }
421
422    /// Starts the parked machines again.
423    ///
424    /// # Errors
425    ///
426    /// As the tool fails, or as the run's state refuses a resume: `nothing_to_resume` for a run
427    /// of which nothing is left (never started, brought down, or its parked machines removed
428    /// meanwhile: its record then reads absent), before any tool acts.
429    pub async fn resume(&self, opts: &RunOptions, events: &dyn Events) -> Result<()> {
430        self.refresh_if(RunState::Parked, opts).await;
431        self.drive(Act::Resume, opts, events).await.map(drop)
432    }
433
434    /// Brings the running run to what the project's files now say.
435    ///
436    /// # Errors
437    ///
438    /// As the tool fails; `not_running`, before any tool acts, when the run isn't ready.
439    pub async fn update(&self, opts: &RunOptions, events: &dyn Events) -> Result<()> {
440        self.drive(Act::Update, opts, events).await.map(drop)
441    }
442
443    /// Runs the project's set-up again (its provisioners), on `machine` or on every machine.
444    ///
445    /// # Errors
446    ///
447    /// As the tool fails; `unsupported` where the format has no set-up of its own to run again;
448    /// `not_running`, before any tool acts, when nothing of the run runs. `with`, when given, runs
449    /// only the provisioner of that name (a Vagrant project's `checks`).
450    pub async fn provision(&self, machine: Option<&str>, with: Option<&str>, opts: &RunOptions, events: &dyn Events) -> Result<()> {
451        self.drive(Act::Provision(machine, with), opts, events).await.map(drop)
452    }
453
454    /// Starts `machine`, one the project leaves down at `up`.
455    ///
456    /// # Errors
457    ///
458    /// As the tool fails; `unsupported` where the format has no such machine; `not_running`,
459    /// before any tool acts, when nothing of the run runs.
460    pub async fn attach(&self, machine: &str, opts: &RunOptions, events: &dyn Events) -> Result<()> {
461        self.drive(Act::Attach(machine), opts, events).await.map(drop)
462    }
463
464    /// Removes `machine` from the running run.
465    ///
466    /// # Errors
467    ///
468    /// As the tool fails; `not_running`, before any tool acts, when the run isn't ready.
469    pub async fn retire(&self, machine: &str, opts: &RunOptions, events: &dyn Events) -> Result<()> {
470        self.drive(Act::Retire(machine), opts, events).await.map(drop)
471    }
472
473    /// Saves `machine` as a box file at `output`, which a later run boots from (`vagrant box add`
474    /// it first): the machine is stopped first and kept, so the run reads failed after, until it
475    /// is resumed or brought down.
476    ///
477    /// # Errors
478    ///
479    /// As the tool fails; `unsupported` where the format makes no box (Compose, Terraform);
480    /// `not_running`, before any tool acts, when the run isn't ready.
481    pub async fn package(&self, machine: &str, output: &Path, opts: &RunOptions, events: &dyn Events) -> Result<()> {
482        self.drive(Act::Package(machine, output), opts, events).await.map(drop)
483    }
484
485    /// Runs `argv` in `machine`, with no terminal: what it said and how it ended. A command that
486    /// runs and fails is a report, not an error.
487    ///
488    /// # Errors
489    ///
490    /// When the command can't be run at all (the tool missing, the machine refused);
491    /// `not_running`, before any tool acts, when nothing of the run runs.
492    pub async fn exec(&self, machine: &str, argv: &[String], opts: &RunOptions, events: &dyn Events) -> Result<ExecReport> {
493        self.operate(Op::Check, opts, events, async |given: &RunOptions, emitter: &Emitter<'_>, _by: OperationId| {
494            let processes = self.operation_processes(given);
495            let ran = self
496                .with_cx(given, emitter, processes.as_ref(), async |cx: &ToolCx<'_>| {
497                    self.driver.exec(cx, machine, argv).await
498                })
499                .await?;
500            let report = ExecReport {
501                machine: machine.to_owned(),
502                exit: ran.exit,
503                stdout: ran.stdout,
504                stderr: ran.stderr,
505            };
506            let data = ResultData::Machine {
507                machine: Some(machine.to_owned()),
508            };
509            Ok(Done::checked(report.exit == 0, report, data))
510        })
511        .await
512    }
513
514    /// The command that opens an interactive console into `machine`, as `user` when given. A
515    /// query: nothing runs.
516    ///
517    /// # Errors
518    ///
519    /// Where the format has no way in.
520    pub async fn console_command(&self, machine: &str, user: Option<&str>) -> Result<ShellCommand> {
521        let user = user.map(crate::console::check_name).transpose()?;
522        let paths = Quiet::of(self);
523        let cx = paths.cx(self, self.tool_env(&RunOptions::new())?);
524        self.driver.console(&cx, machine, user).await
525    }
526}
527
528impl Running<'_> {
529    /// A tool context of this run for work that runs no tool and says nothing (moving files in
530    /// its state folder).
531    fn quiet<T>(&self, work: impl FnOnce(&ToolCx<'_>) -> T) -> T {
532        let paths = Quiet::of(self);
533        let cx = paths.cx(self, Vec::new());
534        work(&cx)
535    }
536
537    /// Moves the Terraform state in `from` into the run's state folder ([`crate::Runner::adopt`]):
538    /// the files moved.
539    pub(crate) fn take_state(&self, from: &std::path::Path) -> Result<Vec<&'static str>> {
540        self.quiet(|cx| crate::formats::terraform::Terraform::adopt(cx, from))
541    }
542
543    /// Puts the state files `moved` back in `from`, best effort (an adoption that failed after).
544    pub(crate) fn give_state_back(&self, from: &std::path::Path, moved: &[&str]) {
545        self.quiet(|cx| crate::formats::terraform::Terraform::give_back(cx, from, moved));
546    }
547}
548
549/// Where `op`, done, leaves the run; none for an op that leaves it where it was.
550fn op_goal(op: Op) -> Option<RunState> {
551    match op {
552        Op::Up | Op::Resume | Op::Update => Some(RunState::Ready),
553        Op::Park => Some(RunState::Parked),
554        Op::Down => Some(RunState::Absent),
555        Op::Check | Op::Provision | Op::Attach | Op::Detach | Op::Retire | Op::Package => None,
556    }
557}