Skip to main content

microvms_protocol/
health.rs

1// SPDX-License-Identifier: Apache-2.0
2//! The `GET /v1/health` response.
3
4use std::borrow::Cow;
5
6use schemars::JsonSchema;
7use serde::{Deserialize, Serialize};
8
9/// `GET /v1/health` response.
10#[derive(Debug, Deserialize, JsonSchema, Serialize)]
11pub struct Health {
12    // The daemon's own version, distinct from `PROTOCOL_VERSION`. `Cow` so the
13    // daemon reports its `CARGO_PKG_VERSION` borrowed while a client deserializes
14    // into an owned string.
15    //
16    // Not a doc comment, deliberately: schemars publishes doc comments as
17    // `description` and `docs/schema.json` is byte-compared, so adding one here is a
18    // schema change. The field was undocumented before the extraction and stays so.
19    pub version: Cow<'static, str>,
20    pub bootstrapped: bool,
21    /// Free space on the daemon's working filesystem, and the reserve it is judged
22    /// against.
23    ///
24    /// Reported so disk pressure is something an orchestrator *watches* rather than
25    /// something it discovers from a failed write. anthropics/claude-code#59856
26    /// filled two 10 GB disks to 100% with never-collected session directories and
27    /// the first symptom was `useradd: No space left on device` — by which point
28    /// every writer in the sandbox was already broken. A number on a health endpoint
29    /// is what makes that curve visible while there is still time to act.
30    ///
31    /// `None` when free space could not be measured, which is deliberately distinct
32    /// from zero: unmeasurable is not full, and a monitor that conflated them would
33    /// page on a missing `statvfs`.
34    pub disk: Option<DiskHealth>,
35    /// Whether any startup identity repair step failed. True means the VM is serving
36    /// with a value from the shared image still in place — a duplicate machine-id or
37    /// boot_id — which is a security-relevant condition an operator may want to
38    /// drain the VM over, but is never a reason for the daemon to refuse to serve.
39    pub identity_degraded: bool,
40    /// False when identity repair was switched off by config. Distinguished from a
41    /// repair that ran and found nothing so a monitor can tell "opted out" from
42    /// "nothing to do".
43    pub identity_repaired: bool,
44    /// Whether any exec is still running right now.
45    ///
46    /// Here so that an orchestrator *outside* the VM can decide whether to keep the
47    /// VM alive, and the "outside" is the whole design. The platform measures
48    /// idleness by inbound traffic through the endpoint proxy, and that proxy
49    /// terminates outside the guest and forwards over loopback (measured;
50    /// `docs/PLATFORM.md`, "The platform's own hook arrives over loopback"). A
51    /// request a guest process sends to the daemon's own port never reaches the
52    /// proxy, so no amount of in-guest traffic can reset the idle timer. A route
53    /// that promised otherwise would be a keepalive that does not keep anything
54    /// alive, discovered when a multi-hour run auto-suspends mid-work.
55    ///
56    /// What does reset it is a poll from outside, and this field is what makes such
57    /// a poll *informed* rather than unconditional: the orchestrator polls, which is
58    /// itself the inbound traffic, and reads whether the workload is busy to decide
59    /// whether to keep polling. The assertion is therefore repeated and explicitly
60    /// the caller's, which is what the daemon self-keepaliving would not be — a hung
61    /// process would then bill to the 8-hour ceiling with nobody asking.
62    ///
63    /// Computed from the exec registry rather than remembered: true iff at least one
64    /// registered exec has not yet published a result. An exec that exited and is
65    /// waiting to be acked is not busy — its output is being *held*, not produced —
66    /// so an orchestrator does not keep a VM alive for a command that finished.
67    ///
68    /// `#[serde(default)]`, unlike every field above it, and the asymmetry is not an
69    /// oversight. The daemon is baked into an image while the client is installed
70    /// separately, so a current client routinely talks to a daemon from whenever that
71    /// image was built — and a required field would make `health()` fail outright
72    /// against a daemon that predates it, turning a missing signal into an
73    /// unreachable VM. False is also the right absence: a daemon that cannot say
74    /// whether it is busy has not asserted that it is.
75    #[serde(default)]
76    pub busy: bool,
77    /// How many execs are registered, in any phase.
78    ///
79    /// Alongside `busy` because the two answer different questions and a monitor
80    /// wants both: `busy: false, execs: 0` is a fresh or drained VM, while
81    /// `busy: false, execs: 7` is a VM holding seven unacked results that somebody
82    /// still has to collect. Terminating the second loses output nobody read.
83    ///
84    /// Defaulted for the same reason as `busy`: a client routinely talks to a daemon
85    /// baked into an older image, and zero is the honest reading of a daemon that
86    /// does not report a count.
87    #[serde(default)]
88    pub execs: usize,
89    /// Every lifecycle-hook invocation the daemon observed, oldest first.
90    ///
91    /// The platform writes no CloudWatch logs for the validate hook, so "did my
92    /// validate hook even run?" has no answer anywhere else. Each entry is the
93    /// daemon's own observation — the hook path that was posted and the daemon's
94    /// clock when it arrived — never anything the guest printed.
95    ///
96    /// One trust caveat travels with this field and is stated rather than implied:
97    /// the hook routes are unauthenticated and reachable over loopback from inside
98    /// the guest, so a hostile workload can *forge additional* entries by posting
99    /// the hook paths itself. It cannot remove or alter real ones — the daemon
100    /// records before it responds and the log is append-capped, keeping the
101    /// earliest entries — so the platform's real firings are the front of the list
102    /// and later spam is what the cap drops.
103    ///
104    /// Defaulted for `busy`'s reason: an older daemon omits the field, and an empty
105    /// list is the honest reading of a daemon that reports no observations.
106    #[serde(default)]
107    pub hooks: Vec<HookObservation>,
108    /// How many hook invocations were dropped once the log reached its cap.
109    ///
110    /// Non-zero means the list above is the *earliest* invocations only — the cap
111    /// keeps first-N so a guest spamming the unauthenticated hook routes cannot
112    /// grow daemon memory or push the platform's real firings out of the record.
113    ///
114    /// Defaulted like `hooks`: an older daemon omits it, and zero is the honest
115    /// reading of a daemon that dropped nothing it could tell us about.
116    #[serde(default)]
117    pub hooks_dropped: u64,
118    /// Each identity-repair step and its outcome, in the order they ran.
119    ///
120    /// Empty until repair runs, which is at the first successful run hook: repair at
121    /// daemon start would run in the image-build VM and be captured by the snapshot,
122    /// giving every VM the same "repaired" identity. `identity_degraded` says whether
123    /// any step failed; this says which one and why.
124    ///
125    /// Defaulted for `busy`'s reason: an older daemon omits it.
126    #[serde(default)]
127    pub identity_steps: Vec<IdentityStep>,
128}
129
130/// One identity-repair step, as the daemon ran it.
131#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
132pub struct IdentityStep {
133    /// `machine-id`, `hostname`, `boot-id`, `random-seed`, or `cached-credential`.
134    pub name: String,
135    /// `repaired`, `not_applicable`, or `failed`.
136    pub outcome: String,
137    /// The OS error for a failed step. Names a path or an errno, never a value.
138    #[serde(default, skip_serializing_if = "Option::is_none")]
139    pub error: Option<String>,
140}
141
142/// What a workload's handler for a lifecycle hook did.
143///
144/// The daemon runs `<hooks dir>/<hook>` when the image carries one. Output is not
145/// here: `/v1/health` is readable without the agent token, so a handler's output
146/// goes to the daemon's log instead.
147#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
148pub struct HandlerOutcome {
149    /// The handler's exit code, or `None` when it was killed or never started.
150    pub exit_code: Option<i32>,
151    /// The signal that ended it, if one did.
152    #[serde(default)]
153    pub signal: Option<i32>,
154    /// Whether the daemon killed it for exceeding its time budget.
155    #[serde(default)]
156    pub timed_out: bool,
157    /// Wall-clock milliseconds from spawn to exit or kill.
158    pub duration_ms: u64,
159    /// Why the handler could not run at all: not executable, or spawn failed.
160    #[serde(default, skip_serializing_if = "Option::is_none")]
161    pub error: Option<String>,
162}
163
164impl HandlerOutcome {
165    /// Whether the handler ran and exited 0.
166    pub fn succeeded(&self) -> bool {
167        self.exit_code == Some(0) && !self.timed_out && self.error.is_none()
168    }
169}
170
171/// One lifecycle-hook invocation, as the daemon observed it.
172///
173/// A daemon-reported fact in the same trust class as an exec's exit code: the
174/// daemon's word about a request it served, carrying nothing the guest printed.
175#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
176pub struct HookObservation {
177    /// Which hook, spelled the way the platform's routes spell it: `ready`,
178    /// `validate`, `run`, `suspend`, `resume`, or `terminate`.
179    pub hook: String,
180    /// Seconds since the epoch on the daemon's clock when the invocation arrived.
181    ///
182    /// The daemon's clock rather than any caller's, and recorded before the handler
183    /// does any work — a run hook that was invoked and refused still fired.
184    pub fired_at: u64,
185    /// The workload handler's outcome, when the image carries a handler for this
186    /// hook. Absent on the wire otherwise, so an entry without one reads exactly as
187    /// it did before handlers existed.
188    #[serde(default, skip_serializing_if = "Option::is_none")]
189    pub handler: Option<HandlerOutcome>,
190}
191
192/// The disk half of [`Health`].
193#[derive(Debug, Deserialize, JsonSchema, Serialize)]
194pub struct DiskHealth {
195    /// Bytes available to an unprivileged writer, from `statvfs` `f_bavail`.
196    pub available_bytes: u64,
197    /// Bytes that must stay free before a write is refused. Zero means the guard is
198    /// disabled.
199    pub reserve_bytes: u64,
200    /// Whether a write would be refused right now. Precomputed rather than left to
201    /// the client, so every consumer applies the same comparison the write path does.
202    pub under_pressure: bool,
203}
204
205#[cfg(test)]
206mod tests {
207    use super::*;
208
209    /// `disk: null` is not `disk` absent: unmeasurable free space is distinct from
210    /// zero, and a client that read a missing key as zero would page on a missing
211    /// `statvfs`.
212    #[test]
213    fn health_reports_an_unmeasurable_disk_as_an_explicit_null() {
214        let written = serde_json::to_string(&Health {
215            version: Cow::Borrowed("0.1.0"),
216            bootstrapped: true,
217            disk: None,
218            identity_degraded: false,
219            identity_repaired: true,
220            busy: false,
221            execs: 0,
222            hooks: Vec::new(),
223            hooks_dropped: 0,
224            identity_steps: Vec::new(),
225        })
226        .expect("serializes");
227        assert!(written.contains(r#""disk":null"#), "{written}");
228
229        let read: Health = serde_json::from_str(&written).expect("deserializes");
230        assert_eq!(read.version, "0.1.0");
231        assert!(read.disk.is_none());
232    }
233
234    /// `busy` and `execs` round-trip, and they are separate facts: a VM holding
235    /// unacked results is not busy, and an orchestrator that conflated the two would
236    /// either keep a finished VM alive or terminate one whose output nobody read.
237    #[test]
238    fn health_carries_busy_and_the_exec_count_as_two_separate_facts() {
239        let written = serde_json::to_string(&Health {
240            version: Cow::Borrowed("0.1.0"),
241            bootstrapped: true,
242            disk: None,
243            identity_degraded: false,
244            identity_repaired: true,
245            busy: false,
246            execs: 7,
247            hooks: Vec::new(),
248            hooks_dropped: 0,
249            identity_steps: Vec::new(),
250        })
251        .expect("serializes");
252        assert!(written.contains(r#""busy":false"#), "{written}");
253        assert!(written.contains(r#""execs":7"#), "{written}");
254
255        let read: Health = serde_json::from_str(&written).expect("deserializes");
256        assert!(!read.busy);
257        assert_eq!(read.execs, 7);
258    }
259
260    /// The hook observations round-trip, spelled as the routes spell them, with the
261    /// dropped count beside them.
262    #[test]
263    fn health_carries_hook_observations_and_the_dropped_count() {
264        let written = serde_json::to_string(&Health {
265            version: Cow::Borrowed("0.1.0"),
266            bootstrapped: true,
267            disk: None,
268            identity_degraded: false,
269            identity_repaired: true,
270            busy: false,
271            execs: 0,
272            hooks: vec![
273                HookObservation {
274                    hook: "validate".to_string(),
275                    fired_at: 1_756_500_000,
276                    handler: None,
277                },
278                HookObservation {
279                    hook: "run".to_string(),
280                    fired_at: 1_756_500_100,
281                    handler: None,
282                },
283            ],
284            hooks_dropped: 3,
285            identity_steps: Vec::new(),
286        })
287        .expect("serializes");
288        // The wire keys are pinned to the response's own convention — snake_case,
289        // like `identity_degraded` beside them. The CLI's history line respells
290        // `fired_at` as `firedAt` because the history file is camelCase; a spelling
291        // only one side writes fails exactly when someone reads it.
292        assert!(
293            written.contains(r#""hooks":[{"hook":"validate","fired_at":1756500000}"#),
294            "{written}"
295        );
296        assert!(written.contains(r#""hooks_dropped":3"#), "{written}");
297
298        let read: Health = serde_json::from_str(&written).expect("deserializes");
299        assert_eq!(read.hooks.len(), 2);
300        assert_eq!(read.hooks[0].hook, "validate");
301        assert_eq!(read.hooks[0].fired_at, 1_756_500_000);
302        assert_eq!(read.hooks_dropped, 3);
303    }
304
305    /// An old daemon's envelope — no `hooks`, no `hooks_dropped` — still parses, with
306    /// the empty defaults. The daemon is baked into an image while the client is
307    /// installed separately, so this is the compatibility floor, not an edge case.
308    #[test]
309    fn an_old_daemons_envelope_parses_with_no_hook_fields() {
310        let read: Health = serde_json::from_str(
311            r#"{"version": "0.1.0", "bootstrapped": true, "disk": null,
312                 "identity_degraded": false, "identity_repaired": true}"#,
313        )
314        .expect("deserializes");
315        assert!(read.hooks.is_empty());
316        assert_eq!(read.hooks_dropped, 0);
317        assert!(!read.busy);
318        assert_eq!(read.execs, 0);
319    }
320
321    /// A handler outcome and the identity steps round-trip, and a hook with no
322    /// handler keeps the exact spelling older clients parse.
323    #[test]
324    fn handler_outcomes_and_identity_steps_round_trip() {
325        let written = serde_json::to_string(&Health {
326            version: Cow::Borrowed("0.1.0"),
327            bootstrapped: true,
328            disk: None,
329            identity_degraded: true,
330            identity_repaired: true,
331            busy: false,
332            execs: 0,
333            hooks: vec![
334                HookObservation {
335                    hook: "run".to_string(),
336                    fired_at: 1,
337                    handler: None,
338                },
339                HookObservation {
340                    hook: "suspend".to_string(),
341                    fired_at: 2,
342                    handler: Some(HandlerOutcome {
343                        exit_code: None,
344                        signal: Some(9),
345                        timed_out: true,
346                        duration_ms: 20_000,
347                        error: None,
348                    }),
349                },
350            ],
351            hooks_dropped: 0,
352            identity_steps: vec![IdentityStep {
353                name: "boot-id".to_string(),
354                outcome: "failed".to_string(),
355                error: Some("EPERM: Operation not permitted".to_string()),
356            }],
357        })
358        .expect("serializes");
359        assert!(
360            written.contains(r#"{"hook":"run","fired_at":1}"#),
361            "{written}"
362        );
363        let read: Health = serde_json::from_str(&written).expect("deserializes");
364        let handler = read.hooks[1].handler.as_ref().expect("a handler outcome");
365        assert!(handler.timed_out && !handler.succeeded());
366        assert_eq!(read.identity_steps[0].outcome, "failed");
367    }
368}