mocklogger/
sd_notify.rs

1// Author: D.S. Ljungmark <spider@skuggor.se>, Modio AB
2// SPDX-License-Identifier: AGPL-3.0-or-later
3use async_std::os::unix::net::UnixDatagram;
4use std::env;
5use std::io::{self, ErrorKind};
6use std::str::FromStr;
7use std::time::Duration;
8
9/// Pick up the socket path to notify and then send the message to it.
10/// Details on the protocol are here <https://www.man7.org/linux/man-pages/man3/sd_notify.3.html>
11pub async fn sd_notify(msg: &str) -> io::Result<()> {
12    if let Some(socket_path) = env::var_os("NOTIFY_SOCKET") {
13        let sock = UnixDatagram::unbound()?;
14        let len = sock.send_to(msg.as_bytes(), socket_path).await?;
15        if len == msg.len() {
16            Ok(())
17        } else {
18            let err = io::Error::new(ErrorKind::WriteZero, "incomplete write");
19            Err(err)
20        }
21    } else {
22        Ok(())
23    }
24}
25
26/// Helper, send "READY=1"
27pub async fn sd_ready() -> io::Result<()> {
28    sd_notify("READY=1").await
29}
30
31/// Helper, send "WATCHDOG=1"
32pub async fn ping_watchdog() -> io::Result<()> {
33    sd_notify("WATCHDOG=1").await
34}
35
36/// Read the env and get the watchdog usec
37pub fn sd_watchdog_usec() -> Option<Duration> {
38    let usec_raw = env::var_os("WATCHDOG_USEC")?;
39    // OsStrings can contain data that are not valid &str, convert here.
40    let usec_str = usec_raw.to_str()?;
41    // Try to parse the string, convert Err to None and bubble up.
42    let usec = u64::from_str(usec_str).ok()?;
43    let dur = Duration::from_micros(usec);
44    Some(dur)
45}