Skip to content

Commit 80a505e

Browse files
committed
Chore: add signal-handling to run-blocking
1 parent 4e588e1 commit 80a505e

File tree

3 files changed

+54
-0
lines changed

3 files changed

+54
-0
lines changed

rust/Cargo.lock

Lines changed: 24 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

rust/crates/greenbone-scanner-framework/Cargo.toml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@ tokio-rustls = { workspace = true }
2020
tracing = { workspace = true }
2121
uuid = { workspace = true }
2222
futures = { workspace = true }
23+
signal-hook-tokio = { version = "0.4.0", features = ["futures-v0_3"] }
24+
signal-hook = "0.4.3"
2325

2426
[dev-dependencies]
2527
insta = { workspace = true }

rust/crates/greenbone-scanner-framework/src/lib.rs

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,10 @@ mod post_scans_id;
5151
mod tls;
5252
use post_scans::PostScansHandler;
5353
use post_scans_id::{PostScansId, PostScansIdHandler};
54+
55+
use futures::stream::StreamExt;
56+
use signal_hook::{consts::signal::*, low_level::exit};
57+
use signal_hook_tokio::Signals;
5458
use tokio::net::TcpListener;
5559

5660
pub trait ExternalError: core::error::Error + Send + Sync + 'static {}
@@ -374,8 +378,32 @@ impl RuntimeBuilder<runtime_builder_states::DeleteScanIDSet> {
374378
}
375379
}
376380

381+
async fn handle_signals(mut signals: Signals) {
382+
while let Some(signal) = signals.next().await {
383+
match signal {
384+
SIGHUP => {
385+
tracing::info!("Ignoring SIGHUP signal.");
386+
}
387+
SIGTERM | SIGINT | SIGQUIT => {
388+
// I thought about handling it gracefully however as the request is handled in a
389+
// background task within the main loop it would just artifically complicate it
390+
// without any kind of benefit.
391+
//
392+
// The risk of corruption is relatively low, hence just exit.
393+
tracing::info!(signal, "Exit based on signal.");
394+
exit(128 + signal);
395+
}
396+
_ => unreachable!(),
397+
}
398+
}
399+
}
400+
377401
impl RuntimeBuilder<runtime_builder_states::End> {
378402
pub async fn run_blocking(self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
403+
let signals = Signals::new([SIGHUP, SIGTERM, SIGINT, SIGQUIT])?;
404+
let _handle_guard = signals.handle();
405+
tokio::task::spawn(handle_signals(signals));
406+
379407
let scanner = Arc::new(self.build_scanner());
380408
let tls_config = match &self.tls {
381409
Some(x) => Some(tls::tls_config(x)?),

0 commit comments

Comments
 (0)