Skip to content
This repository has been archived by the owner on Oct 16, 2023. It is now read-only.

Commit

Permalink
Install graceful shutdown on server
Browse files Browse the repository at this point in the history
This commit enables gracefull shutdown on the server to handle SIGTERM signals from the cluster and improve service restarts
  • Loading branch information
bltavares authored and awoimbee committed Sep 18, 2023
1 parent 97faa61 commit b338e4b
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,10 @@ impl TrowBuilder {
// Start GRPC Backend task
tokio::task::spawn(init_trow_server(self.config.clone())?);

// Listen for termination signal
let handle = axum_server::Handle::new();
tokio::spawn(shutdown_signal(handle.clone()));

if let Some(ref tls) = self.config.tls {
if !(Path::new(&tls.cert_file).is_file() && Path::new(&tls.key_file).is_file()) {
return Err(anyhow!(
Expand All @@ -236,17 +240,50 @@ impl TrowBuilder {
}
let config = RustlsConfig::from_pem_file(&tls.cert_file, &tls.key_file).await?;
axum_server::bind_rustls(self.config.addr, config)
.handle(handle)
.serve(app.into_make_service())
.await?;
} else {
axum_server::bind(self.config.addr)
.handle(handle)
.serve(app.into_make_service())
.await?;
};
Ok(())
}
}

async fn shutdown_signal(handle: axum_server::Handle) {
use std::time::Duration;
use tokio::signal;

let ctrl_c = async {
signal::ctrl_c()
.await
.expect("failed to install Ctrl+C handler");
};

#[cfg(unix)]
let terminate = async {
signal::unix::signal(signal::unix::SignalKind::terminate())
.expect("failed to install signal handler")
.recv()
.await;
};

#[cfg(not(unix))]
let terminate = std::future::pending::<()>();

tokio::select! {
_ = ctrl_c => {},
_ = terminate => {},
}

println!("signal received, starting graceful shutdown");
// Signal the server to shutdown using Handle.
handle.graceful_shutdown(Some(Duration::from_secs(30)));
}

pub fn build_handlers(listen_addr: String) -> Result<ClientInterface> {
event!(Level::DEBUG, "Address for backend: {}", listen_addr);

Expand Down

0 comments on commit b338e4b

Please sign in to comment.