[Python-ideas] Draft PEP (version 0.2): Standard daemon process library

Ben Finney ben+python at benfinney.id.au
Tue Jan 27 01:45:53 CET 2009


Significant changes: new section “Other daemon implementations” with
brief descriptions of their relationship to this PEP.


:PEP:               XXX
:Title:             Standard daemon process library
:Version:           0.2
:Last-Modified:     2009-01-27 11:28
:Author:            Ben Finney <ben+python at 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
    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()

    this_daemon.files_preserve = [important_file, interesting_file]

    this_daemon.working_directory = '/var/lib/foo'
    this_daemon.umask = 0o002

    mail_gid = grp.getgrnam('mail').gr_gid
    this_daemon.gid = mail_gid

    this_daemon.terminate_callback = program_cleanup
    this_daemon.reload_callback = reload_program_config
    this_daemon.reload_signals = [signal.SIGHUP, signal.SIGUSR1]

    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
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
attributes on the instance, before calling the `start` method.

The following attributes 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.

`lockfile_directory`
    :Default: ``'/var/run'``

    Absolute directory path to contain the daemon's lockfile. If
    ``None``, the lockfile behaviour for this daemon is skipped.

`lockfile_name`
    :Default: ``None``

    Base name of the lockfile 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. 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 `lockfile_directory` attribute is not ``None``:

      * Look in that directory for a file named '`lockfile_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 `lockfile_directory` attribute is not ``None``:

      * Create the lockfile for this daemon in that directory, by
        writing a text line containing the current process ID (“pid”)
        to a file named '`lockfile_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.

`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. This performs the following steps:

    * If the `terminate_callback` attribute is not ``None``:

      * Call that object. The return value is discarded.

    * If the `lockfile_directory` attribute is not ``None``:

      * Delete the lockfile 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).


========================
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 (by
  Robert Niederreiter et al) 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 at 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.


-- 
 \      “I went to a garage sale. ‘How much for the garage?’ ‘It's not |
  `\                                        for sale.’” —Steven Wright |
_o__)                                                                  |
Ben Finney




More information about the Python-ideas mailing list