1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// Author: D.S. Ljungmark <spider@skuggor.se>, Modio AB
// SPDX-License-Identifier: AGPL-3.0-or-later
use std::env;
use std::io::{self, ErrorKind};
use tokio::net::UnixDatagram;

/// Pick up the socket path to notify and then send the message to it.
/// Details on the protocol are here <https://www.man7.org/linux/man-pages/man3/sd_notify.3.html>
pub async fn sd_notify(msg: &str) -> io::Result<()> {
    if let Some(socket_path) = env::var_os("NOTIFY_SOCKET") {
        let sock = UnixDatagram::unbound()?;
        let len = sock.send_to(msg.as_bytes(), socket_path).await?;
        if len == msg.len() {
            Ok(())
        } else {
            let err = io::Error::new(ErrorKind::WriteZero, "incomplete write");
            Err(err)
        }
    } else {
        Ok(())
    }
}

/// Helper, send "READY=1"
pub async fn sd_ready() -> io::Result<()> {
    sd_notify("READY=1").await
}

/// Helper, send "WATCHDOG=1"
pub async fn ping_watchdog() -> io::Result<()> {
    sd_notify("WATCHDOG=1").await
}