Debian Codegraph @

upstream/fedora-44/man3/sd_notify.3

raw
1 '\" t
2 .TH "SD_NOTIFY" "3" "" "systemd 259.5" "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 \fBsd_pidfd_get_inode_id\fR(3)
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 RESTART_RESET=1
333 .RS 4
334 Reset the restart counter of the service, which has the effect of restoring the restart duration to
335 \fIRestartSec=\fR
336 if
337 \fIRestartSteps=\fR
338 and
339 \fIRestartMaxDelaySec=\fR
340 are in use\&. For more information, refer to
341 \fBsystemd.service\fR(5)\&.
342 .sp
343 Added in version 258\&.
344 .RE
345 .PP
346 FDSTORE=1
347 .RS 4
348 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
349 \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
350 \fIFileDescriptorStorePreserve=\fR, see
351 \fBsystemd.service\fR(5)\&.
352 .sp
353 The service manager will accept messages for a service only if its
354 \fIFileDescriptorStoreMax=\fR
355 setting is non\-zero (defaults to zero, see
356 \fBsystemd.service\fR(5))\&. The service manager will set the
357 \fI$FDSTORE\fR
358 environment variable for services that have the file descriptor store enabled, see
359 \fBsystemd.exec\fR(5)\&.
360 .sp
361 If
362 \fIFDPOLL=0\fR
363 is not set and the file descriptors are pollable (see
364 \fBepoll_ctl\fR(2)), then any
365 \fBEPOLLHUP\fR
366 or
367 \fBEPOLLERR\fR
368 event seen on them will result in their automatic removal from the store\&.
369 .sp
370 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\&.
371 .sp
372 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
373 /run/, or better, stored in a
374 \fBmemfd_create\fR(2)
375 memory file descriptor\&. Use
376 \fBsd_pid_notify_with_fds()\fR
377 to send messages with
378 "FDSTORE=1"\&. It is recommended to combine
379 \fIFDSTORE=\fR
380 with
381 \fIFDNAME=\fR
382 to make it easier to manage the stored file descriptors\&.
383 .sp
384 For further information on the file descriptor store see the
385 \m[blue]\fBFile Descriptor Store\fR\m[]\&\s-2\u[1]\d\s+2
386 overview\&.
387 .sp
388 Added in version 219\&.
389 .RE
390 .PP
391 FDSTOREREMOVE=1
392 .RS 4
393 Removes file descriptors from the file descriptor store\&. This field needs to be combined with
394 \fIFDNAME=\fR
395 to specify the name of the file descriptors to remove\&.
396 .sp
397 Added in version 236\&.
398 .RE
399 .PP
400 FDNAME=\&...
401 .RS 4
402 When used in combination with
403 \fIFDSTORE=1\fR, specifies a name for the submitted file descriptors\&. When used with
404 \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
405 \fBsd_listen_fds_with_names\fR(3)\&. File descriptors submitted without this field will be called
406 "stored"\&.
407 .sp
408 The name may consist of arbitrary ASCII characters except control characters or
409 ":"\&. It may not be longer than 255 characters\&. If a submitted name does not follow these restrictions, it is ignored\&.
410 .sp
411 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\&.
412 .sp
413 Added in version 233\&.
414 .RE
415 .PP
416 FDPOLL=0
417 .RS 4
418 When used in combination with
419 \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\&.
420 .sp
421 Added in version 246\&.
422 .RE
423 .PP
424 BARRIER=1
425 .RS 4
426 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
427 \fIBARRIER=1\fR
428 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\&.
429 .sp
430 Added in version 246\&.
431 .RE
432 .PP
433 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
434 "X_"
435 followed by some namespace identifier\&. The service manager also sends some messages to
436 \fIits\fR
437 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
438 \fIX_SYSTEMD_UNIT_ACTIVE=\fR, for details see
439 \fBsystemd\fR(1)\&.
440 .SH "RETURN VALUE"
441 .PP
442 On failure, these calls return a negative errno\-style error code\&. If
443 \fI$NOTIFY_SOCKET\fR
444 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
445 \fIFDSTORE=1\fR
446 but the service is not actually configured to permit storing of file descriptors (see above)\&.
447 .SS "Errors"
448 .PP
449 Returned errors may indicate the following problems:
450 .PP
451 \fB\-E2BIG\fR
452 .RS 4
453 More file descriptors passed at once than the system allows\&. On Linux the number of file descriptors that may be passed across
454 \fBAF_UNIX\fR
455 sockets at once is 253, see
456 \fBunix\fR(7)
457 for details\&.
458 .sp
459 Added in version 257\&.
460 .RE
461 .SH "NOTES"
462 .PP
463 Functions described here are available as a shared library, which can be compiled against and linked to with the
464 \fBlibsystemd\fR\ \&\fBpkg-config\fR(1)
465 file\&.
466 .PP
467 The code described here uses
468 \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
469 \fBsetenv\fR(3)
470 from a parallel thread\&. It is recommended to only do calls to
471 \fBsetenv()\fR
472 from an early phase of the program when no other threads have been started\&.
473 .PP
474 These functions send a single datagram with the state string as payload to the socket referenced in the
475 \fI$NOTIFY_SOCKET\fR
476 environment variable\&. If the first character of
477 \fI$NOTIFY_SOCKET\fR
478 is
479 "/"
480 or
481 "@", the string is understood as an
482 \fBAF_UNIX\fR
483 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
484 "vsock:"
485 then the string is understood as an
486 \fBAF_VSOCK\fR
487 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
488 \fBSOCK_DGRAM\fR
489 over
490 \fBAF_VSOCK\fR,
491 \fBSOCK_SEQPACKET\fR
492 will be used instead\&.
493 "vsock\-stream",
494 "vsock\-dgram"
495 and
496 "vsock\-seqpacket"
497 can be used instead of
498 "vsock"
499 to force usage of the corresponding socket type\&. The address should be in the form:
500 "vsock:CID:PORT"\&. Note that unlike other uses of vsock, the CID is mandatory and cannot be
501 "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\&.
502 .SS "Standalone Implementations"
503 .PP
504 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:
505 .sp
506 .it 1 an-trap
507 .nr an-no-space-flag 1
508 .nr an-break-flag 1
509 .br
510 .ps +1
511 \fBC\fR
512 .RS 4
513 .sp
514 .if n \{\
515 .RS 4
516 .\}
517 .nf
518 /* SPDX\-License\-Identifier: MIT\-0 */
519
520 /* Implement the systemd notify protocol without external dependencies\&.
521 * Supports both readiness notification on startup and on reloading,
522 * according to the protocol defined at:
523 * https://www\&.freedesktop\&.org/software/systemd/man/latest/sd_notify\&.html
524 * This protocol is guaranteed to be stable as per:
525 * https://systemd\&.io/PORTABILITY_AND_STABILITY/ */
526
527 #define _GNU_SOURCE 1
528 #include <errno\&.h>
529 #include <inttypes\&.h>
530 #include <signal\&.h>
531 #include <stdbool\&.h>
532 #include <stddef\&.h>
533 #include <stdlib\&.h>
534 #include <stdio\&.h>
535 #include <string\&.h>
536 #include <sys/socket\&.h>
537 #include <sys/un\&.h>
538 #include <time\&.h>
539 #include <unistd\&.h>
540
541 #define _cleanup_(f) __attribute__((cleanup(f)))
542
543 static void closep(int *fd) {
544 if (!fd || *fd < 0)
545 return;
546
547 close(*fd);
548 *fd = \-1;
549 }
550
551 static int notify(const char *message) {
552 union sockaddr_union {
553 struct sockaddr sa;
554 struct sockaddr_un sun;
555 } socket_addr = {
556 \&.sun\&.sun_family = AF_UNIX,
557 };
558 size_t path_length, message_length;
559 _cleanup_(closep) int fd = \-1;
560 const char *socket_path;
561
562 /* Verify the argument first */
563 if (!message)
564 return \-EINVAL;
565
566 message_length = strlen(message);
567 if (message_length == 0)
568 return \-EINVAL;
569
570 /* If the variable is not set, the protocol is a noop */
571 socket_path = getenv("NOTIFY_SOCKET");
572 if (!socket_path)
573 return 0; /* Not set? Nothing to do */
574
575 /* Only AF_UNIX is supported, with path or abstract sockets */
576 if (socket_path[0] != \*(Aq/\*(Aq && socket_path[0] != \*(Aq@\*(Aq)
577 return \-EAFNOSUPPORT;
578
579 path_length = strlen(socket_path);
580 /* Ensure there is room for NUL byte */
581 if (path_length >= sizeof(socket_addr\&.sun\&.sun_path))
582 return \-E2BIG;
583
584 memcpy(socket_addr\&.sun\&.sun_path, socket_path, path_length);
585
586 /* Support for abstract socket */
587 if (socket_addr\&.sun\&.sun_path[0] == \*(Aq@\*(Aq)
588 socket_addr\&.sun\&.sun_path[0] = 0;
589
590 fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0);
591 if (fd < 0)
592 return \-errno;
593
594 if (connect(fd, &socket_addr\&.sa, offsetof(struct sockaddr_un, sun_path) + path_length) != 0)
595 return \-errno;
596
597 ssize_t written = write(fd, message, message_length);
598 if (written != (ssize_t) message_length)
599 return written < 0 ? \-errno : \-EPROTO;
600
601 return 1; /* Notified! */
602 }
603
604 static int notify_ready(void) {
605 return notify("READY=1");
606 }
607
608 static int notify_reloading(void) {
609 /* A buffer with length sufficient to format the maximum UINT64 value\&. */
610 char reload_message[sizeof("RELOADING=1\enMONOTONIC_USEC=18446744073709551615")];
611 struct timespec ts;
612 uint64_t now;
613
614 /* Notify systemd that we are reloading, including a CLOCK_MONOTONIC timestamp in usec
615 * so that the program is compatible with a Type=notify\-reload service\&. */
616
617 if (clock_gettime(CLOCK_MONOTONIC, &ts) < 0)
618 return \-errno;
619
620 if (ts\&.tv_sec < 0 || ts\&.tv_nsec < 0 ||
621 (uint64_t) ts\&.tv_sec > (UINT64_MAX \- (ts\&.tv_nsec / 1000ULL)) / 1000000ULL)
622 return \-EINVAL;
623
624 now = (uint64_t) ts\&.tv_sec * 1000000ULL + (uint64_t) ts\&.tv_nsec / 1000ULL;
625
626 if (snprintf(reload_message, sizeof(reload_message), "RELOADING=1\enMONOTONIC_USEC=%" PRIu64, now) < 0)
627 return \-EINVAL;
628
629 return notify(reload_message);
630 }
631
632 static int notify_stopping(void) {
633 return notify("STOPPING=1");
634 }
635
636 static volatile sig_atomic_t reloading = 0;
637 static volatile sig_atomic_t terminating = 0;
638
639 static void signal_handler(int sig) {
640 if (sig == SIGHUP)
641 reloading = 1;
642 else if (sig == SIGINT || sig == SIGTERM)
643 terminating = 1;
644 }
645
646 int main(int argc, char **argv) {
647 struct sigaction sa = {
648 \&.sa_handler = signal_handler,
649 \&.sa_flags = SA_RESTART,
650 };
651 int r;
652
653 /* Setup signal handlers */
654 sigemptyset(&sa\&.sa_mask);
655 sigaction(SIGHUP, &sa, NULL);
656 sigaction(SIGINT, &sa, NULL);
657 sigaction(SIGTERM, &sa, NULL);
658
659 /* Do more service initialization work here \&... */
660
661 /* Now that all the preparations steps are done, signal readiness */
662
663 r = notify_ready();
664 if (r < 0) {
665 fprintf(stderr, "Failed to notify readiness to $NOTIFY_SOCKET: %s\en", strerror(\-r));
666 return EXIT_FAILURE;
667 }
668
669 while (!terminating) {
670 if (reloading) {
671 reloading = false;
672
673 /* As a separate but related feature, we can also notify the manager
674 * when reloading configuration\&. This allows accurate state\-tracking,
675 * and also automated hook\-in of \*(Aqsystemctl reload\*(Aq without having to
676 * specify manually an ExecReload= line in the unit file\&. */
677
678 r = notify_reloading();
679 if (r < 0) {
680 fprintf(stderr, "Failed to notify reloading to $NOTIFY_SOCKET: %s\en", strerror(\-r));
681 return EXIT_FAILURE;
682 }
683
684 /* Do some reconfiguration work here \&... */
685
686 r = notify_ready();
687 if (r < 0) {
688 fprintf(stderr, "Failed to notify readiness to $NOTIFY_SOCKET: %s\en", strerror(\-r));
689 return EXIT_FAILURE;
690 }
691 }
692
693 /* Do some daemon work here \&... */
694 sleep(5);
695 }
696
697 r = notify_stopping();
698 if (r < 0) {
699 fprintf(stderr, "Failed to report termination to $NOTIFY_SOCKET: %s\en", strerror(\-r));
700 return EXIT_FAILURE;
701 }
702
703 /* Do some shutdown work here \&... */
704
705 return EXIT_SUCCESS;
706 }
707 .fi
708 .if n \{\
709 .RE
710 .\}
711 .RE
712 .sp
713 .it 1 an-trap
714 .nr an-no-space-flag 1
715 .nr an-break-flag 1
716 .br
717 .ps +1
718 \fBPython\fR
719 .RS 4
720 .sp
721 .if n \{\
722 .RS 4
723 .\}
724 .nf
725 #!/usr/bin/python
726 # SPDX\-License\-Identifier: MIT\-0
727 #
728 # Implement the systemd notify protocol without external dependencies\&.
729 # Supports both readiness notification on startup and on reloading,
730 # according to the protocol defined at:
731 # https://www\&.freedesktop\&.org/software/systemd/man/latest/sd_notify\&.html
732 # This protocol is guaranteed to be stable as per:
733 # https://systemd\&.io/PORTABILITY_AND_STABILITY/
734
735 import errno
736 import os
737 import signal
738 import socket
739 import sys
740 import time
741
742 reloading = False
743 terminating = False
744
745 def notify(message):
746 if not message:
747 raise ValueError("notify() requires a message")
748
749 socket_path = os\&.environ\&.get("NOTIFY_SOCKET")
750 if not socket_path:
751 return
752
753 if socket_path[0] not in ("/", "@"):
754 raise OSError(errno\&.EAFNOSUPPORT, "Unsupported socket type")
755
756 # Handle abstract socket\&.
757 if socket_path[0] == "@":
758 socket_path = "\e0" + socket_path[1:]
759
760 with socket\&.socket(socket\&.AF_UNIX, socket\&.SOCK_DGRAM | socket\&.SOCK_CLOEXEC) as sock:
761 sock\&.connect(socket_path)
762 sock\&.sendall(message)
763
764 def notify_ready():
765 notify(b"READY=1")
766
767 def notify_reloading():
768 microsecs = time\&.clock_gettime_ns(time\&.CLOCK_MONOTONIC) // 1000
769 notify(f"RELOADING=1\enMONOTONIC_USEC={microsecs}"\&.encode())
770
771 def notify_stopping():
772 notify(b"STOPPING=1")
773
774 def reload(signum, frame):
775 global reloading
776 reloading = True
777
778 def terminate(signum, frame):
779 global terminating
780 terminating = True
781
782 def main():
783 print("Doing initial setup")
784 global reloading, terminating
785
786 # Set up signal handlers\&.
787 print("Setting up signal handlers")
788 signal\&.signal(signal\&.SIGHUP, reload)
789 signal\&.signal(signal\&.SIGINT, terminate)
790 signal\&.signal(signal\&.SIGTERM, terminate)
791
792 # Do any other setup work here\&.
793
794 # Once all setup is done, signal readiness\&.
795 print("Done setting up")
796 notify_ready()
797
798 print("Starting loop")
799 while not terminating:
800 if reloading:
801 print("Reloading")
802 reloading = False
803
804 # Support notifying the manager when reloading configuration\&.
805 # This allows accurate state tracking as well as automatically
806 # enabling \*(Aqsystemctl reload\*(Aq without needing to manually
807 # specify an ExecReload= line in the unit file\&.
808
809 notify_reloading()
810
811 # Do some reconfiguration work here\&.
812
813 print("Done reloading")
814 notify_ready()
815
816 # Do the real work here \&.\&.\&.
817
818 print("Sleeping for five seconds")
819 time\&.sleep(5)
820
821 print("Terminating")
822 notify_stopping()
823
824 if __name__ == "__main__":
825 sys\&.stdout\&.reconfigure(line_buffering=True)
826 print("Starting app")
827 main()
828 print("Stopped app")
829 .fi
830 .if n \{\
831 .RE
832 .\}
833 .RE
834 .SH "ENVIRONMENT"
835 .PP
836 \fI$NOTIFY_SOCKET\fR
837 .RS 4
838 Set by the service manager for supervised processes for status and start\-up completion notification\&. This environment variable specifies the socket
839 \fBsd_notify()\fR
840 talks to\&. See above for details\&.
841 .RE
842 .SH "EXAMPLES"
843 .PP
844 \fBExample\ \&1.\ \&Start\-up Notification\fR
845 .PP
846 When a service finished starting up, it might issue the following call to notify the service manager:
847 .sp
848 .if n \{\
849 .RS 4
850 .\}
851 .nf
852 sd_notify(0, "READY=1");
853 .fi
854 .if n \{\
855 .RE
856 .\}
857 .PP
858 \fBExample\ \&2.\ \&Extended Start\-up Notification\fR
859 .PP
860 A service could send the following after completing initialization:
861 .sp
862 .if n \{\
863 .RS 4
864 .\}
865 .nf
866 sd_notifyf(0, "READY=1\en"
867 "STATUS=Processing requests\&...\en"
868 "MAINPID=%lu",
869 (unsigned long) getpid());
870 .fi
871 .if n \{\
872 .RE
873 .\}
874 .PP
875 \fBExample\ \&3.\ \&Error Cause Notification\fR
876 .PP
877 A service could send the following shortly before exiting, on failure:
878 .sp
879 .if n \{\
880 .RS 4
881 .\}
882 .nf
883 sd_notifyf(0, "STATUS=Failed to start up: %s\en"
884 "ERRNO=%i",
885 strerror_r(errnum, (char[1024]){}, 1024),
886 errnum);
887 .fi
888 .if n \{\
889 .RE
890 .\}
891 .PP
892 \fBExample\ \&4.\ \&Store a File Descriptor in the Service Manager\fR
893 .PP
894 To store an open file descriptor in the service manager, in order to continue operation after a service restart without losing state, use
895 "FDSTORE=1":
896 .sp
897 .if n \{\
898 .RS 4
899 .\}
900 .nf
901 sd_pid_notify_with_fds(0, 0, "FDSTORE=1\enFDNAME=foobar", &fd, 1);
902 .fi
903 .if n \{\
904 .RE
905 .\}
906 .PP
907 \fBExample\ \&5.\ \&Eliminating race conditions\fR
908 .PP
909 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
910 \fBsd_notify_barrier()\fR
911 to synchronize against reception of all notifications sent before this call is made\&.
912 .sp
913 .if n \{\
914 .RS 4
915 .\}
916 .nf
917 sd_notify(0, "READY=1");
918 /* set timeout to 5 seconds */
919 sd_notify_barrier(0, 5 * 1000000);
920 .fi
921 .if n \{\
922 .RE
923 .\}
924 .SH "HISTORY"
925 .PP
926 \fBsd_pid_notify()\fR,
927 \fBsd_pid_notifyf()\fR, and
928 \fBsd_pid_notify_with_fds()\fR
929 were added in version 219\&.
930 .PP
931 \fBsd_notify_barrier()\fR
932 was added in version 246\&.
933 .PP
934 \fBsd_pid_notifyf_with_fds()\fR
935 and
936 \fBsd_pid_notify_barrier()\fR
937 were added in version 254\&.
938 .SH "SEE ALSO"
939 .PP
940 \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)
941 .SH "NOTES"
942 .IP " 1." 4
943 File Descriptor Store
944 .RS 4
945 \%https://systemd.io/FILE_DESCRIPTOR_STORE
946 .RE