Skip to main content

hyprstream_rpc/
notify.rs

1//! Service notification helpers
2//!
3//! Wraps the systemd sd_notify protocol for service lifecycle notifications.
4//! The sd_notify transport is a plain datagram to `NOTIFY_SOCKET`, so it is
5//! supervisor-agnostic: `ready()` delivers `READY=1` in every build (through
6//! the `systemd` crate where that feature is on, and through a `nix` datagram
7//! send otherwise), and stays a no-op only when `NOTIFY_SOCKET` is unset.
8
9use anyhow::Result;
10
11/// Notify systemd that service is ready
12///
13/// Sends `READY=1` to the notification socket.
14/// This should be called after the service has completed initialization
15/// and is ready to handle requests.
16///
17/// The sd_notify protocol is supervisor-agnostic: the message is a datagram to
18/// whatever `NOTIFY_SOCKET` points at, so a direct-launch supervisor
19/// (`--daemon` / no-systemd fallback, #1585) that provisions a per-child
20/// notification endpoint gets the same post-initialization signal systemd
21/// receives. With `NOTIFY_SOCKET` unset the call stays a no-op in every build.
22#[cfg(feature = "systemd")]
23pub fn ready() -> Result<()> {
24    let state = [("READY", "1")];
25    systemd::daemon::notify(false, state.iter())?;
26    Ok(())
27}
28
29/// Feature-less builds send the same datagram through `nix` so required-native
30/// readiness does not silently degrade to a no-op (and a launcher notification
31/// wait to a guaranteed timeout) on no-systemd builds. Abstract (`@`-prefixed)
32/// socket paths — which real systemd hands out — are addressed through
33/// `UnixAddr::new_abstract` (the sd_notify leading-`@` convention); every
34/// other value is a pathname address.
35#[cfg(not(feature = "systemd"))]
36pub fn ready() -> Result<()> {
37    use nix::sys::socket::{sendto, socket, AddressFamily, MsgFlags, SockFlag, SockType, UnixAddr};
38    use std::os::fd::AsRawFd;
39    use std::os::unix::ffi::OsStrExt;
40
41    let Some(socket_path) = std::env::var_os("NOTIFY_SOCKET") else {
42        return Ok(());
43    };
44    let bytes = socket_path.as_bytes();
45    #[cfg(any(target_os = "linux", target_os = "android"))]
46    let address = {
47        if bytes.first() == Some(&b'@') {
48            UnixAddr::new_abstract(&bytes[1..])?
49        } else {
50            UnixAddr::new(std::path::Path::new(&socket_path))?
51        }
52    };
53    #[cfg(not(any(target_os = "linux", target_os = "android")))]
54    let address = UnixAddr::new(std::path::Path::new(&socket_path))?;
55    let fd = socket(
56        AddressFamily::Unix,
57        SockType::Datagram,
58        SockFlag::empty(),
59        None,
60    )?;
61    sendto(fd.as_raw_fd(), b"READY=1", &address, MsgFlags::empty())?;
62    Ok(())
63}
64
65/// Notify systemd that service is stopping
66///
67/// Sends `STOPPING=1` to the notification socket.
68/// This should be called when the service begins its shutdown sequence.
69#[cfg(feature = "systemd")]
70pub fn stopping() -> Result<()> {
71    let state = [("STOPPING", "1")];
72    systemd::daemon::notify(false, state.iter())?;
73    Ok(())
74}
75
76#[cfg(not(feature = "systemd"))]
77pub fn stopping() -> Result<()> {
78    Ok(())
79}
80
81/// Notify systemd of current status
82///
83/// Sends `STATUS={msg}` to the notification socket.
84/// The status message is displayed in `systemctl status`.
85#[cfg(feature = "systemd")]
86pub fn status(msg: &str) -> Result<()> {
87    let state = [("STATUS", msg)];
88    systemd::daemon::notify(false, state.iter())?;
89    Ok(())
90}
91
92#[cfg(not(feature = "systemd"))]
93pub fn status(_msg: &str) -> Result<()> {
94    Ok(())
95}
96
97/// Ping the watchdog
98///
99/// Sends `WATCHDOG=1` to the notification socket.
100/// Required for services with `WatchdogSec=` configured.
101#[cfg(feature = "systemd")]
102pub fn watchdog() -> Result<()> {
103    let state = [("WATCHDOG", "1")];
104    systemd::daemon::notify(false, state.iter())?;
105    Ok(())
106}
107
108#[cfg(not(feature = "systemd"))]
109pub fn watchdog() -> Result<()> {
110    Ok(())
111}
112
113#[cfg(all(test, unix))]
114mod tests {
115    use super::*;
116    use parking_lot::Mutex;
117
118    /// `NOTIFY_SOCKET` is process-global state: serialize the send regressions.
119    static NOTIFY_ENV_LOCK: Mutex<()> = Mutex::new(());
120
121    const READY_PAYLOAD: &[u8] = b"READY=1";
122
123    #[test]
124    fn ready_sends_datagram_to_pathname_socket() -> anyhow::Result<()> {
125        let _guard = NOTIFY_ENV_LOCK.lock();
126        let path = std::env::temp_dir().join(format!(
127            "hyprstream-notify-pathname-{}-{}.sock",
128            std::process::id(),
129            std::time::SystemTime::now()
130                .duration_since(std::time::UNIX_EPOCH)?
131                .as_nanos()
132        ));
133        let receiver = std::os::unix::net::UnixDatagram::bind(&path)?;
134        receiver.set_read_timeout(Some(std::time::Duration::from_secs(5)))?;
135
136        std::env::set_var("NOTIFY_SOCKET", &path);
137        let outcome = ready();
138        std::env::remove_var("NOTIFY_SOCKET");
139        outcome?;
140
141        let mut buffer = [0u8; 16];
142        let (received, _) = receiver.recv_from(&mut buffer)?;
143        assert_eq!(&buffer[..received], READY_PAYLOAD);
144        Ok(())
145    }
146
147    /// Real systemd hands out abstract `@`-prefixed endpoints; the send side
148    /// must address them with the sd_notify leading-NUL convention.
149    #[test]
150    #[cfg(any(target_os = "linux", target_os = "android"))]
151    fn ready_sends_datagram_to_abstract_socket() -> anyhow::Result<()> {
152        use nix::cmsg_space;
153        use nix::sys::socket::{
154            bind, recvmsg, socket, AddressFamily, MsgFlags, SockFlag, SockType, UnixAddr,
155            UnixCredentials,
156        };
157        use std::io::IoSliceMut;
158        use std::os::fd::AsRawFd;
159
160        let _guard = NOTIFY_ENV_LOCK.lock();
161        let name = format!(
162            "hyprstream-notify-abstract-{}-{}",
163            std::process::id(),
164            std::time::SystemTime::now()
165                .duration_since(std::time::UNIX_EPOCH)?
166                .as_nanos()
167        );
168        let fd = socket(
169            AddressFamily::Unix,
170            SockType::Datagram,
171            SockFlag::SOCK_NONBLOCK | SockFlag::SOCK_CLOEXEC,
172            None,
173        )?;
174        bind(fd.as_raw_fd(), &UnixAddr::new_abstract(name.as_bytes())?)?;
175
176        std::env::set_var("NOTIFY_SOCKET", format!("@{name}"));
177        let outcome = ready();
178        std::env::remove_var("NOTIFY_SOCKET");
179        outcome?;
180
181        let mut buffer = [0u8; 16];
182        let received = {
183            let mut iov = [IoSliceMut::new(&mut buffer)];
184            let mut cmsg = cmsg_space!(UnixCredentials);
185            let message =
186                recvmsg::<UnixAddr>(fd.as_raw_fd(), &mut iov, Some(&mut cmsg), MsgFlags::empty())?;
187            message.bytes
188        };
189        assert!(received > 0);
190        assert_eq!(&buffer[..received], READY_PAYLOAD);
191        Ok(())
192    }
193}