Skip to main content

hyprstream_core/systemd/
notify.rs

1//! Systemd notification support
2//!
3//! Provides a wrapper for communicating with systemd:
4//! - Ready notification (`READY=1`)
5//! - Stopping notification (`STOPPING=1`)
6//! - Status updates (shown in `systemctl status`)
7//! - Watchdog pings (`WATCHDOG=1`)
8//!
9//! # Usage
10//!
11//! ```ignore
12//! use hyprstream_core::systemd::SystemdNotifier;
13//!
14//! // Signal service is ready
15//! SystemdNotifier::ready();
16//!
17//! // Update status (shown in systemctl status)
18//! SystemdNotifier::status("Processing 42 requests");
19//!
20//! // Signal stopping
21//! SystemdNotifier::stopping();
22//! ```
23//!
24//! # Watchdog Integration
25//!
26//! For services with `WatchdogSec=` configured:
27//!
28//! ```ignore
29//! // Check if watchdog is enabled and get ping interval
30//! if let Some(interval) = SystemdNotifier::watchdog_interval() {
31//!     // Ping watchdog at the recommended interval (half of WatchdogSec)
32//!     loop {
33//!         tokio::time::sleep(interval).await;
34//!         if is_healthy().await {
35//!             SystemdNotifier::watchdog();
36//!         }
37//!         // If unhealthy, don't ping - systemd will restart us
38//!     }
39//! }
40//! ```
41
42use std::time::Duration;
43use tracing::{debug, info, trace};
44
45/// Systemd notification wrapper
46///
47/// All methods are no-ops if not running under systemd (no NOTIFY_SOCKET).
48pub struct SystemdNotifier;
49
50impl SystemdNotifier {
51    /// Signal that the service is ready to accept connections
52    ///
53    /// Sends `READY=1` to systemd. For `Type=notify` services, this must be
54    /// called after the service has finished initialization.
55    ///
56    /// # Example
57    ///
58    /// ```ignore
59    /// // After binding listener and starting server
60    /// SystemdNotifier::ready();
61    /// ```
62    pub fn ready() {
63        if Self::is_systemd_managed() {
64            info!("Notifying systemd: READY=1");
65            let _ = hyprstream_rpc::notify::ready();
66        } else {
67            debug!("Not running under systemd, skipping READY notification");
68        }
69    }
70
71    /// Signal that the service is stopping
72    ///
73    /// Sends `STOPPING=1` to systemd. This should be called when starting
74    /// graceful shutdown.
75    ///
76    /// # Example
77    ///
78    /// ```ignore
79    /// // When shutdown signal received
80    /// SystemdNotifier::stopping();
81    /// // Then perform graceful shutdown
82    /// ```
83    pub fn stopping() {
84        if Self::is_systemd_managed() {
85            info!("Notifying systemd: STOPPING=1");
86            let _ = hyprstream_rpc::notify::stopping();
87        } else {
88            debug!("Not running under systemd, skipping STOPPING notification");
89        }
90    }
91
92    /// Update the status message shown in `systemctl status`
93    ///
94    /// Sends `STATUS=<msg>` to systemd. This can be called periodically
95    /// to show useful information in the service status.
96    ///
97    /// # Arguments
98    ///
99    /// * `msg` - Status message to display
100    ///
101    /// # Example
102    ///
103    /// ```ignore
104    /// // Show current activity
105    /// SystemdNotifier::status("Loaded 3 models, serving requests");
106    /// SystemdNotifier::status("Processing 42 active connections");
107    /// ```
108    pub fn status(msg: &str) {
109        if Self::is_systemd_managed() {
110            debug!("Notifying systemd: STATUS={}", msg);
111            let _ = hyprstream_rpc::notify::status(msg);
112        }
113    }
114
115    /// Ping the watchdog timer
116    ///
117    /// Sends `WATCHDOG=1` to systemd. This should ONLY be called when the
118    /// service is healthy. If the service becomes unhealthy, stop pinging
119    /// and let systemd restart it after `WatchdogSec` timeout.
120    ///
121    /// # Important
122    ///
123    /// Only call this when health checks pass. Pinging while unhealthy
124    /// defeats the purpose of the watchdog.
125    ///
126    /// # Example
127    ///
128    /// ```ignore
129    /// if health_check_passed().await {
130    ///     SystemdNotifier::watchdog();
131    /// }
132    /// // If health check fails, don't ping - systemd will restart
133    /// ```
134    pub fn watchdog() {
135        if Self::is_systemd_managed() {
136            trace!("Notifying systemd: WATCHDOG=1");
137            let _ = hyprstream_rpc::notify::watchdog();
138        }
139    }
140
141    /// Get the watchdog ping interval
142    ///
143    /// Returns the recommended interval for pinging the watchdog, which is
144    /// half of the `WatchdogSec` value configured in the unit file.
145    ///
146    /// # Returns
147    ///
148    /// `Some(duration)` if watchdog is enabled, `None` if not configured
149    /// or not running under systemd.
150    ///
151    /// # Example
152    ///
153    /// ```ignore
154    /// if let Some(interval) = SystemdNotifier::watchdog_interval() {
155    ///     info!("Watchdog enabled, pinging every {:?}", interval);
156    ///     // Start watchdog task
157    /// } else {
158    ///     info!("Watchdog not configured");
159    /// }
160    /// ```
161    pub fn watchdog_interval() -> Option<Duration> {
162        std::env::var("WATCHDOG_USEC")
163            .ok()
164            .and_then(|v| v.parse::<u64>().ok())
165            .map(|usec| {
166                // Ping at half the watchdog interval for safety margin
167                Duration::from_micros(usec / 2)
168            })
169    }
170
171    /// Check if running under systemd management
172    ///
173    /// Returns `true` if `NOTIFY_SOCKET` environment variable is set,
174    /// indicating the service was started by systemd with notification
175    /// support enabled.
176    pub fn is_systemd_managed() -> bool {
177        std::env::var("NOTIFY_SOCKET").is_ok()
178    }
179
180    /// Get the PID that systemd expects for notifications
181    ///
182    /// Returns the PID that should be sending notifications. For most
183    /// services this is the main PID (returned by `getpid()`).
184    pub fn expected_pid() -> Option<u32> {
185        std::env::var("WATCHDOG_PID")
186            .or_else(|_| std::env::var("MAINPID"))
187            .ok()
188            .and_then(|v| v.parse().ok())
189    }
190}
191
192#[cfg(test)]
193#[allow(clippy::expect_used, clippy::unwrap_used, clippy::print_stdout)]
194mod tests {
195    use super::*;
196
197    #[test]
198    fn test_is_systemd_managed() {
199        // Should return false when not running under systemd
200        // (NOTIFY_SOCKET not set in test environment)
201        let managed = SystemdNotifier::is_systemd_managed();
202        // This may be true or false depending on test environment
203        println!("Running under systemd: {}", managed);
204    }
205
206    #[test]
207    fn test_watchdog_interval_not_set() {
208        // Should return None when WATCHDOG_USEC is not set
209        std::env::remove_var("WATCHDOG_USEC");
210        assert!(SystemdNotifier::watchdog_interval().is_none());
211    }
212
213    #[test]
214    fn test_ready_no_panic() {
215        // Should not panic even when not running under systemd
216        SystemdNotifier::ready();
217    }
218
219    #[test]
220    fn test_status_no_panic() {
221        // Should not panic even when not running under systemd
222        SystemdNotifier::status("test status");
223    }
224
225    #[test]
226    fn test_stopping_no_panic() {
227        // Should not panic even when not running under systemd
228        SystemdNotifier::stopping();
229    }
230
231    #[test]
232    fn test_watchdog_no_panic() {
233        // Should not panic even when not running under systemd
234        SystemdNotifier::watchdog();
235    }
236}