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