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