1use 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
16#[serde(rename_all = "snake_case")]
17#[non_exhaustive]
18pub enum MachineState {
19 Running,
21 Unhealthy,
23 Exited(i32),
25 Stopped,
27 Absent,
29 Unknown(String),
31 Busy,
34}
35
36impl MachineState {
37 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
60#[non_exhaustive]
61pub struct PublishedPort {
62 pub port: crate::port::GuestPort,
64 pub protocol: Option<Protocol>,
66 pub host_port: crate::port::HostPort,
68}
69
70#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
72#[non_exhaustive]
73pub struct MachineStatus {
74 pub name: String,
76 pub state: MachineState,
78 pub published: Vec<PublishedPort>,
80 #[serde(default, skip_serializing_if = "Option::is_none")]
85 pub address: Option<String>,
86 #[serde(default, skip_serializing_if = "Option::is_none")]
89 pub console: Option<crate::graphical::ConsoleOffer>,
90}
91
92#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
95#[non_exhaustive]
96pub struct MachineUsage {
97 pub name: String,
99 pub cpu_percent: Option<f64>,
102 pub memory_bytes: Option<u64>,
104}
105
106impl MachineUsage {
107 #[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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
122#[non_exhaustive]
123pub struct OutputValue {
124 pub name: String,
126 pub sensitive: bool,
128 pub value: Option<String>,
130 #[serde(skip)]
132 secret: Option<SecretValue>,
133}
134
135impl OutputValue {
136 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 #[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 #[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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
174#[non_exhaustive]
175pub struct Status {
176 pub state: RunState,
180 #[serde(default = "default_live")]
186 pub live: bool,
187 #[serde(default, skip_serializing_if = "Option::is_none")]
190 pub desired: Option<crate::state::Desired>,
191 #[serde(default, skip_serializing_if = "Option::is_none")]
193 pub failed_cause: Option<crate::ErrorCode>,
194 pub provider: Option<Provider>,
196 pub machines: Vec<MachineStatus>,
198 pub outputs: Vec<OutputValue>,
201 #[serde(default, skip_serializing_if = "Option::is_none")]
204 pub native: Option<crate::graphical::NativeApp>,
205 #[serde(default, skip_serializing_if = "Vec::is_empty")]
209 pub parks: Vec<Park>,
210}
211
212impl Status {
213 #[must_use]
215 pub fn any_present(&self) -> bool {
216 any_present(&self.machines)
217 }
218}
219
220#[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
232fn default_live() -> bool {
235 true
236}
237
238#[must_use]
240pub fn status_schema() -> serde_json::Value {
241 crate::events::titled_schema::<Status>("Isothrum run status")
242}
243
244#[derive(Debug, Clone, PartialEq, Eq)]
246#[non_exhaustive]
247pub struct Started {
248 pub record: RunRecord,
250 pub outputs: Vec<OutputValue>,
252}
253
254pub(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 #[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}