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, the message and the embedder's hooks.
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::hooks::Edge;
16use crate::options::{Occupied, RunOptions};
17use crate::params::{params_for_existing, params_for_start};
18use crate::secrets::{check_secrets, sensitive_values};
19use crate::state::{Op, RunState};
20use crate::status::{MachineState, OutputValue, Started, any_target_running};
21use crate::store::RunRecord;
22use crate::{clock, outputs, ready, tools};
23
24/// What `up` finds where it would start the run.
25enum Slot {
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        let opts = &self.connected(opts);
47        let mask = sensitive_values(self.manifest(), &opts.secrets);
48        self.operate(Op::Up, events, mask, async |e: &Emitter<'_>| self.up_work(opts, e).await).await
49    }
50
51    async fn up_work(&self, opts: &RunOptions, events: &Emitter<'_>) -> Result<Done<Started>> {
52        let scope = self.scope(opts.provider.clone());
53        check_secrets(self.manifest(), &opts.secrets, &scope)?;
54        let mut record = self.record_or_fresh()?;
55        self.refuse_elsewhere(&record, opts.host_label.as_deref())?;
56        let params = params_for_start(self.manifest(), &opts.params, &scope)?;
57        if crate::ssh::needed(self.manifest()) {
58            crate::ssh::ensure_key(self.runner.config.processes.as_ref(), &self.runner.config.home).await?;
59        }
60        let mut cx = self.acting(self.cx(params, &opts.secrets, events, opts.provider.clone())?)?;
61        // Leftovers are removed with the names they were made with.
62        Self::bind_record(&mut cx, &record);
63        self.relay(&mut cx).await?;
64        self.driver.preflight(&cx).await?;
65        self.driver.prepare(&cx)?;
66        tools::probe(&cx).await?;
67        let observed = self.observe(&mut cx).await?;
68        match self.slot(&observed, &record, opts.occupied)? {
69            Slot::Parked => return self.resume_work(opts, events, false).await,
70            Slot::Leftovers => self.clear(&mut cx, &record, opts).await?,
71            Slot::Free => {}
72        }
73        // A driver that forwards host ports it picks itself (Vagrant, locally) pins them now, into
74        // the record, so a resume forwards the same ports for the VM's whole life; `bind_record`
75        // below binds them into `cx` for the start's own forwards and status.
76        record.vm_host_ports = self.driver.forward_ports(&cx);
77        record.params = cx.vars.params().clone();
78        record.cloud = self.manifest().cloud;
79        record.host_label.clone_from(&opts.host_label);
80        record.provider.clone_from(&opts.provider);
81        record.started_at = Some(clock::rfc3339(self.runner.config.clock.now()));
82        self.place(&mut record, opts)?;
83        Self::bind_record(&mut cx, &record);
84        self.begin(&mut record, Op::Up)?;
85        crate::executor::state_files::write(&cx, true)?;
86        let ran = self.start(&mut cx).await?;
87        // What the guests wait for once they exist: their secrets, where no store holds them.
88        crate::guest::deliver(&mut cx, None).await?;
89        // The ready conditions may name an output (`${outputs.ip}`, the run host).
90        self.read_outputs(&mut cx).await?;
91        ready::check(&mut cx, Some(&ran)).await?;
92        self.seal(&mut cx, &mut record).await?;
93        let (outputs, message) = self.finish(&mut cx, Edge::AfterUp).await?;
94        record.state = RunState::Ready;
95        Ok(ready_run(record, outputs, message))
96    }
97
98    /// Fails when the run's record puts it on another place than `asked`.
99    pub(crate) fn refuse_elsewhere(&self, record: &RunRecord, asked: Option<&str>) -> Result<()> {
100        match (record.host_label.as_deref(), asked) {
101            (Some(recorded), Some(asked)) if recorded != asked && record.state != RunState::Absent => Err(Error::RunningElsewhere {
102                run: self.name().to_string(),
103                recorded: recorded.into(),
104                asked: asked.into(),
105            }),
106            _ => Ok(()),
107        }
108    }
109
110    fn slot(&self, observed: &Observed, record: &RunRecord, occupied: Occupied) -> Result<Slot> {
111        let exists = observed.machines.iter().any(|m| m.state != MachineState::Absent);
112        let parked = record.state == RunState::Parked;
113        let running = any_target_running(&observed.machines);
114        let already = || Err(Error::AlreadyRunning { run: self.name().to_string() });
115        match occupied {
116            _ if !exists => Ok(Slot::Free),
117            Occupied::Replace => Ok(Slot::Leftovers),
118            // A start that failed with its machines up: what it left goes, then a fresh start.
119            _ if record.state == RunState::Failed => Ok(Slot::Leftovers),
120            _ if running && !parked => already(),
121            Occupied::ResumeParked if parked => Ok(Slot::Parked),
122            Occupied::Refuse if parked => already(),
123            _ => Ok(Slot::Leftovers),
124        }
125    }
126
127    /// Removes what is left of the run: its `down` steps, with the params it was started with
128    /// (the region it was applied in, its seal), never the ones of the start to come.
129    async fn clear(&self, cx: &mut Cx<'_>, record: &RunRecord, opts: &RunOptions) -> Result<()> {
130        cx.events
131            .warning(WarningCode::LeftoversRemoved, "removing what an earlier run left before starting");
132        let fresh = cx.vars.params().clone();
133        if record.started_at.is_some() {
134            cx.vars
135                .set_params(params_for_existing(self.manifest(), Some(&record.params), &opts.params, &cx.scope)?);
136        }
137        let cleared = run_steps(cx, "lifecycle.down", self.manifest().lifecycle.down.as_slice()).await.map(drop);
138        cx.vars.set_params(fresh);
139        cleared
140    }
141
142    /// Where the run goes on its place, kept in `record`: its slot (when the manifest names
143    /// `${run.slot}`), its SSH jump, and its expiry (when the manifest has one).
144    fn place(&self, record: &mut RunRecord, opts: &RunOptions) -> Result<()> {
145        let place = opts.host_label.as_deref();
146        if crate::slot::needed(self.manifest()) {
147            let taken = crate::slot::taken(&self.runner.store.records()?, self.name(), place);
148            record.slot = Some(crate::slot::pick(record.slot, &taken, place)?);
149        }
150        record.ssh_jump.clone_from(&opts.ssh_jump);
151        record.expires_at = self.manifest().expiry.as_ref().map(|e| {
152            let minutes = u64::from(e.default_minutes.unwrap_or(DEFAULT_LIFETIME_MINUTES));
153            let life = opts.lifetime.map_or(minutes * 60, |l| l.as_secs());
154            clock::unix_seconds(self.runner.config.clock.now()).saturating_add(life)
155        });
156        Ok(())
157    }
158
159    /// The start steps; a failure whose message holds one of `recovery.stale_markers` runs the
160    /// recovery steps and starts again, up to `recovery.retries` times. A genuine failure never
161    /// retries.
162    async fn start(&self, cx: &mut Cx<'_>) -> Result<Ran> {
163        let up = self.manifest().lifecycle.up.as_slice();
164        let none = Recovery {
165            stale_markers: Vec::new(),
166            steps: Vec::new(),
167            retries: isoloom_manifest::Retries::default(),
168            apply_retries: None,
169        };
170        let recovery = self.manifest().recovery.as_ref().unwrap_or(&none);
171        let mut left = recovery.retries.get();
172        let mut applies = recovery.apply_retries.map_or(0, isoloom_manifest::Retries::get);
173        loop {
174            cx.stale.take();
175            match run_steps(cx, crate::executor::UP, up).await {
176                Err(e) if left > 0 && cx.stale.take().is_some() => {
177                    left -= 1;
178                    cx.events
179                        .warning(WarningCode::Recovering, &format!("clearing stale state, then starting again: {e}"));
180                    run_steps(cx, "recovery.steps", &recovery.steps).await?;
181                }
182                // A module that converges on a later apply (a cloud's eventual consistency); any
183                // other step's failure is the start's.
184                Err(e @ Error::ToolFailed { .. }) if applies > 0 && applied(up, &e) => {
185                    applies -= 1;
186                    cx.events.warning(WarningCode::Retrying, &format!("applying again: {e}"));
187                }
188                other => return other,
189            }
190        }
191    }
192
193    /// Reads the run's published ports and outputs, fills its message, and runs the hooks at
194    /// `edge`.
195    pub(crate) async fn finish(&self, cx: &mut Cx<'_>, edge: Edge) -> Result<(Vec<OutputValue>, Option<String>)> {
196        let outputs = self.read_outputs(cx).await?;
197        outputs::emit(cx.events, &outputs);
198        let message = outputs::message(self.manifest(), &cx.vars, &outputs);
199        self.hooks(cx, edge, &outputs).await;
200        Ok((outputs, message))
201    }
202}
203
204/// Whether `e` is the failure of a step of `up` that runs `terraform apply`.
205fn applied(up: &[isoloom_manifest::Step], e: &Error) -> bool {
206    let Error::ToolFailed { step, .. } = e else { return false };
207    up.iter().filter(|s| s.id.as_str() == step).any(|s| match &s.run {
208        isoloom_manifest::Run::Argv(argv) => argv_applies(argv),
209        isoloom_manifest::Run::Action { .. } => false,
210    })
211}
212
213/// Whether `argv` (on any host) is `terraform apply …` (or `tofu`), global options such as
214/// `-chdir=<module>` before the subcommand.
215fn argv_applies(argv: &isoloom_manifest::HostArgv) -> bool {
216    let applies = |a: &isoloom_manifest::Argv| {
217        let subcommand = a.args().iter().map(ToString::to_string).find(|w| !w.starts_with('-'));
218        ["terraform", "tofu"].contains(&a.program().as_str()) && subcommand.as_deref() == Some("apply")
219    };
220    match argv {
221        isoloom_manifest::HostArgv::Every(a) => applies(a),
222        isoloom_manifest::HostArgv::PerHost(p) => p
223            .default
224            .iter()
225            .chain(p.linux.iter())
226            .chain(p.macos.iter())
227            .chain(p.windows.iter())
228            .any(applies),
229    }
230}
231
232/// How long a run with an `expiry` lives when neither the embedder nor the manifest says.
233const DEFAULT_LIFETIME_MINUTES: u32 = 240;
234
235/// A run that came up, as the operation returns it and its `result` event says.
236pub(crate) fn ready_run(record: RunRecord, outputs: Vec<OutputValue>, message: Option<String>) -> Done<Started> {
237    let shown: Vec<serde_json::Value> = outputs
238        .iter()
239        .map(|o| json!({ "name": o.name, "role": o.role, "value": if o.sensitive { o.value.as_ref().map(|_| "***".to_owned()) } else { o.value.clone() } }))
240        .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}
249
250#[cfg(test)]
251mod tests {
252    use super::*;
253
254    fn argv(json: &str) -> isoloom_manifest::HostArgv {
255        serde_json::from_str(json).unwrap()
256    }
257
258    #[test]
259    fn an_apply_is_terraforms_apply_subcommand_wherever_its_module() {
260        assert!(argv_applies(&argv(r#"["terraform", "apply", "-auto-approve"]"#)));
261        assert!(argv_applies(&argv(
262            r#"["terraform", "-chdir=${run.state_dir}/module", "apply", "-auto-approve"]"#
263        )));
264        assert!(argv_applies(&argv(r#"["tofu", "apply"]"#)));
265        assert!(!argv_applies(&argv(r#"["terraform", "destroy", "-auto-approve"]"#)));
266        assert!(
267            !argv_applies(&argv(r#"["terraform", "-chdir=apply", "init"]"#)),
268            "a folder named apply isn't the subcommand"
269        );
270        assert!(!argv_applies(&argv(r#"["ssh", "apply"]"#)));
271        assert!(argv_applies(&argv(r#"{"default": ["terraform", "apply"], "windows": ["terraform", "apply"]}"#)));
272    }
273}