daemon.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771
  1. # -*- coding: utf-8 -*-
  2. # daemon/daemon.py
  3. # Part of python-daemon, an implementation of PEP 3143.
  4. #
  5. # Copyright © 2008–2009 Ben Finney <ben+python@benfinney.id.au>
  6. # Copyright © 2007–2008 Robert Niederreiter, Jens Klein
  7. # Copyright © 2004–2005 Chad J. Schroeder
  8. # Copyright © 2003 Clark Evans
  9. # Copyright © 2002 Noah Spurrier
  10. # Copyright © 2001 Jürgen Hermann
  11. #
  12. # This is free software: you may copy, modify, and/or distribute this work
  13. # under the terms of the Python Software Foundation License, version 2 or
  14. # later as published by the Python Software Foundation.
  15. # No warranty expressed or implied. See the file LICENSE.PSF-2 for details.
  16. """ Daemon process behaviour.
  17. """
  18. import os
  19. import sys
  20. import resource
  21. import errno
  22. import signal
  23. import socket
  24. import atexit
  25. class DaemonError(Exception):
  26. """ Base exception class for errors from this module. """
  27. class DaemonOSEnvironmentError(DaemonError, OSError):
  28. """ Exception raised when daemon OS environment setup receives error. """
  29. class DaemonProcessDetachError(DaemonError, OSError):
  30. """ Exception raised when process detach fails. """
  31. class DaemonContext(object):
  32. """ Context for turning the current program into a daemon process.
  33. A `DaemonContext` instance represents the behaviour settings and
  34. process context for the program when it becomes a daemon. The
  35. behaviour and environment is customised by setting options on the
  36. instance, before calling the `open` method.
  37. Each option can be passed as a keyword argument to the `DaemonContext`
  38. constructor, or subsequently altered by assigning to an attribute on
  39. the instance at any time prior to calling `open`. That is, for
  40. options named `wibble` and `wubble`, the following invocation::
  41. foo = daemon.DaemonContext(wibble=bar, wubble=baz)
  42. foo.open()
  43. is equivalent to::
  44. foo = daemon.DaemonContext()
  45. foo.wibble = bar
  46. foo.wubble = baz
  47. foo.open()
  48. The following options are defined.
  49. `files_preserve`
  50. :Default: ``None``
  51. List of files that should *not* be closed when starting the
  52. daemon. If ``None``, all open file descriptors will be closed.
  53. Elements of the list are file descriptors (as returned by a file
  54. object's `fileno()` method) or Python `file` objects. Each
  55. specifies a file that is not to be closed during daemon start.
  56. `chroot_directory`
  57. :Default: ``None``
  58. Full path to a directory to set as the effective root directory of
  59. the process. If ``None``, specifies that the root directory is not
  60. to be changed.
  61. `working_directory`
  62. :Default: ``'/'``
  63. Full path of the working directory to which the process should
  64. change on daemon start.
  65. Since a filesystem cannot be unmounted if a process has its
  66. current working directory on that filesystem, this should either
  67. be left at default or set to a directory that is a sensible “home
  68. directory” for the daemon while it is running.
  69. `umask`
  70. :Default: ``0``
  71. File access creation mask (“umask”) to set for the process on
  72. daemon start.
  73. Since a process inherits its umask from its parent process,
  74. starting the daemon will reset the umask to this value so that
  75. files are created by the daemon with access modes as it expects.
  76. `pidfile`
  77. :Default: ``None``
  78. Context manager for a PID lock file. When the daemon context opens
  79. and closes, it enters and exits the `pidfile` context manager.
  80. `detach_process`
  81. :Default: ``None``
  82. If ``True``, detach the process context when opening the daemon
  83. context; if ``False``, do not detach.
  84. If unspecified (``None``) during initialisation of the instance,
  85. this will be set to ``True`` by default, and ``False`` only if
  86. detaching the process is determined to be redundant; for example,
  87. in the case when the process was started by `init`, by `initd`, or
  88. by `inetd`.
  89. `signal_map`
  90. :Default: system-dependent
  91. Mapping from operating system signals to callback actions.
  92. The mapping is used when the daemon context opens, and determines
  93. the action for each signal's signal handler:
  94. * A value of ``None`` will ignore the signal (by setting the
  95. signal action to ``signal.SIG_IGN``).
  96. * A string value will be used as the name of an attribute on the
  97. ``DaemonContext`` instance. The attribute's value will be used
  98. as the action for the signal handler.
  99. * Any other value will be used as the action for the
  100. signal handler. See the ``signal.signal`` documentation
  101. for details of the signal handler interface.
  102. The default value depends on which signals are defined on the
  103. running system. Each item from the list below whose signal is
  104. actually defined in the ``signal`` module will appear in the
  105. default map:
  106. * ``signal.SIGTTIN``: ``None``
  107. * ``signal.SIGTTOU``: ``None``
  108. * ``signal.SIGTSTP``: ``None``
  109. * ``signal.SIGTERM``: ``'terminate'``
  110. Depending on how the program will interact with its child
  111. processes, it may need to specify a signal map that
  112. includes the ``signal.SIGCHLD`` signal (received when a
  113. child process exits). See the specific operating system's
  114. documentation for more detail on how to determine what
  115. circumstances dictate the need for signal handlers.
  116. `uid`
  117. :Default: ``os.getuid()``
  118. `gid`
  119. :Default: ``os.getgid()``
  120. The user ID (“UID”) value and group ID (“GID”) value to switch
  121. the process to on daemon start.
  122. The default values, the real UID and GID of the process, will
  123. relinquish any effective privilege elevation inherited by the
  124. process.
  125. `prevent_core`
  126. :Default: ``True``
  127. If true, prevents the generation of core files, in order to avoid
  128. leaking sensitive information from daemons run as `root`.
  129. `stdin`
  130. :Default: ``None``
  131. `stdout`
  132. :Default: ``None``
  133. `stderr`
  134. :Default: ``None``
  135. Each of `stdin`, `stdout`, and `stderr` is a file-like object
  136. which will be used as the new file for the standard I/O stream
  137. `sys.stdin`, `sys.stdout`, and `sys.stderr` respectively. The file
  138. should therefore be open, with a minimum of mode 'r' in the case
  139. of `stdin`, and mode 'w+' in the case of `stdout` and `stderr`.
  140. If the object has a `fileno()` method that returns a file
  141. descriptor, the corresponding file will be excluded from being
  142. closed during daemon start (that is, it will be treated as though
  143. it were listed in `files_preserve`).
  144. If ``None``, the corresponding system stream is re-bound to the
  145. file named by `os.devnull`.
  146. """
  147. def __init__(
  148. self,
  149. chroot_directory=None,
  150. working_directory='/',
  151. umask=0,
  152. uid=None,
  153. gid=None,
  154. detach_process=None,
  155. files_preserve=None,
  156. pidfile=None,
  157. stdin=None,
  158. stdout=None,
  159. stderr=None,
  160. signal_map=None,
  161. ):
  162. """ Set up a new instance. """
  163. self.chroot_directory = chroot_directory
  164. self.working_directory = working_directory
  165. self.umask = umask
  166. self.files_preserve = files_preserve
  167. self.pidfile = pidfile
  168. self.stdin = stdin
  169. self.stdout = stdout
  170. self.stderr = stderr
  171. if uid is None:
  172. uid = os.getuid()
  173. self.uid = uid
  174. if gid is None:
  175. gid = os.getgid()
  176. self.gid = gid
  177. if detach_process is None:
  178. detach_process = is_detach_process_context_required()
  179. self.detach_process = detach_process
  180. if signal_map is None:
  181. signal_map = make_default_signal_map()
  182. self.signal_map = signal_map
  183. self._is_open = False
  184. @property
  185. def is_open(self):
  186. """ ``True`` if the instance is currently open. """
  187. return self._is_open
  188. def open(self):
  189. """ Become a daemon process.
  190. :Return: ``None``
  191. Open the daemon context, turning the current program into a daemon
  192. process. This performs the following steps:
  193. * If this instance's `is_open` property is true, return
  194. immediately. This makes it safe to call `open` multiple times on
  195. an instance.
  196. * If the `prevent_core` attribute is true, set the resource limits
  197. for the process to prevent any core dump from the process.
  198. * If the `chroot_directory` attribute is not ``None``, set the
  199. effective root directory of the process to that directory (via
  200. `os.chroot`).
  201. This allows running the daemon process inside a “chroot gaol”
  202. as a means of limiting the system's exposure to rogue behaviour
  203. by the process. Note that the specified directory needs to
  204. already be set up for this purpose.
  205. * Set the process UID and GID to the `uid` and `gid` attribute
  206. values.
  207. * Close all open file descriptors. This excludes those listed in
  208. the `files_preserve` attribute, and those that correspond to the
  209. `stdin`, `stdout`, or `stderr` attributes.
  210. * Change current working directory to the path specified by the
  211. `working_directory` attribute.
  212. * Reset the file access creation mask to the value specified by
  213. the `umask` attribute.
  214. * If the `detach_process` option is true, detach the current
  215. process into its own process group, and disassociate from any
  216. controlling terminal.
  217. * Set signal handlers as specified by the `signal_map` attribute.
  218. * If any of the attributes `stdin`, `stdout`, `stderr` are not
  219. ``None``, bind the system streams `sys.stdin`, `sys.stdout`,
  220. and/or `sys.stderr` to the files represented by the
  221. corresponding attributes. Where the attribute has a file
  222. descriptor, the descriptor is duplicated (instead of re-binding
  223. the name).
  224. * If the `pidfile` attribute is not ``None``, enter its context
  225. manager.
  226. * Mark this instance as open (for the purpose of future `open` and
  227. `close` calls).
  228. * Register the `close` method to be called during Python's exit
  229. processing.
  230. When the function returns, the running program is a daemon
  231. process.
  232. """
  233. if self.is_open:
  234. return
  235. if self.chroot_directory is not None:
  236. change_root_directory(self.chroot_directory)
  237. prevent_core_dump()
  238. change_file_creation_mask(self.umask)
  239. change_working_directory(self.working_directory)
  240. change_process_owner(self.uid, self.gid)
  241. if self.detach_process:
  242. detach_process_context()
  243. signal_handler_map = self._make_signal_handler_map()
  244. set_signal_handlers(signal_handler_map)
  245. exclude_fds = self._get_exclude_file_descriptors()
  246. close_all_open_files(exclude=exclude_fds)
  247. redirect_stream(sys.stdin, self.stdin)
  248. redirect_stream(sys.stdout, self.stdout)
  249. redirect_stream(sys.stderr, self.stderr)
  250. if self.pidfile is not None:
  251. self.pidfile.__enter__()
  252. self._is_open = True
  253. register_atexit_function(self.close)
  254. def __enter__(self):
  255. """ Context manager entry point. """
  256. self.open()
  257. return self
  258. def close(self):
  259. """ Exit the daemon process context.
  260. :Return: ``None``
  261. Close the daemon context. This performs the following steps:
  262. * If this instance's `is_open` property is false, return
  263. immediately. This makes it safe to call `close` multiple times
  264. on an instance.
  265. * If the `pidfile` attribute is not ``None``, exit its context
  266. manager.
  267. * Mark this instance as closed (for the purpose of future `open`
  268. and `close` calls).
  269. """
  270. if not self.is_open:
  271. return
  272. if self.pidfile is not None:
  273. self.pidfile.__exit__()
  274. self._is_open = False
  275. def __exit__(self, exc_type, exc_value, traceback):
  276. """ Context manager exit point. """
  277. self.close()
  278. def terminate(self, signal_number, stack_frame):
  279. """ Signal handler for end-process signals.
  280. :Return: ``None``
  281. Signal handler for the ``signal.SIGTERM`` signal. Performs the
  282. following step:
  283. * Raise a ``SystemExit`` exception explaining the signal.
  284. """
  285. exception = SystemExit(
  286. "Terminating on signal %(signal_number)r"
  287. % vars())
  288. raise exception
  289. def _get_exclude_file_descriptors(self):
  290. """ Return the set of file descriptors to exclude closing.
  291. Returns a set containing the file descriptors for the
  292. items in `files_preserve`, and also each of `stdin`,
  293. `stdout`, and `stderr`:
  294. * If the item is ``None``, it is omitted from the return
  295. set.
  296. * If the item has a ``fileno()`` method, that method's
  297. return value is in the return set.
  298. * Otherwise, the item is in the return set verbatim.
  299. """
  300. files_preserve = self.files_preserve
  301. if files_preserve is None:
  302. files_preserve = []
  303. files_preserve.extend(
  304. item for item in [self.stdin, self.stdout, self.stderr]
  305. if hasattr(item, 'fileno'))
  306. exclude_descriptors = set()
  307. for item in files_preserve:
  308. if item is None:
  309. continue
  310. if hasattr(item, 'fileno'):
  311. exclude_descriptors.add(item.fileno())
  312. else:
  313. exclude_descriptors.add(item)
  314. return exclude_descriptors
  315. def _make_signal_handler(self, target):
  316. """ Make the signal handler for a specified target object.
  317. If `target` is ``None``, returns ``signal.SIG_IGN``. If
  318. `target` is a string, returns the attribute of this
  319. instance named by that string. Otherwise, returns `target`
  320. itself.
  321. """
  322. if target is None:
  323. result = signal.SIG_IGN
  324. elif isinstance(target, basestring):
  325. name = target
  326. result = getattr(self, name)
  327. else:
  328. result = target
  329. return result
  330. def _make_signal_handler_map(self):
  331. """ Make the map from signals to handlers for this instance.
  332. Constructs a map from signal numbers to handlers for this
  333. context instance, suitable for passing to
  334. `set_signal_handlers`.
  335. """
  336. signal_handler_map = dict(
  337. (signal_number, self._make_signal_handler(target))
  338. for (signal_number, target) in self.signal_map.items())
  339. return signal_handler_map
  340. def change_working_directory(directory):
  341. """ Change the working directory of this process.
  342. """
  343. try:
  344. os.chdir(directory)
  345. except Exception, exc:
  346. error = DaemonOSEnvironmentError(
  347. "Unable to change working directory (%(exc)s)"
  348. % vars())
  349. raise error
  350. def change_root_directory(directory):
  351. """ Change the root directory of this process.
  352. Sets the current working directory, then the process root
  353. directory, to the specified `directory`. Requires appropriate
  354. OS privileges for this process.
  355. """
  356. try:
  357. os.chdir(directory)
  358. os.chroot(directory)
  359. except Exception, exc:
  360. error = DaemonOSEnvironmentError(
  361. "Unable to change root directory (%(exc)s)"
  362. % vars())
  363. raise error
  364. def change_file_creation_mask(mask):
  365. """ Change the file creation mask for this process.
  366. """
  367. try:
  368. os.umask(mask)
  369. except Exception, exc:
  370. error = DaemonOSEnvironmentError(
  371. "Unable to change file creation mask (%(exc)s)"
  372. % vars())
  373. raise error
  374. def change_process_owner(uid, gid):
  375. """ Change the owning UID and GID of this process.
  376. Sets the GID then the UID of the process (in that order, to
  377. avoid permission errors) to the specified `gid` and `uid`
  378. values. Requires appropriate OS privileges for this process.
  379. """
  380. try:
  381. os.setgid(gid)
  382. os.setuid(uid)
  383. except Exception, exc:
  384. error = DaemonOSEnvironmentError(
  385. "Unable to change file creation mask (%(exc)s)"
  386. % vars())
  387. raise error
  388. def prevent_core_dump():
  389. """ Prevent this process from generating a core dump.
  390. Sets the soft and hard limits for core dump size to zero. On
  391. Unix, this prevents the process from creating core dump
  392. altogether.
  393. """
  394. core_resource = resource.RLIMIT_CORE
  395. try:
  396. # Ensure the resource limit exists on this platform, by requesting
  397. # its current value
  398. core_limit_prev = resource.getrlimit(core_resource)
  399. except ValueError, exc:
  400. error = DaemonOSEnvironmentError(
  401. "System does not support RLIMIT_CORE resource limit (%(exc)s)"
  402. % vars())
  403. raise error
  404. # Set hard and soft limits to zero, i.e. no core dump at all
  405. core_limit = (0, 0)
  406. resource.setrlimit(core_resource, core_limit)
  407. def detach_process_context():
  408. """ Detach the process context from parent and session.
  409. Detach from the parent process and session group, allowing the
  410. parent to exit while this process continues running.
  411. Reference: “Advanced Programming in the Unix Environment”,
  412. section 13.3, by W. Richard Stevens, published 1993 by
  413. Addison-Wesley.
  414. """
  415. def fork_then_exit_parent(error_message):
  416. """ Fork a child process, then exit the parent process.
  417. If the fork fails, raise a ``DaemonProcessDetachError``
  418. with ``error_message``.
  419. """
  420. try:
  421. pid = os.fork()
  422. if pid > 0:
  423. os._exit(0)
  424. except OSError, exc:
  425. exc_errno = exc.errno
  426. exc_strerror = exc.strerror
  427. error = DaemonProcessDetachError(
  428. "%(error_message)s: [%(exc_errno)d] %(exc_strerror)s" % vars())
  429. raise error
  430. fork_then_exit_parent(error_message="Failed first fork")
  431. os.setsid()
  432. fork_then_exit_parent(error_message="Failed second fork")
  433. def is_process_started_by_init():
  434. """ Determine if the current process is started by `init`.
  435. The `init` process has the process ID of 1; if that is our
  436. parent process ID, return ``True``, otherwise ``False``.
  437. """
  438. result = False
  439. init_pid = 1
  440. if os.getppid() == init_pid:
  441. result = True
  442. return result
  443. def is_socket(fd):
  444. """ Determine if the file descriptor is a socket.
  445. Return ``False`` if querying the socket type of `fd` raises an
  446. error; otherwise return ``True``.
  447. """
  448. result = False
  449. file_socket = socket.fromfd(fd, socket.AF_INET, socket.SOCK_RAW)
  450. try:
  451. socket_type = file_socket.getsockopt(
  452. socket.SOL_SOCKET, socket.SO_TYPE)
  453. except socket.error, exc:
  454. exc_errno = exc.args[0]
  455. if exc_errno == errno.ENOTSOCK:
  456. # Socket operation on non-socket
  457. pass
  458. else:
  459. # Some other socket error
  460. result = True
  461. else:
  462. # No error getting socket type
  463. result = True
  464. return result
  465. def is_process_started_by_superserver():
  466. """ Determine if the current process is started by the superserver.
  467. The internet superserver creates a network socket, and
  468. attaches it to the standard streams of the child process. If
  469. that is the case for this process, return ``True``, otherwise
  470. ``False``.
  471. """
  472. result = False
  473. stdin_fd = sys.__stdin__.fileno()
  474. if is_socket(stdin_fd):
  475. result = True
  476. return result
  477. def is_detach_process_context_required():
  478. """ Determine whether detaching process context is required.
  479. Return ``True`` if the process environment indicates the
  480. process is already detached:
  481. * Process was started by `init`; or
  482. * Process was started by `inetd`.
  483. """
  484. result = True
  485. if is_process_started_by_init() or is_process_started_by_superserver():
  486. result = False
  487. return result
  488. def close_file_descriptor_if_open(fd):
  489. """ Close a file descriptor if already open.
  490. Close the file descriptor `fd`, suppressing an error in the
  491. case the file was not open.
  492. """
  493. try:
  494. os.close(fd)
  495. except OSError, exc:
  496. if exc.errno == errno.EBADF:
  497. # File descriptor was not open
  498. pass
  499. else:
  500. error = DaemonOSEnvironmentError(
  501. "Failed to close file descriptor %(fd)d"
  502. " (%(exc)s)"
  503. % vars())
  504. raise error
  505. MAXFD = 2048
  506. def get_maximum_file_descriptors():
  507. """ Return the maximum number of open file descriptors for this process.
  508. Return the process hard resource limit of maximum number of
  509. open file descriptors. If the limit is “infinity”, a default
  510. value of ``MAXFD`` is returned.
  511. """
  512. limits = resource.getrlimit(resource.RLIMIT_NOFILE)
  513. result = limits[1]
  514. if result == resource.RLIM_INFINITY:
  515. result = MAXFD
  516. return result
  517. def close_all_open_files(exclude=set()):
  518. """ Close all open file descriptors.
  519. Closes every file descriptor (if open) of this process. If
  520. specified, `exclude` is a set of file descriptors to *not*
  521. close.
  522. """
  523. maxfd = get_maximum_file_descriptors()
  524. for fd in reversed(range(maxfd)):
  525. if fd not in exclude:
  526. close_file_descriptor_if_open(fd)
  527. def redirect_stream(system_stream, target_stream):
  528. """ Redirect a system stream to a specified file.
  529. `system_stream` is a standard system stream such as
  530. ``sys.stdout``. `target_stream` is an open file object that
  531. should replace the corresponding system stream object.
  532. If `target_stream` is ``None``, defaults to opening the
  533. operating system's null device and using its file descriptor.
  534. """
  535. if target_stream is None:
  536. target_fd = os.open(os.devnull, os.O_RDWR)
  537. else:
  538. target_fd = target_stream.fileno()
  539. os.dup2(target_fd, system_stream.fileno())
  540. def make_default_signal_map():
  541. """ Make the default signal map for this system.
  542. The signals available differ by system. The map will not
  543. contain any signals not defined on the running system.
  544. """
  545. name_map = {
  546. 'SIGTSTP': None,
  547. 'SIGTTIN': None,
  548. 'SIGTTOU': None,
  549. 'SIGTERM': 'terminate',
  550. }
  551. signal_map = dict(
  552. (getattr(signal, name), target)
  553. for (name, target) in name_map.items()
  554. if hasattr(signal, name))
  555. return signal_map
  556. def set_signal_handlers(signal_handler_map):
  557. """ Set the signal handlers as specified.
  558. The `signal_handler_map` argument is a map from signal number
  559. to signal handler. See the `signal` module for details.
  560. """
  561. for (signal_number, handler) in signal_handler_map.items():
  562. signal.signal(signal_number, handler)
  563. def register_atexit_function(func):
  564. """ Register a function for processing at program exit.
  565. The function `func` is registered for a call with no arguments
  566. at program exit.
  567. """
  568. atexit.register(func)