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

Install graceful shutdown on server #18

Merged
merged 1 commit into from
Sep 18, 2023
Merged
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
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();
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would prefer handle to be called shutdown_handle, but it's OK

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
Loading