mirror of
https://seed.radicle.dev/rad:z4V1sjrXqjvFdnCUbxPFqd5p4DtH5.git
synced 2026-11-28 17:50:28 +08:00
httpd: Drain requests on SIGTERM and SIGINT
httpd only handled SIGHUP, so a stop or restart killed it at once and cut off in-flight clones and archive downloads. On the first signal, stop accepting connections and let in-flight requests finish. A second signal exits at once. The supervisor's stop timeout, e.g., systemd's `TimeoutStopSec`, bounds the drain, so httpd needs no timeout of its own. One downside is that a restart now refuses connections until the drain ends instead of for about a second. Co-authored-by: Daniel Norman <daniel@norman.life>
This commit is contained in:
committed by
Daniel Norman
co-authored by
Daniel Norman
parent
b7977fa4d8
commit
56df1bb3b6
@@ -7,6 +7,10 @@
|
||||
- **404 for missing repos and objects**: Raw, git and API routes return 404
|
||||
instead of 500 for repos the node doesn't have, missing commits, blobs and
|
||||
paths, and paths of the wrong type
|
||||
- **Graceful shutdown**: On SIGTERM or SIGINT, httpd stops accepting connections
|
||||
and lets in-flight requests finish. A second signal exits at once. The
|
||||
supervisor's stop timeout, e.g., systemd's `TimeoutStopSec`, bounds the drain.
|
||||
New connections are refused during the drain, so a restart can take that long
|
||||
|
||||
## radicle-httpd + radicle-search 0.31.0
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
#[cfg(unix)]
|
||||
use tokio::signal::unix::{signal, SignalKind};
|
||||
use tokio::signal::unix::{signal, Signal, SignalKind};
|
||||
|
||||
use anyhow::Context as _;
|
||||
use axum::body::Body;
|
||||
@@ -23,6 +23,7 @@ use axum_listener::{DualAddr, DualListener};
|
||||
use hyper::body::Body as _;
|
||||
use hyper::header::CONTENT_TYPE;
|
||||
use hyper::Method;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use tower_http::cors;
|
||||
use tower_http::cors::CorsLayer;
|
||||
use tower_http::trace::TraceLayer;
|
||||
@@ -92,6 +93,8 @@ pub async fn run(options: Options) -> anyhow::Result<()> {
|
||||
tracing::warn!("Unable to set open file limit: {e}");
|
||||
}
|
||||
|
||||
let termination = TerminationSignals::register()?;
|
||||
|
||||
let listener = DualListener::bind(&options.listen).await?;
|
||||
tracing::info!("listening on {:?}", &options.listen);
|
||||
|
||||
@@ -157,9 +160,70 @@ pub async fn run(options: Options) -> anyhow::Result<()> {
|
||||
)
|
||||
).into_make_service_with_connect_info::<DualAddr>();
|
||||
|
||||
axum::serve(listener, app)
|
||||
.await
|
||||
.map_err(anyhow::Error::from)
|
||||
let drained = CancellationToken::new();
|
||||
let server =
|
||||
axum::serve(listener, app).with_graceful_shutdown(drained.clone().cancelled_owned());
|
||||
|
||||
tokio::select! {
|
||||
result = server => result.map_err(anyhow::Error::from),
|
||||
() = drain(termination, drained) => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Start the drain on the first termination signal. Resolves on the second,
|
||||
/// which cuts the drain short.
|
||||
async fn drain(mut termination: TerminationSignals, drained: CancellationToken) {
|
||||
let first = termination.recv().await;
|
||||
tracing::info!(
|
||||
"Received {first}, draining in-flight requests; send SIGTERM or SIGINT (Ctrl-C) again to exit immediately"
|
||||
);
|
||||
drained.cancel();
|
||||
|
||||
let second = termination.recv().await;
|
||||
tracing::warn!("Received {second} while draining, exiting with requests still in flight");
|
||||
}
|
||||
|
||||
/// SIGTERM and SIGINT handlers. They are registered before the listener is
|
||||
/// bound, so that a signal during startup does not terminate the process, and
|
||||
/// kept for the whole drain, so that a second signal can cut it short.
|
||||
#[cfg(unix)]
|
||||
struct TerminationSignals {
|
||||
sigterm: Signal,
|
||||
sigint: Signal,
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
impl TerminationSignals {
|
||||
fn register() -> anyhow::Result<Self> {
|
||||
Ok(Self {
|
||||
sigterm: signal(SignalKind::terminate())
|
||||
.context("Unable to register SIGTERM handler")?,
|
||||
sigint: signal(SignalKind::interrupt()).context("Unable to register SIGINT handler")?,
|
||||
})
|
||||
}
|
||||
|
||||
/// Wait for the next termination signal, yielding its name.
|
||||
async fn recv(&mut self) -> &'static str {
|
||||
tokio::select! {
|
||||
_ = self.sigterm.recv() => "SIGTERM",
|
||||
_ = self.sigint.recv() => "SIGINT",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
struct TerminationSignals;
|
||||
|
||||
#[cfg(not(unix))]
|
||||
impl TerminationSignals {
|
||||
fn register() -> anyhow::Result<Self> {
|
||||
Ok(Self)
|
||||
}
|
||||
|
||||
async fn recv(&mut self) -> &'static str {
|
||||
let _ = tokio::signal::ctrl_c().await;
|
||||
"SIGINT"
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a router consisting of other sub-routers.
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use std::num::NonZeroUsize;
|
||||
use std::time::Duration;
|
||||
use std::{collections::HashMap, process};
|
||||
|
||||
use anyhow::bail;
|
||||
@@ -39,8 +40,7 @@ Environment
|
||||
Unrecognised values fall back to "text".
|
||||
"#;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
fn main() -> anyhow::Result<()> {
|
||||
// SAFETY: The logger is only initialized once.
|
||||
httpd::logger::init().unwrap();
|
||||
tracing::info!("starting http daemon..");
|
||||
@@ -51,13 +51,18 @@ async fn main() -> anyhow::Result<()> {
|
||||
);
|
||||
|
||||
let options = parse_options()?;
|
||||
let runtime = tokio::runtime::Builder::new_multi_thread()
|
||||
.enable_all()
|
||||
.build()?;
|
||||
let served = runtime.block_on(httpd::run(options));
|
||||
|
||||
match httpd::run(options).await {
|
||||
Ok(()) => {}
|
||||
Err(err) => {
|
||||
tracing::error!("Fatal: {:#}", err);
|
||||
process::exit(1);
|
||||
}
|
||||
// Do not wait for blocking tasks, e.g., repository reads, which can run
|
||||
// for minutes after the drain.
|
||||
runtime.shutdown_timeout(Duration::ZERO);
|
||||
|
||||
if let Err(err) = served {
|
||||
tracing::error!("Fatal: {:#}", err);
|
||||
process::exit(1);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user