"""sd_notify: the one line the node says to systemd.
Separate because it touches a socket and nothing else here does; the
config module should not need `socket`.
"""
from __future__ import annotations
import os
import socket
[docs]def sd_notify(state: str) -> bool:
"""Send state notification to systemd's service manager via NOTIFY_SOCKET.
Zero-dependency Unix datagram implementation supporting filesystem and abstract sockets.
Returns True if sent successfully, False otherwise.
"""
notify_socket = os.environ.get('NOTIFY_SOCKET')
if not notify_socket:
return False
if notify_socket.startswith('@'):
notify_socket = '\0' + notify_socket[1:]
try:
sock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
try:
payload = state.encode('utf-8')
if not payload.endswith(b'\n'):
payload += b'\n'
sock.sendto(payload, notify_socket)
return True
finally:
sock.close()
except Exception:
return False