waratah/shutdown.rs
1//! ctrl-c / SIGTERM shutdown flag for `waratah start`.
2//!
3//! Until this existed, interrupting `waratah start` orphaned every child: the
4//! default SIGINT disposition kills the orchestrator without running the
5//! `SpawnedCluster` / supervisor `Drop` guards. With a handler installed,
6//! the process stays alive long enough to kill its children (and the
7//! notebook sidecar's process group) and exit cleanly. `waratah stop`
8//! rides the same path via SIGTERM.
9
10use tokio::sync::watch;
11
12/// Cloneable view of the "shut down now" flag.
13#[derive(Clone)]
14pub(crate) struct ShutdownWatch {
15 rx: watch::Receiver<bool>,
16}
17
18impl ShutdownWatch {
19 /// Install the signal watcher and return the flag.
20 pub(crate) fn install() -> Self {
21 let (tx, rx) = watch::channel(false);
22 tokio::spawn(async move {
23 let received = async {
24 #[cfg(unix)]
25 {
26 let Ok(mut sigterm) =
27 tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
28 else {
29 return;
30 };
31 tokio::select! {
32 _ = tokio::signal::ctrl_c() => {},
33 _ = sigterm.recv() => {},
34 }
35 }
36 #[cfg(not(unix))]
37 {
38 let _ = tokio::signal::ctrl_c().await;
39 }
40 };
41 received.await;
42 // Generic on purpose: whether the notebook sidecar (or even
43 // spawned storage children) exist depends on the flags.
44 println!("shutdown signal received; stopping child processes");
45 let _ = tx.send(true);
46 });
47 Self { rx }
48 }
49
50 /// Future that resolves once shutdown was signalled. Owned (`'static`)
51 /// so it can be handed to `with_graceful_shutdown` and friends.
52 pub(crate) fn triggered(&self) -> impl std::future::Future<Output = ()> + Send + 'static {
53 let mut rx = self.rx.clone();
54 async move {
55 // The flag may already be set (no `changed()` edge left).
56 if *rx.borrow_and_update() {
57 return;
58 }
59 let _ = rx.changed().await;
60 }
61 }
62}