Skip to main content

isothrum_runner/
status.rs

1//! What a run looks like from outside: its state, its machines and the host ports they publish,
2//! what they use, and the outputs the project gives back, each as its tool reports it. What a machine or a port
3//! is for is the embedder's to know, from the project's own description.
4
5use serde::{Deserialize, Serialize};
6
7use crate::events::MASK;
8use crate::project::Format;
9use crate::project::platform::{Protocol, Provider};
10use crate::secrets::SecretValue;
11use crate::state::{Park, RunState};
12use crate::store::RunRecord;
13
14/// A machine's state, as its engine reports it.
15#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
16#[serde(rename_all = "snake_case")]
17#[non_exhaustive]
18pub enum MachineState {
19    /// Running.
20    Running,
21    /// Running, but failing its health check.
22    Unhealthy,
23    /// Exited with this code (a job that finished, or a machine that died).
24    Exited(i32),
25    /// Created or stopped, not running.
26    Stopped,
27    /// Not there.
28    Absent,
29    /// Something else, as the engine says it.
30    Unknown(String),
31    /// Not read: another process acts on it (Vagrant's lock on the machine, held by a `vagrant
32    /// up` that isn't this runner's), so its state is whatever that action leaves.
33    Busy,
34}
35
36impl MachineState {
37    /// Whether the machine runs: up, whether or not it passes its health check (the one rule for
38    /// "it runs", however it is asked).
39    pub(crate) fn runs(&self) -> bool {
40        matches!(self, MachineState::Running | MachineState::Unhealthy)
41    }
42}
43
44impl std::fmt::Display for MachineState {
45    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
46        match self {
47            MachineState::Running => f.write_str("running"),
48            MachineState::Unhealthy => f.write_str("unhealthy"),
49            MachineState::Exited(code) => write!(f, "exited({code})"),
50            MachineState::Stopped => f.write_str("stopped"),
51            MachineState::Absent => f.write_str("absent"),
52            MachineState::Unknown(s) => f.write_str(s),
53            MachineState::Busy => f.write_str("busy"),
54        }
55    }
56}
57
58/// A published port: where a machine's port answers on the host.
59#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
60#[non_exhaustive]
61pub struct PublishedPort {
62    /// The machine's port, inside it.
63    pub port: crate::port::GuestPort,
64    /// `tcp` or `udp`; `None` when the tool doesn't say (Vagrant's `port`), never guessed.
65    pub protocol: Option<Protocol>,
66    /// The host port it is reached at, at the machine's host address.
67    pub host_port: crate::port::HostPort,
68}
69
70/// One machine of the run, as its tool reports it.
71#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
72#[non_exhaustive]
73pub struct MachineStatus {
74    /// Its name in the project (a Compose service, a Vagrant machine, a module's VM).
75    pub name: String,
76    /// Its state.
77    pub state: MachineState,
78    /// Its published ports.
79    pub published: Vec<PublishedPort>,
80    /// The address it is reached at itself, when its tool says one another computer reaches (a
81    /// VM on a bridged or host-only network, a server's VM, a cloud instance); none for one
82    /// reached only through its published ports. On ESXi, which forwards no port to this
83    /// computer, a machine's ports answer at this address.
84    #[serde(default, skip_serializing_if = "Option::is_none")]
85    pub address: Option<String>,
86    /// Its graphical console, as its hypervisor offers it; none for a machine with no screen to
87    /// speak of (a container), and while not [`Status::live`].
88    #[serde(default, skip_serializing_if = "Option::is_none")]
89    pub console: Option<crate::graphical::ConsoleOffer>,
90}
91
92/// What one machine of a run uses now, as its engine reports it (several instances of it, a
93/// service scaled up, summed).
94#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
95#[non_exhaustive]
96pub struct MachineUsage {
97    /// Its name in the project.
98    pub name: String,
99    /// Its CPU use, in percent of one CPU (over 100 on several); none when the engine has no
100    /// figure for it yet.
101    pub cpu_percent: Option<f64>,
102    /// The memory it uses, in bytes; none when the engine has no figure for it yet.
103    pub memory_bytes: Option<u64>,
104}
105
106impl MachineUsage {
107    /// Machine `name` using `cpu_percent` and `memory_bytes`.
108    #[must_use]
109    pub fn new(name: impl Into<String>, cpu_percent: Option<f64>, memory_bytes: Option<u64>) -> MachineUsage {
110        MachineUsage {
111            name: name.into(),
112            cpu_percent,
113            memory_bytes,
114        }
115    }
116}
117
118/// An output's value (a Terraform module's output). A sensitive one shows as `***` wherever it
119/// is written out (its JSON, its `Debug`, an event); the runner keeps the value itself for the
120/// embedder ([`OutputValue::revealed`]).
121#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
122#[non_exhaustive]
123pub struct OutputValue {
124    /// Its name.
125    pub name: String,
126    /// Whether the value is sensitive.
127    pub sensitive: bool,
128    /// Its value, when it can be read; `***` when it is sensitive.
129    pub value: Option<String>,
130    /// A sensitive output's value itself: never written out.
131    #[serde(skip)]
132    secret: Option<SecretValue>,
133}
134
135impl OutputValue {
136    /// Output `name`'s `value`, masked when it is `sensitive`.
137    pub(crate) fn new(name: String, sensitive: bool, value: Option<String>) -> OutputValue {
138        let (value, secret) = match value {
139            Some(v) if sensitive => (Some(MASK.to_owned()), Some(SecretValue::new(v))),
140            value => (value, None),
141        };
142        OutputValue {
143            name,
144            sensitive,
145            value,
146            secret,
147        }
148    }
149
150    /// The same, a sensitive one with its own value instead of the mask (a status read asked to
151    /// reveal it, [`crate::RunOptions::reveal`]).
152    #[must_use]
153    pub(crate) fn unmasked(mut self) -> OutputValue {
154        if let Some(secret) = &self.secret {
155            self.value = Some(secret.expose().to_owned());
156        }
157        self
158    }
159
160    /// The value itself, a sensitive one unmasked. Never print or log it. `None` when it can't be
161    /// read, and for a sensitive output read back from JSON (which holds only the mask).
162    #[must_use]
163    pub fn revealed(&self) -> Option<&str> {
164        if self.sensitive {
165            self.secret.as_ref().map(SecretValue::expose)
166        } else {
167            self.value.as_deref()
168        }
169    }
170}
171
172/// A run as it stands.
173#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
174#[non_exhaustive]
175pub struct Status {
176    /// Where it stands. While an operation holds the run: the moving state it is in (`creating`
177    /// through an `up`), else, before it records one or for an operation that leaves the run as
178    /// it was meanwhile (an `update`: `ready`), the state the run's record holds.
179    pub state: RunState,
180    /// Whether the machines and outputs were read from the engine now. False while an operation
181    /// holds the run (in this process or another), whose tools a read would contend with (Vagrant
182    /// refuses to read a VM's state while a `vagrant up` provisions it): they are then as the
183    /// runner last read them (none before it ever did), and the outputs the engine itself gives
184    /// are left out.
185    #[serde(default = "default_live")]
186    pub live: bool,
187    /// What the user wants of the run (the last operation that set it: `up`, `park`, `down`);
188    /// none for a run never recorded. With `state`, whether the run is where it should be.
189    #[serde(default, skip_serializing_if = "Option::is_none")]
190    pub desired: Option<crate::state::Desired>,
191    /// Why the run failed, when its recorded state is `failed`.
192    #[serde(default, skip_serializing_if = "Option::is_none")]
193    pub failed_cause: Option<crate::ErrorCode>,
194    /// The Vagrant provider it uses, when it has one.
195    pub provider: Option<Provider>,
196    /// Every machine its tool reports.
197    pub machines: Vec<MachineStatus>,
198    /// What the project gives back (a module's outputs), as read; none while not
199    /// [`Status::live`].
200    pub outputs: Vec<OutputValue>,
201    /// The hypervisor's own app the run's VMs open in ([`crate::Running::native_console`]); none
202    /// where there is none (containers, QEMU), and while not [`Status::live`].
203    #[serde(default, skip_serializing_if = "Option::is_none")]
204    pub native: Option<crate::graphical::NativeApp>,
205    /// The ways the run can be parked, by its format and provider ([`park_modes`]): none for a
206    /// run never recorded, nor for a Terraform module, which is never parked. Whether it can be
207    /// parked now is its `state`'s: a run is parked from `ready`.
208    #[serde(default, skip_serializing_if = "Vec::is_empty")]
209    pub parks: Vec<Park>,
210}
211
212impl Status {
213    /// Whether anything of the run is there: a machine that isn't absent.
214    #[must_use]
215    pub fn any_present(&self) -> bool {
216        any_present(&self.machines)
217    }
218}
219
220/// The ways a run of `format`, on the Vagrant `provider` (none: not Vagrant's, or not known yet),
221/// can be parked: Compose pauses (`pause`) and stops; Vagrant suspends and halts, but for QEMU's
222/// provider, which has no suspend; Terraform parks nothing (`park` is refused).
223#[must_use]
224pub fn park_modes(format: Format, provider: Option<Provider>) -> Vec<Park> {
225    match format {
226        Format::Vagrant if provider == Some(Provider::Qemu) => vec![Park::Shutdown],
227        Format::Compose | Format::Vagrant => vec![Park::Pause, Park::Shutdown],
228        Format::Terraform => Vec::new(),
229    }
230}
231
232/// [`Status::live`]'s default, for a status written before the field existed: every status was
233/// read from the engine then.
234fn default_live() -> bool {
235    true
236}
237
238/// The JSON Schema of a run's status (`isothrum status --json`).
239#[must_use]
240pub fn status_schema() -> serde_json::Value {
241    crate::events::titled_schema::<Status>("Isothrum run status")
242}
243
244/// A run that came up (or resumed).
245#[derive(Debug, Clone, PartialEq, Eq)]
246#[non_exhaustive]
247pub struct Started {
248    /// Its record.
249    pub record: RunRecord,
250    /// Its outputs.
251    pub outputs: Vec<OutputValue>,
252}
253
254/// Whether anything of the run is there: a machine of `machines` that isn't absent.
255pub(crate) fn any_present(machines: &[MachineStatus]) -> bool {
256    machines.iter().any(|m| m.state != MachineState::Absent)
257}
258
259#[cfg(test)]
260mod tests {
261    use super::*;
262
263    /// The JSON `isothrum status --json` prints and an embedder reads: a machine's state by its
264    /// name (an exit with its code), a port with no protocol said as null, the optional fields
265    /// left out when unset; and it reads back as itself.
266    #[test]
267    fn a_status_is_written_as_its_schema_documents_and_reads_back() {
268        let machine = |name: &str, state: MachineState| MachineStatus {
269            name: name.into(),
270            state,
271            published: Vec::new(),
272            address: None,
273            console: None,
274        };
275        let mut web = machine("web", MachineState::Running);
276        web.published = vec![PublishedPort {
277            port: crate::port::GuestPort::new(80),
278            protocol: Some(Protocol::Tcp),
279            host_port: crate::port::HostPort::new(41001),
280        }];
281        let mut vm = machine("vm", MachineState::Unknown("saved".into()));
282        vm.published = vec![PublishedPort {
283            port: crate::port::GuestPort::new(22),
284            protocol: None,
285            host_port: crate::port::HostPort::new(2222),
286        }];
287        vm.address = Some("192.0.2.10".into());
288        let status = Status {
289            state: RunState::Ready,
290            live: true,
291            desired: Some(crate::state::Desired::Running),
292            failed_cause: None,
293            provider: Some(Provider::Virtualbox),
294            machines: vec![web, machine("job", MachineState::Exited(3)), vm],
295            outputs: vec![OutputValue::new("url".into(), false, Some("http://127.0.0.1:41001".into()))],
296            native: None,
297            parks: vec![Park::Pause, Park::Shutdown],
298        };
299        let json = serde_json::to_value(&status).unwrap();
300        assert_eq!(
301            json,
302            serde_json::json!({
303                "state": "ready", "live": true, "desired": "running", "provider": "virtualbox",
304                "machines": [
305                    {"name": "web", "state": "running", "published": [{"port": 80, "protocol": "tcp", "host_port": 41001}]},
306                    {"name": "job", "state": {"exited": 3}, "published": []},
307                    {"name": "vm", "state": {"unknown": "saved"}, "published": [{"port": 22, "protocol": null, "host_port": 2222}], "address": "192.0.2.10"}
308                ],
309                "outputs": [{"name": "url", "sensitive": false, "value": "http://127.0.0.1:41001"}],
310                "parks": ["pause", "shutdown"]
311            })
312        );
313        assert_eq!(serde_json::from_value::<Status>(json).unwrap(), status);
314    }
315
316    #[test]
317    fn a_run_is_parked_as_its_format_and_provider_can() {
318        assert_eq!(park_modes(Format::Compose, None), [Park::Pause, Park::Shutdown]);
319        assert_eq!(park_modes(Format::Vagrant, Some(Provider::Virtualbox)), [Park::Pause, Park::Shutdown]);
320        assert_eq!(park_modes(Format::Vagrant, Some(Provider::Qemu)), [Park::Shutdown]);
321        assert_eq!(park_modes(Format::Terraform, None), []);
322    }
323
324    #[test]
325    fn a_status_from_before_live_reads_as_live() {
326        let json = r#"{"state":"ready","provider":null,"machines":[],"outputs":[]}"#;
327        let status: Status = serde_json::from_str(json).unwrap();
328        assert!(status.live);
329    }
330
331    #[test]
332    fn a_sensitive_output_is_masked_and_kept() {
333        let out = OutputValue::new("token".into(), true, Some("s3cret".into()));
334        assert_eq!((out.value.as_deref(), out.revealed()), (Some(MASK), Some("s3cret")));
335        assert!(!serde_json::to_string(&out).unwrap().contains("s3cret"));
336    }
337}