Skip to main content

isothrum_runner/
status.rs

1//! What a run looks like from outside: its state, machines, networks and outputs. Roles,
2//! addresses and networks come from the manifest; the engine only says what runs and which host
3//! ports it got.
4
5use std::collections::BTreeMap;
6
7use isoloom_manifest::{Manifest, OutputRole, Protocol, Provider, Role};
8use serde::{Deserialize, Serialize};
9
10use crate::events::MASK;
11use crate::secrets::SecretValue;
12use crate::state::RunState;
13use crate::store::RunRecord;
14
15/// A machine's state, as its engine reports it.
16#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
17#[serde(rename_all = "snake_case")]
18#[non_exhaustive]
19pub enum MachineState {
20    /// Running.
21    Running,
22    /// Running, but failing its health check.
23    Unhealthy,
24    /// Exited with this code (a job that finished, or a machine that died).
25    Exited(i32),
26    /// Created or stopped, not running.
27    Stopped,
28    /// Not there.
29    Absent,
30    /// Something else, as the engine says it.
31    Unknown(String),
32    /// Not read: another process acts on it (Vagrant's lock on the machine, held by a `vagrant
33    /// up` that isn't this runner's), so its state is whatever that action leaves.
34    Busy,
35}
36
37impl MachineState {
38    /// Whether the machine runs: up, whether or not it passes its health check (the one rule for
39    /// "it runs", however it is asked).
40    pub(crate) fn runs(&self) -> bool {
41        matches!(self, MachineState::Running | MachineState::Unhealthy)
42    }
43}
44
45impl std::fmt::Display for MachineState {
46    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47        match self {
48            MachineState::Running => f.write_str("running"),
49            MachineState::Unhealthy => f.write_str("unhealthy"),
50            MachineState::Exited(code) => write!(f, "exited({code})"),
51            MachineState::Stopped => f.write_str("stopped"),
52            MachineState::Absent => f.write_str("absent"),
53            MachineState::Unknown(s) => f.write_str(s),
54            MachineState::Busy => f.write_str("busy"),
55        }
56    }
57}
58
59/// A published port: where a machine's port answers on the host.
60#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
61#[non_exhaustive]
62pub struct PublishedPort {
63    /// The machine's port.
64    pub port: u16,
65    /// `tcp` or `udp`.
66    pub protocol: Protocol,
67    /// The host port.
68    pub host_port: u16,
69}
70
71/// One machine of the manifest, as it stands.
72#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
73#[non_exhaustive]
74pub struct MachineStatus {
75    /// Its name.
76    pub name: String,
77    /// What it is for.
78    pub role: Role,
79    /// Its state.
80    pub state: MachineState,
81    /// Its static addresses, by network.
82    pub addresses: BTreeMap<String, String>,
83    /// Its published ports.
84    pub published: Vec<PublishedPort>,
85    /// Its graphical console under the run's provider, as the manifest offers it (`none` and
86    /// why where there is none); `None` when the manifest says nothing (a container).
87    #[serde(default, skip_serializing_if = "Option::is_none")]
88    pub console: Option<crate::graphical::ConsoleOffer>,
89}
90
91/// A network of the run.
92#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
93#[non_exhaustive]
94pub struct NetworkView {
95    /// Its name in the spec.
96    pub name: String,
97    /// Its block.
98    pub cidr: String,
99    /// Whether it reaches the internet.
100    pub internet: bool,
101    /// Its name where the target created it (`web-portal_backend`), when known.
102    pub native: Option<String>,
103}
104
105/// An output's value. A sensitive one shows as `***` wherever it is written out (its JSON, its
106/// `Debug`, an event); the runner keeps the value itself for its own use (a guest delivery's
107/// address, masking it in what tools print).
108#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
109#[non_exhaustive]
110pub struct OutputValue {
111    /// Its name.
112    pub name: String,
113    /// What it is for (`entry`: where a user starts, the address to open).
114    pub role: OutputRole,
115    /// Whether the value is sensitive.
116    pub sensitive: bool,
117    /// Its value, when it can be read; `***` when it is sensitive.
118    pub value: Option<String>,
119    /// A sensitive output's value itself: never written out.
120    #[serde(skip)]
121    secret: Option<SecretValue>,
122}
123
124impl OutputValue {
125    /// Output `name`'s `value`, masked when it is `sensitive`.
126    pub(crate) fn new(name: String, role: OutputRole, sensitive: bool, value: Option<String>) -> OutputValue {
127        let (value, secret) = match value {
128            Some(v) if sensitive => (Some(MASK.to_owned()), Some(SecretValue::new(v))),
129            value => (value, None),
130        };
131        OutputValue {
132            name,
133            role,
134            sensitive,
135            value,
136            secret,
137        }
138    }
139
140    /// The value itself, a sensitive one unmasked. Never print or log it. `None` when it can't be
141    /// read, and for a sensitive output read back from JSON (which holds only the mask).
142    #[must_use]
143    pub(crate) fn revealed(&self) -> Option<&str> {
144        if self.sensitive {
145            self.secret.as_ref().map(SecretValue::expose)
146        } else {
147            self.value.as_deref()
148        }
149    }
150}
151
152/// A run as it stands.
153#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
154#[non_exhaustive]
155pub struct Status {
156    /// Where it stands. While an operation holds the run: the moving state it is in (`starting`
157    /// through an `up`), else, before it records one or for an operation that leaves the run as
158    /// it was meanwhile (an `update`: `ready`), the state the run's record holds.
159    pub state: RunState,
160    /// Whether the machines and outputs were read from the engine now. False while an operation
161    /// holds the run (in this process or another), whose tools a read would contend with (Vagrant
162    /// refuses to read a VM's state while a `vagrant up` provisions it): they are then as the
163    /// runner last read them (none before it ever did), and the outputs the engine itself gives
164    /// are left out.
165    #[serde(default = "live_when_absent")]
166    pub live: bool,
167    /// The Vagrant provider it uses, when it has one.
168    pub provider: Option<Provider>,
169    /// Every machine of the manifest.
170    pub machines: Vec<MachineStatus>,
171    /// The run's networks.
172    pub networks: Vec<NetworkView>,
173    /// Its outputs, each filled from what was read. While not [`Status::live`], an output the
174    /// engine itself gives (a Terraform output) has only its default, if any.
175    pub outputs: Vec<OutputValue>,
176    /// The run's message, filled, once the run is ready.
177    pub message: Option<String>,
178    /// The hypervisor's own app that shows the run's running VMs in a window of its own
179    /// ([`crate::Running::native_console`]), and what of it this computer needs; none where the
180    /// run's provider has none (vagrant-qemu), or for a run of containers.
181    #[serde(default, skip_serializing_if = "Option::is_none")]
182    pub native: Option<crate::NativeApp>,
183}
184
185impl Status {
186    /// Whether anything of the run is there: a machine that isn't absent.
187    #[must_use]
188    pub fn any_present(&self) -> bool {
189        any_present(&self.machines)
190    }
191}
192
193/// [`Status::live`] in a status written before it existed: every status was read from the
194/// engine then.
195fn live_when_absent() -> bool {
196    true
197}
198
199/// The JSON Schema of a run's status (`isothrum status --json`).
200#[must_use]
201pub fn status_schema() -> serde_json::Value {
202    crate::events::titled_schema::<Status>("Isothrum run status")
203}
204
205/// A run that came up (or resumed).
206#[derive(Debug, Clone, PartialEq, Eq)]
207#[non_exhaustive]
208pub struct Started {
209    /// Its record.
210    pub record: RunRecord,
211    /// Its outputs.
212    pub outputs: Vec<OutputValue>,
213    /// The run's message, filled (a sensitive output never substituted).
214    pub message: Option<String>,
215}
216
217/// The state of a run whose machines are `machines`, given its record, while no operation holds
218/// it. Absent when nothing is there; parked when its record says so and none runs
219/// ([`any_member_running`]: one up with a failing healthcheck runs); failed when its record says
220/// its start failed, or an operation never recorded how it ended (its record still moving: its
221/// process was killed), whatever runs; ready when every member machine runs healthy; failed
222/// otherwise.
223pub(crate) fn derive_state(machines: &[MachineStatus], record: Option<&RunRecord>) -> RunState {
224    if !any_present(machines) {
225        return RunState::Absent;
226    }
227    if record.is_some_and(|r| r.state == RunState::Parked) && !any_member_running(machines) {
228        return RunState::Parked;
229    }
230    let members: Vec<&MachineStatus> = machines.iter().filter(|m| m.role == Role::Member).collect();
231    let running = |m: &&MachineStatus| m.state == MachineState::Running;
232    // A start that failed after its machines came up (a Terraform apply whose router never
233    // reported its address, a set-up step that failed) left them running: the run isn't ready.
234    // So did one whose process died midway: its set-up may not have run.
235    if record.is_some_and(|r| r.state == RunState::Failed || r.state.is_moving()) {
236        return RunState::Failed;
237    }
238    if !members.is_empty() && members.iter().all(running) {
239        RunState::Ready
240    } else {
241        RunState::Failed
242    }
243}
244
245/// Whether anything of the run is there: a machine of `machines` that isn't absent.
246pub(crate) fn any_present(machines: &[MachineStatus]) -> bool {
247    machines.iter().any(|m| m.state != MachineState::Absent)
248}
249
250/// The member machines of `machines` that are gone (absent) while something of the run is
251/// there: removed outside the runner.
252pub(crate) fn gone_members(machines: &[MachineStatus]) -> Vec<String> {
253    if !any_present(machines) {
254        return Vec::new();
255    }
256    machines
257        .iter()
258        .filter(|m| m.role == Role::Member && m.state == MachineState::Absent)
259        .map(|m| m.name.clone())
260        .collect()
261}
262
263/// Whether any member machine of `machines` runs.
264pub(crate) fn any_member_running(machines: &[MachineStatus]) -> bool {
265    machines.iter().any(|m| m.role == Role::Member && m.state.runs())
266}
267
268/// The manifest's networks, their native names filled by `native`.
269pub(crate) fn networks(manifest: &Manifest, native: impl Fn(&isoloom_manifest::Template) -> Option<String>) -> Vec<NetworkView> {
270    manifest
271        .networks
272        .iter()
273        .map(|n| NetworkView {
274            name: n.name.to_string(),
275            cidr: n.cidr.to_string(),
276            internet: n.internet,
277            native: n.native.as_ref().and_then(&native),
278        })
279        .collect()
280}
281
282#[cfg(test)]
283mod tests {
284    use super::*;
285
286    fn machine(role: Role, state: MachineState) -> MachineStatus {
287        MachineStatus {
288            name: "m".into(),
289            role,
290            state,
291            addresses: BTreeMap::new(),
292            published: Vec::new(),
293            console: None,
294        }
295    }
296
297    #[test]
298    fn a_run_is_ready_when_every_member_runs() {
299        use MachineState::{Absent, Exited, Running, Stopped};
300        let all = |ms: Vec<MachineStatus>| derive_state(&ms, None);
301        assert_eq!(all(vec![machine(Role::Member, Absent), machine(Role::Job, Absent)]), RunState::Absent);
302        assert_eq!(
303            all(vec![
304                machine(Role::Member, Running),
305                machine(Role::Job, Exited(0)),
306                machine(Role::Infra, Running)
307            ]),
308            RunState::Ready
309        );
310        assert_eq!(all(vec![machine(Role::Member, Running), machine(Role::Member, Exited(1))]), RunState::Failed);
311        assert_eq!(all(vec![machine(Role::Member, Stopped)]), RunState::Failed);
312        assert_eq!(all(vec![machine(Role::Member, MachineState::Unhealthy)]), RunState::Failed);
313    }
314
315    #[test]
316    fn a_status_from_before_live_reads_as_live() {
317        let json = r#"{"state":"ready","provider":null,"machines":[],"networks":[],"outputs":[],"message":null}"#;
318        let status: Status = serde_json::from_str(json).unwrap();
319        assert!(status.live);
320    }
321
322    #[test]
323    fn a_parked_run_with_nothing_running_is_parked() {
324        let mut record = crate::store::RunRecord::fresh(
325            crate::name::RunName::new("r").unwrap(),
326            "/x".into(),
327            isoloom_manifest::Target::Docker,
328            isoloom_manifest::Driver::Compose,
329        );
330        record.state = RunState::Parked;
331        let stopped = vec![machine(Role::Member, MachineState::Exited(0))];
332        assert_eq!(derive_state(&stopped, Some(&record)), RunState::Parked);
333        assert!(!any_member_running(&stopped));
334        // Regression: a member up with a failing healthcheck runs, as `check` and `provision`
335        // see it, so the run isn't parked (nor ready).
336        let unhealthy = vec![machine(Role::Member, MachineState::Unhealthy)];
337        assert!(any_member_running(&unhealthy));
338        assert_eq!(derive_state(&unhealthy, Some(&record)), RunState::Failed);
339    }
340}