1
# -*- coding: utf-8 -*-
4
# Part of python-daemon, an implementation of PEP 3143.
6
# Copyright © 2008–2010 Ben Finney <ben+python@benfinney.id.au>
7
# Copyright © 2007–2008 Robert Niederreiter, Jens Klein
8
# Copyright © 2004–2005 Chad J. Schroeder
9
# Copyright © 2003 Clark Evans
10
# Copyright © 2002 Noah Spurrier
11
# Copyright © 2001 Jürgen Hermann
13
# This is free software: you may copy, modify, and/or distribute this work
14
# under the terms of the Python Software Foundation License, version 2 or
15
# later as published by the Python Software Foundation.
16
# No warranty expressed or implied. See the file LICENSE.PSF-2 for details.
18
""" Daemon process behaviour.
30
class DaemonError(Exception):
31
""" Base exception class for errors from this module. """
34
class DaemonOSEnvironmentError(DaemonError, OSError):
35
""" Exception raised when daemon OS environment setup receives error. """
38
class DaemonProcessDetachError(DaemonError, OSError):
39
""" Exception raised when process detach fails. """
42
class DaemonContext(object):
43
""" Context for turning the current program into a daemon process.
45
A `DaemonContext` instance represents the behaviour settings and
46
process context for the program when it becomes a daemon. The
47
behaviour and environment is customised by setting options on the
48
instance, before calling the `open` method.
50
Each option can be passed as a keyword argument to the `DaemonContext`
51
constructor, or subsequently altered by assigning to an attribute on
52
the instance at any time prior to calling `open`. That is, for
53
options named `wibble` and `wubble`, the following invocation::
55
foo = daemon.DaemonContext(wibble=bar, wubble=baz)
60
foo = daemon.DaemonContext()
65
The following options are defined.
70
List of files that should *not* be closed when starting the
71
daemon. If ``None``, all open file descriptors will be closed.
73
Elements of the list are file descriptors (as returned by a file
74
object's `fileno()` method) or Python `file` objects. Each
75
specifies a file that is not to be closed during daemon start.
80
Full path to a directory to set as the effective root directory of
81
the process. If ``None``, specifies that the root directory is not
87
Full path of the working directory to which the process should
88
change on daemon start.
90
Since a filesystem cannot be unmounted if a process has its
91
current working directory on that filesystem, this should either
92
be left at default or set to a directory that is a sensible “home
93
directory” for the daemon while it is running.
98
File access creation mask (“umask”) to set for the process on
101
Since a process inherits its umask from its parent process,
102
starting the daemon will reset the umask to this value so that
103
files are created by the daemon with access modes as it expects.
108
Context manager for a PID lock file. When the daemon context opens
109
and closes, it enters and exits the `pidfile` context manager.
114
If ``True``, detach the process context when opening the daemon
115
context; if ``False``, do not detach.
117
If unspecified (``None``) during initialisation of the instance,
118
this will be set to ``True`` by default, and ``False`` only if
119
detaching the process is determined to be redundant; for example,
120
in the case when the process was started by `init`, by `initd`, or
124
:Default: system-dependent
126
Mapping from operating system signals to callback actions.
128
The mapping is used when the daemon context opens, and determines
129
the action for each signal's signal handler:
131
* A value of ``None`` will ignore the signal (by setting the
132
signal action to ``signal.SIG_IGN``).
134
* A string value will be used as the name of an attribute on the
135
``DaemonContext`` instance. The attribute's value will be used
136
as the action for the signal handler.
138
* Any other value will be used as the action for the
139
signal handler. See the ``signal.signal`` documentation
140
for details of the signal handler interface.
142
The default value depends on which signals are defined on the
143
running system. Each item from the list below whose signal is
144
actually defined in the ``signal`` module will appear in the
147
* ``signal.SIGTTIN``: ``None``
149
* ``signal.SIGTTOU``: ``None``
151
* ``signal.SIGTSTP``: ``None``
153
* ``signal.SIGTERM``: ``'terminate'``
155
Depending on how the program will interact with its child
156
processes, it may need to specify a signal map that
157
includes the ``signal.SIGCHLD`` signal (received when a
158
child process exits). See the specific operating system's
159
documentation for more detail on how to determine what
160
circumstances dictate the need for signal handlers.
163
:Default: ``os.getuid()``
166
:Default: ``os.getgid()``
168
The user ID (“UID”) value and group ID (“GID”) value to switch
169
the process to on daemon start.
171
The default values, the real UID and GID of the process, will
172
relinquish any effective privilege elevation inherited by the
178
If true, prevents the generation of core files, in order to avoid
179
leaking sensitive information from daemons run as `root`.
190
Each of `stdin`, `stdout`, and `stderr` is a file-like object
191
which will be used as the new file for the standard I/O stream
192
`sys.stdin`, `sys.stdout`, and `sys.stderr` respectively. The file
193
should therefore be open, with a minimum of mode 'r' in the case
194
of `stdin`, and mode 'w+' in the case of `stdout` and `stderr`.
196
If the object has a `fileno()` method that returns a file
197
descriptor, the corresponding file will be excluded from being
198
closed during daemon start (that is, it will be treated as though
199
it were listed in `files_preserve`).
201
If ``None``, the corresponding system stream is re-bound to the
202
file named by `os.devnull`.
208
chroot_directory=None,
209
working_directory='/',
222
""" Set up a new instance. """
223
self.chroot_directory = chroot_directory
224
self.working_directory = working_directory
226
self.prevent_core = prevent_core
227
self.files_preserve = files_preserve
228
self.pidfile = pidfile
240
if detach_process is None:
241
detach_process = is_detach_process_context_required()
242
self.detach_process = detach_process
244
if signal_map is None:
245
signal_map = make_default_signal_map()
246
self.signal_map = signal_map
248
self._is_open = False
252
""" ``True`` if the instance is currently open. """
256
""" Become a daemon process.
259
Open the daemon context, turning the current program into a daemon
260
process. This performs the following steps:
262
* If this instance's `is_open` property is true, return
263
immediately. This makes it safe to call `open` multiple times on
266
* If the `prevent_core` attribute is true, set the resource limits
267
for the process to prevent any core dump from the process.
269
* If the `chroot_directory` attribute is not ``None``, set the
270
effective root directory of the process to that directory (via
273
This allows running the daemon process inside a “chroot gaol”
274
as a means of limiting the system's exposure to rogue behaviour
275
by the process. Note that the specified directory needs to
276
already be set up for this purpose.
278
* Set the process UID and GID to the `uid` and `gid` attribute
281
* Close all open file descriptors. This excludes those listed in
282
the `files_preserve` attribute, and those that correspond to the
283
`stdin`, `stdout`, or `stderr` attributes.
285
* Change current working directory to the path specified by the
286
`working_directory` attribute.
288
* Reset the file access creation mask to the value specified by
289
the `umask` attribute.
291
* If the `detach_process` option is true, detach the current
292
process into its own process group, and disassociate from any
293
controlling terminal.
295
* Set signal handlers as specified by the `signal_map` attribute.
297
* If any of the attributes `stdin`, `stdout`, `stderr` are not
298
``None``, bind the system streams `sys.stdin`, `sys.stdout`,
299
and/or `sys.stderr` to the files represented by the
300
corresponding attributes. Where the attribute has a file
301
descriptor, the descriptor is duplicated (instead of re-binding
304
* If the `pidfile` attribute is not ``None``, enter its context
307
* Mark this instance as open (for the purpose of future `open` and
310
* Register the `close` method to be called during Python's exit
313
When the function returns, the running program is a daemon
320
if self.chroot_directory is not None:
321
change_root_directory(self.chroot_directory)
323
if self.prevent_core:
326
change_file_creation_mask(self.umask)
327
change_working_directory(self.working_directory)
328
change_process_owner(self.uid, self.gid)
330
if self.detach_process:
331
detach_process_context()
333
signal_handler_map = self._make_signal_handler_map()
334
set_signal_handlers(signal_handler_map)
336
exclude_fds = self._get_exclude_file_descriptors()
337
close_all_open_files(exclude=exclude_fds)
339
redirect_stream(sys.stdin, self.stdin)
340
redirect_stream(sys.stdout, self.stdout)
341
redirect_stream(sys.stderr, self.stderr)
343
if self.pidfile is not None:
344
self.pidfile.__enter__()
348
register_atexit_function(self.close)
351
""" Context manager entry point. """
356
""" Exit the daemon process context.
359
Close the daemon context. This performs the following steps:
361
* If this instance's `is_open` property is false, return
362
immediately. This makes it safe to call `close` multiple times
365
* If the `pidfile` attribute is not ``None``, exit its context
368
* Mark this instance as closed (for the purpose of future `open`
375
if self.pidfile is not None:
376
# Follow the interface for telling a context manager to exit,
377
# <URL:http://docs.python.org/library/stdtypes.html#typecontextmanager>.
378
self.pidfile.__exit__(None, None, None)
380
self._is_open = False
382
def __exit__(self, exc_type, exc_value, traceback):
383
""" Context manager exit point. """
386
def terminate(self, signal_number, stack_frame):
387
""" Signal handler for end-process signals.
390
Signal handler for the ``signal.SIGTERM`` signal. Performs the
393
* Raise a ``SystemExit`` exception explaining the signal.
396
exception = SystemExit(
397
"Terminating on signal %(signal_number)r"
401
def _get_exclude_file_descriptors(self):
402
""" Return the set of file descriptors to exclude closing.
404
Returns a set containing the file descriptors for the
405
items in `files_preserve`, and also each of `stdin`,
406
`stdout`, and `stderr`:
408
* If the item is ``None``, it is omitted from the return
411
* If the item has a ``fileno()`` method, that method's
412
return value is in the return set.
414
* Otherwise, the item is in the return set verbatim.
417
files_preserve = self.files_preserve
418
if files_preserve is None:
420
files_preserve.extend(
421
item for item in [self.stdin, self.stdout, self.stderr]
422
if hasattr(item, 'fileno'))
423
exclude_descriptors = set()
424
for item in files_preserve:
427
if hasattr(item, 'fileno'):
428
exclude_descriptors.add(item.fileno())
430
exclude_descriptors.add(item)
431
return exclude_descriptors
433
def _make_signal_handler(self, target):
434
""" Make the signal handler for a specified target object.
436
If `target` is ``None``, returns ``signal.SIG_IGN``. If
437
`target` is a string, returns the attribute of this
438
instance named by that string. Otherwise, returns `target`
443
result = signal.SIG_IGN
444
elif isinstance(target, basestring):
446
result = getattr(self, name)
452
def _make_signal_handler_map(self):
453
""" Make the map from signals to handlers for this instance.
455
Constructs a map from signal numbers to handlers for this
456
context instance, suitable for passing to
457
`set_signal_handlers`.
460
signal_handler_map = dict(
461
(signal_number, self._make_signal_handler(target))
462
for (signal_number, target) in self.signal_map.items())
463
return signal_handler_map
466
def change_working_directory(directory):
467
""" Change the working directory of this process.
471
except Exception, exc:
472
error = DaemonOSEnvironmentError(
473
"Unable to change working directory (%(exc)s)"
478
def change_root_directory(directory):
479
""" Change the root directory of this process.
481
Sets the current working directory, then the process root
482
directory, to the specified `directory`. Requires appropriate
483
OS privileges for this process.
489
except Exception, exc:
490
error = DaemonOSEnvironmentError(
491
"Unable to change root directory (%(exc)s)"
496
def change_file_creation_mask(mask):
497
""" Change the file creation mask for this process.
501
except Exception, exc:
502
error = DaemonOSEnvironmentError(
503
"Unable to change file creation mask (%(exc)s)"
508
def change_process_owner(uid, gid):
509
""" Change the owning UID and GID of this process.
511
Sets the GID then the UID of the process (in that order, to
512
avoid permission errors) to the specified `gid` and `uid`
513
values. Requires appropriate OS privileges for this process.
519
except Exception, exc:
520
error = DaemonOSEnvironmentError(
521
"Unable to change file creation mask (%(exc)s)"
526
def prevent_core_dump():
527
""" Prevent this process from generating a core dump.
529
Sets the soft and hard limits for core dump size to zero. On
530
Unix, this prevents the process from creating core dump
534
core_resource = resource.RLIMIT_CORE
537
# Ensure the resource limit exists on this platform, by requesting
539
core_limit_prev = resource.getrlimit(core_resource)
540
except ValueError, exc:
541
error = DaemonOSEnvironmentError(
542
"System does not support RLIMIT_CORE resource limit (%(exc)s)"
546
# Set hard and soft limits to zero, i.e. no core dump at all
548
resource.setrlimit(core_resource, core_limit)
551
def detach_process_context():
552
""" Detach the process context from parent and session.
554
Detach from the parent process and session group, allowing the
555
parent to exit while this process continues running.
557
Reference: “Advanced Programming in the Unix Environment”,
558
section 13.3, by W. Richard Stevens, published 1993 by
563
def fork_then_exit_parent(error_message):
564
""" Fork a child process, then exit the parent process.
566
If the fork fails, raise a ``DaemonProcessDetachError``
567
with ``error_message``.
575
exc_errno = exc.errno
576
exc_strerror = exc.strerror
577
error = DaemonProcessDetachError(
578
"%(error_message)s: [%(exc_errno)d] %(exc_strerror)s" % vars())
581
fork_then_exit_parent(error_message="Failed first fork")
583
fork_then_exit_parent(error_message="Failed second fork")
586
def is_process_started_by_init():
587
""" Determine if the current process is started by `init`.
589
The `init` process has the process ID of 1; if that is our
590
parent process ID, return ``True``, otherwise ``False``.
596
if os.getppid() == init_pid:
603
""" Determine if the file descriptor is a socket.
605
Return ``False`` if querying the socket type of `fd` raises an
606
error; otherwise return ``True``.
611
file_socket = socket.fromfd(fd, socket.AF_INET, socket.SOCK_RAW)
614
socket_type = file_socket.getsockopt(
615
socket.SOL_SOCKET, socket.SO_TYPE)
616
except socket.error, exc:
617
exc_errno = exc.args[0]
618
if exc_errno == errno.ENOTSOCK:
619
# Socket operation on non-socket
622
# Some other socket error
625
# No error getting socket type
631
def is_process_started_by_superserver():
632
""" Determine if the current process is started by the superserver.
634
The internet superserver creates a network socket, and
635
attaches it to the standard streams of the child process. If
636
that is the case for this process, return ``True``, otherwise
642
stdin_fd = sys.__stdin__.fileno()
643
if is_socket(stdin_fd):
649
def is_detach_process_context_required():
650
""" Determine whether detaching process context is required.
652
Return ``True`` if the process environment indicates the
653
process is already detached:
655
* Process was started by `init`; or
657
* Process was started by `inetd`.
661
if is_process_started_by_init() or is_process_started_by_superserver():
667
def close_file_descriptor_if_open(fd):
668
""" Close a file descriptor if already open.
670
Close the file descriptor `fd`, suppressing an error in the
671
case the file was not open.
677
if exc.errno == errno.EBADF:
678
# File descriptor was not open
681
error = DaemonOSEnvironmentError(
682
"Failed to close file descriptor %(fd)d"
690
def get_maximum_file_descriptors():
691
""" Return the maximum number of open file descriptors for this process.
693
Return the process hard resource limit of maximum number of
694
open file descriptors. If the limit is “infinity”, a default
695
value of ``MAXFD`` is returned.
698
limits = resource.getrlimit(resource.RLIMIT_NOFILE)
700
if result == resource.RLIM_INFINITY:
705
def close_all_open_files(exclude=set()):
706
""" Close all open file descriptors.
708
Closes every file descriptor (if open) of this process. If
709
specified, `exclude` is a set of file descriptors to *not*
713
maxfd = get_maximum_file_descriptors()
714
for fd in reversed(range(maxfd)):
715
if fd not in exclude:
716
close_file_descriptor_if_open(fd)
719
def redirect_stream(system_stream, target_stream):
720
""" Redirect a system stream to a specified file.
722
`system_stream` is a standard system stream such as
723
``sys.stdout``. `target_stream` is an open file object that
724
should replace the corresponding system stream object.
726
If `target_stream` is ``None``, defaults to opening the
727
operating system's null device and using its file descriptor.
730
if target_stream is None:
731
target_fd = os.open(os.devnull, os.O_RDWR)
733
target_fd = target_stream.fileno()
734
os.dup2(target_fd, system_stream.fileno())
737
def make_default_signal_map():
738
""" Make the default signal map for this system.
740
The signals available differ by system. The map will not
741
contain any signals not defined on the running system.
748
'SIGTERM': 'terminate',
751
(getattr(signal, name), target)
752
for (name, target) in name_map.items()
753
if hasattr(signal, name))
758
def set_signal_handlers(signal_handler_map):
759
""" Set the signal handlers as specified.
761
The `signal_handler_map` argument is a map from signal number
762
to signal handler. See the `signal` module for details.
765
for (signal_number, handler) in signal_handler_map.items():
766
signal.signal(signal_number, handler)
769
def register_atexit_function(func):
770
""" Register a function for processing at program exit.
772
The function `func` is registered for a call with no arguments
776
atexit.register(func)