
Significant changes in this version: New section distinguishing a Unix daemon from a “service”; clarify that the API makes the *current* program into a daemon process; consistently discuss PID files (instead of lock files). :PEP: XXX :Title: Standard daemon process library :Version: 0.4 :Last-Modified: 2009-01-29 16:32 :Author: Ben Finney <ben+python@benfinney.id.au> :Status: Draft :Type: Standards Track :Content-Type: text/x-rst :Created: 2009-01-26 :Python-Version: 3.1 :Post-History: ======== Abstract ======== Writing a program to become a well-behaved Unix daemon is somewhat complex and tricky to get right, yet the steps are largely similar for any daemon regardless of what else the program may need to do. This PEP introduces a module to the Python standard library that provides a simple interface to the task of becoming a daemon process. .. contents:: .. Table of Contents: Abstract Specification Example usage Interface ``Daemon`` objects ``DaemonError`` objects Motivation Rationale Correct daemon behaviour A daemon is not a service Reference Implementation Other daemon implementations References Copyright ============= Specification ============= Example usage ============= Simple example of usage:: import daemon from spam import do_main_program this_daemon = daemon.Daemon() this_daemon.start() do_main_program() More complex example usage:: import os import grp import signal import daemon from spam import ( initial_program_setup, do_main_program, program_cleanup, reload_program_config, ) initial_program_setup() important_file = open('spam.data', 'w') interesting_file = open('eggs.data', 'w') this_daemon = daemon.Daemon( working_directory='/var/lib/foo', umask=0o002, terminate_callback=program_cleanup, reload_callback=reload_program_config, reload_signals=[signal.SIGHUP, signal.SIGUSR1], ) this_daemon.files_preserve = [important_file, interesting_file] mail_gid = grp.getgrnam('mail').gr_gid this_daemon.gid = mail_gid this_daemon.start() do_main_program() Interface ========= A new module, `daemon`, is added to the standard library. The module defines a class, `Daemon`, used to represent the settings and controls for a daemon process. An exception class, `DaemonError`, is defined for exceptions raised from the module. ``Daemon`` objects ================== A `Daemon` instance represents the behaviour settings for the process when it becomes a daemon. The behaviour is customised by setting options on the instance, before calling the `start` method. Each option can be passed as a keyword argument to the `Daemon` constructor, or subsequently altered by assigning to an attribute on the instance at any time prior to calling `start`. That is, for an option named `wibble`, the following invocation:: foo = daemon.Daemon(wibble=bar) foo.start() is equivalent to:: foo = daemon.Daemon() foo.wibble = bar foo.start() The following options are defined. `files_preserve` :Default: ``None`` List of files that should *not* be closed when starting the daemon. If ``None``, all open file descriptors will be closed. Elements of the list are file descriptors (as returned by a file object's `fileno()` method) or Python `file` objects. Each specifies a file that is not to be closed during daemon start. `chroot_directory` :Default: ``None`` Full path to a directory to set as the effective root directory of the process. If ``None``, specifies that the root directory is not to be changed. `working_directory` :Default: ``'/'`` Full path of the working directory to which the process should change on daemon start. Since a filesystem cannot be unmounted if a process has its current working directory on that filesystem, this should either be left at default or set to a directory that is a sensible “home directory” for the daemon while it is running. `pidfile_directory` :Default: ``'/var/run'`` Absolute directory path to contain the daemon's PID file. If ``None``, the PID file behaviour for this daemon is skipped. `pidfile_name` :Default: ``None`` Base name of the PID file for this daemon, without directory or suffix. If ``None``, the name is derived from the process command line. `umask` :Default: ``0`` File access creation mask (“umask”) to set for the process on daemon start. Since a process inherits its umask from its parent process, starting the daemon will reset the umask to this value so that files are created by the daemon with access modes as it expects. `ignore_signals` :Default: ``[signal.SIGTTOU, signal.SIGTTIN, signal.SIGTSTP]`` List of signals that the process should ignore (by setting the signal action to ``signal.SIG_IGN``) on daemon start. `terminate_signals` :Default: ``[signal.SIGTERM]`` List of signals that the process should interpret as a request to terminate cleanly. `terminate_callback` :Default: ``None`` Callable to invoke when the process receives any of the `terminate_signals` signals, before then terminating the process. `reload_signals` :Default: ``[signal.SIGHUP]`` List of signals that the process should interpret as a request to reload runtime configuration. `reload_callback` :Default: ``None`` Callable to invoke when the process receives any of the `reload_signals` signals. `uid` :Default: ``None`` The user ID (“uid”) value to switch the process to on daemon start. `gid` :Default: ``None`` The group ID (“gid”) value to switch the process to on daemon start. `prevent_core` :Default: ``True`` If true, prevents the generation of core files, in order to avoid leaking sensitive information from daemons run as `root`. `stdout` :Default: ``None`` File-like object, open for writing (in append mode, 'w+'), that will be used as the new value of `sys.stdout`. If it represents an actual file, it should be listed in `files_preserve` to prevent it being closed during daemon start. If ``None``, then `sys.stdout` is not re-bound. `stderr` :Default: ``None`` File-like object, open for writing (in append mode, 'w+'), that will be used as the new value of `sys.stderr`. If it represents an actual file, it should be listed in `files_preserve` to prevent it being closed during daemon start. If ``None``, then `sys.stderr` is not re-bound. The following methods are defined. `start()` :Return: ``None`` Start the daemon, turning the current program into a daemon process. This performs the following steps: * If the `chroot_directory` attribute is not ``None``: * Set the effective root directory of the process to that directory (via `os.chroot`). This allows running the daemon process inside a “chroot gaol” as a means of limiting the system's exposure to rogue behaviour by the process. * If the `pidfile_directory` attribute is not ``None``: * Look in that directory for a file named '`pidfile_name`.pid'; if it exists, raise a `DaemonError` to prevent multiple instances of the daemon process. * Close all open file descriptors, excluding those listed in the `files_preserve` attribute. * Change current working directory to the path specified by the `working_directory` attribute. * Reset the file access creation mask to the value specified by the `umask` attribute. * Detach the current process into its own process group, and disassociate from any controlling terminal. This step is skipped if it is determined to be redundant: if the process was started by `init`, by `initd`, or by `inetd`. * Set signal handlers as specified by the `ignore_signals`, `terminate_signals`, `reload_signals` attributes. * If the `prevent_core` attribute is true: * Set the resource limits for the process to prevent any core dump from the process. * Set the process uid and gid to the true uid and gid of the process, to relinquish any elevated privilege. * If the `pidfile_directory` attribute is not ``None``: * Create the PID file for this daemon in that directory, by writing a text line containing the current process ID (“PID”) to a file named '`pidfile_name`.pid'. * If either of the attributes `uid` or `gid` are not ``None``: * Set the process uid and/or gid to the specified values. * If either of the attributes `stdout` or `stderr` are not ``None``: * Bind the names `sys.stdout` and/or `sys.stderr` to the corresponding objects. When the function returns, the running program is a daemon process. `reload()` :Return: ``None`` Reload the daemon configuration. The meaning of this is entirely defined by the customisation of this daemon: if the `reload_callback` attribute is not ``None``, call that object. The return value is discarded. `stop()` :Return: ``None`` Stop the daemon, ending the program. This performs the following steps: * If the `terminate_callback` attribute is not ``None``: * Call that object. The return value is discarded. * If the `pidfile_directory` attribute is not ``None``: * Delete the PID file for this daemon. * Raise a `SystemExit` exception. ``DaemonError`` objects ======================= The `DaemonError` class inherits from `Exception`. The module implementation will raise an instance of `DaemonError` when an error occurs in processing daemon behaviour. ========== Motivation ========== The majority of programs written to be Unix daemons either implement behaviour very similar to that in the `specification`_, or are poorly-behaved daemons by the `correct daemon behaviour`_. Since these steps should be much the same in most implementations but are very particular and easy to omit or implement incorrectly, they are a prime target for a standard well-tested implementation in the standard library. ========= Rationale ========= Correct daemon behaviour ======================== According to Stevens in [stevens]_ §2.6, a program should perform the following steps to become a Unix daemon process. * Close all open file descriptors. * Change current working directory. * Reset the file access creation mask. * Run in the background. * Disassociate from process group. * Ignore terminal I/O signals. * Disassociate from control terminal. * Don't reacquire a control terminal. * Correctly handle the following circumstances: * Started by System V `init` process. * Daemon termination by ``SIGTERM`` signal. * Children generate ``SIGCLD`` signal. The `daemon` tool [slack-daemon]_ lists (in its summary of features) behaviour that should be performed when turning a program into a well-behaved Unix daemon process. It differs from this PEP's intent in that it invokes a *separate* program as a daemon process. The following features are appropriate for a daemon that starts itself once the program is already running: * Sets up the correct process context for a daemon. * Behaves sensibly when started by `initd(8)` or `inetd(8)`. * Revokes any suid or sgid privileges to reduce security risks in case daemon is incorrectly installed with special privileges. * Prevents the generation of core files to prevent leaking sensitive information from daemons run as root (optional). * Names the daemon by creating and locking a PID file to guarantee that only one daemon with the given name can execute at any given time (optional). * Sets the user and group under which to run the daemon (optional, root only). * Creates a chroot gaol (optional, root only). * Captures the daemon's stdout and stderr and directs them to syslog (optional). A daemon is not a service ========================= This PEP addresses only Unix-style daemons, for which the above correct behaviour is relevant, as opposed to comparable behaviours on other operating systems. There is a related concept in many systems, called a “service”. A service differs from the model in this PEP, in that rather than having the *current* program continue to run as a daemon process, a service starts an *additional* process to run in the background, and the current process communicates with that additional process via some defined channels. The Unix-style daemon model in this PEP can be used, among other things, to implement the background-process part of a service; but this PEP does not address the other aspects of setting up and managing a service. It is the opinion of this PEP's author that combining the two disparate systems of behaviour under a single API would be contrary to the focus of this PEP. ======================== Reference Implementation ======================== The `python-daemon` package [python-daemon]_. As of 2009-01-26, the package is under active development and is not yet a full implementation of this PEP. Other daemon implementations ============================ Prior to this PEP, several existing third-party Python libraries or tools implemented some of this PEP's `correct daemon behaviour`_. The `reference implementation`_ is a fairly direct successor from the following implementations: * Many good ideas were contributed by the community to Python cookbook recipe 66012 [cookbook-66012]_. * The `bda.daemon` library [bda.daemon]_ is an implementation of [cookbook-66012]_. It is the predecessor of [python-daemon]_. Other Python daemon implementations that differ from this PEP: * The `zdaemon` tool [zdaemon]_ was written for the Zope project. Like [slack-daemon]_, it differs from this specification because it is used to run another program as a daemon process. * The Python library `daemon` [clapper-daemon]_ is (according to its homepage) no longer maintained. As of version 1.0.1, it implements the basic steps from [stevens]_. * The `daemonize` library [seutter-daemonize]_ also implements the basic steps from [stevens]_. * Twisted [twisted]_ includes, perhaps unsurprisingly, an implementation of a process daemonisation API that is integrated with the rest of the Twisted framework; it differs significantly from the API in this PEP. * The Python `initd` library [dagitses-initd]_, which uses [clapper-daemon]_, implements an equivalent of Unix `initd(8)` for controlling a daemon process. ========== References ========== .. [stevens] `Unix Network Programming`, W. Richard Stevens, 1994 Prentice Hall. .. [slack-daemon] The (non-Python) “libslack” implementation of a `daemon` tool `<http://www.libslack.org/daemon/>`_ by “raf” <raf@raf.org>. .. [python-daemon] The `python-daemon` library `<http://pypi.python.org/pypi/python-daemon/>`_ by Ben Finney et al. .. [cookbook-66012] Python Cookbook recipe 66012, “Fork a daemon process on Unix” `<http://code.activestate.com/recipes/66012/>`_. .. [bda.daemon] The `bda.daemon` library `<http://pypi.python.org/pypi/bda.daemon/>`_ by Robert Niederreiter et al. .. [zdaemon] The `zdaemon` tool `<http://pypi.python.org/pypi/zdaemon/>`_ by Guido van Rossum et al. .. [clapper-daemon] The `daemon` library `<http://pypi.python.org/pypi/daemon/>`_ by Brian Clapper. .. [seutter-daemonize] The `daemonize` library `<http://daemonize.sourceforge.net/>`_ by Jerry Seutter. .. [twisted] The `Twisted` application framework `<http://pypi.python.org/pypi/Twisted/>`_ by Glyph Lefkowitz et al. .. [dagitses-initd] The Python `initd` library `<http://pypi.python.org/pypi/initd/>`_ by Michael Andreas Dagitses. ========= Copyright ========= This work is hereby placed in the public domain. To the extent that placing a work in the public domain is not legally possible, the copyright holder hereby grants to all recipients of this work all rights and freedoms that would otherwise be restricted by copyright. .. Local variables: mode: rst coding: utf-8 time-stamp-start: "^:Last-Modified:[ ]+" time-stamp-end: "$" time-stamp-line-limit: 20 time-stamp-format: "%:y-%02m-%02d %02H:%02M" End: vim: filetype=rst fileencoding=utf-8 :