"""systemd watchdog ping (sd_notify), stdlib-only. Restart=always only catches a process that DIES. It cannot catch a process that is alive but stuck — a v4l2 read blocking on a wedged USB controller, a HailoRT call that never returns, a sqlite lock. In that state the daemon keeps its PID, stops detecting, and the only signal is the dashboard turning the device offline 120s later: an unattended site then waits for a human to notice. WatchdogSec + this ping turns that into an automatic restart. No pysystemd dependency (the air-gapped bundle carries only wheels we vendor): the protocol is one datagram to $NOTIFY_SOCKET. """ import os import socket def sd_notify(state: str) -> bool: """Send a status datagram to systemd. Returns False when not running under systemd (NOTIFY_SOCKET unset) or on any socket error — never raises, because a telemetry failure must not take down detection.""" addr = os.environ.get("NOTIFY_SOCKET") if not addr: return False # AF_UNIX does not exist on Windows, where developers run the test suite. Guard rather than # let an AttributeError escape a function whose whole contract is "never raises". if not hasattr(socket, "AF_UNIX"): return False # Abstract namespace sockets start with '@' on Linux; the kernel expects a NUL byte. if addr.startswith("@"): addr = "\0" + addr[1:] try: with socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) as sock: sock.connect(addr) sock.sendall(state.encode()) return True except OSError: return False def ping() -> bool: """One 'I am still looping' keepalive.""" return sd_notify("WATCHDOG=1") def ready() -> bool: """Announce startup completion. Harmless under Type=exec; required if the unit ever switches to Type=notify.""" return sd_notify("READY=1")