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