Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 19 additions & 2 deletions native/guard/src/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<TcpStream> {
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()?;
Expand Down Expand Up @@ -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());
}
}
28 changes: 28 additions & 0 deletions native/guard/src/plan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::*;
Expand Down Expand Up @@ -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");
}
}
115 changes: 108 additions & 7 deletions native/guard/src/run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Builds>, t: Tuning, tm: Times, build: String, mode: Mode, skip: Vec<String>, hist: Vec<Fail>, remote: Vec<u64>, why: String, hub_pid: u32, state: &'static str, stable: bool, last_req: Value, since: u64, probation: Option<String>, low: Vec<String>, space_at: Option<Instant>, swept: Vec<String>, sweep: Option<(Child, Instant)>, down: Vec<String>, down_before: Vec<String>, /** the hub before this start ended badly (a crash, a hang): it tells its clients so (BACKPLANE_PREV_END) */ crashed: bool, _guard_lock: Option<File> }
struct Guard { o: Opts, d: Dir, b: Option<Builds>, t: Tuning, tm: Times, build: String, mode: Mode, skip: Vec<String>, hist: Vec<Fail>, remote: Vec<u64>, why: String, hub_pid: u32, state: &'static str, stable: bool, last_req: Value, since: u64, probation: Option<String>, low: Vec<String>, space_at: Option<Instant>, swept: Vec<String>, sweep: Option<(Child, Instant)>, down: Vec<String>, down_before: Vec<String>, /** 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<File> }

/// 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() }
Expand Down Expand Up @@ -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::<u32>().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() }
Expand Down Expand Up @@ -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
}
Expand All @@ -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();
Expand All @@ -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) => {}
Expand Down Expand Up @@ -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());
Expand Down Expand Up @@ -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));
}
Expand Down Expand Up @@ -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());
Expand All @@ -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);
}
}
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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));
}
}
Loading
Loading