diff --git a/crates/bot/src/main.rs b/crates/bot/src/main.rs index e0425530..5be0bfbb 100644 --- a/crates/bot/src/main.rs +++ b/crates/bot/src/main.rs @@ -240,10 +240,22 @@ async fn async_main() -> Result<()> { jmodguard::resources::set_build_commit(option_env!("JMODGUARD_BUILD_SHA")); jmodguard::resources::process_started_at_ms(); + if offline_cache { + jmodguard_bot::startup::observe_shared_config(cfg).await?; + tracing::info!("bot process stopped"); + return Ok(()); + } + + let launcher_refusal = jmodguard::launcher_child::refusal_message(); + if launcher_refusal.is_some() { + // A launcher can stop the held bot as soon as health or refusal is visible. + jmodguard::arm_shutdown_listener(); + } + // Liveness must accept before database retry. Platform probes hit this // port while `open_with_until_ready` waits on a waking database or a // local SQLite lock. - if !offline_cache && let Some(bind) = cfg.health_bind() { + if let Some(bind) = cfg.health_bind() { let listener = jmodguard_bot::health::bind(&bind).await?; tokio::spawn(async move { if let Err(error) = jmodguard_bot::health::serve_listener_as(listener, "bot").await { @@ -252,13 +264,7 @@ async fn async_main() -> Result<()> { }); } - if offline_cache { - jmodguard_bot::startup::observe_shared_config(cfg).await?; - tracing::info!("bot process stopped"); - return Ok(()); - } - - if let Some(message) = jmodguard::launcher_child::refusal_message() { + if let Some(message) = launcher_refusal { tracing::error!("{message}"); idle_until_shutdown().await; return Ok(()); diff --git a/crates/runtime/src/lib.rs b/crates/runtime/src/lib.rs index 160869a0..d7e8ca80 100644 --- a/crates/runtime/src/lib.rs +++ b/crates/runtime/src/lib.rs @@ -113,12 +113,30 @@ fn shutdown_latch() -> &'static ShutdownLatch { LATCH.get_or_init(ShutdownLatch::new) } -fn arm_shutdown_listener() { +/// Starts the shared listener on the current Tokio runtime. On Unix, register +/// SIGTERM before returning so it can arrive before the listener task runs. +pub fn arm_shutdown_listener() { static ARMED: std::sync::Once = std::sync::Once::new(); ARMED.call_once(|| { let latch = shutdown_latch(); + #[cfg(unix)] + let sigterm = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()); tokio::spawn(async move { - wait_for_os_shutdown().await; + #[cfg(unix)] + match sigterm { + Ok(mut sigterm) => tokio::select! { + _ = sigterm.recv() => {} + _ = wait_for_ctrl_c() => {} + }, + Err(error) => { + tracing::error!( + "failed to install SIGTERM handler: {error}; waiting for Ctrl+C" + ); + wait_for_ctrl_c().await; + } + } + #[cfg(not(unix))] + wait_for_ctrl_c().await; tracing::info!("stop signal arrived ({})", shutdown_context()); if let Ok(mut slot) = SIGNAL_AT.lock() { *slot = Some(Instant::now()); @@ -128,34 +146,8 @@ fn arm_shutdown_listener() { }); } -async fn wait_for_os_shutdown() { - let ctrl_c = tokio::signal::ctrl_c(); - #[cfg(unix)] - { - let mut sigterm = - match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) { - Ok(signal) => signal, - Err(error) => { - tracing::error!( - "failed to install SIGTERM handler: {error}; waiting for Ctrl+C" - ); - if let Err(error) = ctrl_c.await { - tracing::error!("ctrl_c handler failed: {error}"); - } - return; - } - }; - tokio::select! { - result = ctrl_c => { - if let Err(error) = result { - tracing::error!("ctrl_c handler failed: {error}"); - } - } - _ = sigterm.recv() => {} - } - } - #[cfg(not(unix))] - if let Err(error) = ctrl_c.await { +async fn wait_for_ctrl_c() { + if let Err(error) = tokio::signal::ctrl_c().await { tracing::error!("ctrl_c handler failed: {error}"); } } @@ -163,7 +155,7 @@ async fn wait_for_os_shutdown() { /// Completes when the process should stop (Ctrl+C or SIGTERM). /// /// Magic Containers sends SIGTERM on restart/redeploy. The first waiter -/// arms the OS handler; later waiters share the same latch so a signal +/// arms the OS handler if needed; later waiters share the same latch so a signal /// during remote database retry still stops the Discord gateway and API /// listener after that work unwinds. pub async fn shutdown_signal() { diff --git a/crates/runtime/tests/shutdown.rs b/crates/runtime/tests/shutdown.rs new file mode 100644 index 00000000..d838b99f --- /dev/null +++ b/crates/runtime/tests/shutdown.rs @@ -0,0 +1,20 @@ +#![cfg(unix)] + +use std::process::Command; +use std::time::Duration; + +#[tokio::test(flavor = "current_thread")] +async fn sigterm_is_captured_before_the_listener_task_runs() { + jmodguard_runtime::arm_shutdown_listener(); + // No await on this thread until after the signal. The listener task can + // only start receiving once SIGTERM has already been sent. + let status = Command::new("kill") + .arg("-TERM") + .arg(std::process::id().to_string()) + .status() + .unwrap(); + assert!(status.success()); + tokio::time::timeout(Duration::from_secs(5), jmodguard_runtime::shutdown_signal()) + .await + .expect("the first waiter must observe the signal sent after arming"); +} diff --git a/src/lib.rs b/src/lib.rs index 99190793..1748537d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -18,6 +18,7 @@ pub mod evidence_transfer; pub mod launcher_child; pub mod launcher_link; pub mod read_link; +pub use jmodguard_runtime::arm_shutdown_listener; pub use jmodguard_runtime::cgroup; pub use jmodguard_runtime::health; pub use jmodguard_runtime::log_shutdown_finished;