Skip to content

Commit

Permalink
daemon.notify accepts multiple args
Browse files Browse the repository at this point in the history
  • Loading branch information
miccoli committed Aug 27, 2023
1 parent 7e36c36 commit d85dba2
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 8 deletions.
29 changes: 22 additions & 7 deletions src/trick17/daemon.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,18 +65,33 @@ def listen_fds() -> Iterator[tuple[int, str]]:
return zip(fds, names, strict=True)


def notify(state: str) -> bool:
"""notify 'state' to systemd; returns
def notify(*msg: str) -> bool:
"""notify '*msg' messages to systemd;
returns
- True if notification sent to socket,
- False if environment variable with notification socket is not set."""

sock_path: str = os.getenv(trick17.SD_NOTIFY_SOCKET_ENV, "")
if not sock_path:
return False

if not sock_path.startswith("/"):
msg = f"notify to socket type '{sock_path}' not supported"
raise NotImplementedError(msg)
with util.make_socket() as sock:
util.send_dgram_or_fd(sock, state.encode(), sock_path)
state = "\n".join(m.strip() for m in msg)

match sock_path.split(":"):
case [dest] if dest.startswith("/"):
# AF_UNIX
with util.make_socket() as sock:
util.send_dgram_or_fd(sock, state.encode(), sock_path)
case [dest] if dest.startswith("@"):
# Linux abstract namespace socket
errmsg = f"Abstract namespace sockets not implemented ('{sock_path}')"
raise NotImplementedError(errmsg)
case ["vsock", cid, port]: # noqa: F841
# AF_VSOCK
errmsg = f"AF_VSOCK sockets not implemented ('{sock_path}')"
raise NotImplementedError(errmsg)
case _:
errmsg = f"Unrecognized type of socket: {sock_path}"
raise ValueError(errmsg)

return True
2 changes: 1 addition & 1 deletion tests/test_daemon.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ def test_booted():


def test_notify():
ret = daemon.notify("READY=1")
ret = daemon.notify("READY=1", "STATUS=running")
assert ret is False


Expand Down
16 changes: 16 additions & 0 deletions tests/tnotify.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
#!/usr/bin/env python
import sys

from trick17 import daemon


def main():
ok = daemon.notify("READY=1", "STATUS=notified")
if ok:
sys.exit(0)
else:
sys.exit("Unable to send notification")


if __name__ == "__main__":
main()
2 changes: 2 additions & 0 deletions tests/tnotify.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
#!/bin/sh
systemd-run --user --wait --service-type=notify -d -E PYTHONPATH=src tests/tnotify.py

0 comments on commit d85dba2

Please sign in to comment.