Debian Codegraph @

upstream/debian-trixie/man3/sd_notify.3

raw
1 '\" t
2 .TH "SD_NOTIFY" "3" "" "systemd 257.13" "sd_notify"
3 .\" -----------------------------------------------------------------
4 .\" * Define some portability stuff
5 .\" -----------------------------------------------------------------
6 .\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
7 .\" http://bugs.debian.org/507673
8 .\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html
9 .\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
10 .ie \n(.g .ds Aq \(aq
11 .el .ds Aq '
12 .\" -----------------------------------------------------------------
13 .\" * set default formatting
14 .\" -----------------------------------------------------------------
15 .\" disable hyphenation
16 .nh
17 .\" disable justification (adjust text to left margin only)
18 .ad l
19 .\" -----------------------------------------------------------------
20 .\" * MAIN CONTENT STARTS HERE *
21 .\" -----------------------------------------------------------------
22 .SH "NAME"
23 sd_notify, sd_notifyf, sd_pid_notify, sd_pid_notifyf, sd_pid_notify_with_fds, sd_pid_notifyf_with_fds, sd_notify_barrier, sd_pid_notify_barrier \- Notify service manager about start\-up completion and other service status changes
24 .SH "SYNOPSIS"
25 .sp
26 .ft B
27 .nf
28 #include <systemd/sd\-daemon\&.h>
29 .fi
30 .ft
31 .HP \w'int\ sd_notify('u
32 .BI "int sd_notify(int\ " "unset_environment" ", const\ char\ *" "state" ");"
33 .HP \w'int\ sd_notifyf('u
34 .BI "int sd_notifyf(int\ " "unset_environment" ", const\ char\ *" "format" ", \&...);"
35 .HP \w'int\ sd_pid_notify('u
36 .BI "int sd_pid_notify(pid_t\ " "pid" ", int\ " "unset_environment" ", const\ char\ *" "state" ");"
37 .HP \w'int\ sd_pid_notifyf('u
38 .BI "int sd_pid_notifyf(pid_t\ " "pid" ", int\ " "unset_environment" ", const\ char\ *" "format" ", \&...);"
39 .HP \w'int\ sd_pid_notify_with_fds('u
40 .BI "int sd_pid_notify_with_fds(pid_t\ " "pid" ", int\ " "unset_environment" ", const\ char\ *" "state" ", const\ int\ *" "fds" ", unsigned\ " "n_fds" ");"
41 .HP \w'int\ sd_pid_notifyf_with_fds('u
42 .BI "int sd_pid_notifyf_with_fds(pid_t\ " "pid" ", int\ " "unset_environment" ", const\ int\ *" "fds" ", size_t\ " "n_fds" ", const\ char\ *" "format" ", \&...);"
43 .HP \w'int\ sd_notify_barrier('u
44 .BI "int sd_notify_barrier(int\ " "unset_environment" ", uint64_t\ " "timeout" ");"
45 .HP \w'int\ sd_pid_notify_barrier('u
46 .BI "int sd_pid_notify_barrier(pid_t\ " "pid" ", int\ " "unset_environment" ", uint64_t\ " "timeout" ");"
47 .SH "DESCRIPTION"
48 .PP
49 \fBsd_notify()\fR
50 may be called by a service to notify the service manager about state changes\&. It can be used to send arbitrary information, encoded in an environment\-block\-like string\&. Most importantly, it can be used for start\-up or reload completion notifications\&.
51 .PP
52 If the
53 \fIunset_environment\fR
54 parameter is non\-zero,
55 \fBsd_notify()\fR
56 will unset the
57 \fI$NOTIFY_SOCKET\fR
58 environment variable before returning (regardless of whether the function call itself succeeded or not)\&. Further calls to
59 \fBsd_notify()\fR
60 will then silently do nothing, and the variable is no longer inherited by child processes\&.
61 .PP
62 The
63 \fIstate\fR
64 parameter should contain a newline\-separated list of variable assignments, similar in style to an environment block\&. A trailing newline is implied if none is specified\&. The string may contain any kind of variable assignments, but see the next section for a list of assignments understood by the service manager\&.
65 .PP
66 Note that systemd will accept status data sent from a service only if the
67 \fINotifyAccess=\fR
68 option is correctly set in the service definition file\&. See
69 \fBsystemd.service\fR(5)
70 for details\&.
71 .PP
72 Note that
73 \fBsd_notify()\fR
74 notifications may be attributed to units correctly only if either the sending process is still around at the time PID 1 processes the message, or if the sending process is explicitly runtime\-tracked by the service manager\&. The latter is the case if the service manager originally forked off the process, i\&.e\&. on all processes that match
75 \fINotifyAccess=\fR\fBmain\fR
76 or
77 \fINotifyAccess=\fR\fBexec\fR\&. Conversely, if an auxiliary process of the unit sends an
78 \fBsd_notify()\fR
79 message and immediately exits, the service manager might not be able to properly attribute the message to the unit, and thus will ignore it, even if
80 \fINotifyAccess=\fR\fBall\fR
81 is set for it\&.
82 .PP
83 Hence, to eliminate all race conditions involving lookup of the client\*(Aqs unit and attribution of notifications to units correctly,
84 \fBsd_notify_barrier()\fR
85 may be used\&. This call acts as a synchronization point and ensures all notifications sent before this call have been picked up by the service manager when it returns successfully\&. Use of
86 \fBsd_notify_barrier()\fR
87 is needed for clients which are not invoked by the service manager, otherwise this synchronization mechanism is unnecessary for attribution of notifications to the unit\&.
88 .PP
89 \fBsd_notifyf()\fR
90 is similar to
91 \fBsd_notify()\fR
92 but takes a
93 \fBprintf()\fR\-like format string plus arguments\&.
94 .PP
95 \fBsd_pid_notify()\fR
96 and
97 \fBsd_pid_notifyf()\fR
98 are similar to
99 \fBsd_notify()\fR
100 and
101 \fBsd_notifyf()\fR
102 but take a process ID (PID) to use as originating PID for the message as first argument\&. This is useful to send notification messages on behalf of other processes, provided the appropriate privileges are available\&. Effectively, this means that a privileged invocation of
103 \fBsd_pid_notify()\fR
104 may circumvent
105 \fINotifyAccess=main\fR
106 or
107 \fINotifyAccess=exec\fR
108 restrictions enforced for a service\&. If the PID argument is specified as 0, the process ID of the calling process is used, in which case the calls are fully equivalent to
109 \fBsd_notify()\fR
110 and
111 \fBsd_notifyf()\fR\&.
112 .PP
113 \fBsd_pid_notify_with_fds()\fR
114 is similar to
115 \fBsd_pid_notify()\fR
116 but takes an additional array of file descriptors\&. These file descriptors are sent along the notification message to the service manager\&. This is particularly useful for sending
117 "FDSTORE=1"
118 messages, as described above\&. The additional arguments are a pointer to the file descriptor array plus the number of file descriptors in the array\&. If the number of file descriptors is passed as 0, the call is fully equivalent to
119 \fBsd_pid_notify()\fR, i\&.e\&. no file descriptors are passed\&. Note that file descriptors sent to the service manager on a message without
120 "FDSTORE=1"
121 are immediately closed on reception\&.
122 .PP
123 \fBsd_pid_notifyf_with_fds()\fR
124 is a combination of
125 \fBsd_pid_notify_with_fds()\fR
126 and
127 \fBsd_notifyf()\fR, i\&.e\&. it accepts both a PID and a set of file descriptors as input, and processes a format string to generate the state string\&.
128 .PP
129 \fBsd_notify_barrier()\fR
130 allows the caller to synchronize against reception of previously sent notification messages and uses the
131 \fIBARRIER=1\fR
132 command\&. It takes a relative
133 \fItimeout\fR
134 value in microseconds which is passed to
135 \fBppoll\fR(2)\&. A value of UINT64_MAX is interpreted as infinite timeout\&.
136 .PP
137 \fBsd_pid_notify_barrier()\fR
138 is just like
139 \fBsd_notify_barrier()\fR, but allows specifying the originating PID for the notification message\&.
140 .SH "WELL\-KNOWN ASSIGNMENTS"
141 .PP
142 The following assignments have a defined meaning:
143 .PP
144 READY=1
145 .RS 4
146 Tells the service manager that service startup is finished, or the service finished re\-loading its configuration\&. This is only used by systemd if the service definition file has
147 \fIType=notify\fR
148 or
149 \fIType=notify\-reload\fR
150 set\&. Since there is little value in signaling non\-readiness, the only value services should send is
151 "READY=1"
152 (i\&.e\&.
153 "READY=0"
154 is not defined)\&.
155 .RE
156 .PP
157 RELOADING=1
158 .RS 4
159 Tells the service manager that the service is beginning to reload its configuration\&. This is useful to allow the service manager to track the service\*(Aqs internal state, and present it to the user\&. Note that a service that sends this notification must also send a
160 "READY=1"
161 notification when it completed reloading its configuration\&. Reloads the service manager is notified about with this mechanisms are propagated in the same way as they are when originally initiated through the service manager\&. This message is particularly relevant for
162 \fIType=notify\-reload\fR
163 services, to inform the service manager that the request to reload the service has been received and is now being processed\&.
164 .sp
165 Added in version 217\&.
166 .RE
167 .PP
168 STOPPING=1
169 .RS 4
170 Tells the service manager that the service is beginning its shutdown\&. This is useful to allow the service manager to track the service\*(Aqs internal state, and present it to the user\&.
171 .sp
172 Added in version 217\&.
173 .RE
174 .PP
175 MONOTONIC_USEC=\&...
176 .RS 4
177 A field carrying the monotonic timestamp (as per
178 \fBCLOCK_MONOTONIC\fR) formatted in decimal in μs, when the notification message was generated by the client\&. This is typically used in combination with
179 "RELOADING=1", to allow the service manager to properly synchronize reload cycles\&. See
180 \fBsystemd.service\fR(5)
181 for details, specifically
182 "Type=notify\-reload"\&.
183 .sp
184 Added in version 253\&.
185 .RE
186 .PP
187 STATUS=\&...
188 .RS 4
189 Passes a single\-line UTF\-8 status string back to the service manager that describes the service state\&. This is free\-form and can be used for various purposes: general state feedback, fsck\-like programs could pass completion percentages and failing programs could pass a human\-readable error message\&. Example:
190 "STATUS=Completed 66% of file system check\&..."
191 .sp
192 Added in version 233\&.
193 .RE
194 .PP
195 NOTIFYACCESS=\&...
196 .RS 4
197 Reset the access to the service status notification socket during runtime, overriding
198 \fINotifyAccess=\fR
199 setting in the service unit file\&. See
200 \fBsystemd.service\fR(5)
201 for details, specifically
202 "NotifyAccess="
203 for a list of accepted values\&.
204 .sp
205 Added in version 254\&.
206 .RE
207 .PP
208 ERRNO=\&...
209 .RS 4
210 If a service fails, the errno\-style error code, formatted as string\&. Example:
211 "ERRNO=2"
212 for ENOENT\&.
213 .sp
214 Added in version 233\&.
215 .RE
216 .PP
217 BUSERROR=\&...
218 .RS 4
219 If a service fails, the D\-Bus error\-style error code\&. Example:
220 "BUSERROR=org\&.freedesktop\&.DBus\&.Error\&.TimedOut"\&.
221 .sp
222 Added in version 233\&.
223 .RE
224 .PP
225 VARLINKERROR=\&...
226 .RS 4
227 If a service fails, the Varlink error\-style error code\&. Example:
228 "VARLINKERROR=org\&.varlink\&.service\&.InvalidParameter"\&.
229 .sp
230 Added in version 257\&.
231 .RE
232 .PP
233 EXIT_STATUS=\&...
234 .RS 4
235 The exit status of a service or the manager itself\&. Note that
236 \fBsystemd\fR
237 currently does not consume this value when sent by services, so this assignment is only informational\&. The manager will send this notification to
238 \fIits\fR
239 notification socket, which may be used to collect an exit status from the system (a container or VM) as it shuts down\&. For example,
240 \fBmkosi\fR(1)
241 makes use of this\&. The value to return may be set via the
242 \fBsystemctl\fR(1)
243 \fBexit\fR
244 verb\&.
245 .sp
246 Added in version 254\&.
247 .RE
248 .PP
249 MAINPID=\&...
250 .RS 4
251 Change the main process ID (PID) of the service\&. This is especially useful in the case where the real main process is not directly forked off by the service manager\&. Example:
252 "MAINPID=4711"\&.
253 .sp
254 Added in version 233\&.
255 .RE
256 .PP
257 MAINPIDFDID=\&...
258 .RS 4
259 The pidfd inode number of the new main process (specified through
260 \fIMAINPID=\fR)\&. This information can be acquired through
261 \fBfstat\fR(2)
262 on the pidfd and is used to identify the process in a race\-free fashion\&. Alternatively, a pidfd can be sent directly to the service manager (see
263 \fIMAINPIDFD=1\fR
264 below)\&.
265 .sp
266 Added in version 257\&.
267 .RE
268 .PP
269 MAINPIDFD=1
270 .RS 4
271 Similar to
272 \fIMAINPID=\fR
273 with
274 \fIMAINPIDFDID=\fR, but the process is referenced directly by the pidfd passed to the service manager\&. This is useful if pidfd id is not supported on the system\&. Exactly one fd is expected for this notification\&.
275 .sp
276 Added in version 257\&.
277 .RE
278 .PP
279 WATCHDOG=1
280 .RS 4
281 Tells the service manager to update the watchdog timestamp\&. This is the keep\-alive ping that services need to issue in regular intervals if
282 \fIWatchdogSec=\fR
283 is enabled for it\&. See
284 \fBsystemd.service\fR(5)
285 for information how to enable this functionality and
286 \fBsd_watchdog_enabled\fR(3)
287 for the details of how the service can check whether the watchdog is enabled\&.
288 .RE
289 .PP
290 WATCHDOG=trigger
291 .RS 4
292 Tells the service manager that the service detected an internal error that should be handled by the configured watchdog options\&. This will trigger the same behaviour as if
293 \fIWatchdogSec=\fR
294 is enabled and the service did not send
295 "WATCHDOG=1"
296 in time\&. Note that
297 \fIWatchdogSec=\fR
298 does not need to be enabled for
299 "WATCHDOG=trigger"
300 to trigger the watchdog action\&. See
301 \fBsystemd.service\fR(5)
302 for information about the watchdog behavior\&.
303 .sp
304 Added in version 243\&.
305 .RE
306 .PP
307 WATCHDOG_USEC=\&...
308 .RS 4
309 Reset
310 \fIwatchdog_usec\fR
311 value during runtime\&. Notice that this is not available when using
312 \fBsd_event_set_watchdog()\fR
313 or
314 \fBsd_watchdog_enabled()\fR\&. Example :
315 "WATCHDOG_USEC=20000000"
316 .sp
317 Added in version 233\&.
318 .RE
319 .PP
320 EXTEND_TIMEOUT_USEC=\&...
321 .RS 4
322 Tells the service manager to extend the startup, runtime or shutdown service timeout corresponding the current state\&. The value specified is a time in microseconds during which the service must send a new message\&. A service timeout will occur if the message is not received, but only if the runtime of the current state is beyond the original maximum times of
323 \fITimeoutStartSec=\fR,
324 \fIRuntimeMaxSec=\fR, and
325 \fITimeoutStopSec=\fR\&. See
326 \fBsystemd.service\fR(5)
327 for effects on the service timeouts\&.
328 .sp
329 Added in version 236\&.
330 .RE
331 .PP
332 FDSTORE=1
333 .RS 4
334 Store file descriptors in the service manager\&. File descriptors sent this way will be held for the service by the service manager and will later be handed back using the usual file descriptor passing logic at the next start or restart of the service, see
335 \fBsd_listen_fds\fR(3)\&. Any open sockets and other file descriptors which should not be closed during a restart may be stored this way\&. When a service is stopped, its file descriptor store is discarded and all file descriptors in it are closed, except when overridden with
336 \fIFileDescriptorStorePreserve=\fR, see
337 \fBsystemd.service\fR(5)\&.
338 .sp
339 The service manager will accept messages for a service only if its
340 \fIFileDescriptorStoreMax=\fR
341 setting is non\-zero (defaults to zero, see
342 \fBsystemd.service\fR(5))\&. The service manager will set the
343 \fI$FDSTORE\fR
344 environment variable for services that have the file descriptor store enabled, see
345 \fBsystemd.exec\fR(5)\&.
346 .sp
347 If
348 \fIFDPOLL=0\fR
349 is not set and the file descriptors are pollable (see
350 \fBepoll_ctl\fR(2)), then any
351 \fBEPOLLHUP\fR
352 or
353 \fBEPOLLERR\fR
354 event seen on them will result in their automatic removal from the store\&.
355 .sp
356 Multiple sets of file descriptors may be sent in separate messages, in which case the sets are combined\&. The service manager removes duplicate file descriptors (those pointing to the same object) before passing them to the service\&.
357 .sp
358 This functionality should be used to implement services that can restart after an explicit request or a crash without losing state\&. Application state can either be serialized to a file in
359 /run/, or better, stored in a
360 \fBmemfd_create\fR(2)
361 memory file descriptor\&. Use
362 \fBsd_pid_notify_with_fds()\fR
363 to send messages with
364 "FDSTORE=1"\&. It is recommended to combine
365 \fIFDSTORE=\fR
366 with
367 \fIFDNAME=\fR
368 to make it easier to manage the stored file descriptors\&.
369 .sp
370 For further information on the file descriptor store see the
371 \m[blue]\fBFile Descriptor Store\fR\m[]\&\s-2\u[1]\d\s+2
372 overview\&.
373 .sp
374 Added in version 219\&.
375 .RE
376 .PP
377 FDSTOREREMOVE=1
378 .RS 4
379 Removes file descriptors from the file descriptor store\&. This field needs to be combined with
380 \fIFDNAME=\fR
381 to specify the name of the file descriptors to remove\&.
382 .sp
383 Added in version 236\&.
384 .RE
385 .PP
386 FDNAME=\&...
387 .RS 4
388 When used in combination with
389 \fIFDSTORE=1\fR, specifies a name for the submitted file descriptors\&. When used with
390 \fIFDSTOREREMOVE=1\fR, specifies the name for the file descriptors to remove\&. This name is passed to the service during activation, and may be queried using
391 \fBsd_listen_fds_with_names\fR(3)\&. File descriptors submitted without this field will be called
392 "stored"\&.
393 .sp
394 The name may consist of arbitrary ASCII characters except control characters or
395 ":"\&. It may not be longer than 255 characters\&. If a submitted name does not follow these restrictions, it is ignored\&.
396 .sp
397 Note that if multiple file descriptors are submitted in a single message, the specified name will be used for all of them\&. In order to assign different names to submitted file descriptors, submit them in separate messages\&.
398 .sp
399 Added in version 233\&.
400 .RE
401 .PP
402 FDPOLL=0
403 .RS 4
404 When used in combination with
405 \fIFDSTORE=1\fR, disables polling of the submitted file descriptors regardless of whether or not they are pollable\&. As this option disables automatic cleanup of the submitted file descriptors on EPOLLERR and EPOLLHUP, care must be taken to ensure proper manual cleanup\&. Use of this option is not generally recommended except for when automatic cleanup has unwanted behavior such as prematurely discarding file descriptors from the store\&.
406 .sp
407 Added in version 246\&.
408 .RE
409 .PP
410 BARRIER=1
411 .RS 4
412 Tells the service manager that the client is explicitly requesting synchronization by means of closing the file descriptor sent with this command\&. The service manager guarantees that the processing of a
413 \fIBARRIER=1\fR
414 command will only happen after all previous notification messages sent before this command have been processed\&. Hence, this command accompanied with a single file descriptor can be used to synchronize against reception of all previous status messages\&. Note that this command cannot be mixed with other notifications, and has to be sent in a separate message to the service manager, otherwise all assignments will be ignored\&. Note that sending 0 or more than 1 file descriptor with this command is a violation of the protocol\&.
415 .sp
416 Added in version 246\&.
417 .RE
418 .PP
419 The notification messages sent by services are interpreted by the service manager\&. Unknown assignments are ignored\&. Thus, it is safe (but often without effect) to send assignments which are not in this list\&. The protocol is extensible, but care should be taken to ensure private extensions are recognizable as such\&. Specifically, it is recommend to prefix them with
420 "X_"
421 followed by some namespace identifier\&. The service manager also sends some messages to
422 \fIits\fR
423 notification socket, which may then consumed by a supervising machine or container manager further up the stack\&. The service manager sends a number of extension fields, for example
424 \fIX_SYSTEMD_UNIT_ACTIVE=\fR, for details see
425 \fBsystemd\fR(1)\&.
426 .SH "RETURN VALUE"
427 .PP
428 On failure, these calls return a negative errno\-style error code\&. If
429 \fI$NOTIFY_SOCKET\fR
430 was not set and hence no status message could be sent, 0 is returned\&. If the status was sent, these functions return a positive value\&. In order to support both service managers that implement this scheme and those which do not, it is generally recommended to ignore the return value of this call\&. Note that the return value simply indicates whether the notification message was enqueued properly, it does not reflect whether the message could be processed successfully\&. Specifically, no error is returned when a file descriptor is attempted to be stored using
431 \fIFDSTORE=1\fR
432 but the service is not actually configured to permit storing of file descriptors (see above)\&.
433 .SS "Errors"
434 .PP
435 Returned errors may indicate the following problems:
436 .PP
437 \fB\-E2BIG\fR
438 .RS 4
439 More file descriptors passed at once than the system allows\&. On Linux the number of file descriptors that may be passed across
440 \fBAF_UNIX\fR
441 sockets at once is 253, see
442 \fBunix\fR(7)
443 for details\&.
444 .sp
445 Added in version 257\&.
446 .RE
447 .SH "NOTES"
448 .PP
449 Functions described here are available as a shared library, which can be compiled against and linked to with the
450 \fBlibsystemd\fR\ \&\fBpkg-config\fR(1)
451 file\&.
452 .PP
453 The code described here uses
454 \fBgetenv\fR(3), which is declared to be not multi\-thread\-safe\&. This means that the code calling the functions described here must not call
455 \fBsetenv\fR(3)
456 from a parallel thread\&. It is recommended to only do calls to
457 \fBsetenv()\fR
458 from an early phase of the program when no other threads have been started\&.
459 .PP
460 These functions send a single datagram with the state string as payload to the socket referenced in the
461 \fI$NOTIFY_SOCKET\fR
462 environment variable\&. If the first character of
463 \fI$NOTIFY_SOCKET\fR
464 is
465 "/"
466 or
467 "@", the string is understood as an
468 \fBAF_UNIX\fR
469 or Linux abstract namespace socket (respectively), and in both cases the datagram is accompanied by the process credentials of the sending service, using SCM_CREDENTIALS\&. If the string starts with
470 "vsock:"
471 then the string is understood as an
472 \fBAF_VSOCK\fR
473 address, which is useful for hypervisors/VMMs or other processes on the host to receive a notification when a virtual machine has finished booting\&. Note that in case the hypervisor does not support
474 \fBSOCK_DGRAM\fR
475 over
476 \fBAF_VSOCK\fR,
477 \fBSOCK_SEQPACKET\fR
478 will be used instead\&.
479 "vsock\-stream",
480 "vsock\-dgram"
481 and
482 "vsock\-seqpacket"
483 can be used instead of
484 "vsock"
485 to force usage of the corresponding socket type\&. The address should be in the form:
486 "vsock:CID:PORT"\&. Note that unlike other uses of vsock, the CID is mandatory and cannot be
487 "VMADDR_CID_ANY"\&. Note that PID1 will send the VSOCK packets from a privileged port (i\&.e\&.: lower than 1024), as an attempt to address concerns that unprivileged processes in the guest might try to send malicious notifications to the host, driving it to make destructive decisions based on them\&.
488 .SS "Standalone Implementations"
489 .PP
490 Note that, while using this library should be preferred in order to avoid code duplication, it is also possible to reimplement the simple readiness notification protocol without external dependencies, as demonstrated in the following self\-contained examples from several languages:
491 .sp
492 .it 1 an-trap
493 .nr an-no-space-flag 1
494 .nr an-break-flag 1
495 .br
496 .ps +1
497 \fBC\fR
498 .RS 4
499 .sp
500 .if n \{\
501 .RS 4
502 .\}
503 .nf
504 /* SPDX\-License\-Identifier: MIT\-0 */
505
506 /* Implement the systemd notify protocol without external dependencies\&.
507 * Supports both readiness notification on startup and on reloading,
508 * according to the protocol defined at:
509 * https://www\&.freedesktop\&.org/software/systemd/man/latest/sd_notify\&.html
510 * This protocol is guaranteed to be stable as per:
511 * https://systemd\&.io/PORTABILITY_AND_STABILITY/ */
512
513 #define _GNU_SOURCE 1
514 #include <errno\&.h>
515 #include <inttypes\&.h>
516 #include <signal\&.h>
517 #include <stdbool\&.h>
518 #include <stddef\&.h>
519 #include <stdlib\&.h>
520 #include <stdio\&.h>
521 #include <string\&.h>
522 #include <sys/socket\&.h>
523 #include <sys/un\&.h>
524 #include <time\&.h>
525 #include <unistd\&.h>
526
527 #define _cleanup_(f) __attribute__((cleanup(f)))
528
529 static void closep(int *fd) {
530 if (!fd || *fd < 0)
531 return;
532
533 close(*fd);
534 *fd = \-1;
535 }
536
537 static int notify(const char *message) {
538 union sockaddr_union {
539 struct sockaddr sa;
540 struct sockaddr_un sun;
541 } socket_addr = {
542 \&.sun\&.sun_family = AF_UNIX,
543 };
544 size_t path_length, message_length;
545 _cleanup_(closep) int fd = \-1;
546 const char *socket_path;
547
548 /* Verify the argument first */
549 if (!message)
550 return \-EINVAL;
551
552 message_length = strlen(message);
553 if (message_length == 0)
554 return \-EINVAL;
555
556 /* If the variable is not set, the protocol is a noop */
557 socket_path = getenv("NOTIFY_SOCKET");
558 if (!socket_path)
559 return 0; /* Not set? Nothing to do */
560
561 /* Only AF_UNIX is supported, with path or abstract sockets */
562 if (socket_path[0] != \*(Aq/\*(Aq && socket_path[0] != \*(Aq@\*(Aq)
563 return \-EAFNOSUPPORT;
564
565 path_length = strlen(socket_path);
566 /* Ensure there is room for NUL byte */
567 if (path_length >= sizeof(socket_addr\&.sun\&.sun_path))
568 return \-E2BIG;
569
570 memcpy(socket_addr\&.sun\&.sun_path, socket_path, path_length);
571
572 /* Support for abstract socket */
573 if (socket_addr\&.sun\&.sun_path[0] == \*(Aq@\*(Aq)
574 socket_addr\&.sun\&.sun_path[0] = 0;
575
576 fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0);
577 if (fd < 0)
578 return \-errno;
579
580 if (connect(fd, &socket_addr\&.sa, offsetof(struct sockaddr_un, sun_path) + path_length) != 0)
581 return \-errno;
582
583 ssize_t written = write(fd, message, message_length);
584 if (written != (ssize_t) message_length)
585 return written < 0 ? \-errno : \-EPROTO;
586
587 return 1; /* Notified! */
588 }
589
590 static int notify_ready(void) {
591 return notify("READY=1");
592 }
593
594 static int notify_reloading(void) {
595 /* A buffer with length sufficient to format the maximum UINT64 value\&. */
596 char reload_message[sizeof("RELOADING=1\enMONOTONIC_USEC=18446744073709551615")];
597 struct timespec ts;
598 uint64_t now;
599
600 /* Notify systemd that we are reloading, including a CLOCK_MONOTONIC timestamp in usec
601 * so that the program is compatible with a Type=notify\-reload service\&. */
602
603 if (clock_gettime(CLOCK_MONOTONIC, &ts) < 0)
604 return \-errno;
605
606 if (ts\&.tv_sec < 0 || ts\&.tv_nsec < 0 ||
607 (uint64_t) ts\&.tv_sec > (UINT64_MAX \- (ts\&.tv_nsec / 1000ULL)) / 1000000ULL)
608 return \-EINVAL;
609
610 now = (uint64_t) ts\&.tv_sec * 1000000ULL + (uint64_t) ts\&.tv_nsec / 1000ULL;
611
612 if (snprintf(reload_message, sizeof(reload_message), "RELOADING=1\enMONOTONIC_USEC=%" PRIu64, now) < 0)
613 return \-EINVAL;
614
615 return notify(reload_message);
616 }
617
618 static int notify_stopping(void) {
619 return notify("STOPPING=1");
620 }
621
622 static volatile sig_atomic_t reloading = 0;
623 static volatile sig_atomic_t terminating = 0;
624
625 static void signal_handler(int sig) {
626 if (sig == SIGHUP)
627 reloading = 1;
628 else if (sig == SIGINT || sig == SIGTERM)
629 terminating = 1;
630 }
631
632 int main(int argc, char **argv) {
633 struct sigaction sa = {
634 \&.sa_handler = signal_handler,
635 \&.sa_flags = SA_RESTART,
636 };
637 int r;
638
639 /* Setup signal handlers */
640 sigemptyset(&sa\&.sa_mask);
641 sigaction(SIGHUP, &sa, NULL);
642 sigaction(SIGINT, &sa, NULL);
643 sigaction(SIGTERM, &sa, NULL);
644
645 /* Do more service initialization work here \&... */
646
647 /* Now that all the preparations steps are done, signal readiness */
648
649 r = notify_ready();
650 if (r < 0) {
651 fprintf(stderr, "Failed to notify readiness to $NOTIFY_SOCKET: %s\en", strerror(\-r));
652 return EXIT_FAILURE;
653 }
654
655 while (!terminating) {
656 if (reloading) {
657 reloading = false;
658
659 /* As a separate but related feature, we can also notify the manager
660 * when reloading configuration\&. This allows accurate state\-tracking,
661 * and also automated hook\-in of \*(Aqsystemctl reload\*(Aq without having to
662 * specify manually an ExecReload= line in the unit file\&. */
663
664 r = notify_reloading();
665 if (r < 0) {
666 fprintf(stderr, "Failed to notify reloading to $NOTIFY_SOCKET: %s\en", strerror(\-r));
667 return EXIT_FAILURE;
668 }
669
670 /* Do some reconfiguration work here \&... */
671
672 r = notify_ready();
673 if (r < 0) {
674 fprintf(stderr, "Failed to notify readiness to $NOTIFY_SOCKET: %s\en", strerror(\-r));
675 return EXIT_FAILURE;
676 }
677 }
678
679 /* Do some daemon work here \&... */
680 sleep(5);
681 }
682
683 r = notify_stopping();
684 if (r < 0) {
685 fprintf(stderr, "Failed to report termination to $NOTIFY_SOCKET: %s\en", strerror(\-r));
686 return EXIT_FAILURE;
687 }
688
689 /* Do some shutdown work here \&... */
690
691 return EXIT_SUCCESS;
692 }
693 .fi
694 .if n \{\
695 .RE
696 .\}
697 .RE
698 .sp
699 .it 1 an-trap
700 .nr an-no-space-flag 1
701 .nr an-break-flag 1
702 .br
703 .ps +1
704 \fBPython\fR
705 .RS 4
706 .sp
707 .if n \{\
708 .RS 4
709 .\}
710 .nf
711 #!/usr/bin/env python3
712 # SPDX\-License\-Identifier: MIT\-0
713 #
714 # Implement the systemd notify protocol without external dependencies\&.
715 # Supports both readiness notification on startup and on reloading,
716 # according to the protocol defined at:
717 # https://www\&.freedesktop\&.org/software/systemd/man/latest/sd_notify\&.html
718 # This protocol is guaranteed to be stable as per:
719 # https://systemd\&.io/PORTABILITY_AND_STABILITY/
720
721 import errno
722 import os
723 import signal
724 import socket
725 import sys
726 import time
727
728 reloading = False
729 terminating = False
730
731 def notify(message):
732 if not message:
733 raise ValueError("notify() requires a message")
734
735 socket_path = os\&.environ\&.get("NOTIFY_SOCKET")
736 if not socket_path:
737 return
738
739 if socket_path[0] not in ("/", "@"):
740 raise OSError(errno\&.EAFNOSUPPORT, "Unsupported socket type")
741
742 # Handle abstract socket\&.
743 if socket_path[0] == "@":
744 socket_path = "\e0" + socket_path[1:]
745
746 with socket\&.socket(socket\&.AF_UNIX, socket\&.SOCK_DGRAM | socket\&.SOCK_CLOEXEC) as sock:
747 sock\&.connect(socket_path)
748 sock\&.sendall(message)
749
750 def notify_ready():
751 notify(b"READY=1")
752
753 def notify_reloading():
754 microsecs = time\&.clock_gettime_ns(time\&.CLOCK_MONOTONIC) // 1000
755 notify(f"RELOADING=1\enMONOTONIC_USEC={microsecs}"\&.encode())
756
757 def notify_stopping():
758 notify(b"STOPPING=1")
759
760 def reload(signum, frame):
761 global reloading
762 reloading = True
763
764 def terminate(signum, frame):
765 global terminating
766 terminating = True
767
768 def main():
769 print("Doing initial setup")
770 global reloading, terminating
771
772 # Set up signal handlers\&.
773 print("Setting up signal handlers")
774 signal\&.signal(signal\&.SIGHUP, reload)
775 signal\&.signal(signal\&.SIGINT, terminate)
776 signal\&.signal(signal\&.SIGTERM, terminate)
777
778 # Do any other setup work here\&.
779
780 # Once all setup is done, signal readiness\&.
781 print("Done setting up")
782 notify_ready()
783
784 print("Starting loop")
785 while not terminating:
786 if reloading:
787 print("Reloading")
788 reloading = False
789
790 # Support notifying the manager when reloading configuration\&.
791 # This allows accurate state tracking as well as automatically
792 # enabling \*(Aqsystemctl reload\*(Aq without needing to manually
793 # specify an ExecReload= line in the unit file\&.
794
795 notify_reloading()
796
797 # Do some reconfiguration work here\&.
798
799 print("Done reloading")
800 notify_ready()
801
802 # Do the real work here \&.\&.\&.
803
804 print("Sleeping for five seconds")
805 time\&.sleep(5)
806
807 print("Terminating")
808 notify_stopping()
809
810 if __name__ == "__main__":
811 sys\&.stdout\&.reconfigure(line_buffering=True)
812 print("Starting app")
813 main()
814 print("Stopped app")
815 .fi
816 .if n \{\
817 .RE
818 .\}
819 .RE
820 .SH "ENVIRONMENT"
821 .PP
822 \fI$NOTIFY_SOCKET\fR
823 .RS 4
824 Set by the service manager for supervised processes for status and start\-up completion notification\&. This environment variable specifies the socket
825 \fBsd_notify()\fR
826 talks to\&. See above for details\&.
827 .RE
828 .SH "EXAMPLES"
829 .PP
830 \fBExample\ \&1.\ \&Start\-up Notification\fR
831 .PP
832 When a service finished starting up, it might issue the following call to notify the service manager:
833 .sp
834 .if n \{\
835 .RS 4
836 .\}
837 .nf
838 sd_notify(0, "READY=1");
839 .fi
840 .if n \{\
841 .RE
842 .\}
843 .PP
844 \fBExample\ \&2.\ \&Extended Start\-up Notification\fR
845 .PP
846 A service could send the following after completing initialization:
847 .sp
848 .if n \{\
849 .RS 4
850 .\}
851 .nf
852 sd_notifyf(0, "READY=1\en"
853 "STATUS=Processing requests\&...\en"
854 "MAINPID=%lu",
855 (unsigned long) getpid());
856 .fi
857 .if n \{\
858 .RE
859 .\}
860 .PP
861 \fBExample\ \&3.\ \&Error Cause Notification\fR
862 .PP
863 A service could send the following shortly before exiting, on failure:
864 .sp
865 .if n \{\
866 .RS 4
867 .\}
868 .nf
869 sd_notifyf(0, "STATUS=Failed to start up: %s\en"
870 "ERRNO=%i",
871 strerror_r(errnum, (char[1024]){}, 1024),
872 errnum);
873 .fi
874 .if n \{\
875 .RE
876 .\}
877 .PP
878 \fBExample\ \&4.\ \&Store a File Descriptor in the Service Manager\fR
879 .PP
880 To store an open file descriptor in the service manager, in order to continue operation after a service restart without losing state, use
881 "FDSTORE=1":
882 .sp
883 .if n \{\
884 .RS 4
885 .\}
886 .nf
887 sd_pid_notify_with_fds(0, 0, "FDSTORE=1\enFDNAME=foobar", &fd, 1);
888 .fi
889 .if n \{\
890 .RE
891 .\}
892 .PP
893 \fBExample\ \&5.\ \&Eliminating race conditions\fR
894 .PP
895 When the client sending the notifications is not spawned by the service manager, it may exit too quickly and the service manager may fail to attribute them correctly to the unit\&. To prevent such races, use
896 \fBsd_notify_barrier()\fR
897 to synchronize against reception of all notifications sent before this call is made\&.
898 .sp
899 .if n \{\
900 .RS 4
901 .\}
902 .nf
903 sd_notify(0, "READY=1");
904 /* set timeout to 5 seconds */
905 sd_notify_barrier(0, 5 * 1000000);
906 .fi
907 .if n \{\
908 .RE
909 .\}
910 .SH "HISTORY"
911 .PP
912 \fBsd_pid_notify()\fR,
913 \fBsd_pid_notifyf()\fR, and
914 \fBsd_pid_notify_with_fds()\fR
915 were added in version 219\&.
916 .PP
917 \fBsd_notify_barrier()\fR
918 was added in version 246\&.
919 .PP
920 \fBsd_pid_notifyf_with_fds()\fR
921 and
922 \fBsd_pid_notify_barrier()\fR
923 were added in version 254\&.
924 .SH "SEE ALSO"
925 .PP
926 \fBsystemd\fR(1), \fBsd-daemon\fR(3), \fBsd_listen_fds\fR(3), \fBsd_listen_fds_with_names\fR(3), \fBsd_watchdog_enabled\fR(3), \fBdaemon\fR(7), \fBsystemd.service\fR(5)
927 .SH "NOTES"
928 .IP " 1." 4
929 File Descriptor Store
930 .RS 4
931 \%https://systemd.io/FILE_DESCRIPTOR_STORE
932 .RE