Skip to main content

isothrum_runner/run/
existing.rs

1//! The operations on a run that exists: `down`, `park`, `resume` and `check`. Each replays the
2//! params the run was started with.
3
4use serde_json::json;
5
6use super::Running;
7use super::operation::Done;
8use super::up::ready_run;
9use crate::Result;
10use crate::checks::{self, CheckReport};
11use crate::error::Error;
12use crate::events::{Emitter, Events};
13use crate::executor::{Cx, run_steps};
14use crate::hooks::Edge;
15use crate::options::RunOptions;
16use crate::params::params_for_existing;
17use crate::secrets::sensitive_values;
18use crate::state::{Op, Park, RunState};
19use crate::status::{MachineState, Started, any_target_running};
20use crate::store::RunRecord;
21use crate::{ready, tools};
22
23impl Running<'_> {
24    /// Removes everything the run created (containers, networks, volumes).
25    ///
26    /// # Errors
27    ///
28    /// Fails, after its `error` event, when the run is recorded elsewhere, a `down` step fails, or
29    /// the run's state can't be locked or written.
30    pub async fn down(&self, opts: &RunOptions, events: &dyn Events) -> Result<()> {
31        let opts = &self.connected(opts);
32        let mask = sensitive_values(self.manifest(), &opts.secrets);
33        self.operate(Op::Down, events, mask, async |e: &Emitter<'_>| {
34            let (mut record, mut cx) = self.existing(opts, e).await?;
35            self.hooks(&cx, Edge::BeforeDown, &[]).await;
36            self.begin(&mut record, Op::Down)?;
37            run_steps(&mut cx, "lifecycle.down", self.manifest().lifecycle.down.as_slice()).await?;
38            // The manifest's steps remove the project's own containers; an ad-hoc attacker box has
39            // no project, so reap it too or it is left running and still read as the lab.
40            self.driver.reap_attacker(&cx).await;
41            self.driver.after_down(&cx)?;
42            crate::executor::state_files::forget(&cx)?;
43            self.forget_seal()?;
44            crate::archive::forget(&cx)?;
45            Ok(Done {
46                value: (),
47                ok: true,
48                data: json!({ "state": RunState::Absent }),
49                state: Some(RunState::Absent),
50            })
51        })
52        .await
53    }
54
55    /// Stops the run, keeping what it created, with the manifest's `park` steps for `mode`.
56    ///
57    /// # Errors
58    ///
59    /// Fails with `not_parkable` when the manifest has no steps for `mode`, with `not_running` when
60    /// nothing of the run is there, and as [`Running::down`] does for a step or the state.
61    pub async fn park(&self, mode: Park, events: &dyn Events) -> Result<()> {
62        let opts = self.connected(&RunOptions::default());
63        let mask = sensitive_values(self.manifest(), &opts.secrets);
64        self.operate(Op::Park, events, mask, async |e: &Emitter<'_>| {
65            let park = self.manifest().lifecycle.park.as_ref();
66            let steps = park.and_then(|p| if mode == Park::Pause { p.pause.as_ref() } else { p.shutdown.as_ref() });
67            let steps = steps.ok_or_else(|| Error::NotParkable {
68                run: self.name().to_string(),
69                mode: mode.as_str(),
70            })?;
71            let (mut record, mut cx) = self.existing(&opts, e).await?;
72            if !self.exists(&mut cx).await? {
73                return Err(Error::NotRunning { run: self.name().to_string() });
74            }
75            self.hooks(&cx, Edge::BeforePark, &[]).await;
76            self.begin(&mut record, Op::Park)?;
77            run_steps(&mut cx, "lifecycle.park", steps).await?;
78            // The ad-hoc attacker box is no project container, so the park steps leave it running
79            // while the lab is parked (and a workload scan then still reads the lab as running).
80            // Reap it: a resumed lab re-attaches one, as a launched lab does.
81            self.driver.reap_attacker(&cx).await;
82            Ok(Done {
83                value: (),
84                ok: true,
85                data: json!({ "state": RunState::Parked }),
86                state: Some(RunState::Parked),
87            })
88        })
89        .await
90    }
91
92    /// Starts a parked run again, as it was: nothing is re-created, so inputs aren't needed again.
93    ///
94    /// # Errors
95    ///
96    /// Fails with `nothing_to_resume` when nothing is left (the parked mark is dropped), and as
97    /// [`Running::up`] does for a tool, a step, a ready condition or the state.
98    pub async fn resume(&self, opts: &RunOptions, events: &dyn Events) -> Result<Started> {
99        let opts = &self.connected(opts);
100        let mask = sensitive_values(self.manifest(), &opts.secrets);
101        self.operate(Op::Resume, events, mask, async |e: &Emitter<'_>| self.resume_work(opts, e, true).await)
102            .await
103    }
104
105    /// Resumes the run; `probe`: its tools are checked first (an `up` that resumes did it).
106    pub(crate) async fn resume_work(&self, opts: &RunOptions, events: &Emitter<'_>, probe: bool) -> Result<Done<Started>> {
107        let (mut record, mut cx) = self.existing(opts, events).await?;
108        if probe {
109            tools::probe(&cx).await?;
110        }
111        if !self.exists(&mut cx).await? {
112            // Nothing left: the parked mark goes, and a fresh start is the way back.
113            record.state = RunState::Absent;
114            self.runner.store.save(&record)?;
115            return Err(Error::NothingToResume { run: self.name().to_string() });
116        }
117        self.begin(&mut record, Op::Resume)?;
118        run_steps(&mut cx, "lifecycle.resume", &self.manifest().lifecycle.resume).await?;
119        ready::check(&mut cx, None).await?;
120        let (outputs, message) = self.finish(&mut cx, Edge::AfterResume).await?;
121        record.state = RunState::Ready;
122        Ok(ready_run(record, outputs, message))
123    }
124
125    /// Runs the run's checks against the running run.
126    ///
127    /// # Errors
128    ///
129    /// Fails with `not_running` when no target machine runs, and when a setup or teardown step
130    /// fails. A failing check isn't an error: the report says it (`ok: false`).
131    pub async fn check(&self, opts: &RunOptions, events: &dyn Events) -> Result<CheckReport> {
132        let opts = &self.connected(opts);
133        let mask = sensitive_values(self.manifest(), &opts.secrets);
134        self.operate(Op::Check, events, mask, async |e: &Emitter<'_>| {
135            let (_, mut cx) = self.existing(opts, e).await?;
136            let observed = self.observe(&mut cx).await?;
137            if !any_target_running(&observed.machines) {
138                return Err(Error::NotRunning { run: self.name().to_string() });
139            }
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    /// target 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        let opts = &self.connected(opts);
160        let mask = sensitive_values(self.manifest(), &opts.secrets);
161        self.operate(Op::Provision, events, mask, async |e: &Emitter<'_>| {
162            let provision = self.manifest().lifecycle.provision.as_ref().ok_or_else(|| Error::Unsupported {
163                what: "provisioning this run (its manifest has no provision steps)".into(),
164            })?;
165            let (_, mut cx) = self.existing(opts, e).await?;
166            if let Some(m) = machine {
167                if !self
168                    .manifest()
169                    .machines
170                    .iter()
171                    .any(|x| x.name.as_str() == m && x.role == isoloom_manifest::Role::Target)
172                {
173                    return Err(Error::MachineUnknown {
174                        run: self.name().to_string(),
175                        machine: m.to_owned(),
176                    });
177                }
178                cx.vars.set_machine(m);
179            }
180            if !any_target_running(&self.observe(&mut cx).await?.machines) {
181                return Err(Error::NotRunning { run: self.name().to_string() });
182            }
183            let (list, steps) = match machine {
184                Some(_) => ("lifecycle.provision.machine", &provision.machine),
185                None => ("lifecycle.provision.all", &provision.all),
186            };
187            run_steps(&mut cx, list, steps).await?;
188            Ok(Done {
189                value: (),
190                ok: true,
191                data: json!({ "machine": machine }),
192                state: None,
193            })
194        })
195        .await
196    }
197
198    /// The record and the context of an operation on a run that exists: refused when the run is
199    /// recorded elsewhere, its recorded params replayed.
200    pub(crate) async fn existing<'a>(&'a self, opts: &'a RunOptions, events: &'a Emitter<'a>) -> Result<(RunRecord, Cx<'a>)> {
201        let record = self.record_or_fresh()?;
202        self.refuse_elsewhere(&record, opts.host_label.as_deref())?;
203        let recorded = (record.started_at.is_some()).then_some(&record.params);
204        let provider = record.provider.clone().or_else(|| opts.provider.clone());
205        let params = params_for_existing(self.manifest(), recorded, &opts.params, &self.scope(provider.clone()))?;
206        // A run taken over from an embedder's old runtime, or acted on from another home, may
207        // name a key this runner hasn't made yet.
208        if crate::ssh::needed(self.manifest()) {
209            crate::ssh::ensure_key(self.runner.config.processes.as_ref(), &self.runner.config.home).await?;
210        }
211        let mut cx = self.acting(self.cx(params, &opts.secrets, events, provider)?)?;
212        Self::bind_record(&mut cx, &record);
213        self.driver.prepare(&cx)?;
214        crate::executor::state_files::write(&cx, false)?;
215        self.relay(&mut cx).await?;
216        Ok((record, cx))
217    }
218
219    /// Whether anything of the run is there.
220    async fn exists(&self, cx: &mut Cx<'_>) -> Result<bool> {
221        Ok(self.observe(cx).await?.machines.iter().any(|m| m.state != MachineState::Absent))
222    }
223}