diff --git a/crates/rhema-claw/src/abort.rs b/crates/rhema-claw/src/abort.rs index 6de1b71..6112dc3 100644 --- a/crates/rhema-claw/src/abort.rs +++ b/crates/rhema-claw/src/abort.rs @@ -57,6 +57,25 @@ impl AbortRegistry { } } + /// Cuts every live dispatch, `n` of them: what the daemon's shutdown + /// does so each running turn ends the way the abort route ends it — + /// dangling calls closed, session written back, released — instead + /// of vanishing with the process. The count is the listeners that + /// took the signal. + pub fn signal_all(&self) -> usize { + let senders: Vec> = self + .live + .lock() + .unwrap_or_else(PoisonError::into_inner) + .values() + .cloned() + .collect(); + senders + .iter() + .filter(|sender| sender.try_send(()).is_ok()) + .count() + } + /// Arms a listener for `key`. The guard is the dispatch's side: hold /// it across the whole dispatch chain, drop it to unregister. pub fn listen(self: &Arc, key: &str) -> AbortGuard { @@ -165,6 +184,22 @@ mod tests { assert!(!registry.signal("job:rhema#7"), "the entry is gone"); } + #[test] + fn signal_all_cuts_every_live_dispatch() { + let registry = Arc::new(AbortRegistry::new()); + let mut interactive = registry.listen("interactive:web"); + let mut forge = registry.listen("github:issue:acme/widgets#7"); + + assert_eq!(registry.signal_all(), 2); + assert!(interactive.take(), "the chat turn is cut"); + assert!(forge.take(), "the forge turn is cut too"); + + // With nothing live the count is zero, not an error. + drop(interactive); + drop(forge); + assert_eq!(registry.signal_all(), 0); + } + #[test] fn keys_abort_independently() { let registry = Arc::new(AbortRegistry::new()); diff --git a/crates/rhema-claw/src/daemon.rs b/crates/rhema-claw/src/daemon.rs index be8eb04..45ebb98 100644 --- a/crates/rhema-claw/src/daemon.rs +++ b/crates/rhema-claw/src/daemon.rs @@ -760,9 +760,16 @@ impl Daemon { /// The resident loop: the HTTP surface comes up first (a resident is /// talked to), then detect, hand the long lanes to their own tasks, - /// sleep, until ctrl-c. A failed pass is logged, not fatal — a forge - /// outage or a dead backend must not end a daemon whose next pass may - /// simply succeed. + /// sleep, until a shutdown signal. A failed pass is logged, not + /// fatal — a forge outage or a dead backend must not end a daemon + /// whose next pass may simply succeed. + /// + /// Shutting down is graceful because the alternative is losing a + /// turn to the kernel: the daemon is PID 1 in its container, and a + /// signal it has no handler for is dropped, so the kubelet waits out + /// the grace period and SIGKILLs the process wherever its turn + /// happens to be. [`shutdown_signal`] watches SIGTERM, the signal a + /// rollout and a `kubectl delete` send, alongside ctrl-c. pub async fn run(&self) -> Result<(), ClawError> { self.bootstrap().await?; let listener = tokio::net::TcpListener::bind(&self.listen).await?; @@ -774,18 +781,113 @@ impl Daemon { } }); eprintln!("[claw] http listening on {addr}"); + let mut shutdown = std::pin::pin!(shutdown_signal()); loop { - if let Err(err) = self.resident_tick().await { - eprintln!("[claw] warning: pass failed: {err}"); - } - tokio::select! { - () = tokio::time::sleep(self.poll_interval) => {} - _ = tokio::signal::ctrl_c() => { - server.abort(); - return Ok(()); + // The pass is a future the loop keeps across the signal + // rather than await it bare: a rollout lands mid-turn more + // often than between turns, and dropping the future there + // would be the SIGKILL this exists to avoid. + let mut pass = std::pin::pin!(self.resident_tick()); + let stopping = tokio::select! { + result = &mut pass => { + if let Err(err) = result { + eprintln!("[claw] warning: pass failed: {err}"); + } + false } + () = &mut shutdown => { + let deadline = self.start_shutdown(); + if tokio::time::timeout_at(deadline, &mut pass).await.is_err() { + eprintln!( + "[claw] shutdown: the interactive pass did not return in {SHUTDOWN_DRAIN:?}" + ); + } + self.await_off_tick_passes(deadline).await; + true + } + }; + if stopping { + break; + } + let stopping = tokio::select! { + () = tokio::time::sleep(self.poll_interval) => false, + () = &mut shutdown => { + let deadline = self.start_shutdown(); + self.await_off_tick_passes(deadline).await; + true + } + }; + if stopping { + break; } } + server.abort(); + Ok(()) + } + + /// Opens a shutdown: logs it, cuts every live turn, and answers the + /// deadline the drain shares. All three handlers listen on the abort + /// registry, so each running turn ends the way the abort route ends + /// it — dangling calls closed, session written back, released — + /// instead of dying wherever it was. + fn start_shutdown(&self) -> tokio::time::Instant { + eprintln!("[claw] shutting down"); + let cut = self.http.aborts().signal_all(); + if cut > 0 { + eprintln!("[claw] shutdown: cutting {cut} live turn(s)"); + } + tokio::time::Instant::now() + SHUTDOWN_DRAIN + } + + /// Waits for the lanes that run off the tick, up to `deadline`. Their + /// passes are tasks this loop spawned, so cutting a turn only asks + /// its task to end; the release that writes the session back lands a + /// moment later. + async fn await_off_tick_passes(&self, deadline: tokio::time::Instant) { + while self.forge_pass_busy.load(Ordering::Acquire) + || self.jobs_pass_busy.load(Ordering::Acquire) + { + if tokio::time::Instant::now() >= deadline { + eprintln!("[claw] shutdown: a forge or jobs pass is still running"); + return; + } + tokio::time::sleep(Duration::from_millis(50)).await; + } + } +} + +/// How long a shutdown waits for the work it cut to return: a cut turn +/// closes its dangling calls and writes its session back in well under a +/// second, and a hung one must not hold the process past the pod's grace +/// period. +const SHUTDOWN_DRAIN: Duration = Duration::from_secs(10); + +/// Resolves on the first shutdown signal: SIGTERM, which is what a +/// rollout and a `kubectl delete` send, or SIGINT from a shell. Watching +/// only ctrl-c meant the daemon never saw a rollout coming, and the +/// kubelet SIGKILLed it once the grace period ran out. +async fn shutdown_signal() { + #[cfg(unix)] + { + use tokio::signal::unix::{SignalKind, signal}; + match signal(SignalKind::terminate()) { + Ok(mut terminate) => { + tokio::select! { + _ = terminate.recv() => {} + _ = tokio::signal::ctrl_c() => {} + } + } + Err(err) => { + // Without the stream a rollout ends at the grace period + // instead of here; ctrl-c still works. + eprintln!("[claw] warning: cannot watch SIGTERM: {err}"); + let _ = tokio::signal::ctrl_c().await; + } + } + } + #[cfg(not(unix))] + { + let _ = tokio::signal::ctrl_c().await; } }