Skip to main content

gunnar_server/
stop_record.rs

1//! **The last stop, kept where it survives the stop** (2026-10-01, the real test2 run 9:
2//! vm1 stopped cleanly, but its power-off steps were lost — the narration and the disk log
3//! die with the read-only remount of /data — and UpCloud reported `stopped` 46 s after the
4//! soft stop, so nobody could tell the guest's power-off from the provider's reporting).
5//! After the quiesce and just before the power goes, ONE line is written on the ESP (its
6//! own filesystem, flipped read-write for that write); the next boot says it at INFO and
7//! removes it.
8
9/// Where the record lives on the ESP.
10pub const RECORD: &str = "/boot/gunnar-last-stop.txt";
11
12/// The words the next boot says the record in — what the installer's kit looks for.
13pub const SAID: &str = "the previous stop (kept on the ESP):";
14
15/// **The record**: `power_off_epoch_ms=<ms> <the stop's line>` — one line, no newline in it.
16pub fn render(power_off_epoch_ms: u128, line: &str) -> String {
17    format!("power_off_epoch_ms={power_off_epoch_ms} {}\n", line.replace('\n', " "))
18}
19
20/// The power-off time out of a record (or out of the line the next boot said it in).
21pub fn power_off_epoch_ms(text: &str) -> Option<u128> {
22    text.split("power_off_epoch_ms=").nth(1)?.split_whitespace().next()?.parse().ok()
23}
24
25/// Write the record for a stop said as `line`, stamped now — the last write before the power.
26pub fn keep(line: &str) -> bool {
27    let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis()).unwrap_or(0);
28    crate::narrate::write_esp_file(std::path::Path::new(RECORD), render(now, line).as_bytes())
29}
30
31/// At boot: say the previous stop's record (if any) at INFO, then remove it.
32pub fn say_previous() {
33    let path = std::path::Path::new(RECORD);
34    if let Ok(text) = std::fs::read_to_string(path) {
35        tracing::info!("{SAID} {}", text.trim());
36        crate::narrate::remove_esp_file(path);
37    }
38}
39
40#[cfg(test)]
41mod tests {
42    use super::*;
43
44    /// One line, the power-off time first and readable back, the stop's own words after it.
45    #[test]
46    fn a_stop_record_is_one_line_whose_power_off_time_reads_back() {
47        let r = render(1_790_850_910_705, "front: stopped cleanly on ACPI power button — power-off: sync(2) done in 3 ms; 2 writer(s) released;\n/data remounted read-only in 41 ms");
48        assert_eq!(r.matches('\n').count(), 1, "{r}");
49        assert!(r.starts_with("power_off_epoch_ms=1790850910705 front: stopped cleanly"), "{r}");
50        assert_eq!(power_off_epoch_ms(&r), Some(1_790_850_910_705));
51        assert_eq!(power_off_epoch_ms(&format!("INFO {SAID} {r}")), Some(1_790_850_910_705), "read back out of the next boot's line too");
52    }
53}