]> git.ipfire.org Git - thirdparty/systemd.git/blame - man/daemon.xml
Merge pull request #14105 from keszybz/man-directives-cleanup
[thirdparty/systemd.git] / man / daemon.xml
CommitLineData
64aba792 1<?xml version='1.0'?> <!--*-nxml-*-->
3a54a157 2<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN"
12b42c76 3 "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd">
0307f791 4<!-- SPDX-License-Identifier: LGPL-2.1+ -->
64aba792 5
62adf224 6<refentry id="daemon">
64aba792 7
798d3a52
ZJS
8 <refentryinfo>
9 <title>daemon</title>
10 <productname>systemd</productname>
798d3a52
ZJS
11 </refentryinfo>
12
13 <refmeta>
14 <refentrytitle>daemon</refentrytitle>
15 <manvolnum>7</manvolnum>
16 </refmeta>
17
18 <refnamediv>
19 <refname>daemon</refname>
20 <refpurpose>Writing and packaging system daemons</refpurpose>
21 </refnamediv>
22
23 <refsect1>
24 <title>Description</title>
25
26 <para>A daemon is a service process that runs in the background
27 and supervises the system or provides functionality to other
28 processes. Traditionally, daemons are implemented following a
29 scheme originating in SysV Unix. Modern daemons should follow a
30 simpler yet more powerful scheme (here called "new-style"
31 daemons), as implemented by
32 <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>.
33 This manual page covers both schemes, and in particular includes
34 recommendations for daemons that shall be included in the systemd
35 init system.</para>
36
37 <refsect2>
38 <title>SysV Daemons</title>
39
40 <para>When a traditional SysV daemon starts, it should execute
41 the following steps as part of the initialization. Note that
42 these steps are unnecessary for new-style daemons (see below),
43 and should only be implemented if compatibility with SysV is
44 essential.</para>
45
46 <orderedlist>
47 <listitem><para>Close all open file descriptors except
48 standard input, output, and error (i.e. the first three file
49 descriptors 0, 1, 2). This ensures that no accidentally passed
50 file descriptor stays around in the daemon process. On Linux,
51 this is best implemented by iterating through
52 <filename>/proc/self/fd</filename>, with a fallback of
53 iterating from file descriptor 3 to the value returned by
54 <function>getrlimit()</function> for
55 <constant>RLIMIT_NOFILE</constant>. </para></listitem>
56
57 <listitem><para>Reset all signal handlers to their default.
58 This is best done by iterating through the available signals
59 up to the limit of <constant>_NSIG</constant> and resetting
60 them to <constant>SIG_DFL</constant>.</para></listitem>
61
62 <listitem><para>Reset the signal mask
63 using
64 <function>sigprocmask()</function>.</para></listitem>
65
66 <listitem><para>Sanitize the environment block, removing or
67 resetting environment variables that might negatively impact
68 daemon runtime.</para></listitem>
69
70 <listitem><para>Call <function>fork()</function>, to create a
71 background process.</para></listitem>
72
73 <listitem><para>In the child, call
74 <function>setsid()</function> to detach from any terminal and
75 create an independent session.</para></listitem>
76
5f428300
LP
77 <listitem><para>In the child, call <function>fork()</function> again, to ensure that the daemon can
78 never re-acquire a terminal again. (This relevant if the program — and all its dependencies — does
79 not carefully specify `O_NOCTTY` on each and every single `open()` call that might potentially open a
80 TTY device node.)</para></listitem>
798d3a52
ZJS
81
82 <listitem><para>Call <function>exit()</function> in the first
83 child, so that only the second child (the actual daemon
84 process) stays around. This ensures that the daemon process is
85 re-parented to init/PID 1, as all daemons should
86 be.</para></listitem>
87
88 <listitem><para>In the daemon process, connect
89 <filename>/dev/null</filename> to standard input, output, and
90 error.</para></listitem>
91
92 <listitem><para>In the daemon process, reset the umask to 0,
93 so that the file modes passed to <function>open()</function>,
94 <function>mkdir()</function> and suchlike directly control the
95 access mode of the created files and
96 directories.</para></listitem>
97
98 <listitem><para>In the daemon process, change the current
99 directory to the root directory (/), in order to avoid that
100 the daemon involuntarily blocks mount points from being
101 unmounted.</para></listitem>
102
103 <listitem><para>In the daemon process, write the daemon PID
104 (as returned by <function>getpid()</function>) to a PID file,
f8b68539 105 for example <filename index='false'>/run/foobar.pid</filename> (for a
798d3a52
ZJS
106 hypothetical daemon "foobar") to ensure that the daemon cannot
107 be started more than once. This must be implemented in
108 race-free fashion so that the PID file is only updated when it
109 is verified at the same time that the PID previously stored in
110 the PID file no longer exists or belongs to a foreign
111 process.</para></listitem>
112
113 <listitem><para>In the daemon process, drop privileges, if
114 possible and applicable.</para></listitem>
115
116 <listitem><para>From the daemon process, notify the original
117 process started that initialization is complete. This can be
118 implemented via an unnamed pipe or similar communication
119 channel that is created before the first
120 <function>fork()</function> and hence available in both the
121 original and the daemon process.</para></listitem>
122
123 <listitem><para>Call <function>exit()</function> in the
124 original process. The process that invoked the daemon must be
125 able to rely on that this <function>exit()</function> happens
126 after initialization is complete and all external
127 communication channels are established and
128 accessible.</para></listitem>
129 </orderedlist>
130
131 <para>The BSD <function>daemon()</function> function should not
132 be used, as it implements only a subset of these steps.</para>
133
134 <para>A daemon that needs to provide compatibility with SysV
135 systems should implement the scheme pointed out above. However,
136 it is recommended to make this behavior optional and
137 configurable via a command line argument to ease debugging as
138 well as to simplify integration into systems using
139 systemd.</para>
140 </refsect2>
141
142 <refsect2>
143 <title>New-Style Daemons</title>
144
145 <para>Modern services for Linux should be implemented as
146 new-style daemons. This makes it easier to supervise and control
147 them at runtime and simplifies their implementation.</para>
148
149 <para>For developing a new-style daemon, none of the
150 initialization steps recommended for SysV daemons need to be
151 implemented. New-style init systems such as systemd make all of
152 them redundant. Moreover, since some of these steps interfere
153 with process monitoring, file descriptor passing and other
154 functionality of the init system, it is recommended not to
155 execute them when run as new-style service.</para>
156
b9a049b1
LP
157 <para>Note that new-style init systems guarantee execution of daemon processes in a clean process context: it is
158 guaranteed that the environment block is sanitized, that the signal handlers and mask is reset and that no
159 left-over file descriptors are passed. Daemons will be executed in their own session, with standard input
160 connected to <filename>/dev/null</filename> and standard output/error connected to the
161 <citerefentry><refentrytitle>systemd-journald.service</refentrytitle><manvolnum>8</manvolnum></citerefentry>
162 logging service, unless otherwise configured. The umask is reset.
798d3a52
ZJS
163 </para>
164
165 <para>It is recommended for new-style daemons to implement the
166 following:</para>
167
168 <orderedlist>
169 <listitem><para>If <constant>SIGTERM</constant> is received,
170 shut down the daemon and exit cleanly.</para></listitem>
171
172 <listitem><para>If <constant>SIGHUP</constant> is received,
173 reload the configuration files, if this
174 applies.</para></listitem>
175
176 <listitem><para>Provide a correct exit code from the main
177 daemon process, as this is used by the init system to detect
178 service errors and problems. It is recommended to follow the
179 exit code scheme as defined in the <ulink
180 url="http://refspecs.linuxbase.org/LSB_3.1.1/LSB-Core-generic/LSB-Core-generic/iniscrptact.html">LSB
181 recommendations for SysV init
182 scripts</ulink>.</para></listitem>
183
184 <listitem><para>If possible and applicable, expose the
185 daemon's control interface via the D-Bus IPC system and grab a
186 bus name as last step of initialization.</para></listitem>
187
188 <listitem><para>For integration in systemd, provide a
189 <filename>.service</filename> unit file that carries
190 information about starting, stopping and otherwise maintaining
191 the daemon. See
192 <citerefentry><refentrytitle>systemd.service</refentrytitle><manvolnum>5</manvolnum></citerefentry>
193 for details.</para></listitem>
194
195 <listitem><para>As much as possible, rely on the init system's
196 functionality to limit the access of the daemon to files,
197 services and other resources, i.e. in the case of systemd,
198 rely on systemd's resource limit control instead of
199 implementing your own, rely on systemd's privilege dropping
200 code instead of implementing it in the daemon, and similar.
201 See
202 <citerefentry><refentrytitle>systemd.exec</refentrytitle><manvolnum>5</manvolnum></citerefentry>
203 for the available controls.</para></listitem>
204
205 <listitem><para>If D-Bus is used, make your daemon
206 bus-activatable by supplying a D-Bus service activation
207 configuration file. This has multiple advantages: your daemon
208 may be started lazily on-demand; it may be started in parallel
ccddd104 209 to other daemons requiring it — which maximizes
798d3a52
ZJS
210 parallelization and boot-up speed; your daemon can be
211 restarted on failure without losing any bus requests, as the
212 bus queues requests for activatable services. See below for
213 details.</para></listitem>
214
215 <listitem><para>If your daemon provides services to other
216 local processes or remote clients via a socket, it should be
217 made socket-activatable following the scheme pointed out
218 below. Like D-Bus activation, this enables on-demand starting
219 of services as well as it allows improved parallelization of
220 service start-up. Also, for state-less protocols (such as
221 syslog, DNS), a daemon implementing socket-based activation
222 can be restarted without losing a single request. See below
223 for details.</para></listitem>
224
225 <listitem><para>If applicable, a daemon should notify the init
226 system about startup completion or status updates via the
227 <citerefentry><refentrytitle>sd_notify</refentrytitle><manvolnum>3</manvolnum></citerefentry>
228 interface.</para></listitem>
229
230 <listitem><para>Instead of using the
231 <function>syslog()</function> call to log directly to the
232 system syslog service, a new-style daemon may choose to simply
233 log to standard error via <function>fprintf()</function>,
234 which is then forwarded to syslog by the init system. If log
235 levels are necessary, these can be encoded by prefixing
236 individual log lines with strings like
237 <literal>&lt;4&gt;</literal> (for log level 4 "WARNING" in the
238 syslog priority scheme), following a similar style as the
239 Linux kernel's <function>printk()</function> level system. For
240 details, see
241 <citerefentry><refentrytitle>sd-daemon</refentrytitle><manvolnum>3</manvolnum></citerefentry>
242 and
243 <citerefentry><refentrytitle>systemd.exec</refentrytitle><manvolnum>5</manvolnum></citerefentry>.</para></listitem>
244
5f428300
LP
245 <listitem><para>As new-style daemons are invoked without a controlling TTY (but as their own session
246 leaders) care should be taken to always specify `O_NOCTTY` on `open()` calls that possibly reference
247 a TTY device node, so that no controlling TTY is accidentally acquired.</para></listitem>
248
798d3a52
ZJS
249 </orderedlist>
250
251 <para>These recommendations are similar but not identical to the
252 <ulink
253 url="https://developer.apple.com/library/mac/documentation/MacOSX/Conceptual/BPSystemStartup/Chapters/CreatingLaunchdJobs.html">Apple
254 MacOS X Daemon Requirements</ulink>.</para>
255 </refsect2>
256
257 </refsect1>
258 <refsect1>
259 <title>Activation</title>
260
261 <para>New-style init systems provide multiple additional
262 mechanisms to activate services, as detailed below. It is common
263 that services are configured to be activated via more than one
264 mechanism at the same time. An example for systemd:
265 <filename>bluetoothd.service</filename> might get activated either
266 when Bluetooth hardware is plugged in, or when an application
267 accesses its programming interfaces via D-Bus. Or, a print server
268 daemon might get activated when traffic arrives at an IPP port, or
269 when a printer is plugged in, or when a file is queued in the
270 printer spool directory. Even for services that are intended to be
271 started on system bootup unconditionally, it is a good idea to
272 implement some of the various activation schemes outlined below,
273 in order to maximize parallelization. If a daemon implements a
274 D-Bus service or listening socket, implementing the full bus and
275 socket activation scheme allows starting of the daemon with its
276 clients in parallel (which speeds up boot-up), since all its
277 communication channels are established already, and no request is
278 lost because client requests will be queued by the bus system (in
279 case of D-Bus) or the kernel (in case of sockets) until the
280 activation is completed.</para>
281
282 <refsect2>
283 <title>Activation on Boot</title>
284
285 <para>Old-style daemons are usually activated exclusively on
286 boot (and manually by the administrator) via SysV init scripts,
287 as detailed in the <ulink
288 url="http://refspecs.linuxbase.org/LSB_3.1.1/LSB-Core-generic/LSB-Core-generic/iniscrptact.html">LSB
289 Linux Standard Base Core Specification</ulink>. This method of
290 activation is supported ubiquitously on Linux init systems, both
291 old-style and new-style systems. Among other issues, SysV init
292 scripts have the disadvantage of involving shell scripts in the
293 boot process. New-style init systems generally employ updated
294 versions of activation, both during boot-up and during runtime
295 and using more minimal service description files.</para>
296
297 <para>In systemd, if the developer or administrator wants to
298 make sure that a service or other unit is activated
299 automatically on boot, it is recommended to place a symlink to
300 the unit file in the <filename>.wants/</filename> directory of
301 either <filename>multi-user.target</filename> or
302 <filename>graphical.target</filename>, which are normally used
303 as boot targets at system startup. See
304 <citerefentry><refentrytitle>systemd.unit</refentrytitle><manvolnum>5</manvolnum></citerefentry>
305 for details about the <filename>.wants/</filename> directories,
306 and
307 <citerefentry><refentrytitle>systemd.special</refentrytitle><manvolnum>7</manvolnum></citerefentry>
308 for details about the two boot targets.</para>
309
310 </refsect2>
311
312 <refsect2>
313 <title>Socket-Based Activation</title>
314
315 <para>In order to maximize the possible parallelization and
316 robustness and simplify configuration and development, it is
317 recommended for all new-style daemons that communicate via
318 listening sockets to employ socket-based activation. In a
319 socket-based activation scheme, the creation and binding of the
320 listening socket as primary communication channel of daemons to
321 local (and sometimes remote) clients is moved out of the daemon
322 code and into the init system. Based on per-daemon
323 configuration, the init system installs the sockets and then
324 hands them off to the spawned process as soon as the respective
325 daemon is to be started. Optionally, activation of the service
326 can be delayed until the first inbound traffic arrives at the
327 socket to implement on-demand activation of daemons. However,
328 the primary advantage of this scheme is that all providers and
329 all consumers of the sockets can be started in parallel as soon
330 as all sockets are established. In addition to that, daemons can
331 be restarted with losing only a minimal number of client
332 transactions, or even any client request at all (the latter is
333 particularly true for state-less protocols, such as DNS or
334 syslog), because the socket stays bound and accessible during
335 the restart, and all requests are queued while the daemon cannot
336 process them.</para>
337
338 <para>New-style daemons which support socket activation must be
339 able to receive their sockets from the init system instead of
340 creating and binding them themselves. For details about the
341 programming interfaces for this scheme provided by systemd, see
342 <citerefentry><refentrytitle>sd_listen_fds</refentrytitle><manvolnum>3</manvolnum></citerefentry>
343 and
344 <citerefentry><refentrytitle>sd-daemon</refentrytitle><manvolnum>3</manvolnum></citerefentry>.
345 For details about porting existing daemons to socket-based
346 activation, see below. With minimal effort, it is possible to
347 implement socket-based activation in addition to traditional
348 internal socket creation in the same codebase in order to
349 support both new-style and old-style init systems from the same
350 daemon binary.</para>
351
352 <para>systemd implements socket-based activation via
353 <filename>.socket</filename> units, which are described in
354 <citerefentry><refentrytitle>systemd.socket</refentrytitle><manvolnum>5</manvolnum></citerefentry>.
355 When configuring socket units for socket-based activation, it is
356 essential that all listening sockets are pulled in by the
357 special target unit <filename>sockets.target</filename>. It is
358 recommended to place a
359 <varname>WantedBy=sockets.target</varname> directive in the
360 <literal>[Install]</literal> section to automatically add such a
361 dependency on installation of a socket unit. Unless
362 <varname>DefaultDependencies=no</varname> is set, the necessary
363 ordering dependencies are implicitly created for all socket
364 units. For more information about
365 <filename>sockets.target</filename>, see
366 <citerefentry><refentrytitle>systemd.special</refentrytitle><manvolnum>7</manvolnum></citerefentry>.
367 It is not necessary or recommended to place any additional
368 dependencies on socket units (for example from
369 <filename>multi-user.target</filename> or suchlike) when one is
370 installed in <filename>sockets.target</filename>.</para>
371 </refsect2>
372
373 <refsect2>
374 <title>Bus-Based Activation</title>
375
376 <para>When the D-Bus IPC system is used for communication with
377 clients, new-style daemons should employ bus activation so that
378 they are automatically activated when a client application
379 accesses their IPC interfaces. This is configured in D-Bus
380 service files (not to be confused with systemd service unit
381 files!). To ensure that D-Bus uses systemd to start-up and
382 maintain the daemon, use the <varname>SystemdService=</varname>
383 directive in these service files to configure the matching
384 systemd service for a D-Bus service. e.g.: For a D-Bus service
385 whose D-Bus activation file is named
386 <filename>org.freedesktop.RealtimeKit.service</filename>, make
387 sure to set
388 <varname>SystemdService=rtkit-daemon.service</varname> in that
389 file to bind it to the systemd service
390 <filename>rtkit-daemon.service</filename>. This is needed to
391 make sure that the daemon is started in a race-free fashion when
392 activated via multiple mechanisms simultaneously.</para>
393 </refsect2>
394
395 <refsect2>
396 <title>Device-Based Activation</title>
397
398 <para>Often, daemons that manage a particular type of hardware
399 should be activated only when the hardware of the respective
400 kind is plugged in or otherwise becomes available. In a
401 new-style init system, it is possible to bind activation to
402 hardware plug/unplug events. In systemd, kernel devices
403 appearing in the sysfs/udev device tree can be exposed as units
404 if they are tagged with the string <literal>systemd</literal>.
405 Like any other kind of unit, they may then pull in other units
406 when activated (i.e. plugged in) and thus implement device-based
407 activation. systemd dependencies may be encoded in the udev
408 database via the <varname>SYSTEMD_WANTS=</varname> property. See
409 <citerefentry><refentrytitle>systemd.device</refentrytitle><manvolnum>5</manvolnum></citerefentry>
410 for details. Often, it is nicer to pull in services from devices
411 only indirectly via dedicated targets. Example: Instead of
412 pulling in <filename>bluetoothd.service</filename> from all the
413 various bluetooth dongles and other hardware available, pull in
414 bluetooth.target from them and
415 <filename>bluetoothd.service</filename> from that target. This
416 provides for nicer abstraction and gives administrators the
417 option to enable <filename>bluetoothd.service</filename> via
418 controlling a <filename>bluetooth.target.wants/</filename>
419 symlink uniformly with a command like <command>enable</command>
420 of
421 <citerefentry><refentrytitle>systemctl</refentrytitle><manvolnum>1</manvolnum></citerefentry>
422 instead of manipulating the udev ruleset.</para>
423 </refsect2>
424
425 <refsect2>
426 <title>Path-Based Activation</title>
427
428 <para>Often, runtime of daemons processing spool files or
429 directories (such as a printing system) can be delayed until
430 these file system objects change state, or become non-empty.
431 New-style init systems provide a way to bind service activation
432 to file system changes. systemd implements this scheme via
433 path-based activation configured in <filename>.path</filename>
434 units, as outlined in
435 <citerefentry><refentrytitle>systemd.path</refentrytitle><manvolnum>5</manvolnum></citerefentry>.</para>
436 </refsect2>
437
438 <refsect2>
439 <title>Timer-Based Activation</title>
440
441 <para>Some daemons that implement clean-up jobs that are
442 intended to be executed in regular intervals benefit from
443 timer-based activation. In systemd, this is implemented via
444 <filename>.timer</filename> units, as described in
445 <citerefentry><refentrytitle>systemd.timer</refentrytitle><manvolnum>5</manvolnum></citerefentry>.</para>
446 </refsect2>
447
448 <refsect2>
449 <title>Other Forms of Activation</title>
450
451 <para>Other forms of activation have been suggested and
452 implemented in some systems. However, there are often simpler or
453 better alternatives, or they can be put together of combinations
454 of the schemes above. Example: Sometimes, it appears useful to
455 start daemons or <filename>.socket</filename> units when a
456 specific IP address is configured on a network interface,
457 because network sockets shall be bound to the address. However,
458 an alternative to implement this is by utilizing the Linux
459 <constant>IP_FREEBIND</constant> socket option, as accessible
460 via <varname>FreeBind=yes</varname> in systemd socket files (see
461 <citerefentry><refentrytitle>systemd.socket</refentrytitle><manvolnum>5</manvolnum></citerefentry>
462 for details). This option, when enabled, allows sockets to be
463 bound to a non-local, not configured IP address, and hence
464 allows bindings to a particular IP address before it actually
465 becomes available, making such an explicit dependency to the
466 configured address redundant. Another often suggested trigger
467 for service activation is low system load. However, here too, a
468 more convincing approach might be to make proper use of features
b938cb90 469 of the operating system, in particular, the CPU or I/O scheduler
798d3a52
ZJS
470 of Linux. Instead of scheduling jobs from userspace based on
471 monitoring the OS scheduler, it is advisable to leave the
472 scheduling of processes to the OS scheduler itself. systemd
b938cb90 473 provides fine-grained access to the CPU and I/O schedulers. If a
798d3a52 474 process executed by the init system shall not negatively impact
b938cb90 475 the amount of CPU or I/O bandwidth available to other processes,
798d3a52
ZJS
476 it should be configured with
477 <varname>CPUSchedulingPolicy=idle</varname> and/or
478 <varname>IOSchedulingClass=idle</varname>. Optionally, this may
479 be combined with timer-based activation to schedule background
480 jobs during runtime and with minimal impact on the system, and
481 remove it from the boot phase itself.</para>
482 </refsect2>
483
484 </refsect1>
485 <refsect1>
f95b0be7 486 <title>Integration with systemd</title>
798d3a52
ZJS
487
488 <refsect2>
f95b0be7 489 <title>Writing systemd Unit Files</title>
798d3a52
ZJS
490
491 <para>When writing systemd unit files, it is recommended to
492 consider the following suggestions:</para>
493
494 <orderedlist>
495 <listitem><para>If possible, do not use the
496 <varname>Type=forking</varname> setting in service files. But
497 if you do, make sure to set the PID file path using
498 <varname>PIDFile=</varname>. See
499 <citerefentry><refentrytitle>systemd.service</refentrytitle><manvolnum>5</manvolnum></citerefentry>
500 for details.</para></listitem>
501
502 <listitem><para>If your daemon registers a D-Bus name on the
503 bus, make sure to use <varname>Type=dbus</varname> in the
504 service file if possible.</para></listitem>
505
506 <listitem><para>Make sure to set a good human-readable
507 description string with
508 <varname>Description=</varname>.</para></listitem>
509
510 <listitem><para>Do not disable
511 <varname>DefaultDependencies=</varname>, unless you really
512 know what you do and your unit is involved in early boot or
513 late system shutdown.</para></listitem>
514
515 <listitem><para>Normally, little if any dependencies should
516 need to be defined explicitly. However, if you do configure
517 explicit dependencies, only refer to unit names listed on
518 <citerefentry><refentrytitle>systemd.special</refentrytitle><manvolnum>7</manvolnum></citerefentry>
519 or names introduced by your own package to keep the unit file
520 operating system-independent.</para></listitem>
521
522 <listitem><para>Make sure to include an
523 <literal>[Install]</literal> section including installation
524 information for the unit file. See
525 <citerefentry><refentrytitle>systemd.unit</refentrytitle><manvolnum>5</manvolnum></citerefentry>
526 for details. To activate your service on boot, make sure to
527 add a <varname>WantedBy=multi-user.target</varname> or
528 <varname>WantedBy=graphical.target</varname> directive. To
529 activate your socket on boot, make sure to add
530 <varname>WantedBy=sockets.target</varname>. Usually, you also
531 want to make sure that when your service is installed, your
532 socket is installed too, hence add
533 <varname>Also=foo.socket</varname> in your service file
534 <filename>foo.service</filename>, for a hypothetical program
535 <filename>foo</filename>.</para></listitem>
536
537 </orderedlist>
538 </refsect2>
539
540 <refsect2>
f95b0be7 541 <title>Installing systemd Service Files</title>
798d3a52
ZJS
542
543 <para>At the build installation time (e.g. <command>make
544 install</command> during package build), packages are
545 recommended to install their systemd unit files in the directory
546 returned by <command>pkg-config systemd
547 --variable=systemdsystemunitdir</command> (for system services)
548 or <command>pkg-config systemd
549 --variable=systemduserunitdir</command> (for user services).
550 This will make the services available in the system on explicit
551 request but not activate them automatically during boot.
552 Optionally, during package installation (e.g. <command>rpm
553 -i</command> by the administrator), symlinks should be created
554 in the systemd configuration directories via the
555 <command>enable</command> command of the
556 <citerefentry><refentrytitle>systemctl</refentrytitle><manvolnum>1</manvolnum></citerefentry>
557 tool to activate them automatically on boot.</para>
558
559 <para>Packages using
560 <citerefentry project='die-net'><refentrytitle>autoconf</refentrytitle><manvolnum>1</manvolnum></citerefentry>
561 are recommended to use a configure script
562 excerpt like the following to determine the
563 unit installation path during source
564 configuration:</para>
565
566 <programlisting>PKG_PROG_PKG_CONFIG
62adf224 567AC_ARG_WITH([systemdsystemunitdir],
fc9acf25 568 [AS_HELP_STRING([--with-systemdsystemunitdir=DIR], [Directory for systemd service files])],,
5486855f
MG
569 [with_systemdsystemunitdir=auto])
570AS_IF([test "x$with_systemdsystemunitdir" = "xyes" -o "x$with_systemdsystemunitdir" = "xauto"], [
571 def_systemdsystemunitdir=$($PKG_CONFIG --variable=systemdsystemunitdir systemd)
572
573 AS_IF([test "x$def_systemdsystemunitdir" = "x"],
798d3a52
ZJS
574 [AS_IF([test "x$with_systemdsystemunitdir" = "xyes"],
575 [AC_MSG_ERROR([systemd support requested but pkg-config unable to query systemd package])])
576 with_systemdsystemunitdir=no],
577 [with_systemdsystemunitdir="$def_systemdsystemunitdir"])])
5486855f
MG
578AS_IF([test "x$with_systemdsystemunitdir" != "xno"],
579 [AC_SUBST([systemdsystemunitdir], [$with_systemdsystemunitdir])])
fc9acf25 580AM_CONDITIONAL([HAVE_SYSTEMD], [test "x$with_systemdsystemunitdir" != "xno"])</programlisting>
62adf224 581
798d3a52
ZJS
582 <para>This snippet allows automatic
583 installation of the unit files on systemd
584 machines, and optionally allows their
585 installation even on machines lacking
586 systemd. (Modification of this snippet for the
587 user unit directory is left as an exercise for the
588 reader.)</para>
62adf224 589
798d3a52
ZJS
590 <para>Additionally, to ensure that
591 <command>make distcheck</command> continues to
592 work, it is recommended to add the following
593 to the top-level <filename>Makefile.am</filename>
594 file in
595 <citerefentry project='die-net'><refentrytitle>automake</refentrytitle><manvolnum>1</manvolnum></citerefentry>-based
596 projects:</para>
62adf224 597
73da5022 598 <programlisting>AM_DISTCHECK_CONFIGURE_FLAGS = \
798d3a52 599 --with-systemdsystemunitdir=$$dc_install_base/$(systemdsystemunitdir)</programlisting>
62adf224 600
798d3a52 601 <para>Finally, unit files should be installed in the system with an automake excerpt like the following:</para>
62adf224 602
798d3a52 603 <programlisting>if HAVE_SYSTEMD
62adf224 604systemdsystemunit_DATA = \
798d3a52
ZJS
605 foobar.socket \
606 foobar.service
62adf224
LP
607endif</programlisting>
608
798d3a52
ZJS
609 <para>In the
610 <citerefentry project='die-net'><refentrytitle>rpm</refentrytitle><manvolnum>8</manvolnum></citerefentry>
611 <filename>.spec</filename> file, use snippets like the following
612 to enable/disable the service during
613 installation/deinstallation. This makes use of the RPM macros
614 shipped along systemd. Consult the packaging guidelines of your
615 distribution for details and the equivalent for other package
616 managers.</para>
8a422bb2 617
798d3a52 618 <para>At the top of the file:</para>
8a422bb2 619
798d3a52 620 <programlisting>BuildRequires: systemd
8a422bb2
LP
621%{?systemd_requires}</programlisting>
622
798d3a52 623 <para>And as scriptlets, further down:</para>
62adf224 624
798d3a52 625 <programlisting>%post
8a422bb2 626%systemd_post foobar.service foobar.socket
62adf224
LP
627
628%preun
8a422bb2 629%systemd_preun foobar.service foobar.socket
ee5762e3
LP
630
631%postun
8a422bb2
LP
632%systemd_postun</programlisting>
633
798d3a52
ZJS
634 <para>If the service shall be restarted during upgrades, replace
635 the <literal>%postun</literal> scriptlet above with the
636 following:</para>
8a422bb2 637
798d3a52 638 <programlisting>%postun
8a422bb2
LP
639%systemd_postun_with_restart foobar.service</programlisting>
640
798d3a52
ZJS
641 <para>Note that <literal>%systemd_post</literal> and
642 <literal>%systemd_preun</literal> expect the names of all units
643 that are installed/removed as arguments, separated by spaces.
644 <literal>%systemd_postun</literal> expects no arguments.
645 <literal>%systemd_postun_with_restart</literal> expects the
646 units to restart as arguments.</para>
647
648 <para>To facilitate upgrades from a package version that shipped
649 only SysV init scripts to a package version that ships both a
650 SysV init script and a native systemd service file, use a
651 fragment like the following:</para>
652
653 <programlisting>%triggerun -- foobar &lt; 0.47.11-1
63415a2d 654if /sbin/chkconfig --level 5 foobar ; then
798d3a52 655 /bin/systemctl --no-reload enable foobar.service foobar.socket >/dev/null 2>&amp;1 || :
6908d384
LP
656fi</programlisting>
657
798d3a52
ZJS
658 <para>Where 0.47.11-1 is the first package version that includes
659 the native unit file. This fragment will ensure that the first
660 time the unit file is installed, it will be enabled if and only
661 if the SysV init script is enabled, thus making sure that the
662 enable status is not changed. Note that
663 <command>chkconfig</command> is a command specific to Fedora
664 which can be used to check whether a SysV init script is
665 enabled. Other operating systems will have to use different
666 commands here.</para>
667 </refsect2>
668 </refsect1>
669
670 <refsect1>
671 <title>Porting Existing Daemons</title>
672
673 <para>Since new-style init systems such as systemd are compatible
674 with traditional SysV init systems, it is not strictly necessary
675 to port existing daemons to the new style. However, doing so
676 offers additional functionality to the daemons as well as
677 simplifying integration into new-style init systems.</para>
678
679 <para>To port an existing SysV compatible daemon, the following
680 steps are recommended:</para>
681
682 <orderedlist>
683 <listitem><para>If not already implemented, add an optional
684 command line switch to the daemon to disable daemonization. This
685 is useful not only for using the daemon in new-style init
686 systems, but also to ease debugging.</para></listitem>
687
688 <listitem><para>If the daemon offers interfaces to other
689 software running on the local system via local
690 <constant>AF_UNIX</constant> sockets, consider implementing
691 socket-based activation (see above). Usually, a minimal patch is
692 sufficient to implement this: Extend the socket creation in the
693 daemon code so that
694 <citerefentry><refentrytitle>sd_listen_fds</refentrytitle><manvolnum>3</manvolnum></citerefentry>
695 is checked for already passed sockets first. If sockets are
696 passed (i.e. when <function>sd_listen_fds()</function> returns a
697 positive value), skip the socket creation step and use the
698 passed sockets. Secondly, ensure that the file system socket
699 nodes for local <constant>AF_UNIX</constant> sockets used in the
700 socket-based activation are not removed when the daemon shuts
701 down, if sockets have been passed. Third, if the daemon normally
702 closes all remaining open file descriptors as part of its
703 initialization, the sockets passed from the init system must be
704 spared. Since new-style init systems guarantee that no left-over
705 file descriptors are passed to executed processes, it might be a
706 good choice to simply skip the closing of all remaining open
707 file descriptors if sockets are passed.</para></listitem>
708
709 <listitem><para>Write and install a systemd unit file for the
710 service (and the sockets if socket-based activation is used, as
711 well as a path unit file, if the daemon processes a spool
712 directory), see above for details.</para></listitem>
713
714 <listitem><para>If the daemon exposes interfaces via D-Bus,
715 write and install a D-Bus activation file for the service, see
716 above for details.</para></listitem>
717 </orderedlist>
718 </refsect1>
719
720 <refsect1>
721 <title>Placing Daemon Data</title>
722
723 <para>It is recommended to follow the general guidelines for
724 placing package files, as discussed in
725 <citerefentry><refentrytitle>file-hierarchy</refentrytitle><manvolnum>7</manvolnum></citerefentry>.</para>
726 </refsect1>
727
728 <refsect1>
729 <title>See Also</title>
730 <para>
731 <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>,
732 <citerefentry><refentrytitle>sd-daemon</refentrytitle><manvolnum>3</manvolnum></citerefentry>,
733 <citerefentry><refentrytitle>sd_listen_fds</refentrytitle><manvolnum>3</manvolnum></citerefentry>,
734 <citerefentry><refentrytitle>sd_notify</refentrytitle><manvolnum>3</manvolnum></citerefentry>,
735 <citerefentry><refentrytitle>daemon</refentrytitle><manvolnum>3</manvolnum></citerefentry>,
736 <citerefentry><refentrytitle>systemd.service</refentrytitle><manvolnum>5</manvolnum></citerefentry>,
737 <citerefentry><refentrytitle>file-hierarchy</refentrytitle><manvolnum>7</manvolnum></citerefentry>
738 </para>
739 </refsect1>
64aba792
LP
740
741</refentry>