Skip to main content

isothrum_runner/run/
up.rs

1//! Starting a run: the occupied-slot rules, the start steps with their recovery retry, the ready
2//! conditions, then outputs and the message.
3
4use isoloom_manifest::Recovery;
5use serde_json::json;
6
7use super::Running;
8use super::operation::Done;
9use crate::Result;
10use crate::driver::Observed;
11use crate::error::Error;
12use crate::events::WarningCode;
13use crate::events::{Emitter, Events};
14use crate::executor::{Cx, Ran, run_steps};
15use crate::options::{Occupied, RunOptions};
16use crate::params::{params_for_existing, params_for_start};
17use crate::secrets::check_secrets;
18use crate::slot::Asked;
19use crate::state::{Op, RunState};
20use crate::status::{OutputValue, Started, any_member_running, any_present};
21use crate::store::RunRecord;
22use crate::{clock, outputs, ready, tools};
23
24/// What `up` finds where it would start the run.
25enum Occupancy {
26    /// Nothing of the run exists.
27    Free,
28    /// Something is left (a failed start, stopped machines): removed before the start.
29    Leftovers,
30    /// The run is parked, and the embedder resumes parked runs.
31    Parked,
32}
33
34impl Running<'_> {
35    /// Starts the run: refused while it runs or runs elsewhere; a parked run is resumed (with
36    /// [`Occupied::ResumeParked`]); leftovers are removed first.
37    ///
38    /// # Errors
39    ///
40    /// Fails, after its `error` event, when the run is up already (`already_running`) or recorded
41    /// elsewhere (`running_elsewhere`); when a param, secret or tool is missing or refused; when a
42    /// host port is taken (`port_in_use`); when a step fails or runs out of time (`tool_failed`,
43    /// `tool_missing`, `timeout`); when a ready condition doesn't hold (`not_ready`); or when the
44    /// run's state can't be locked or written (`locked`, `io`).
45    pub async fn up(&self, opts: &RunOptions, events: &dyn Events) -> Result<Started> {
46        self.operate(Op::Up, opts, events, async |connected: &RunOptions, e: &Emitter<'_>| {
47            self.up_work(connected, e).await
48        })
49        .await
50    }
51
52    async fn up_work(&self, opts: &RunOptions, events: &Emitter<'_>) -> Result<Done<Started>> {
53        let scope = self.scope(opts.provider);
54        check_secrets(self.manifest(), &opts.secrets, &scope)?;
55        let mut record = self.record_or_fresh()?;
56        self.refuse_elsewhere(&record, opts.host_label.as_deref())?;
57        let params = params_for_start(self.manifest(), &opts.params, &scope)?;
58        self.ensure_ssh_key().await?;
59        let mut cx = self.acting(self.cx(params, &opts.secrets, events, opts.provider)?)?;
60        // Leftovers are removed with the names they were made with.
61        Self::bind_record(&mut cx, &record);
62        self.relay(&mut cx).await?;
63        self.driver.preflight(&cx).await?;
64        self.driver.prepare(&cx)?;
65        crate::graphical::chosen::ensure(&cx)?;
66        tools::probe(&cx).await?;
67        let observed = self.observe(&mut cx).await?;
68        match self.occupancy(&observed, &record, opts.occupied)? {
69            Occupancy::Parked => return self.resume_parked(opts, events).await,
70            Occupancy::Leftovers => self.clear(&mut cx, &record, opts).await?,
71            Occupancy::Free => {}
72        }
73        self.record_start(&mut record, &cx, opts)?;
74        // The slot is picked and recorded (the run `starting`) under the home's lock: a start
75        // in another process waits, then sees it taken.
76        let place = opts.host_label.as_deref();
77        let slot = crate::slot::choose(&self.runner.store, self.manifest(), self.name(), place, Asked::Own(record.slot)).await?;
78        slot.keep_in(&mut record);
79        self.place(&mut record, opts);
80        Self::bind_record(&mut cx, &record);
81        self.begin(&mut record, Op::Up)?;
82        drop(slot);
83        crate::executor::state_files::write(&cx, true)?;
84        self.converge(&mut cx).await?;
85        self.seal(&mut cx, &mut record).await?;
86        self.ready(&mut cx, record).await
87    }
88
89    /// What a fresh start of `cx`'s run with `opts` keeps in its `record`: the host ports it
90    /// pins, the manifest it runs from, its params, cloud, place, provider and start time. Fails
91    /// when no free host port is left to pin one to, or the loopback can't be bound to find one.
92    fn record_start(&self, record: &mut RunRecord, cx: &Cx<'_>, opts: &RunOptions) -> Result<()> {
93        // A driver that forwards host ports it picks itself (Vagrant, locally) pins them now, into
94        // the record, so a resume forwards the same ports for the VM's whole life; `bind_record`
95        // binds them into `cx` for the start's own forwards and status.
96        record.vm_host_ports = self.driver.pin_vm_ports(cx)?;
97        // Every VM the start boots, boots with the Vagrantfile of this manifest.
98        self.runs_from_this(record);
99        record.params = cx.vars.params().clone();
100        record.cloud = self.manifest().cloud;
101        record.host_label.clone_from(&opts.host_label);
102        record.provider = opts.provider;
103        record.started_at = Some(clock::rfc3339(self.runner.config.clock.now()));
104        Ok(())
105    }
106
107    /// `up`'s steps ([`Running::start`]), then what follows them at `up` and `update`: the
108    /// guests' secrets (what they wait for once they exist, where no store holds them), the
109    /// outputs (a ready condition may name one: `${outputs.ip}`, the run host) and the ready
110    /// conditions.
111    pub(super) async fn converge(&self, cx: &mut Cx<'_>) -> Result<()> {
112        let ran = self.start(cx).await?;
113        crate::guest::deliver(cx, None).await?;
114        self.read_outputs(cx).await?;
115        ready::check(cx, Some(&ran)).await
116    }
117
118    /// The end of an operation that leaves the run ready: its outputs and message read
119    /// ([`Running::finish`]), and `record` marked ready.
120    pub(super) async fn ready(&self, cx: &mut Cx<'_>, mut record: RunRecord) -> Result<Done<Started>> {
121        let (outputs, message) = self.finish(cx).await?;
122        record.state = RunState::Ready;
123        Ok(ready_run(record, outputs, message))
124    }
125
126    /// Resumes the parked run an `up` found, as an operation on the run that exists: its tools
127    /// were checked by the `up`.
128    async fn resume_parked(&self, opts: &RunOptions, events: &Emitter<'_>) -> Result<Done<Started>> {
129        let (record, mut cx) = self.existing(opts, events).await?;
130        self.resume_work(record, &mut cx).await
131    }
132
133    /// Fails when the run's record puts it on another place than `asked`.
134    pub(crate) fn refuse_elsewhere(&self, record: &RunRecord, asked: Option<&str>) -> Result<()> {
135        match (record.host_label.as_deref(), asked) {
136            (Some(recorded), Some(asked)) if recorded != asked && record.state != RunState::Absent => Err(Error::RunningElsewhere {
137                run: self.name().to_string(),
138                recorded: recorded.into(),
139                asked: asked.into(),
140            }),
141            _ => Ok(()),
142        }
143    }
144
145    /// What `up` finds of the run (`observed`, `record`) where it would start it, and what
146    /// `occupied` makes of it; refused while it runs.
147    fn occupancy(&self, observed: &Observed, record: &RunRecord, occupied: Occupied) -> Result<Occupancy> {
148        let exists = any_present(&observed.machines);
149        let parked = record.state == RunState::Parked;
150        let running = any_member_running(&observed.machines);
151        let already = || Err(Error::AlreadyRunning { run: self.name().to_string() });
152        match occupied {
153            _ if !exists => Ok(Occupancy::Free),
154            Occupied::Replace => Ok(Occupancy::Leftovers),
155            // A start that failed with its machines up: what it left goes, then a fresh start.
156            _ if record.state == RunState::Failed => Ok(Occupancy::Leftovers),
157            _ if running && !parked => already(),
158            // A parked run a machine of which was removed meanwhile can't resume as it was: what
159            // is left goes, then a fresh start (`resume` alone refuses it: `nothing_to_resume`).
160            Occupied::ResumeParked if parked && crate::status::gone_members(&observed.machines).is_empty() => Ok(Occupancy::Parked),
161            _ => Ok(Occupancy::Leftovers),
162        }
163    }
164
165    /// Removes what is left of the run: its `down` steps, with the params it was started with
166    /// (the region it was applied in, its seal), never the ones of the start to come.
167    async fn clear(&self, cx: &mut Cx<'_>, record: &RunRecord, opts: &RunOptions) -> Result<()> {
168        cx.events
169            .warning(WarningCode::LeftoversRemoved, "removing what an earlier run left before starting");
170        let fresh = cx.vars.params().clone();
171        if let Some(replayed) = record.replayed_params() {
172            cx.vars
173                .set_params(params_for_existing(self.manifest(), Some(replayed), &opts.params, &cx.scope)?);
174        }
175        let cleared = crate::executor::run_down_steps(cx).await.map(drop);
176        cx.vars.set_params(fresh);
177        cleared
178    }
179
180    /// Where the run goes on its place, kept in `record` beside its slot: its SSH jump, and its
181    /// expiry (when the manifest has one).
182    fn place(&self, record: &mut RunRecord, opts: &RunOptions) {
183        record.ssh_jump.clone_from(&opts.ssh_jump);
184        record.expires_at = self.manifest().expiry.as_ref().map(|e| {
185            let minutes = u64::from(e.default_minutes.unwrap_or(DEFAULT_LIFETIME_MINUTES));
186            let life = opts.lifetime.map_or(minutes * 60, |l| l.as_secs());
187            clock::unix_seconds(self.runner.config.clock.now()).saturating_add(life)
188        });
189    }
190
191    /// The start steps; a failure after a step printed one of `recovery.stale_markers` (any line
192    /// of an argv or `ssh.run` step's, see [`crate::executor::LineWatch`]) runs the recovery steps
193    /// and starts again, up to `recovery.retries` times. A genuine failure never retries.
194    pub(super) async fn start(&self, cx: &mut Cx<'_>) -> Result<Ran> {
195        let up = self.manifest().lifecycle.up.as_slice();
196        let none = Recovery {
197            stale_markers: Vec::new(),
198            steps: Vec::new(),
199            retries: isoloom_manifest::Retries::default(),
200            apply_retries: None,
201        };
202        let recovery = self.manifest().recovery.as_ref().unwrap_or(&none);
203        let mut left = recovery.retries.get();
204        let mut applies = recovery.apply_retries.map_or(0, isoloom_manifest::Retries::get);
205        loop {
206            cx.stale.take();
207            match crate::executor::run_up_steps(cx, up).await {
208                Err(e) if left > 0 && !cx.stale.take().is_empty() => {
209                    left -= 1;
210                    cx.events
211                        .warning(WarningCode::Recovering, &format!("clearing stale state, then starting again: {e}"));
212                    run_steps(cx, "recovery.steps", &recovery.steps).await?;
213                }
214                // A module that converges on a later apply (a cloud's eventual consistency); any
215                // other step's failure is the start's.
216                Err(e @ Error::ToolFailed { .. }) if applies > 0 && self.driver.reapplies(up, &e) => {
217                    applies -= 1;
218                    cx.events.warning(WarningCode::Retrying, &format!("applying again: {e}"));
219                }
220                other => return other,
221            }
222        }
223    }
224
225    /// Reads the run's published ports and outputs (a warning for each output whose format
226    /// couldn't be filled), and fills its message.
227    async fn finish(&self, cx: &mut Cx<'_>) -> Result<(Vec<OutputValue>, Option<String>)> {
228        let read = self.read_outputs(cx).await?;
229        outputs::emit(cx.events, &read);
230        let message = outputs::message(self.manifest(), &cx.vars, &read.values);
231        Ok((read.values, message))
232    }
233}
234
235/// How long a run with an `expiry` lives when neither the embedder nor the manifest says.
236const DEFAULT_LIFETIME_MINUTES: u32 = 240;
237
238/// A run that came up, as the operation returns it and its `result` event says.
239fn ready_run(record: RunRecord, outputs: Vec<OutputValue>, message: Option<String>) -> Done<Started> {
240    let shown: Vec<serde_json::Value> = outputs.iter().map(|o| json!({ "name": o.name, "role": o.role, "value": o.value })).collect();
241    let data = json!({ "state": RunState::Ready, "outputs": shown, "message": message });
242    Done {
243        value: Started { record, outputs, message },
244        ok: true,
245        data,
246        state: Some(RunState::Ready),
247    }
248}