|
| 1 | +/* |
| 2 | + * Copyright (c) Meta Platforms, Inc. and affiliates. |
| 3 | + * All rights reserved. |
| 4 | + * |
| 5 | + * This source code is licensed under the BSD-style license found in the |
| 6 | + * LICENSE file in the root directory of this source tree. |
| 7 | + */ |
| 8 | + |
| 9 | +use std::collections::HashMap; |
| 10 | +use std::future::Future; |
| 11 | +use std::pin::Pin; |
| 12 | +use std::sync::Arc; |
| 13 | +use std::sync::Mutex; |
| 14 | +use std::sync::OnceLock; |
| 15 | + |
| 16 | +use nix::sys::signal; |
| 17 | +use tokio_stream::StreamExt; |
| 18 | + |
| 19 | +type AsyncCleanupCallback = Pin<Box<dyn Future<Output = ()> + Send>>; |
| 20 | + |
| 21 | +/// Global signal manager that coordinates cleanup across all signal handlers |
| 22 | +pub(crate) struct GlobalSignalManager { |
| 23 | + cleanup_callbacks: Arc<Mutex<HashMap<u64, AsyncCleanupCallback>>>, |
| 24 | + next_id: Arc<Mutex<u64>>, |
| 25 | + _listener: tokio::task::JoinHandle<()>, |
| 26 | +} |
| 27 | + |
| 28 | +impl GlobalSignalManager { |
| 29 | + fn new() -> Self { |
| 30 | + let listener = tokio::spawn(async move { |
| 31 | + if let Ok(mut signals) = |
| 32 | + signal_hook_tokio::Signals::new([signal::SIGINT as i32, signal::SIGTERM as i32]) |
| 33 | + { |
| 34 | + if let Some(signal) = signals.next().await { |
| 35 | + tracing::info!("received signal: {}", signal); |
| 36 | + |
| 37 | + get_signal_manager().execute_all_cleanups().await; |
| 38 | + |
| 39 | + match signal::Signal::try_from(signal) { |
| 40 | + Ok(sig) => { |
| 41 | + if let Err(err) = |
| 42 | + // SAFETY: We're setting the handle to SigDfl (default system behaviour) |
| 43 | + unsafe { signal::signal(sig, signal::SigHandler::SigDfl) } |
| 44 | + { |
| 45 | + tracing::error!( |
| 46 | + "failed to restore default signal handler for {}: {}", |
| 47 | + sig, |
| 48 | + err |
| 49 | + ); |
| 50 | + } |
| 51 | + |
| 52 | + // Re-raise the signal to trigger default behavior (process termination) |
| 53 | + if let Err(err) = signal::raise(sig) { |
| 54 | + tracing::error!("failed to re-raise signal {}: {}", sig, err); |
| 55 | + } |
| 56 | + } |
| 57 | + Err(err) => { |
| 58 | + tracing::error!("failed to convert signal {}: {}", signal, err); |
| 59 | + } |
| 60 | + } |
| 61 | + } |
| 62 | + } |
| 63 | + }); |
| 64 | + Self { |
| 65 | + cleanup_callbacks: Arc::new(Mutex::new(HashMap::new())), |
| 66 | + next_id: Arc::new(Mutex::new(0)), |
| 67 | + _listener: listener, |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | + /// Register a cleanup callback and return a unique ID for later unregistration |
| 72 | + fn register_cleanup(&self, callback: AsyncCleanupCallback) -> u64 { |
| 73 | + let mut next_id = self.next_id.lock().unwrap_or_else(|e| e.into_inner()); |
| 74 | + let id = *next_id; |
| 75 | + *next_id += 1; |
| 76 | + drop(next_id); |
| 77 | + |
| 78 | + let mut callbacks = self |
| 79 | + .cleanup_callbacks |
| 80 | + .lock() |
| 81 | + .unwrap_or_else(|e| e.into_inner()); |
| 82 | + callbacks.insert(id, callback); |
| 83 | + tracing::info!("registered signal cleanup callback with ID: {}", id); |
| 84 | + id |
| 85 | + } |
| 86 | + |
| 87 | + /// Unregister a cleanup callback by ID |
| 88 | + fn unregister_cleanup(&self, id: u64) { |
| 89 | + let mut callbacks = self |
| 90 | + .cleanup_callbacks |
| 91 | + .lock() |
| 92 | + .unwrap_or_else(|e| e.into_inner()); |
| 93 | + if callbacks.remove(&id).is_some() { |
| 94 | + tracing::info!("unregistered signal cleanup callback with ID: {}", id); |
| 95 | + } else { |
| 96 | + tracing::warn!( |
| 97 | + "attempted to unregister non-existent cleanup callback with ID: {}", |
| 98 | + id |
| 99 | + ); |
| 100 | + } |
| 101 | + } |
| 102 | + |
| 103 | + /// Execute all registered cleanup callbacks asynchronously |
| 104 | + async fn execute_all_cleanups(&self) { |
| 105 | + let callbacks = { |
| 106 | + let mut callbacks = self |
| 107 | + .cleanup_callbacks |
| 108 | + .lock() |
| 109 | + .unwrap_or_else(|e| e.into_inner()); |
| 110 | + std::mem::take(&mut *callbacks) |
| 111 | + }; |
| 112 | + |
| 113 | + let futures = callbacks.into_iter().map(|(id, future)| async move { |
| 114 | + tracing::debug!("executing cleanup callback with ID: {}", id); |
| 115 | + future.await; |
| 116 | + }); |
| 117 | + |
| 118 | + futures::future::join_all(futures).await; |
| 119 | + } |
| 120 | +} |
| 121 | + |
| 122 | +/// Global instance of the signal manager |
| 123 | +static SIGNAL_MANAGER: OnceLock<GlobalSignalManager> = OnceLock::new(); |
| 124 | + |
| 125 | +/// Get the global signal manager instance |
| 126 | +pub(crate) fn get_signal_manager() -> &'static GlobalSignalManager { |
| 127 | + SIGNAL_MANAGER.get_or_init(GlobalSignalManager::new) |
| 128 | +} |
| 129 | + |
| 130 | +/// RAII guard that automatically unregisters a signal cleanup callback when dropped |
| 131 | +pub struct SignalCleanupGuard { |
| 132 | + id: u64, |
| 133 | +} |
| 134 | + |
| 135 | +impl SignalCleanupGuard { |
| 136 | + fn new(id: u64) -> Self { |
| 137 | + Self { id } |
| 138 | + } |
| 139 | + |
| 140 | + /// Get the ID of the registered cleanup callback |
| 141 | + pub fn id(&self) -> u64 { |
| 142 | + self.id |
| 143 | + } |
| 144 | +} |
| 145 | + |
| 146 | +impl Drop for SignalCleanupGuard { |
| 147 | + fn drop(&mut self) { |
| 148 | + get_signal_manager().unregister_cleanup(self.id); |
| 149 | + } |
| 150 | +} |
| 151 | + |
| 152 | +/// Register a cleanup callback to be executed on SIGINT/SIGTERM |
| 153 | +/// Returns a unique ID that can be used to unregister the callback |
| 154 | +pub fn register_signal_cleanup(callback: AsyncCleanupCallback) -> u64 { |
| 155 | + get_signal_manager().register_cleanup(callback) |
| 156 | +} |
| 157 | + |
| 158 | +/// Register a scoped cleanup callback to be executed on SIGINT/SIGTERM |
| 159 | +/// Returns a guard that automatically unregisters the callback when dropped |
| 160 | +pub fn register_signal_cleanup_scoped(callback: AsyncCleanupCallback) -> SignalCleanupGuard { |
| 161 | + let id = get_signal_manager().register_cleanup(callback); |
| 162 | + SignalCleanupGuard::new(id) |
| 163 | +} |
| 164 | + |
| 165 | +/// Unregister a previously registered cleanup callback |
| 166 | +pub fn unregister_signal_cleanup(id: u64) { |
| 167 | + get_signal_manager().unregister_cleanup(id); |
| 168 | +} |
0 commit comments