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