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
22 changes: 14 additions & 8 deletions crates/bot/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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(());
Expand Down
54 changes: 23 additions & 31 deletions crates/runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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());
Expand All @@ -128,42 +146,16 @@ 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}");
}
}

/// 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() {
Expand Down
20 changes: 20 additions & 0 deletions crates/runtime/tests/shutdown.rs
Original file line number Diff line number Diff line change
@@ -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");
}
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
Loading