1use 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
17#[serde(rename_all = "snake_case")]
18#[non_exhaustive]
19pub enum MachineState {
20 Running,
22 Unhealthy,
24 Exited(i32),
26 Stopped,
28 Absent,
30 Unknown(String),
32 Busy,
35}
36
37impl MachineState {
38 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
61#[non_exhaustive]
62pub struct PublishedPort {
63 pub port: u16,
65 pub protocol: Protocol,
67 pub host_port: u16,
69}
70
71#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
73#[non_exhaustive]
74pub struct MachineStatus {
75 pub name: String,
77 pub role: Role,
79 pub state: MachineState,
81 pub addresses: BTreeMap<String, String>,
83 pub published: Vec<PublishedPort>,
85 #[serde(default, skip_serializing_if = "Option::is_none")]
88 pub console: Option<crate::graphical::ConsoleOffer>,
89}
90
91#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
93#[non_exhaustive]
94pub struct NetworkView {
95 pub name: String,
97 pub cidr: String,
99 pub internet: bool,
101 pub native: Option<String>,
103}
104
105#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
109#[non_exhaustive]
110pub struct OutputValue {
111 pub name: String,
113 pub role: OutputRole,
115 pub sensitive: bool,
117 pub value: Option<String>,
119 #[serde(skip)]
121 secret: Option<SecretValue>,
122}
123
124impl OutputValue {
125 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 #[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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
154#[non_exhaustive]
155pub struct Status {
156 pub state: RunState,
160 #[serde(default = "live_when_absent")]
166 pub live: bool,
167 pub provider: Option<Provider>,
169 pub machines: Vec<MachineStatus>,
171 pub networks: Vec<NetworkView>,
173 pub outputs: Vec<OutputValue>,
176 pub message: Option<String>,
178 #[serde(default, skip_serializing_if = "Option::is_none")]
182 pub native: Option<crate::NativeApp>,
183}
184
185impl Status {
186 #[must_use]
188 pub fn any_present(&self) -> bool {
189 any_present(&self.machines)
190 }
191}
192
193fn live_when_absent() -> bool {
196 true
197}
198
199#[must_use]
201pub fn status_schema() -> serde_json::Value {
202 crate::events::titled_schema::<Status>("Isothrum run status")
203}
204
205#[derive(Debug, Clone, PartialEq, Eq)]
207#[non_exhaustive]
208pub struct Started {
209 pub record: RunRecord,
211 pub outputs: Vec<OutputValue>,
213 pub message: Option<String>,
215}
216
217pub(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 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
245pub(crate) fn any_present(machines: &[MachineStatus]) -> bool {
247 machines.iter().any(|m| m.state != MachineState::Absent)
248}
249
250pub(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
263pub(crate) fn any_member_running(machines: &[MachineStatus]) -> bool {
265 machines.iter().any(|m| m.role == Role::Member && m.state.runs())
266}
267
268pub(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 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}