From a92bc930ee2174d41a236753a1ff06d8d6a996c4 Mon Sep 17 00:00:00 2001 From: i2cjak Date: Mon, 23 Nov 2026 16:30:57 -0500 Subject: [PATCH] fix(guard,host): stop rescue alert loop, ghost guard on reinstall, and stale Hub is down banner Fixes #1626 - Track rescue entry across retries via RescueState in native/guard/src/plan.rs so one_run()'s state="starting" transition no longer re-fires "Hub is down" desktop notifications and incidents on every rescue retry; clear "Hub is down" on healthy recovery and reset RescueState on control requests. - Suppress any stale uncleared "Hub is down" incident in native/host/src/guard.rs::notice() while the hub is running, still surfacing any other open incident beneath it. - Keep the guard lock File handle in Guard and verify lock-path ownership via sys::same_file() (inode/dev on Unix, path existence on Windows); exit cleanly (stopping only its own child) if the guard directory/lock was removed or replaced (e.g. reinstall without stopping the old guard). - Escalate orphan hub termination in end_orphan() from SIGTERM -> SIGABRT -> SIGKILL via end_pid() so a wedged process holding the port cannot trap the guard in infinite End::Machine rescue loops. - Try all resolved socket addresses in http::call() instead of only the first address returned by to_socket_addrs(). --- native/guard/src/http.rs | 21 ++++++- native/guard/src/plan.rs | 28 ++++++++++ native/guard/src/run.rs | 115 ++++++++++++++++++++++++++++++++++++--- native/guard/src/sys.rs | 56 ++++++++++++++++++- native/host/src/guard.rs | 15 ++++- 5 files changed, 220 insertions(+), 15 deletions(-) diff --git a/native/guard/src/http.rs b/native/guard/src/http.rs index 1276cc1ae5..caf0cc77b3 100644 --- a/native/guard/src/http.rs +++ b/native/guard/src/http.rs @@ -2,9 +2,19 @@ use sha2::{Digest, Sha256}; use std::{io::{Read, Write}, net::{TcpListener, TcpStream, ToSocketAddrs}, sync::{atomic::{AtomicBool, Ordering::SeqCst}, Arc}, time::Duration}; +fn connect_any(addrs: &[std::net::SocketAddr], timeout: Duration) -> Option { + let deadline = std::time::Instant::now() + timeout; + for a in addrs { + let left = deadline.saturating_duration_since(std::time::Instant::now()); + if left.is_zero() { return None } + if let Ok(s) = TcpStream::connect_timeout(a, left) { return Some(s) } + } + None +} + pub fn call(addr: &str, method: &str, path: &str, token: &str, body: &str, timeout: Duration) -> Option<(u16, String)> { - let a = addr.to_socket_addrs().ok()?.next()?; - let mut s = TcpStream::connect_timeout(&a, timeout).ok()?; + let addrs: Vec<_> = addr.to_socket_addrs().ok()?.collect(); + let mut s = connect_any(&addrs, timeout)?; s.set_read_timeout(Some(timeout)).ok()?; s.set_write_timeout(Some(timeout)).ok()?; let auth = if token.is_empty() { String::new() } else { format!("Authorization: Bearer {token}\r\n") }; s.write_all(format!("{method} {path} HTTP/1.1\r\nHost: {addr}\r\n{auth}Content-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len()).as_bytes()).ok()?; @@ -111,4 +121,11 @@ mod tests { loop { match TcpListener::bind(&a) { Ok(_) => break, Err(e) => { assert!(std::time::Instant::now() < end, "the port is free for the hub again: {e}"); std::thread::sleep(Duration::from_millis(50)) } } } } #[test] fn nothing_listening_is_none_not_a_hang() { assert!(call("127.0.0.1:1", "GET", "/", "", "", Duration::from_millis(200)).is_none()); } + #[test] fn connect_any_falls_through_to_live_address() { + let dead = { let l = TcpListener::bind("127.0.0.1:0").unwrap(); l.local_addr().unwrap() }; + let (a, _s) = start_on_a_free_port(); + let live: std::net::SocketAddr = a.parse().unwrap(); + assert!(connect_any(&[dead, live], Duration::from_secs(5)).is_some()); + assert!(connect_any(&[dead], Duration::from_millis(200)).is_none()); + } } diff --git a/native/guard/src/plan.rs b/native/guard/src/plan.rs index 0ef5b86802..0752382b45 100644 --- a/native/guard/src/plan.rs +++ b/native/guard/src/plan.rs @@ -178,6 +178,22 @@ impl SleepClock { pub fn waking(&self, awake_s: u64) -> bool { self.woke.map_or(false, |w| awake_s.saturating_sub(w) < WAKE_GRACE_S) } } +/// Tracks whether the guard is currently in rescue mode so automatic retry loops alert once on entry, +/// never re-alert on each retry (even though `one_run` transitions `state` through `"starting"`), and +/// reset only on hub recovery or an explicit control request. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct RescueState { pub active: bool } +impl RescueState { + /// Enter or stay in rescue. Returns `true` only on the first entry (when an alert should fire). + pub fn enter(&mut self) -> bool { + if self.active { return false } + self.active = true; + true + } + /// Leave rescue (hub came up healthy, or a control request reset the plan). Returns `true` if previously in rescue. + pub fn leave(&mut self) -> bool { std::mem::replace(&mut self.active, false) } +} + #[cfg(test)] mod tests { use super::*; @@ -353,4 +369,16 @@ mod tests { assert!(proven(true, &json!({"status": "ok", "folding": 0}), false, 60, 60)); assert!(!proven(true, &json!({"status": "ok", "folding": 0}), true, 120, 60)); } + + #[test] + fn rescue_alerts_once_across_retries_until_recovery_or_reset() { + let mut r = RescueState::default(); + assert!(!r.leave(), "not in rescue yet"); + assert!(r.enter(), "first entry into rescue fires an alert"); + assert!(!r.enter(), "subsequent automatic retries stay silent"); + assert!(!r.enter(), "even across multiple retries"); + assert!(r.leave(), "hub recovered or control request cleared rescue"); + assert!(!r.leave(), "already left"); + assert!(r.enter(), "a later rescue episode alerts again"); + } } diff --git a/native/guard/src/run.rs b/native/guard/src/run.rs index 010f17b90b..95bcce157d 100644 --- a/native/guard/src/run.rs +++ b/native/guard/src/run.rs @@ -11,13 +11,41 @@ pub struct Opts { pub home: PathBuf, pub port: u16, pub host: String, pub builds struct Times { probe: u64, misses: u32, stable: u64, stall: u64, boot: u64, floor: u64, warn: u64 } fn env(n: &str, d: u64) -> u64 { std::env::var(n).ok().and_then(|v| v.parse().ok()).unwrap_or(d) } -struct Guard { o: Opts, d: Dir, b: Option, t: Tuning, tm: Times, build: String, mode: Mode, skip: Vec, hist: Vec, remote: Vec, why: String, hub_pid: u32, state: &'static str, stable: bool, last_req: Value, since: u64, probation: Option, low: Vec, space_at: Option, swept: Vec, sweep: Option<(Child, Instant)>, down: Vec, down_before: Vec, /** the hub before this start ended badly (a crash, a hang): it tells its clients so (BACKPLANE_PREV_END) */ crashed: bool, _guard_lock: Option } +struct Guard { o: Opts, d: Dir, b: Option, t: Tuning, tm: Times, build: String, mode: Mode, skip: Vec, hist: Vec, remote: Vec, why: String, hub_pid: u32, state: &'static str, stable: bool, last_req: Value, since: u64, probation: Option, low: Vec, space_at: Option, swept: Vec, sweep: Option<(Child, Instant)>, down: Vec, down_before: Vec, /** the hub before this start ended badly (a crash, a hang): it tells its clients so (BACKPLANE_PREV_END) */ crashed: bool, lock: File, rescue_state: plan::RescueState, _guard_lock: Option } /// What a request changed. enum Move { Nothing, Restart, Exit } pub fn say(line: &str) { eprintln!("guard: {line}"); } +fn wait_dead(pid: u32, wait: Duration) -> bool { + let end = Instant::now() + wait; + loop { + if !sys::alive(pid) { return true } + if Instant::now() >= end { return false } + std::thread::sleep(Duration::from_millis(50)); + } +} + +fn end_pid(pid: u32, term_wait: Duration, abort_wait: Duration, kill_wait: Duration) -> bool { + if pid <= 1 || pid == std::process::id() { return false } + if pid > i32::MAX as u32 { return false } + sys::term(pid); + if wait_dead(pid, term_wait) { return true } + sys::abort(pid); + if wait_dead(pid, abort_wait) { return true } + sys::kill(pid); + wait_dead(pid, kill_wait) +} + +fn clear_down_alert(rescue_state: &mut plan::RescueState, d: &Dir, build: &str) -> bool { + if rescue_state.leave() || d.open_alert("Hub is down") { + d.clear("Hub is back", &format!("running {}", Guard::short(build)), "Hub is down", build); + return true; + } + false +} + impl Guard { fn dir_of(&self, id: &str) -> PathBuf { match &self.b { Some(b) => b.dir(id), None => PathBuf::from(id) } } fn exists(&self, id: &str) -> bool { sys::hub_exe(&self.dir_of(id)).exists() } @@ -143,15 +171,25 @@ impl Guard { OpenOptions::new().create(true).append(true).open(l).map_or(Stdio::null(), Stdio::from) } + fn owns_lock(&self) -> bool { sys::same_file(&self.lock, &self.d.path("lock")) } + + fn quit_replaced(&mut self, c: Option<&mut Child>) -> ! { + say("guard lock was removed or replaced; stopping"); + if let Some(c) = c { sys::stop_child(c, 10_000); } + std::process::exit(0) + } + /// A hub of this home still holding hub.lock while this guard holds the guard lock is an orphan: its guard was killed. The pid comes from the lock it holds. fn end_orphan(&self) { + if !self.owns_lock() { return } let lock = self.o.home.join("hub.lock"); let Ok(f) = File::open(&lock) else { return }; if f.try_lock().is_ok() { let _ = f.unlock(); return } let Some(pid) = fs::read_to_string(&lock).ok().and_then(|s| s.split_whitespace().next().and_then(|p| p.parse::().ok())) else { return }; say(&format!("a hub (pid {pid}) from before this guard still holds {}: ending it", self.o.home.display())); - sys::term(pid); for _ in 0..100 { if !sys::alive(pid) { return } std::thread::sleep(Duration::from_millis(100)); } - sys::abort(pid); std::thread::sleep(Duration::from_millis(500)); + if !end_pid(pid, Duration::from_secs(10), Duration::from_secs(3), Duration::from_secs(2)) { + say(&format!("orphan hub (pid {pid}) did not exit")); + } } fn port_free(&self) -> bool { std::net::TcpListener::bind(self.addr()).is_ok() } @@ -223,7 +261,7 @@ impl Guard { self.probation = Some(self.build.clone()); self.down_before = self.down.clone(); self.set_aside_checkpoints(); self.build = b; self.mode = Mode::Normal; self.answer(&id, true, "updating"); } } - self.hist.clear(); self.why.clear(); + self.hist.clear(); self.why.clear(); self.rescue_state.leave(); std::thread::sleep(Duration::from_millis(600)); // the hub's route is reading the answer Move::Restart } @@ -243,6 +281,7 @@ impl Guard { /// Start the hub and stay with it until it ends. fn one_run(&mut self) -> End { + if !self.owns_lock() { self.quit_replaced(None) } self.stable = false; self.hub_pid = 0; self.set("starting"); let mut child = match self.spawn() { Ok(c) => c, Err(e) => return e }; self.hub_pid = child.id(); self.pin(); self.publish(); @@ -255,6 +294,7 @@ impl Guard { loop { if clock.tick(std::time::SystemTime::now(), sys::awake_s()) { misses = 0; say("the machine slept; health checks start counting again"); } if sys::stop_asked() { self.quit(Some(&mut child)) } + if !self.owns_lock() { self.quit_replaced(Some(&mut child)) } match child.try_wait() { Ok(Some(s)) => { self.hub_pid = 0; return self.classify(s) } Ok(None) => {} @@ -286,7 +326,13 @@ impl Guard { let why = self.wrong_build(&said).unwrap_or_default(); say(&format!("{} is not the build it was staged as: {why}; ending it", Self::short(&self.build))); sys::stop_child(&mut child, 10_000); self.hub_pid = 0; return End::Failed(why) } - None if well => { ready_at = Some(sys::awake_s()); say(&format!("{} answers, {} ms after its start", Self::short(&self.build), t0.elapsed().as_millis())); self.set(if self.mode == Mode::Safe { "safe" } else { "running" }); if control && !self.has_control(&self.build) { let mut c = self.d.lines("control"); c.push(self.build.clone()); let from = c.len().saturating_sub(32); let _ = self.d.put("control", &(c[from..].join("\n") + "\n")); } } + None if well => { + ready_at = Some(sys::awake_s()); + say(&format!("{} answers, {} ms after its start", Self::short(&self.build), t0.elapsed().as_millis())); + self.set(if self.mode == Mode::Safe { "safe" } else { "running" }); + clear_down_alert(&mut self.rescue_state, &self.d, &self.build); + if control && !self.has_control(&self.build) { let mut c = self.d.lines("control"); c.push(self.build.clone()); let from = c.len().saturating_sub(32); let _ = self.d.put("control", &(c[from..].join("\n") + "\n")); } + } None => { let now_awake = sys::awake_s(); let m = fs::metadata(self.d.path("phase")).ok().and_then(|m| m.modified().ok()); @@ -333,6 +379,7 @@ impl Guard { let t = Instant::now(); while t.elapsed().as_secs() < secs { if sys::stop_asked() { self.quit(None) } + if !self.owns_lock() { self.quit_replaced(None) } if let Some(r) = self.d.take_request() { match self.request(r) { Move::Restart => return true, Move::Exit => self.quit(None), Move::Nothing => {} } } std::thread::sleep(Duration::from_millis(200)); } @@ -364,6 +411,7 @@ impl Guard { loop { let end = self.one_run(); if sys::stop_asked() { self.quit(None) } + if !self.owns_lock() { self.quit_replaced(None) } self.crashed = matches!(end, End::Failed(_)); self.fold_failure(&end); let (good, bad) = (self.d.good(), self.bad()); @@ -386,7 +434,9 @@ impl Guard { self.set_aside_checkpoints(); self.build = build; self.mode = Mode::Safe; } Next::Rescue { after, why } => { - if self.state != "rescue" { self.alert("Hub is down", &why, "answering on its port for a restart, and trying again by itself"); } + if self.rescue_state.enter() { + self.alert("Hub is down", &why, "answering on its port for a restart, and trying again by itself"); + } self.rescue(after, &why); } } @@ -480,7 +530,8 @@ pub fn run(o: Opts) -> i32 { let t = Tuning { tries: env("BACKPLANE_GUARD_TRIES", 3) as usize, window: env("BACKPLANE_GUARD_WINDOW", 600), pause: env("BACKPLANE_GUARD_PAUSE", 1), machine_pause: env("BACKPLANE_GUARD_MACHINE_PAUSE", 5), rescue_retry: env("BACKPLANE_GUARD_RESCUE_RETRY", 120) }; let tm = Times { probe: env("BACKPLANE_GUARD_PROBE", 5), misses: env("BACKPLANE_GUARD_MISSES", 6) as u32, stable: env("BACKPLANE_GUARD_STABLE", 60), stall: env("BACKPLANE_GUARD_STALL", 300), boot: env("BACKPLANE_GUARD_BOOT", 900), floor: env("BACKPLANE_GUARD_MIN_FREE", 1 << 30), warn: env("BACKPLANE_DISK_WARN_GB", 75).saturating_mul(1_000_000_000) }; let mode = if o.safe { Mode::Safe } else { Mode::Normal }; - let mut g = Guard { d, b, t, tm, build, mode, skip: vec![], hist: vec![], remote: vec![], why: String::new(), hub_pid: 0, state: "starting", stable: false, last_req: Value::Null, since: now(), probation: None, low: vec![], space_at: None, swept: vec![], sweep: None, down: vec![], down_before: vec![], crashed: false, _guard_lock, o }; + let rescue_state = plan::RescueState { active: d.open_alert("Hub is down") }; + let mut g = Guard { d, b, t, tm, build, mode, skip: vec![], hist: vec![], remote: vec![], why: String::new(), hub_pid: 0, state: "starting", stable: false, last_req: Value::Null, since: now(), probation: None, low: vec![], space_at: None, swept: vec![], sweep: None, down: vec![], down_before: vec![], crashed: false, lock, rescue_state, _guard_lock, o }; // a build already marked bad is not started: the newest one that is not if bad.contains(&g.build) { if let Some(to) = g.rollback_to() { say(&format!("{} is marked bad: starting {to}", g.build)); g.build = to; } } g.pin(); g.go() @@ -520,4 +571,54 @@ mod tests { d.put("peers.json", r#"{"peers":[]}"#).unwrap(); let ts2 = now() + 1; let sig2 = format!("sha256={}", http::hmac(&[0xab, 0xcd], format!("{ts2}.{body}").as_bytes())); assert!(!allowed(&h, &d, &req("/hub/control", "POST", hs(sig2, ts2), body), &seen), "a link that is no longer the owner's"); } + #[test] fn lock_ownership_detects_removed_or_replaced_lock_file() { + let (_h, d) = home("lock-own"); + let p = d.path("lock"); + let lock = OpenOptions::new().create(true).write(true).truncate(false).open(&p).unwrap(); + lock.try_lock().unwrap(); + assert!(sys::same_file(&lock, &p)); + let aside = d.path("lock.old"); + fs::rename(&p, &aside).unwrap(); + assert!(!sys::same_file(&lock, &p), "missing lock path is no longer owned"); + let replacement = OpenOptions::new().create(true).write(true).truncate(false).open(&p).unwrap(); + drop(replacement); + assert!(!sys::same_file(&lock, &p), "recreated lock path is a different file"); + } + #[test] fn rescue_recovery_clears_open_hub_is_down_incident() { + let (_h, d) = home("rescue-clear"); + d.incident("Hub is down", "port held", "answering on its port for a restart, and trying again by itself", "v0.16.4"); + assert!(d.open_alert("Hub is down")); + let mut rescue = plan::RescueState { active: d.open_alert("Hub is down") }; + assert!(!rescue.enter(), "restarted guard sees open rescue alert and stays silent on retries"); + assert!(clear_down_alert(&mut rescue, &d, "v0.16.4")); + assert!(!rescue.active); + assert!(!d.open_alert("Hub is down")); + assert!(!clear_down_alert(&mut rescue, &d, "v0.16.4"), "second recovery call does not write a duplicate clear"); + } + #[cfg(unix)] #[test] fn end_pid_escalates_to_sigkill_when_term_and_abort_are_ignored() { + for bad in [0, 1, std::process::id(), (i32::MAX as u32) + 1, u32::MAX] { + assert!(!end_pid(bad, Duration::from_millis(10), Duration::from_millis(10), Duration::from_millis(10)), "must refuse pid {bad}"); + } + let dir = crate::tmp::dir("end-pid"); + let marker = dir.join("ready"); + let mut child = Command::new("sh") + .args(["-c", r#"trap '' TERM ABRT; printf ready > "$1"; exec sleep 30"#, "sh"]) + .arg(&marker) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .unwrap(); + let deadline = Instant::now() + Duration::from_secs(2); + while !marker.exists() { + assert!(Instant::now() < deadline, "child never armed signal traps"); + std::thread::sleep(Duration::from_millis(10)); + } + let pid = child.id(); + let reaper = std::thread::spawn(move || child.wait().unwrap()); + let dead = end_pid(pid, Duration::from_millis(150), Duration::from_millis(150), Duration::from_secs(2)); + let status = reaper.join().unwrap(); + assert!(dead, "end_pid must finish once SIGKILL reaps the child"); + assert_eq!(sys::signal_of(&status), Some(libc::SIGKILL)); + } } diff --git a/native/guard/src/sys.rs b/native/guard/src/sys.rs index f1d111d8a6..555f004c6f 100644 --- a/native/guard/src/sys.rs +++ b/native/guard/src/sys.rs @@ -19,11 +19,30 @@ use std::{path::Path, process::{Child, Command, ExitStatus}}; } } } - pub fn signal(pid: u32, sig: i32) { unsafe { libc::kill(pid as i32, sig); } } + pub fn signal(pid: u32, sig: i32) { + if pid > 1 && pid <= i32::MAX as u32 { + unsafe { libc::kill(pid as i32, sig); } + } + } pub fn term(pid: u32) { signal(pid, libc::SIGTERM) } /// SIGABRT: a hung hub leaves a core if the machine keeps them, then dies pub fn abort(pid: u32) { signal(pid, libc::SIGABRT) } - pub fn alive(pid: u32) -> bool { pid != 0 && (unsafe { libc::kill(pid as i32, 0) } == 0 || std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)) } + pub fn kill(pid: u32) { signal(pid, libc::SIGKILL) } + /// Whether `path` still names the same file inode as the open handle `held` (false if unlinked or replaced, e.g. after a reinstall). + pub fn same_file(held: &std::fs::File, path: &std::path::Path) -> bool { + use std::os::unix::fs::MetadataExt; + let Ok(a) = held.metadata() else { return true }; + match std::fs::metadata(path) { + Ok(b) => a.dev() == b.dev() && a.ino() == b.ino(), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => false, + Err(_) => true, + } + } + pub fn alive(pid: u32) -> bool { + pid > 0 && pid <= i32::MAX as u32 + && (unsafe { libc::kill(pid as i32, 0) } == 0 + || std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)) + } /// (free to this user, total) of the filesystem holding `p` pub fn space(p: &std::path::Path) -> Option<(u64, u64)> { use std::os::unix::ffi::OsStrExt; @@ -45,9 +64,40 @@ use std::{path::Path, process::{Child, Command, ExitStatus}}; pub fn stop_asked() -> bool { false } pub fn term(pid: u32) { let _ = quiet("taskkill").args(["/PID", &pid.to_string()]).output(); } pub fn abort(pid: u32) { let _ = quiet("taskkill").args(["/F", "/PID", &pid.to_string()]).output(); } + pub fn kill(pid: u32) { abort(pid) } + #[repr(C)] + struct FileTime { low: u32, high: u32 } + #[repr(C)] + struct ByHandleFileInformation { + attrs: u32, + creation: FileTime, + last_access: FileTime, + last_write: FileTime, + volume_serial: u32, + size_high: u32, + size_low: u32, + links: u32, + index_high: u32, + index_low: u32, + } + fn file_id(f: &std::fs::File) -> Option<(u32, u32, u32)> { + use std::os::windows::io::AsRawHandle; + let mut info: ByHandleFileInformation = unsafe { std::mem::zeroed() }; + (unsafe { GetFileInformationByHandle(f.as_raw_handle() as *mut core::ffi::c_void, &mut info) } != 0) + .then_some((info.volume_serial, info.index_high, info.index_low)) + } + pub fn same_file(held: &std::fs::File, path: &std::path::Path) -> bool { + let Some(a) = file_id(held) else { return true }; + match std::fs::File::open(path) { + Ok(other) => file_id(&other).map_or(true, |b| a == b), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => false, + Err(_) => true, + } + } pub fn alive(pid: u32) -> bool { quiet("tasklist").args(["/FI", &format!("PID eq {pid}"), "/NH"]).output().map_or(false, |o| String::from_utf8_lossy(&o.stdout).contains(&pid.to_string())) } #[link(name = "kernel32")] extern "system" { fn GetDiskFreeSpaceExW(dir: *const u16, free: *mut u64, total: *mut u64, all: *mut u64) -> i32; + fn GetFileInformationByHandle(handle: *mut core::ffi::c_void, info: *mut ByHandleFileInformation) -> i32; fn QueryUnbiasedInterruptTime(unbiased_time: *mut u64) -> i32; } /// Monotonic awake seconds since first call (`QueryUnbiasedInterruptTime` excludes standby/hibernation). @@ -69,7 +119,7 @@ use std::{path::Path, process::{Child, Command, ExitStatus}}; fn quiet(name: &str) -> std::process::Command { use std::os::windows::process::CommandExt; let mut c = std::process::Command::new(name); c.creation_flags(NO_WINDOW); c } pub fn signal_of(_: &std::process::ExitStatus) -> Option { None } } -pub use os::{abort, alive, awake_s, clean_signals, detach, signal_of, space, stop_asked, term, watch_stop}; +pub use os::{abort, alive, awake_s, clean_signals, detach, kill, same_file, signal_of, space, stop_asked, term, watch_stop}; pub fn free_bytes(p: &Path) -> Option { space(p).map(|s| s.0) } /// The hub program in a build folder. diff --git a/native/host/src/guard.rs b/native/host/src/guard.rs index f01bcc3275..b6dc879308 100644 --- a/native/host/src/guard.rs +++ b/native/host/src/guard.rs @@ -178,8 +178,9 @@ pub fn last_why(home: &Path) -> String { format!("{}: {}", last["what"].as_str().unwrap_or(""), last["did"].as_str().unwrap_or("")) } /// The newest incident still open: a record that `clears` an alert (the guard's "Disk has room again") closes it, and is no news itself. -fn open_incident(s: &Value) -> Value { - let mut cleared: Vec<&str> = vec![]; +fn open_incident(s: &Value) -> Value { open_incident_for(s, &[]) } +fn open_incident_for(s: &Value, skip: &[&str]) -> Value { + let mut cleared: Vec<&str> = skip.to_vec(); for i in s["incidents"].as_array().map(|a| a.as_slice()).unwrap_or(&[]).iter().rev() { if let Some(c) = i["clears"].as_str() { cleared.push(c); continue } if cleared.contains(&i["what"].as_str().unwrap_or("")) { continue } @@ -190,7 +191,7 @@ fn open_incident(s: &Value) -> Value { /// What a client shows about the hub, and when: `text` empty means all is well. pub fn notice(s: &Value) -> Value { let safe = s["hub"]["safe"] == true; let degraded = s["hub"]["degraded"].as_array().map_or(0, Vec::len) > 0; - let last = open_incident(s); + let last = open_incident_for(s, &["Hub is down"]); let fresh = last["at"].as_u64().map_or(false, |at| now_s().saturating_sub(at) < 3600); let text = if safe { format!("Safe mode: agents, routines and bots are paused. {}", last["why"].as_str().unwrap_or("")) } else if degraded { format!("Hub is running without {}.", s["hub"]["degraded"].as_array().map_or(String::new(), |a| a.iter().filter_map(Value::as_str).collect::>().join(", "))) } @@ -365,4 +366,12 @@ mod tests { assert!(with(vec![crash.clone(), full.clone(), room.clone()]).starts_with("Hub crashed"), "an earlier incident it did not clear still shows"); assert!(with(vec![full.clone(), room, full]).starts_with("Disk nearly full"), "full again: told again"); } + #[test] fn a_running_hub_never_shows_a_stale_hub_is_down_notice() { + let down = json!({"at": now_s() - 30, "what": "Hub is down", "why": "port held", "did": "answering on its port for a restart, and trying again by itself"}); + let full = json!({"at": now_s() - 60, "what": "Disk nearly full", "why": "7.1 GB free", "did": "free space on this disk"}); + let calm = json!({"hub": {"safe": false, "degraded": []}, "guard": {}}); + let with = |i: Vec| { let mut c = calm.clone(); c["incidents"] = json!(i); notice(&c)["text"].as_str().unwrap().to_string() }; + assert_eq!(with(vec![down.clone()]), "", "an uncleared Hub is down incident is suppressed while the hub is running"); + assert!(with(vec![full, down]).starts_with("Disk nearly full"), "an earlier open incident underneath still shows"); + } }