Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Writing a well-behaved daemon

403 views
Skip to first unread message

Ben Finney

unread,
Sep 26, 2008, 1:08:33 AM9/26/08
to
Howdy all,

Writing a Python program to become a Unix daemon is relatively
well-documented: there's a recipe for detaching the process and
running in its own process group. However, there's much more to a Unix
daemon than simply detaching. At a minimum, a well-behaved Unix daemon
must at least:

* Detach the process into its own process group

* Close stdin, redirect stdout and stderr to a null device

* Handle its own PID file: refuse to start if the PID file already
exists, write the PID file on startup otherwise, and remove the PID
file on termination

* Revoke setuid and setgid privileges, which are strongly deprecated
these days

* Handle interrupts, cleaning up the process and PID file as necessary

* (possible others)

There are also many other commonly-expected tasks that well-behaved
Unix daemons perform (drop privileges to a nominated non-root user and
group after daemonising, redirect output to syslog instead, operate in
a chroot jail, respawn when terminated, etc.).

All of this stuff has been done numerous times before, and the basics
are mostly agreed upon. Yet all of these are tricky to implement
correctly, and tedious to re-implement in every program intended to
run as a daemon.


The 'daemon' program <URL:http://www.libslack.org/daemon/> covers all
these, and allows an arbitrary process to be started as a well-behaved
Unix daemon process. It's not a good assumption that this program is
installed on an arbitrary system though, and it seems excessive to ask
the recipient of one's program to get a third-party program just in
order to make a daemon process.

I'd love to be able to have something similar for Python programs,
e.g. a 'become_well_behaved_daemon()' function that implements all the
above and perhaps takes optional arguments for the optional features.

My searches for such functionality haven't borne much fruit though.
Apart from scattered recipes, none of which cover all the essentials
(let alone the optional features) of 'daemon', I can't find anything
that could be relied upon. This is surprising, since I'd expect this
in Python's standard library.

Can anyone point me to the equivalent of the 'daemon' program in the
form of a well-tested Python library?

--
\ “Tis more blessed to give than to receive; for example, wedding |
`\ presents.” —Henry L. Mencken |
_o__) |
Ben Finney

Sean DiZazzo

unread,
Sep 26, 2008, 1:31:59 AM9/26/08
to

http://code.activestate.com/recipes/66012/

I actually use a brew of the original recipe combined with several of
the great comments. The commenters add alot of the functionality that
you are looking for. It works very well on most counts, but doesn't
handle being killed well. The daemons often last for a few weeks to a
month before something unexpected kills them off. If I was more
careful, I think they could live much longer.

Looks like somebody did the same thing I did and posted it.

http://svn.plone.org/svn/collective/bda.daemon/trunk/bda/daemon/daemon.py

~Sean

Ben Finney

unread,
Sep 26, 2008, 3:13:29 AM9/26/08
to
Sean DiZazzo <half.i...@gmail.com> writes:

> Looks like somebody did the same thing I did and posted it.
>
> http://svn.plone.org/svn/collective/bda.daemon/trunk/bda/daemon/daemon.py

Thanks, I've not seen that before.

It still seems loony to me that something this difficult to do right,
yet so similar across different use cases, isn't in the standard
library, where bugs need only be fixed in one place.

--
\ “Pinky, are you pondering what I'm pondering?” “Wuh, I think |
`\ so, Brain, but how will we get three pink flamingos into one |
_o__) pair of Capri pants?” —_Pinky and The Brain_ |
Ben Finney

Sean DiZazzo

unread,
Sep 26, 2008, 2:20:36 PM9/26/08
to
On Sep 26, 12:13 am, Ben Finney <bignose+hates-s...@benfinney.id.au>
wrote:

> Sean DiZazzo <half.ital...@gmail.com> writes:
> > Looks like somebody did the same thing I did and posted it.
>
> >http://svn.plone.org/svn/collective/bda.daemon/trunk/bda/daemon/daemo...

>
> Thanks, I've not seen that before.
>
> It still seems loony to me that something this difficult to do right,
> yet so similar across different use cases, isn't in the standard
> library, where bugs need only be fixed in one place.
>
> --
>  \        “Pinky, are you pondering what I'm pondering?” “Wuh, I think |
>   `\      so, Brain, but how will we get three pink flamingos into one |
> _o__)                     pair of Capri pants?” —_Pinky and The Brain_ |
> Ben Finney

+1 I think it would be a great addition.

Ben Finney

unread,
Mar 20, 2009, 5:58:58 AM3/20/09
to
Ben Finney <b...@benfinney.id.au> writes:

> Writing a Python program to become a Unix daemon is relatively
> well-documented: there's a recipe for detaching the process and
> running in its own process group. However, there's much more to a
> Unix daemon than simply detaching.

[…]

> My searches for such functionality haven't borne much fruit though.
> Apart from scattered recipes, none of which cover all the essentials
> (let alone the optional features) of 'daemon', I can't find anything
> that could be relied upon. This is surprising, since I'd expect this
> in Python's standard library.

I've submitted PEP 3143 <URL:http://www.python.org/dev/peps/pep-3143/>
to meet this need, and have re-worked an existing library into a new
‘python-daemon’ <URL:http://pypi.python.org/pypi/python-daemon/>
library, the reference implementation.

Now I need wider testing and scrutiny of the implementation and
specification.

One point to note: This is only intended to address the task of a
program transforming *itself* into a daemon process. If you want to
spawn off *extra* processes and manage them through a “service”
channel, you want something this spec was never meant to cover. You
may be interested in discussing that further on a separate thread at
<URL:http://mail.python.org/pipermail/python-ideas/2009-January/002606.html>.


If you want to turn your program into a well-behaved daemon process,
I'd like to know how well PEP 3143 works for you. Please try it out
for your daemon programs and discuss!

--
\ “The whole area of [treating source code as intellectual |
`\ property] is almost assuring a customer that you are not going |
_o__) to do any innovation in the future.” —Gary Barnett |
Ben Finney

Ben Finney

unread,
Mar 20, 2009, 6:47:00 AM3/20/09
to
Ben Finney <ben+p...@benfinney.id.au> writes:

> I've submitted PEP 3143 <URL:http://www.python.org/dev/peps/pep-3143/>
> to meet this need, and have re-worked an existing library into a new
> ‘python-daemon’ <URL:http://pypi.python.org/pypi/python-daemon/>
> library, the reference implementation.
>
> Now I need wider testing and scrutiny of the implementation and
> specification.


PEP: 3143
Title: Standard daemon process library
Version: $Revision: 1.1 $
Last-Modified: $Date: 2009-03-19 12:51 $
Author: Ben Finney <ben+p...@benfinney.id.au>
Status: Draft
Type: Standards Track
Content-Type: text/x-rst
Created: 2009-01-26
Python-Version: 3.2
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 package 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
``DaemonContext`` 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 direct `DaemonContext` usage::

import daemon

from spam import do_main_program

with daemon.DaemonContext() as daemon_context:
do_main_program()

More complex example usage::

import os
import grp
import signal
import daemon
import lockfile

from spam import (
initial_program_setup,
do_main_program,
program_cleanup,
reload_program_config,
)

context = daemon.DaemonContext(
working_directory='/var/lib/foo',
umask=0o002,
pidfile=lockfile.FileLock('/var/run/spam.pid'),
)

context.signal_map = {
signal.SIGTERM: program_cleanup,
signal.SIGHUP: 'terminate',
signal.SIGUSR1: reload_program_config,
}

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

important_file = open('spam.data', 'w')
interesting_file = open('eggs.data', 'w')
context.files_preserve = [important_file, interesting_file]

initial_program_setup()

with context:
do_main_program()


Interface
=========

A new package, `daemon`, is added to the standard library.

A class, `DaemonContext`, is defined to represent the settings and
process context for the program running as a daemon process.


``DaemonContext`` objects
=========================

A `DaemonContext` instance represents the behaviour settings and
process context for the program when it becomes a daemon. The
behaviour and environment is customised by setting options on the
instance, before calling the `open` method.

Each option can be passed as a keyword argument to the `DaemonContext`
constructor, or subsequently altered by assigning to an attribute on
the instance at any time prior to calling `open`. That is, for
options named `wibble` and `wubble`, the following invocation::

foo = daemon.DaemonContext(wibble=bar, wubble=baz)
foo.open()

is equivalent to::

foo = daemon.DaemonContext()
foo.wibble = bar
foo.wubble = baz
foo.open()

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.

`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.

`pidfile`
:Default: ``None``

Context manager for a PID lock file. When the daemon context opens
and closes, it enters and exits the `pidfile` context manager.

`detach_process`
:Default: ``None``

If ``True``, detach the process context when opening the daemon
context; if ``False``, do not detach.

If unspecified (``None``) during initialisation of the instance,
this will be set to ``True`` by default, and ``False`` only if
detaching the process is determined to be redundant; for example,
in the case when the process was started by `init`, by `initd`, or
by `inetd`.

`signal_map`
:Default: system-dependent

Mapping from operating system signals to callback actions.

The mapping is used when the daemon context opens, and determines
the action for each signal's signal handler:

* A value of ``None`` will ignore the signal (by setting the
signal action to ``signal.SIG_IGN``).

* A string value will be used as the name of an attribute on the
``DaemonContext`` instance. The attribute's value will be used
as the action for the signal handler.

* Any other value will be used as the action for the signal
handler.

The default value depends on which signals are defined on the
running system. Each item from the list below whose signal is
actually defined in the ``signal`` module will appear in the
default map:

* ``signal.SIGCLD``: ``None``

* ``signal.SIGTTIN``: ``None``

* ``signal.SIGTTOU``: ``None``

* ``signal.SIGTSTP``: ``None``

* ``signal.SIGTERM``: ``'terminate'``

`uid`
:Default: ``os.getuid()``

`gid`
:Default: ``os.getgid()``

The user ID (“UID”) value and group ID (“GID”) value to switch
the process to on daemon start.

The default values, the real UID and GID of the process, will
relinquish any effective privilege elevation inherited by the
process.

`prevent_core`
:Default: ``True``

If true, prevents the generation of core files, in order to avoid
leaking sensitive information from daemons run as `root`.

`stdin`
:Default: ``None``

`stdout`
:Default: ``None``

`stderr`
:Default: ``None``

Each of `stdin`, `stdout`, and `stderr` is a file-like object
which will be used as the new file for the standard I/O stream
`sys.stdin`, `sys.stdout`, and `sys.stderr` respectively. The file
should therefore be open, with a minimum of mode 'r' in the case
of `stdin`, and mode 'w+' in the case of `stdout` and `stderr`.

If the object has a `fileno()` method that returns a file
descriptor, the corresponding file will be excluded from being
closed during daemon start (that is, it will be treated as though
it were listed in `files_preserve`).

If ``None``, the corresponding system stream is re-bound to the
file named by `os.devnull`.


The following methods are defined.

`open()`
:Return: ``None``

Open the daemon context, turning the current program into a daemon
process. This performs the following steps:

* If the `prevent_core` attribute is true, set the resource limits
for the process to prevent any core dump from the process.

* 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. Note that the specified directory needs to
already be set up for this purpose.

* Set the process UID and GID to the `uid` and `gid` attribute
values.

* Close all open file descriptors. This excludes those listed in
the `files_preserve` attribute, and those that correspond to the
`stdin`, `stdout`, or `stderr` attributes.

* 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.

* If the `detach_process` option is true, detach the current
process into its own process group, and disassociate from any
controlling terminal.

* Set signal handlers as specified by the `signal_map` attribute.

* If any of the attributes `stdin`, `stdout`, `stderr` are not
``None``, bind the system streams `sys.stdin`, `sys.stdout`,
and/or `sys.stderr` to the files represented by the
corresponding attributes. Where the attribute has a file
descriptor, the descriptor is duplicated (instead of re-binding
the name).

* If the `pidfile` attribute is not ``None``, enter its context
manager.

When the function returns, the running program is a daemon
process.

`close()`
:Return: ``None``

Close the daemon context. This does nothing by default, but may be
overridden by a derived class.

`terminate(signal_number, stack_frame)`
:Return: ``None``

Signal handler for the ``signal.SIGTERM`` signal. Performs the
following steps:

* If the `pidfile` attribute is not ``None``, exit its context
manager.

* Call the `close()` method.

* Raise a ``SystemExit`` exception.

The class also implements the context manager protocol via
``__enter__`` and ``__exit__`` methods.

`__enter__()`
:Return: The ``DaemonContext`` instance

Call the instance's `open()` method, then return the instance.

`__exit__(exc_type, exc_value, exc_traceback)`
:Return: ``True`` or ``False`` as defined by the context manager
protocol

Call the instance's `close()` method, then return ``True`` if the
exception was handled or ``False`` if it was not.


==========
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.


========================
Reference Implementation
========================

The `python-daemon` package [python-daemon]_.

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
recipes #66012 [cookbook-66012]_ and #278731 [cookbook-278731]_.

* 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]_.

* Ray Burr's `daemon.py` module [burr-daemon]_ provides the [stevens]_
procedure as well as PID file handling and redirection of output to
syslog.

* 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” <r...@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/>`_.

.. [cookbook-278731]

Python Cookbook recipe 278731, “Creating a daemon the Python way”
`<http://code.activestate.com/recipes/278731/>`_.

.. [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.

.. [burr-daemon]

The `daemon.py` module
`<http://www.nightmare.com/~ryb/code/daemon.py>`_ by Ray Burr.

.. [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.


--
\ “It ain't so much the things we don't know that get us in |
`\ trouble. It's the things we know that ain't so.” —Artemus Ward |
_o__) (1834-67), U.S. journalist |
Ben Finney

Jean-Paul Calderone

unread,
Mar 20, 2009, 9:02:15 AM3/20/09
to pytho...@python.org
On Fri, 20 Mar 2009 20:58:58 +1100, Ben Finney <ben+p...@benfinney.id.au> wrote:
>Ben Finney <b...@benfinney.id.au> writes:
>
>> Writing a Python program to become a Unix daemon is relatively
>> well-documented: there's a recipe for detaching the process and
>> running in its own process group. However, there's much more to a
>> Unix daemon than simply detaching.
>[…]
>
>> My searches for such functionality haven't borne much fruit though.
>> Apart from scattered recipes, none of which cover all the essentials
>> (let alone the optional features) of 'daemon', I can't find anything
>> that could be relied upon. This is surprising, since I'd expect this
>> in Python's standard library.
>
>I've submitted PEP 3143 <URL:http://www.python.org/dev/peps/pep-3143/>
>to meet this need, and have re-worked an existing library into a new
>‘python-daemon’ <URL:http://pypi.python.org/pypi/python-daemon/>
>library, the reference implementation.
>
>Now I need wider testing and scrutiny of the implementation and
>specification.

The biggest shortcoming seems to be a complete lack of unit tests. A
quick skim of the code suggests that part of it don't even work at all
and have never been tested, even interactively, since they must surely
fail. For example, uid/gid setting is broken.

I'd recommend adding an automated test suite, fixing all the issues that
come up during that process, and then asking for scrutiny again.

Jean-Paul

Jean-Paul Calderone

unread,
Mar 20, 2009, 9:39:12 AM3/20/09
to pytho...@python.org
On Fri, 20 Mar 2009 21:47:00 +1100, Ben Finney <bignose+h...@benfinney.id.au> wrote:
>
> [snip]

Somewhat by accident I noticed this other part of the PEP:

>
>Other Python daemon implementations that differ from this PEP:
>

> [snip]


>
>* 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.

What do you mean be "integrated"? Twisted's daemonization code is
in a free function which depends only on the os module. It's basically
as un-integrated as could be (it's also only 14 lines long).

Jean-Paul

Floris Bruynooghe

unread,
Mar 20, 2009, 11:47:47 AM3/20/09
to
On Mar 20, 9:58 am, Ben Finney <ben+pyt...@benfinney.id.au> wrote:
> Ben Finney <b...@benfinney.id.au> writes:
> > Writing a Python program to become a Unix daemon is relatively
> > well-documented: there's a recipe for detaching the process and
> > running in its own process group. However, there's much more to a
> > Unix daemon than simply detaching.
>
> […]
>
> > My searches for such functionality haven't borne much fruit though.
> > Apart from scattered recipes, none of which cover all the essentials
> > (let alone the optional features) of 'daemon', I can't find anything
> > that could be relied upon. This is surprising, since I'd expect this
> > in Python's standard library.
>
> I've submitted PEP 3143 <URL:http://www.python.org/dev/peps/pep-3143/>
> to meet this need, and have re-worked an existing library into a new
> ‘python-daemon’ <URL:http://pypi.python.org/pypi/python-daemon/>
> library, the reference implementation.
>
> Now I need wider testing and scrutiny of the implementation and
> specification.

Had a quick look at the PEP and it looks very nice IMHO.

One of the things that might be interesting is keeping file
descriptors from the logging module open by default. So that you can
setup your loggers before you daemonise --I do this so that I can
complain on stdout if that gives trouble-- and are still able to use
them once you've daemonised. I haven't looked at how feasable this is
yet so it might be difficult, but useful anyway.


Regards
Floris

Ben Finney

unread,
Mar 21, 2009, 7:06:45 PM3/21/09
to
Floris Bruynooghe <floris.b...@gmail.com> writes:

> Had a quick look at the PEP and it looks very nice IMHO.

Thank you. I hope you can try the implementation and report feedback
on that too.

> One of the things that might be interesting is keeping file
> descriptors from the logging module open by default.

Hmm. I see that this would be a good idea. but it raises the question
of how to manage the set of file handles that should not be closed on
becoming a daemon.

So far, the logic of closing the file descriptors is a little complex:

* Close all open file descriptors. This excludes those listed in
the `files_preserve` attribute, and those that correspond to the
`stdin`, `stdout`, or `stderr` attributes.

Extending that by saying “… and also any file descriptors for
``logging.FileHandler`` objects” starts to make the description too
complex. I have a strong instinct that it the description is complex,
the design might be bad.

Can you suggest an alternative API that will ensure that all file
descriptors get closed *except* those that should not be closed?

--
\ “The Bermuda Triangle got tired of warm weather. It moved to |
`\ Alaska. Now Santa Claus is missing.” —Steven Wright |
_o__) |
Ben Finney

Ben Finney

unread,
Mar 21, 2009, 7:19:58 PM3/21/09
to
Jean-Paul Calderone <exa...@divmod.com> writes:

> The biggest shortcoming seems to be a complete lack of unit tests.

A full unit test suite is in the source distribution's ‘tests/’
directory. You can run it with ‘python ./setup.py test’.

> A quick skim of the code suggests that part of it don't even work at
> all and have never been tested, even interactively, since they must
> surely fail. For example, uid/gid setting is broken.

This doesn't help identify the problem. Can you explain what you see
as broken, preferably after running the code to observe its behaviour?

--
\ “Science shows that belief in God is not only obsolete. It is |
`\ also incoherent.” —Victor J. Stenger, 2001 |
_o__) |
Ben Finney

Jean-Paul Calderone

unread,
Mar 21, 2009, 9:29:37 PM3/21/09
to pytho...@python.org
On Sun, 22 Mar 2009 10:19:58 +1100, Ben Finney <ben+p...@benfinney.id.au> wrote:
>Jean-Paul Calderone <exa...@divmod.com> writes:
>
>> The biggest shortcoming seems to be a complete lack of unit tests.
>
>A full unit test suite is in the source distribution's ‘tests/’
>directory. You can run it with ‘python ./setup.py test’.

Of course this is correct. My apologizes for my incorrect statement. I
was probably looking for the tests in the "daemon" directory, not used to
seeing them outside the package they are testing. In my hurry I didn't
see them.

>> A quick skim of the code suggests that part of it don't even work at
>> all and have never been tested, even interactively, since they must
>> surely fail. For example, uid/gid setting is broken.
>
>This doesn't help identify the problem. Can you explain what you see
>as broken, preferably after running the code to observe its behaviour?

Here is a demonstration of the problem:

# python -c '
from __future__ import with_statement
import sys, daemon, os
with daemon.DaemonContext(stdout=sys.stdout, stdin=sys.stdin,
stderr=sys.stderr, uid=1, gid=1) as c:
pass
'
Traceback (most recent call last):
File "<string>", line 5, in <module>
File "daemon/daemon.py", line 342, in __enter__
File "daemon/daemon.py", line 325, in open
OSError: [Errno 1] Operation not permitted

This happens because setuid is called before setgid. This means that by
the time setgid is called, it is no longer allowed. Reversing the order
is a simple fix. An additional feature which would be useful for the
library to provide, however, would be the setting of euid and egid instead
of uid and gid. This is necessary, for example, to write an SSH daemon
which gives out user shells.

Jean-Paul

Ben Finney

unread,
Mar 24, 2009, 12:42:46 AM3/24/09
to pytho...@python.org
Jean-Paul Calderone <exa...@divmod.com> writes:

> Here is a demonstration of the problem:
>
> # python -c '
> from __future__ import with_statement
> import sys, daemon, os
> with daemon.DaemonContext(stdout=sys.stdout, stdin=sys.stdin,
> stderr=sys.stderr, uid=1, gid=1) as c:
> pass
> '
> Traceback (most recent call last):
> File "<string>", line 5, in <module>
> File "daemon/daemon.py", line 342, in __enter__
> File "daemon/daemon.py", line 325, in open
> OSError: [Errno 1] Operation not permitted

This hadn't occurred during my testing, but I can see the logic of it.
I've now added a test and fixed this; it will be in the next release.
Thank you!

> An additional feature which would be useful for the library to
> provide, however, would be the setting of euid and egid instead of
> uid and gid. This is necessary, for example, to write an SSH daemon
> which gives out user shells.

That sounds rather more specific than is needed for the generic
library being proposed here. I'm wary of adding features to an API
that is already quite complex.

Isn't setting the EUID and EGID something that is just as easily done
*after* the program achieves a daemon process?

--
\ “If it ain't bust don't fix it is a very sound principle and |
`\ remains so despite the fact that I have slavishly ignored it |
_o__) all my life.” —Douglas Adams |
Ben Finney

Jean-Paul Calderone

unread,
Mar 24, 2009, 10:11:22 AM3/24/09
to pytho...@python.org
On Tue, 24 Mar 2009 15:42:46 +1100, Ben Finney <bignose+h...@benfinney.id.au> wrote:
>Jean-Paul Calderone <exa...@divmod.com> writes:
>
> [snip]

>
>> An additional feature which would be useful for the library to
>> provide, however, would be the setting of euid and egid instead of
>> uid and gid. This is necessary, for example, to write an SSH daemon
>> which gives out user shells.
>
>That sounds rather more specific than is needed for the generic
>library being proposed here. I'm wary of adding features to an API
>that is already quite complex.
>
>Isn't setting the EUID and EGID something that is just as easily done
>*after* the program achieves a daemon process?

That depends.

If you mean that one can ignore the uid and gid setting features of the
proposed library so that they are not changed during daemonization and
then make the appropriate calls from the application afterwards, then
yes.

Otherwise, no. Since this means all of your daemon startup code is forced
to run as a privileged process when it might otherwise have run without
those privileges, I think it's worth the tiny additional complexity it
will bring to the API (and it really is pretty tiny, something on the order
of a new `set_effective=True´ flag).

Jean-Paul

Floris Bruynooghe

unread,
Mar 24, 2009, 10:58:36 AM3/24/09
to
On Mar 21, 11:06 pm, Ben Finney <ben+pyt...@benfinney.id.au> wrote:

> Floris Bruynooghe <floris.bruynoo...@gmail.com> writes:
> > Had a quick look at the PEP and it looks very nice IMHO.
>
> Thank you. I hope you can try the implementation and report feedback
> on that too.
>
> > One of the things that might be interesting is keeping file
> > descriptors from the logging module open by default.
>
> Hmm. I see that this would be a good idea. but it raises the question
> of how to manage the set of file handles that should not be closed on
> becoming a daemon.
>
> So far, the logic of closing the file descriptors is a little complex:
>
>     * Close all open file descriptors. This excludes those listed in
>       the `files_preserve` attribute, and those that correspond to the
>       `stdin`, `stdout`, or `stderr` attributes.
>
> Extending that by saying “… and also any file descriptors for
> ``logging.FileHandler`` objects” starts to make the description too
> complex. I have a strong instinct that it the description is complex,
> the design might be bad.
>
> Can you suggest an alternative API that will ensure that all file
> descriptors get closed *except* those that should not be closed?

Not an answer yet, but I'll try to find time in the next few days to
play with this and tell you what I think. logging.FileHandler would
be too narrow in any case I think.


Regards
Floris

Ben Finney

unread,
Mar 24, 2009, 5:51:55 PM3/24/09
to pytho...@python.org
Jean-Paul Calderone <exa...@divmod.com> writes:

> On Tue, 24 Mar 2009 15:42:46 +1100, Ben Finney <bignose+h...@benfinney.id.au> wrote:
> >That sounds rather more specific than is needed for the generic
> >library being proposed here. I'm wary of adding features to an API
> >that is already quite complex.
> >
> >Isn't setting the EUID and EGID something that is just as easily
> >done *after* the program achieves a daemon process?
>
> That depends.
>
> If you mean that one can ignore the uid and gid setting features of the
> proposed library so that they are not changed during daemonization and
> then make the appropriate calls from the application afterwards, then
> yes.

Yes, that's what I meant.

> Otherwise, no. Since this means all of your daemon startup code is
> forced to run as a privileged process when it might otherwise have
> run without those privileges

Er? You can still set the real UID and GID via the DaemonContext API,
and then also set the EUID and EGID.

> I think it's worth the tiny additional complexity it will bring to
> the API (and it really is pretty tiny, something on the order of a
> new `set_effective=True´ flag).

It leads immediately to the request to set *both* real UID/GID *and*
effective UID/GID to separate values.

Can you describe the use case more, so I can understand better how
common it might be? In what circumstances must one not change the real
UID/GID but instead change the effective UID/GID, *and* must change
them during daemonisation?

--
\ “One thing vampire children have to be taught early on is, |
`\ don't run with a wooden stake.” —Jack Handey |
_o__) |
Ben Finney

Ben Finney

unread,
Mar 25, 2009, 9:46:47 AM3/25/09
to Francis Irving
Ben Finney <ben+p...@benfinney.id.au> writes:

> I've submitted PEP 3143
> <URL:http://www.python.org/dev/peps/pep-3143/> to meet this need,
> and have re-worked an existing library into a new ‘python-daemon’
> <URL:http://pypi.python.org/pypi/python-daemon/> library, the
> reference implementation.
>
> Now I need wider testing and scrutiny of the implementation and
> specification.

Thank you to those who have submitted bug reports so far. I have
addressed some bugs and uploaded version 1.4.4 of ‘python-daemon’ to
PyPI. Changes include:

* Catch and report some OSError exceptions thrown by various steps.

* Wait until later in the daemonisation process to cloase all open
file descriptors. This gives a chance to see errors reported earlier
in the process!

* Redirect standard streams to the null device if no stream specified.

Testing and feedback is still welcome, I want to knock this PEP and
implementation into better shape.

--
\ “I have never imputed to Nature a purpose or a goal, or |
`\ anything that could be understood as anthropomorphic.” —Albert |
_o__) Einstein, unsent letter, 1955 |
Ben Finney

Ben Finney

unread,
Mar 26, 2009, 4:49:02 AM3/26/09
to
(replying in ‘comp.lang.python’ for wider feedback on this issue)

On 26-Mar-2009, Francis Irving wrote:
> On Thu, Mar 26, 2009 at 12:51:06AM +1100, Ben Finney wrote:
> > The ‘python-daemon’ distribution includes a module,
> > ‘daemon.pidlockfile’. The ‘daemon.pidlockfile.PIDLockFile’ class is
> > intended to be used for this purpose.
>
> > I am working with the developer of ‘lockfile’ to incorporate the
> > ‘PIDLockFile’ class into that library.
>
> Ah! I didn't know about that! Can you update:
>
> a) The example in the PEP to use it.

No, PEP 3143 is deliberately not tied to that implementation. PID file
handling is purely an interface from the point of view of that PEP.

When I said “the PIDLockFile class is intended to be used for this
purpose”, that's strictly one-way. PEP 3143 is not meant to refer to
the PIDLockFile class, only to a generic interface (context manager)
for a ‘pidfile’ object.

If the ‘pidlockfile’ module improves enough, and the ‘lockfile’
maintainer gets my changes into a release in time, I may update the
PEP to recommend that; but so far, it's outside the scope.

> b) In the documentation, give a list of different classes that might
> be appropriate to use here. Recommending that one, but pointing to
> the ones in lockfile also.

I don't have one to recommend yet:

> c) Its own documentation (maybe some doctests in the source? or some
> help?) which show how it works.
>
> I'm still not having much luck with it though :(

This is part of why it's not recommended in the PEP; it's not really
ready. Thank you for testing it :-)

> It doesn't seem to have a constructor which sets its path, so do I
> do:
>
> ourlockfile = daemon.pidlockfile.PIDLockFile

Presuming you mean ‘daemon.pidlockfile.PIDLockFile()’ here (that is,
get the return value of the class constructor, not the class itself).

> ourlockfile.path = '/tmp/mydaemon.pid'
> context = daemon.DaemonContext(
> pidfile=ourlockfile,
> stdout=logout,
> stderr=logout
> )
>
> If so, it doesn't work, it just exits without an error.

Can you please provide the full traceback?

> Another thing:
>
> I've noticed there are some ^L characters in daemon.py, e.g. just
> before "class DaemonError", "def change_working_directory" etc.

Yes. That is a page break (ASCII FF), useful for printing the file or
navigating the text file by “page”. Python, like most languages,
treats them like any other whitespace in the source.

> So, I think that PIDLockFile will leave the lockfile there if the
> daemon is killed abruptly (say with "kill -9" or due to some bug).
> Certainly, all the lock classes in lockfile.py have the problem that
> it stays locked int hat circumstance.

I have my programs delete the lockfile on start-up if it's stale (i.e.
check for the existence of the file on start-up and delete it if the
referenced PID is not running). Perhaps there are better ways.

> This page (which seems pretty good anyway, and I'm sure you've
> seen!) section 6) suggests using lockf, although I believe from
> elsewhere that fcntl will do also.
>
> http://www.enderunix.org/docs/eng/daemon.php

No, I've not seen that, but I have seen others; they tend to differ in
the details. I have looked for a more canonical reference for the
intricacies of PID file handling, but it seems to be much more ad hoc
than the definition of the daemonisation procedure.

> My impression is that the lockf is linked to the process, so if the
> process is killed the kernel will automatically free it. So my
> suggestion would be to store the pid in a pidfile, and lockf it. Not
> sure that is the exact convention used by most daemons on Debian,
> but it might be.

On Linux at least, ‘lockf’ is not defined to alter the file at all; it
doesn't cause it to be created nor removed. It is purely for a lock on
an existing file.

> It wouldn't be cross platform though. I imagine Windows code for
> this should be very different from Unix, however - making a service.

Explicitly outside the scope of PEP 3143; though it is hoped that the
described functionality will make a good basis on which to *build*
such a service, on Unix.

> Would be lovely to have something that provided one interface to
> both eventually, but probably too wild for now!

There is a skeletal PEP on the ‘python-ideas’ list for this purpose
<URL:http://mail.python.org/pipermail/python-ideas/2009-January/002606.html>.
Anyone should feel free to develop it further.

> > Thank you for your testing and feedback!
>
> And thank you!
>
> Your project is well worth doing, Unix daemons are so arcane, and to
> make them more Pythonic is lovely.

--
\ “When we talk to God, we're praying. When God talks to us, |
`\ we're schizophrenic.” —Jane Wagner, via Lily Tomlin, 1985 |
_o__) |
Ben Finney <b...@benfinney.id.au>

Ben Finney

unread,
Mar 26, 2009, 5:04:47 AM3/26/09
to
Ben Finney <ben+p...@benfinney.id.au> writes:

> (replying in ‘comp.lang.python’ for wider feedback on this issue)
>
> On 26-Mar-2009, Francis Irving wrote:
> > ourlockfile.path = '/tmp/mydaemon.pid'
> > context = daemon.DaemonContext(
> > pidfile=ourlockfile,
> > stdout=logout,
> > stderr=logout
> > )
> >
> > If so, it doesn't work, it just exits without an error.

^^^^^^^

> Can you please provide the full traceback?

My apologies; no of course you can't :-) Okay, I will have a look at
what might be happening; can I ask you to do some diagnosis as well to
see if you *can* get an informative output?

> > So, I think that PIDLockFile will leave the lockfile there if the
> > daemon is killed abruptly (say with "kill -9" or due to some bug).
> > Certainly, all the lock classes in lockfile.py have the problem
> > that it stays locked int hat circumstance.
>
> I have my programs delete the lockfile on start-up if it's stale
> (i.e. check for the existence of the file on start-up and delete it
> if the referenced PID is not running). Perhaps there are better
> ways.

In the case of the ‘lockfile’ library, Skip is aiming for a
cross-platform solution, with atomic behaviour; he has implemented
lock acquisition with a ‘link’ operation on Unix, and a ‘mkdir’
operation on Windows.

But both of those, of course, create a new file. What I want is to
lock an existing file. Is ‘lockf’ particularly prone to cross-platform
troubles on Unix variants? (Since the “become a daemon” pattern
makes no sense on anything but Unix, I'm only concerned with PID file
behaviour that works on Unix.)

> > This page (which seems pretty good anyway, and I'm sure you've
> > seen!) section 6) suggests using lockf, although I believe from
> > elsewhere that fcntl will do also.
> >
> > http://www.enderunix.org/docs/eng/daemon.php
>
> No, I've not seen that, but I have seen others; they tend to differ
> in the details. I have looked for a more canonical reference for the
> intricacies of PID file handling, but it seems to be much more ad
> hoc than the definition of the daemonisation procedure.

I would very much like to see something akin to the canonical Stevens
references on other Unix topics, but specifically for “good PID file
management”. Does anyone have any pointers?

--
\ “Faith, n. Belief without evidence in what is told by one who |
`\ speaks without knowledge, of things without parallel.” —Ambrose |
_o__) Bierce, _The Devil's Dictionary_, 1906 |
Ben Finney

Aahz

unread,
Mar 28, 2009, 7:13:05 PM3/28/09
to
In article <87iqlwv...@benfinney.id.au>,

Ben Finney <bignose+h...@benfinney.id.au> wrote:
>
>In the case of the ‘lockfile’ library, Skip is aiming for a
>cross-platform solution, with atomic behaviour; he has implemented
>lock acquisition with a ‘link’ operation on Unix, and a ‘mkdir’
>operation on Windows.
>
>But both of those, of course, create a new file. What I want is to
>lock an existing file. Is ‘lockf’ particularly prone to cross-platform
>troubles on Unix variants? (Since the “become a daemon” pattern
>makes no sense on anything but Unix, I'm only concerned with PID file
>behaviour that works on Unix.)

IIUC, you must use something like Skip's trick to work correctly with
NFS.
--
Aahz (aa...@pythoncraft.com) <*> http://www.pythoncraft.com/

"At Resolver we've found it useful to short-circuit any doubt and just
refer to comments in code as 'lies'. :-)"
--Michael Foord paraphrases Christian Muirhead on python-dev, 2009-3-22

Ben Finney

unread,
Mar 28, 2009, 8:37:00 PM3/28/09
to
aa...@pythoncraft.com (Aahz) writes:

> In article <87iqlwv...@benfinney.id.au>,
> Ben Finney <bignose+h...@benfinney.id.au> wrote:

> >In the case of the ‘lockfile’ library, Skip is aiming for a


> >cross-platform solution, with atomic behaviour; he has implemented

> >lock acquisition with a ‘link’ operation on Unix, and a
> >‘mkdir’ operation on Windows.


> >
> >But both of those, of course, create a new file. What I want is to

> >lock an existing file. Is ‘lockf’ particularly prone to
> >cross-platform troubles on Unix variants? (Since the “become a
> >daemon� pattern makes no sense on anything but Unix, I'm only


> >concerned with PID file behaviour that works on Unix.)

Hmm, looks like your client is messing up character encoding.

> IIUC, you must use something like Skip's trick to work correctly with
> NFS.

Okay. But is that something that needs to be accommodated with,
specifically, PID file handling? Why would a PID file ever need to be
on NFS storage instead of local?

--
\ “The cost of a thing is the amount of what I call life which is |
`\ required to be exchanged for it, immediately or in the long |
_o__) run.” —Henry David Thoreau |
Ben Finney

Cameron Simpson

unread,
Mar 28, 2009, 10:10:43 PM3/28/09
to pytho...@python.org
On 29Mar2009 11:37, Ben Finney <ben+p...@benfinney.id.au> wrote:
| aa...@pythoncraft.com (Aahz) writes:
| > In article <87iqlwv...@benfinney.id.au>,
| > Ben Finney <bignose+h...@benfinney.id.au> wrote:
| > >In the case of the ‘lockfile’ library, Skip is aiming for a
| > >cross-platform solution, with atomic behaviour; he has implemented
| > >lock acquisition with a ‘link’ operation on Unix, and a
| > >‘mkdir’ operation on Windows.

I've been using mkdir on UNIX for my own locks; also an NFS-safe
operation needing no file-level locks. I've also seen
open("lockfile",O_RDWR,0) suggested; since it atomicly makes a
non-writable file, only the first opener gets to succeed.

| > >But both of those, of course, create a new file. What I want is to
| > >lock an existing file. Is ‘lockf’ particularly prone to
| > >cross-platform troubles on Unix variants?

NFS can be run without a lock daemon, and I have vague recollections
of NFS lock daemons not talking to each other on different platforms
(eg Solaris vs Linux or Linux vs *BSD). I have no idea if that is still
a current issue.

| > IIUC, you must use something like Skip's trick to work correctly with
| > NFS.
|
| Okay. But is that something that needs to be accommodated with,
| specifically, PID file handling? Why would a PID file ever need to be
| on NFS storage instead of local?

If you're talking about a system daemon, maybe never; at any rate it is
rare. However there's plenty of occasions when I want to start a daemon,
as me, for my own personal purposes. It doesn't do any uid/gid juggling
or privilege dropping, but it's a perfectly reasonable thing to want to
use your daemon module to do everything else (detach, pid locks, etc).

Conbine that with "my home dir is NFS shared across our LAN" and you're
instantly into routine lockfile-on-NFS land.

I speak as one who was in that circumstance in my former life.

Cheers,
--
Cameron Simpson <c...@zip.com.au> DoD#743
http://www.cskk.ezoshosting.com/cs/

NFS: Not a File System

Ben Finney

unread,
Mar 28, 2009, 10:22:43 PM3/28/09
to
Cameron Simpson <c...@zip.com.au> writes:

> […] there's plenty of occasions when I want to start a daemon, as


> me, for my own personal purposes. It doesn't do any uid/gid juggling
> or privilege dropping, but it's a perfectly reasonable thing to want
> to use your daemon module to do everything else (detach, pid locks,
> etc).
>
> Conbine that with "my home dir is NFS shared across our LAN" and
> you're instantly into routine lockfile-on-NFS land.

Yes, that's a simple use case that I do want to support. Thanks, I'll
see how best to accommodate it.

--
\ “People come up to me and say, ‘Emo, do people really come up |
`\ to you?’” —Emo Philips |
_o__) |
Ben Finney

Aahz

unread,
Mar 29, 2009, 10:10:22 AM3/29/09
to
In article <87zlf5q...@benfinney.id.au>,

Ben Finney <ben+p...@benfinney.id.au> wrote:
>aa...@pythoncraft.com (Aahz) writes:
>> In article <87iqlwv...@benfinney.id.au>,
>> Ben Finney <bignose+h...@benfinney.id.au> wrote:
>>>
>>>In the case of the ‘lockfile’ library, Skip is aiming for a
>>>cross-platform solution, with atomic behaviour; he has implemented
>>>lock acquisition with a ‘link’ operation on Unix, and a
>>>‘mkdir’ operation on Windows.
>>>
>>>But both of those, of course, create a new file. What I want is to
>>>lock an existing file. Is ‘lockf’ particularly prone to
>>>cross-platform troubles on Unix variants? (Since the “become a
>>>daemon� pattern makes no sense on anything but Unix, I'm only
>>>concerned with PID file behaviour that works on Unix.)
>
>Hmm, looks like your client is messing up character encoding.

Yes, it does, I'm using trn3.6 from the early 90s, and trn4 has some
annoying bugs that keep me from upgrading. Maybe one of these years I'll
switch to slrn. (Plus I've never bothered setting up vim to handle
Unicode. Just call me ASCII Boy.)

>> IIUC, you must use something like Skip's trick to work correctly with
>> NFS.
>
>Okay. But is that something that needs to be accommodated with,
>specifically, PID file handling? Why would a PID file ever need to be
>on NFS storage instead of local?

That's the question. You'll probably get some complaints from people
running diskless machines, eventually, some years down the line. At the
very least, you need to document this as a known limitation.

JanC

unread,
Mar 30, 2009, 2:03:10 AM3/30/09
to
Aahz wrote:

>>Okay. But is that something that needs to be accommodated with,
>>specifically, PID file handling? Why would a PID file ever need to be
>>on NFS storage instead of local?
>
> That's the question. You'll probably get some complaints from people
> running diskless machines, eventually, some years down the line.

I think on diskless machines using a tmpfs (or similar) for PID files would
be more sane anyway, but of course not everybody will (or can?) use
that...


--
JanC

0 new messages