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