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;
6use std::path::PathBuf;
7
8use isoloom_manifest::{Manifest, OutputRole, Protocol, Role};
9use serde::{Deserialize, Serialize};
10
11use crate::state::RunState;
12use crate::store::RunRecord;
13
14/// The command that opens an interactive shell into a machine: the runner builds it (it alone
15/// knows the runtime — the Compose project and files, the Vagrant define), the embedder runs it
16/// in its own terminal. Addresses the box by service or define name, never a guessed container.
17#[derive(Debug, Clone, Serialize)]
18pub struct ShellCommand {
19    /// The program to run (`docker`, `vagrant`).
20    pub program: String,
21    /// Its arguments.
22    pub args: Vec<String>,
23    /// The folder to run it in (the run's folder).
24    pub cwd: Option<PathBuf>,
25    /// Variables to run it with, besides the embedder's own (a Vagrant run's state folder,
26    /// `VAGRANT_DOTFILE_PATH`, without which Vagrant doesn't find the VM; its forwarded ports).
27    /// Empty for a Compose run.
28    #[serde(default)]
29    pub env: Vec<(String, String)>,
30}
31
32/// A machine's state, as its engine reports it.
33#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
34#[serde(rename_all = "snake_case")]
35#[non_exhaustive]
36pub enum MachineState {
37    /// Running.
38    Running,
39    /// Running, but failing its health check.
40    Unhealthy,
41    /// Exited with this code (a job that finished, or a machine that died).
42    Exited(i32),
43    /// Created or stopped, not running.
44    Stopped,
45    /// Not there.
46    Absent,
47    /// Something else, as the engine says it.
48    Unknown(String),
49}
50
51impl std::fmt::Display for MachineState {
52    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
53        match self {
54            MachineState::Running => f.write_str("running"),
55            MachineState::Unhealthy => f.write_str("unhealthy"),
56            MachineState::Exited(code) => write!(f, "exited({code})"),
57            MachineState::Stopped => f.write_str("stopped"),
58            MachineState::Absent => f.write_str("absent"),
59            MachineState::Unknown(s) => f.write_str(s),
60        }
61    }
62}
63
64/// A published port: where a machine's port answers on the host.
65#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
66#[non_exhaustive]
67pub struct PublishedPort {
68    /// The machine's port.
69    pub port: u16,
70    /// `tcp` or `udp`.
71    pub protocol: Protocol,
72    /// The host port.
73    pub host_port: u16,
74}
75
76/// One machine of the manifest, as it stands.
77#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
78#[non_exhaustive]
79pub struct MachineStatus {
80    /// Its name.
81    pub name: String,
82    /// What it is for.
83    pub role: Role,
84    /// Its state.
85    pub state: MachineState,
86    /// Its static addresses, by network.
87    pub addresses: BTreeMap<String, String>,
88    /// Its published ports.
89    pub published: Vec<PublishedPort>,
90}
91
92/// A network of the run.
93#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
94#[non_exhaustive]
95pub struct NetworkView {
96    /// Its name in the spec.
97    pub name: String,
98    /// Its block.
99    pub cidr: String,
100    /// Whether it reaches the internet.
101    pub internet: bool,
102    /// Its name where the target created it (`flag-portal_lab`), when known.
103    pub native: Option<String>,
104}
105
106/// An output's value.
107#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
108#[non_exhaustive]
109pub struct OutputValue {
110    /// Its name.
111    pub name: String,
112    /// What it is for (`entry` is the Open button).
113    pub role: OutputRole,
114    /// Whether the value is sensitive.
115    pub sensitive: bool,
116    /// Its value, when it can be read.
117    pub value: Option<String>,
118}
119
120/// A run as it stands.
121#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
122#[non_exhaustive]
123pub struct Status {
124    /// Where it stands.
125    pub state: RunState,
126    /// The Vagrant provider it uses, when it has one.
127    pub provider: Option<String>,
128    /// Every machine of the manifest.
129    pub machines: Vec<MachineStatus>,
130    /// The run's networks.
131    pub networks: Vec<NetworkView>,
132    /// Its outputs, read live.
133    pub outputs: Vec<OutputValue>,
134    /// The run's message, filled, once the run is ready.
135    pub message: Option<String>,
136}
137
138/// A run that came up (or resumed).
139#[derive(Debug, Clone, PartialEq, Eq)]
140#[non_exhaustive]
141pub struct Started {
142    /// Its record.
143    pub record: RunRecord,
144    /// Its outputs.
145    pub outputs: Vec<OutputValue>,
146    /// The run's message, filled (a sensitive output never substituted).
147    pub message: Option<String>,
148}
149
150/// The state of a run whose machines are `machines`, given its record. Ready when every target
151/// machine runs; parked when its record says so and none runs; absent when nothing is there.
152pub(crate) fn derive_state(machines: &[MachineStatus], record: Option<&RunRecord>) -> RunState {
153    let present = machines.iter().any(|m| m.state != MachineState::Absent);
154    if !present {
155        return RunState::Absent;
156    }
157    let targets: Vec<&MachineStatus> = machines.iter().filter(|m| m.role == Role::Target).collect();
158    let running = |m: &&MachineStatus| m.state == MachineState::Running;
159    if record.is_some_and(|r| r.state == RunState::Parked) && !targets.iter().any(running) {
160        return RunState::Parked;
161    }
162    // A start that failed after its machines came up (a Terraform apply whose router never
163    // reported its address, a set-up step that failed) left them running: the run isn't ready.
164    if record.is_some_and(|r| r.state == RunState::Failed) {
165        return RunState::Failed;
166    }
167    if !targets.is_empty() && targets.iter().all(running) {
168        RunState::Ready
169    } else {
170        RunState::Failed
171    }
172}
173
174/// Whether any target machine of `machines` runs.
175pub(crate) fn any_target_running(machines: &[MachineStatus]) -> bool {
176    machines
177        .iter()
178        .any(|m| m.role == Role::Target && matches!(m.state, MachineState::Running | MachineState::Unhealthy))
179}
180
181/// The manifest's networks, their native names filled by `native`.
182pub(crate) fn networks(manifest: &Manifest, native: impl Fn(&isoloom_manifest::Template) -> Option<String>) -> Vec<NetworkView> {
183    manifest
184        .networks
185        .iter()
186        .map(|n| NetworkView {
187            name: n.name.to_string(),
188            cidr: n.cidr.to_string(),
189            internet: n.internet,
190            native: n.native.as_ref().and_then(&native),
191        })
192        .collect()
193}
194
195#[cfg(test)]
196mod tests {
197    use super::*;
198
199    fn machine(role: Role, state: MachineState) -> MachineStatus {
200        MachineStatus {
201            name: "m".into(),
202            role,
203            state,
204            addresses: BTreeMap::new(),
205            published: Vec::new(),
206        }
207    }
208
209    #[test]
210    fn a_run_is_ready_when_every_target_runs() {
211        use MachineState::{Absent, Exited, Running, Stopped};
212        let all = |ms: Vec<MachineStatus>| derive_state(&ms, None);
213        assert_eq!(all(vec![machine(Role::Target, Absent), machine(Role::Job, Absent)]), RunState::Absent);
214        assert_eq!(
215            all(vec![
216                machine(Role::Target, Running),
217                machine(Role::Job, Exited(0)),
218                machine(Role::Infra, Running)
219            ]),
220            RunState::Ready
221        );
222        assert_eq!(all(vec![machine(Role::Target, Running), machine(Role::Target, Exited(1))]), RunState::Failed);
223        assert_eq!(all(vec![machine(Role::Target, Stopped)]), RunState::Failed);
224        assert_eq!(all(vec![machine(Role::Target, MachineState::Unhealthy)]), RunState::Failed);
225    }
226
227    #[test]
228    fn a_parked_run_with_nothing_running_is_parked() {
229        let mut record = crate::store::RunRecord::fresh(
230            crate::name::RunName::new("r").unwrap(),
231            "/x".into(),
232            String::new(),
233            isoloom_manifest::Target::Docker,
234            isoloom_manifest::Driver::Compose,
235        );
236        record.state = RunState::Parked;
237        let stopped = vec![machine(Role::Target, MachineState::Exited(0))];
238        assert_eq!(derive_state(&stopped, Some(&record)), RunState::Parked);
239        assert!(!any_target_running(&stopped));
240    }
241}