Debian Codegraph @

man/notify-selfcontained-example.py

raw
1 #!/usr/bin/python
2 # SPDX-License-Identifier: MIT-0
3 #
4 # Implement the systemd notify protocol without external dependencies.
5 # Supports both readiness notification on startup and on reloading,
6 # according to the protocol defined at:
7 # https://www.freedesktop.org/software/systemd/man/latest/sd_notify.html
8 # This protocol is guaranteed to be stable as per:
9 # https://systemd.io/PORTABILITY_AND_STABILITY/
10
11 import errno
12 import os
13 import signal
14 import socket
15 import sys
16 import time
17
18 reloading = False
19 terminating = False
20
21
22 def notify(message):
23 if not message:
24 raise ValueError('notify() requires a message')
25
26 socket_path = os.environ.get('NOTIFY_SOCKET')
27 if not socket_path:
28 return
29
30 if socket_path[0] not in ('/', '@'):
31 raise OSError(errno.EAFNOSUPPORT, 'Unsupported socket type')
32
33 # Handle abstract socket.
34 if socket_path[0] == '@':
35 socket_path = '\0' + socket_path[1:]
36
37 with socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM | socket.SOCK_CLOEXEC) as sock:
38 sock.connect(socket_path)
39 sock.sendall(message)
40
41
42 def notify_ready():
43 notify(b'READY=1')
44
45
46 def notify_reloading():
47 microsecs = time.clock_gettime_ns(time.CLOCK_MONOTONIC) // 1000
48 notify(f'RELOADING=1\nMONOTONIC_USEC={microsecs}'.encode())
49
50
51 def notify_stopping():
52 notify(b'STOPPING=1')
53
54
55 def reload(signum, frame):
56 global reloading
57 reloading = True
58
59
60 def terminate(signum, frame):
61 global terminating
62 terminating = True
63
64
65 def main():
66 print('Doing initial setup')
67 global reloading, terminating
68
69 # Set up signal handlers.
70 print('Setting up signal handlers')
71 signal.signal(signal.SIGHUP, reload)
72 signal.signal(signal.SIGINT, terminate)
73 signal.signal(signal.SIGTERM, terminate)
74
75 # Do any other setup work here.
76
77 # Once all setup is done, signal readiness.
78 print('Done setting up')
79 notify_ready()
80
81 print('Starting loop')
82 while not terminating:
83 if reloading:
84 print('Reloading')
85 reloading = False
86
87 # Support notifying the manager when reloading configuration.
88 # This allows accurate state tracking as well as automatically
89 # enabling 'systemctl reload' without needing to manually
90 # specify an ExecReload= line in the unit file.
91
92 notify_reloading()
93
94 # Do some reconfiguration work here.
95
96 print('Done reloading')
97 notify_ready()
98
99 # Do the real work here ...
100
101 print('Sleeping for five seconds')
102 time.sleep(5)
103
104 print('Terminating')
105 notify_stopping()
106
107
108 if __name__ == '__main__':
109 sys.stdout.reconfigure(line_buffering=True)
110 print('Starting app')
111 main()
112 print('Stopped app')