Skip to main content

isothrum_runner/run/
status.rs

1//! A run's status: what its tool reports now, reconciled with its record; and what its machines
2//! use now, as their engine samples it ([`Running::usage`]).
3
4use super::{Emitter, LastObserved, OutputValue, Result, RunOptions, RunState, Running, Seen, Status, ToolCx};
5use crate::formats::SeenMachine;
6use crate::status::{MachineState, MachineStatus, PublishedPort};
7
8impl Running<'_> {
9    /// The run as its tool reports it now, reconciled with its record: an operation of this
10    /// process on the run leaves the machines as last read (not live).
11    ///
12    /// # Errors
13    ///
14    /// As the tool fails to answer; the store's.
15    pub async fn status(&self) -> Result<Status> {
16        self.status_with(&RunOptions::new()).await
17    }
18
19    /// [`Running::status`], its tools given `opts`' values and secrets beside the recorded ones:
20    /// what a read of the project's own servers needs (a Proxmox VE module's API token, for its
21    /// VMs' states on the server).
22    ///
23    /// # Errors
24    ///
25    /// As [`Running::status`]; `server_auth_failed` when a server refuses the credentials.
26    pub async fn status_with(&self, opts: &RunOptions) -> Result<Status> {
27        if self.runner.op_of(&self.name).is_none() {
28            self.cut_off_dead_holder()?;
29        }
30        let record = self.runner.store.record(&self.name)?;
31        let recorded = record.as_ref().map_or(RunState::Absent, |r| r.state);
32        let row = self.runner.store.db().read(|tx| tx.run(&self.name))?;
33        if self.held(recorded)? {
34            return Ok(as_last_read(recorded, row.as_ref(), &[]));
35        }
36        let emitter = Emitter::silent(self.name.as_str(), self.runner.config.clock.as_ref());
37        let (seen, derived, screens, native) = self
38            .with_cx(opts, &emitter, self.runner.config.processes.as_ref(), async |cx: &ToolCx<'_>| {
39                let (seen, derived) = self.driver.observe(cx).await?;
40                let screens = self.screens(cx, &seen).await;
41                let native = self.driver.native_app(cx, &seen);
42                Ok((seen, derived, screens, native))
43            })
44            .await?;
45        let now = row.as_ref().map_or(recorded, |r| r.state);
46        let derived = self.unless_kept_failed(derived, now, record.as_ref());
47        let derived = unless_only_added(derived, now, &seen.machines, row.as_ref());
48        // A machine another process acts on (Vagrant's lock refused the read): the run as last read,
49        // that machine busy, nothing reconciled.
50        let busy: Vec<&str> = seen
51            .machines
52            .iter()
53            .filter(|m| m.state == MachineState::Busy)
54            .map(|m| m.name.as_str())
55            .collect();
56        if !busy.is_empty() {
57            return Ok(as_last_read(recorded, row.as_ref(), &busy));
58        }
59        let observed = LastObserved {
60            machines: machine_statuses(&seen.machines),
61        };
62        let state = if row.is_some() {
63            self.runner
64                .store
65                .db()
66                .write(|tx| tx.observe(&self.name, &observed, derived))?
67                .map_or(recorded, |t| t.to())
68        } else {
69            derived
70        };
71        let settled = self.runner.store.db().read(|tx| tx.run(&self.name))?;
72        let mut status = status_of(&seen, state, true, settled.as_ref());
73        if opts.reveal {
74            status.outputs = status.outputs.into_iter().map(OutputValue::unmasked).collect();
75        }
76        for (machine, console) in status.machines.iter_mut().zip(screens) {
77            machine.console = console;
78        }
79        status.native = native;
80        Ok(status)
81    }
82
83    /// `derived`, the state the tool's read gives, unless the run, `now` failed, stays so until an
84    /// operation ends well: its tool can't read readiness live (#113), or a start failed it whose
85    /// work the tool can't tell finished (Vagrant's: a VM running says nothing of its
86    /// provisioning). `record` says how its last operation ended.
87    fn unless_kept_failed(&self, derived: RunState, now: RunState, record: Option<&crate::store::RunRecord>) -> RunState {
88        let failed_start = record
89            .and_then(|r| r.last.as_ref())
90            .is_some_and(|last| !last.ok && super::op_goal(last.op) == Some(RunState::Ready));
91        if derived == RunState::Ready && now == RunState::Failed && !self.driver.ready_by_observation(failed_start) {
92            RunState::Failed
93        } else {
94            derived
95        }
96    }
97
98    /// Whether an operation holds the run, so its tool isn't asked (it would contend with it, as
99    /// Vagrant's locks do): one of this process, one the record says moves it, or one another live
100    /// process runs on it now (an attach, a provision, a retire move no state).
101    pub(super) fn held(&self, recorded: RunState) -> Result<bool> {
102        if self.runner.op_of(&self.name).is_some() || recorded.is_moving() {
103            return Ok(true);
104        }
105        let running = self.runner.store.db().read(|tx| tx.unfinished(&self.name))?;
106        Ok(running.iter().any(|o| o.started_at.is_some() && o.owner.is_alive()))
107    }
108
109    /// A run held moving (`creating`, `parking`, …) by an operation whose process is gone (killed,
110    /// crashed, another boot) is cut off: that operation ends `abandoned` and the run moves to
111    /// `failed` (`cancelled`), as the next operation on it would at its start, so a status says so
112    /// instead of `creating` for good, and the next `up` takes it over. A run an operation of a
113    /// live process holds stays as it is.
114    fn cut_off_dead_holder(&self) -> Result<()> {
115        let name = &self.name;
116        let at = crate::clock::rfc3339(self.runner.config.clock.now());
117        self.runner.store.db().write(|tx| {
118            let Some(row) = tx.run(name)? else { return Ok(()) };
119            if !row.state.is_moving() {
120                return Ok(());
121            }
122            let started: Vec<_> = tx.unfinished(name)?.into_iter().filter(|o| o.started_at.is_some()).collect();
123            let Some(last) = started.last() else { return Ok(()) };
124            if started.iter().any(|o| o.owner.is_alive()) {
125                return Ok(());
126            }
127            for left in &started {
128                tx.end_operation(left.id, crate::store::Outcome::Abandoned, Some(crate::ErrorCode::Cancelled))?;
129            }
130            tx.apply(name, crate::state::Transition::cut_off(row.state, last.id)?)?;
131            let mut record = row.record;
132            record.last = Some(crate::store::LastOp::ended(last.op, Some(crate::ErrorCode::Cancelled), at));
133            tx.save_record(&record, row.desired)
134        })
135    }
136
137    /// Reads the run's status when its record says `state`, so the record says what its tool
138    /// reports now (a parked run whose machines were removed reads absent). A read that fails
139    /// leaves the record as it was: the operation then meets the tool's failure itself.
140    pub(super) async fn refresh_if(&self, state: RunState, opts: &RunOptions) {
141        let recorded = self.runner.store.record(&self.name).ok().flatten().map(|r| r.state);
142        if recorded == Some(state)
143            && let Err(e) = self.status_with(opts).await
144        {
145            tracing::debug!(error = %e, "the run's status couldn't be read before its operation");
146        }
147    }
148
149    /// What the project gives back now (a module's outputs), read from the tool.
150    pub(super) async fn outputs(&self, opts: &RunOptions) -> Result<Vec<OutputValue>> {
151        let emitter = Emitter::silent(self.name.as_str(), self.runner.config.clock.as_ref());
152        let (seen, _) = self
153            .with_cx(opts, &emitter, self.runner.config.processes.as_ref(), async |cx: &ToolCx<'_>| {
154                self.driver.observe(cx).await
155            })
156            .await?;
157        Ok(status_of(&seen, RunState::Ready, true, None).outputs)
158    }
159
160    /// What each running machine of the run uses now, by name, as its engine samples it once:
161    /// a Compose project's containers (`docker stats`); none for a format whose tool reports no
162    /// per-machine figure (Vagrant, Terraform). A machine not running has none. `opts` gives
163    /// what the tools get. Emits nothing and never locks the run.
164    ///
165    /// # Errors
166    ///
167    /// As the tool fails: its engine doesn't answer, or its answer can't be read.
168    pub async fn usage(&self, opts: &RunOptions) -> Result<Vec<crate::MachineUsage>> {
169        let emitter = Emitter::silent(self.name.as_str(), self.runner.config.clock.as_ref());
170        self.with_cx(opts, &emitter, self.runner.config.processes.as_ref(), async |cx: &ToolCx<'_>| {
171            self.driver.usage(cx).await
172        })
173        .await
174    }
175}
176
177/// `derived`, unless the run, `now` ready, reads failed for machines alone that it never had: each
178/// absent now, and absent or unlisted at the last read (one its files declare since its last
179/// operation, the update that makes it still to come), every other machine as that read saw it.
180/// The run stays ready then, so that update isn't refused as `not_running`. A machine removed
181/// outside the run (seen there before, absent now), or any other change, fails it as before; a
182/// run never read (an operation's own read counts) is as `derived` says.
183fn unless_only_added(derived: RunState, now: RunState, machines: &[SeenMachine], row: Option<&crate::store::RunRow>) -> RunState {
184    let Some(last) = row.and_then(|r| r.observed.as_ref()) else {
185        return derived;
186    };
187    if derived != RunState::Failed || now != RunState::Ready {
188        return derived;
189    }
190    let was = |name: &str| last.machines.iter().find(|m| m.name == name).map(|m| &m.state);
191    let added = |m: &SeenMachine| m.state == MachineState::Absent && was(&m.name).is_none_or(|s| *s == MachineState::Absent);
192    let unchanged = |m: &SeenMachine| was(&m.name) == Some(&m.state);
193    if machines.iter().any(added) && machines.iter().all(|m| added(m) || unchanged(m)) {
194        RunState::Ready
195    } else {
196        derived
197    }
198}
199
200/// The run in `state` as last read (not live): its machines as the last read saw them, those of
201/// `busy` busy (another process acts on them). A run absent has none.
202fn as_last_read(state: RunState, row: Option<&crate::store::RunRow>, busy: &[&str]) -> Status {
203    let mut status = status_of(&Seen::default(), state, false, row);
204    if state != RunState::Absent {
205        status.machines = row.and_then(|r| r.observed.as_ref()).map(|o| o.machines.clone()).unwrap_or_default();
206    }
207    for name in busy {
208        match status.machines.iter_mut().find(|m| m.name == *name) {
209            Some(m) => m.state = MachineState::Busy,
210            None => status.machines.push(MachineStatus {
211                name: (*name).to_owned(),
212                state: MachineState::Busy,
213                published: Vec::new(),
214                address: None,
215                console: None,
216            }),
217        }
218    }
219    status
220}
221
222/// The status of the run in `state` with `seen` as read.
223pub(super) fn status_of(seen: &Seen, state: RunState, live: bool, row: Option<&crate::store::RunRow>) -> Status {
224    let outputs = seen
225        .outputs
226        .iter()
227        .map(|(name, o)| OutputValue::new(name.clone(), o.sensitive, Some(o.value.clone())))
228        .collect();
229    Status {
230        state,
231        live,
232        desired: row.map(|r| r.desired),
233        failed_cause: row.and_then(|r| r.failed_cause),
234        provider: row.and_then(|r| r.record.provider),
235        machines: machine_statuses(&seen.machines),
236        outputs,
237        native: None,
238        parks: row.map(|r| crate::status::park_modes(r.record.format, r.record.provider)).unwrap_or_default(),
239    }
240}
241
242/// `machines` as the status reports them. A port whose protocol the tool doesn't say has none,
243/// never a guessed one.
244pub(super) fn machine_statuses(machines: &[SeenMachine]) -> Vec<MachineStatus> {
245    machines
246        .iter()
247        .map(|m| MachineStatus {
248            name: m.name.clone(),
249            state: m.state.clone(),
250            published: m
251                .published
252                .iter()
253                .map(|p| PublishedPort {
254                    port: p.guest,
255                    protocol: p.protocol,
256                    host_port: p.host,
257                })
258                .collect(),
259            address: m.address.clone(),
260            console: None,
261        })
262        .collect()
263}