Debian Codegraph @

upstream/debian-unstable/man3/sd_notify.3

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