Skip to main content

isothrum_runner/run/
existing.rs

1//! The operations on a run that exists: `down`, `park`, `resume`, `check` and `provision`. Each
2//! replays the params the run was started with.
3
4use serde_json::json;
5
6use super::Running;
7use super::operation::Done;
8use crate::Result;
9use crate::checks::{self, CheckReport};
10use crate::error::Error;
11use crate::events::{Emitter, Events};
12use crate::executor::{Cx, run_steps};
13use crate::options::RunOptions;
14use crate::params::params_for_existing;
15use crate::state::{Op, Park, RunState};
16use crate::status::Started;
17use crate::store::RunRecord;
18use crate::{ready, tools};
19
20impl Running<'_> {
21    /// Removes everything the run created, through its `down` steps: containers, networks and
22    /// volumes, VMs, a module's resources.
23    ///
24    /// # Errors
25    ///
26    /// Fails, after its `error` event, when the run is recorded elsewhere, a `down` step fails, or
27    /// the run's state can't be locked or written.
28    pub async fn down(&self, opts: &RunOptions, events: &dyn Events) -> Result<()> {
29        self.operate(Op::Down, opts, events, async |connected: &RunOptions, e: &Emitter<'_>| {
30            let (mut record, mut cx) = self.existing(connected, e).await?;
31            self.begin(&mut record, Op::Down)?;
32            crate::executor::run_down_steps(&mut cx).await?;
33            self.driver.after_down(&cx)?;
34            crate::executor::state_files::forget(&cx)?;
35            crate::ssh::forget(&cx)?;
36            self.forget_seal()?;
37            crate::archive::forget(&cx)?;
38            // A status while the next start holds the run shows no machine of this one.
39            self.runner.store.forget_seen(self.name())?;
40            Ok(Done {
41                value: (),
42                ok: true,
43                data: json!({ "state": RunState::Absent }),
44                state: Some(RunState::Absent),
45            })
46        })
47        .await
48    }
49
50    /// Stops the run, keeping what it created, with the manifest's `park` steps for `mode`; `opts`
51    /// as the other operations take them (the place the run is on, the params and secrets its steps
52    /// read). Its SSH goes through the jump the run recorded at `up`.
53    ///
54    /// # Errors
55    ///
56    /// Fails with `not_parkable` when the manifest has no steps for `mode`, with `not_running` when
57    /// nothing of the run is there, and as [`Running::down`] does for a run recorded elsewhere, a
58    /// step or the state.
59    pub async fn park(&self, mode: Park, opts: &RunOptions, events: &dyn Events) -> Result<()> {
60        self.operate(Op::Park, opts, events, async |connected: &RunOptions, e: &Emitter<'_>| {
61            let park = self.manifest().lifecycle.park.as_ref();
62            let steps = park.and_then(|p| if mode == Park::Pause { p.pause.as_ref() } else { p.shutdown.as_ref() });
63            let steps = steps.ok_or_else(|| Error::NotParkable {
64                run: self.name().to_string(),
65                mode: mode.as_str(),
66            })?;
67            let (mut record, mut cx) = self.existing(connected, e).await?;
68            if !self.exists(&mut cx).await? {
69                return Err(Error::NotRunning { run: self.name().to_string() });
70            }
71            self.begin(&mut record, Op::Park)?;
72            run_steps(&mut cx, "lifecycle.park", steps).await?;
73            Ok(Done {
74                value: (),
75                ok: true,
76                data: json!({ "state": RunState::Parked }),
77                state: Some(RunState::Parked),
78            })
79        })
80        .await
81    }
82
83    /// Starts a parked run again, as it was: nothing is re-created, so inputs aren't needed again.
84    ///
85    /// # Errors
86    ///
87    /// Fails with `nothing_to_resume` when nothing is left (the parked mark is dropped) or a
88    /// member machine is gone (removed outside the runner: the run is then recorded `failed`, so
89    /// the next `up` clears what is left and starts it afresh), and as
90    /// [`Running::up`] does for a tool, a step, a ready condition or the state.
91    pub async fn resume(&self, opts: &RunOptions, events: &dyn Events) -> Result<Started> {
92        self.operate(Op::Resume, opts, events, async |connected: &RunOptions, e: &Emitter<'_>| {
93            let (record, mut cx) = self.existing(connected, e).await?;
94            tools::probe(&cx).await?;
95            self.resume_work(record, &mut cx).await
96        })
97        .await
98    }
99
100    /// Resumes the run of `record` in `cx` (the context of an operation on the run that exists,
101    /// [`Running::existing`]), its tools already checked.
102    pub(crate) async fn resume_work(&self, mut record: RunRecord, cx: &mut Cx<'_>) -> Result<Done<Started>> {
103        let observed = self.observe(cx).await?;
104        if !crate::status::any_present(&observed.machines) {
105            // Nothing left: the parked mark goes, and a fresh start is the way back.
106            record.state = RunState::Absent;
107            self.runner.store.save(&record)?;
108            return Err(Error::NothingToResume { run: self.name().to_string() });
109        }
110        let gone = crate::status::gone_members(&observed.machines);
111        if !gone.is_empty() {
112            // A machine removed outside the runner: the resume steps would bring back the rest
113            // without it, or a VM's would make it again from its image, never set up (`vagrant up
114            // --no-provision`), and call the run ready. What is left is a failed run's, which
115            // the next start clears.
116            record.state = RunState::Failed;
117            self.runner.store.save(&record)?;
118            return Err(Error::PartlyGone {
119                run: self.name().to_string(),
120                machines: gone,
121            });
122        }
123        self.begin(&mut record, Op::Resume)?;
124        run_steps(cx, "lifecycle.resume", &self.manifest().lifecycle.resume).await?;
125        ready::check(cx, None).await?;
126        self.ready(cx, record).await
127    }
128
129    /// Runs the run's checks against the running run.
130    ///
131    /// # Errors
132    ///
133    /// Fails with `not_running` when no member machine runs, and when a setup or teardown step
134    /// fails. A failing check isn't an error: the report says it (`ok: false`).
135    pub async fn check(&self, opts: &RunOptions, events: &dyn Events) -> Result<CheckReport> {
136        self.operate(Op::Check, opts, events, async |connected: &RunOptions, e: &Emitter<'_>| {
137            let (_, mut cx) = self.existing(connected, e).await?;
138            let observed = self.observe_running(&mut cx).await?;
139            // A runner's step may name an output (`${outputs.ip}`, the router it goes through).
140            self.bind_observed(&mut cx, observed);
141            let report = checks::run(&mut cx).await?;
142            let data = json!({ "passed": report.results.iter().filter(|r| r.ok).count(), "failed": report.results.iter().filter(|r| !r.ok).count(), "unfinished": report.unfinished });
143            Ok(Done { ok: report.ok, value: report, data, state: None })
144        })
145        .await
146    }
147
148    /// Runs the run's set-up again on its running machines, every one or `machine` (a run machine
149    /// of the manifest), without rebuilding them: the manifest's `provision` steps. The values
150    /// given at launch aren't kept by the runner: pass them again in `opts`.
151    ///
152    /// # Errors
153    ///
154    /// Fails with `machine_unknown` for a machine the run doesn't have, `not_running` when no
155    /// member machine runs, `unsupported` when the manifest has no provision steps, and as
156    /// [`Running::up`] does for a step or the state.
157    pub async fn provision(&self, machine: Option<&str>, opts: &RunOptions, events: &dyn Events) -> Result<()> {
158        self.operate(Op::Provision, opts, events, async |connected: &RunOptions, e: &Emitter<'_>| {
159            let provision = self.manifest().lifecycle.provision.as_ref().ok_or_else(|| Error::Unsupported {
160                what: "provisioning this run (its manifest has no provision steps)".into(),
161            })?;
162            let (_, mut cx) = self.existing(connected, e).await?;
163            if let Some(m) = machine {
164                // Only a member machine is provisioned: another (the run's router, its checks)
165                // is as unknown here as a name the run doesn't have.
166                if self.machine_named(m)?.role != isoloom_manifest::Role::Member {
167                    return Err(Error::MachineUnknown {
168                        run: self.name().to_string(),
169                        machine: m.to_owned(),
170                    });
171                }
172                cx.vars.set_machine(m);
173            }
174            self.observe_running(&mut cx).await?;
175            let (list, steps) = match machine {
176                Some(_) => ("lifecycle.provision.machine", &provision.machine),
177                None => ("lifecycle.provision.all", &provision.all),
178            };
179            run_steps(&mut cx, list, steps).await?;
180            Ok(Done {
181                value: (),
182                ok: true,
183                data: json!({ "machine": machine }),
184                state: None,
185            })
186        })
187        .await
188    }
189
190    /// The record and the context of an operation on a run that exists: refused when the run is
191    /// recorded elsewhere, its recorded params replayed.
192    pub(crate) async fn existing<'a>(&'a self, opts: &'a RunOptions, events: &'a Emitter<'a>) -> Result<(RunRecord, Cx<'a>)> {
193        let record = self.record_or_fresh()?;
194        self.refuse_elsewhere(&record, opts.host_label.as_deref())?;
195        let provider = record.provider.or(opts.provider);
196        let params = params_for_existing(self.manifest(), record.replayed_params(), &opts.params, &self.scope(provider))?;
197        // An adopted run ([`crate::Runner::adopt`]), or one acted on from another home, may
198        // name a key this runner hasn't made yet.
199        self.ensure_ssh_key().await?;
200        let mut cx = self.acting(self.cx(params, &opts.secrets, events, provider)?)?;
201        Self::bind_record(&mut cx, &record);
202        self.driver.prepare(&cx)?;
203        crate::graphical::chosen::ensure(&cx)?;
204        crate::executor::state_files::write(&cx, false)?;
205        self.relay(&mut cx).await?;
206        Ok((record, cx))
207    }
208
209    /// Whether anything of the run is there.
210    async fn exists(&self, cx: &mut Cx<'_>) -> Result<bool> {
211        Ok(crate::status::any_present(&self.observe(cx).await?.machines))
212    }
213}