daemon.py 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049
  1. # daemon/daemon.py
  2. # Part of ‘python-daemon’, an implementation of PEP 3143.
  3. #
  4. # This is free software, and you are welcome to redistribute it under
  5. # certain conditions; see the end of this file for copyright
  6. # information, grant of license, and disclaimer of warranty.
  7. """ Daemon process behaviour. """
  8. import atexit
  9. import errno
  10. import os
  11. import pwd
  12. import resource
  13. import signal
  14. import socket
  15. import sys
  16. import warnings
  17. class DaemonError(Exception):
  18. """ Base exception class for errors from this module. """
  19. class DaemonOSEnvironmentError(DaemonError, OSError):
  20. """ Exception raised when daemon OS environment setup receives error. """
  21. class DaemonProcessDetachError(DaemonError, OSError):
  22. """ Exception raised when process detach fails. """
  23. class DaemonContext:
  24. """ Context for turning the current program into a daemon process.
  25. A `DaemonContext` instance represents the behaviour settings and
  26. process context for the program when it becomes a daemon. The
  27. behaviour and environment is customised by setting options on the
  28. instance, before calling the `open` method.
  29. Each option can be passed as a keyword argument to the `DaemonContext`
  30. constructor, or subsequently altered by assigning to an attribute on
  31. the instance at any time prior to calling `open`. That is, for
  32. options named `wibble` and `wubble`, the following invocation::
  33. foo = daemon.DaemonContext(wibble=bar, wubble=baz)
  34. foo.open()
  35. is equivalent to::
  36. foo = daemon.DaemonContext()
  37. foo.wibble = bar
  38. foo.wubble = baz
  39. foo.open()
  40. The following options are defined.
  41. `files_preserve`
  42. :Default: ``None``
  43. List of files that should *not* be closed when starting the
  44. daemon. If ``None``, all open file descriptors will be closed.
  45. Elements of the list are file descriptors (as returned by a file
  46. object's `fileno()` method) or Python `file` objects. Each
  47. specifies a file that is not to be closed during daemon start.
  48. `chroot_directory`
  49. :Default: ``None``
  50. Full path to a directory to set as the effective root directory of
  51. the process. If ``None``, specifies that the root directory is not
  52. to be changed.
  53. `working_directory`
  54. :Default: ``'/'``
  55. Full path of the working directory to which the process should
  56. change on daemon start.
  57. Since a filesystem cannot be unmounted if a process has its
  58. current working directory on that filesystem, this should either
  59. be left at default or set to a directory that is a sensible “home
  60. directory” for the daemon while it is running.
  61. `umask`
  62. :Default: ``0``
  63. File access creation mask (“umask”) to set for the process on
  64. daemon start.
  65. A daemon should not rely on the parent process's umask value,
  66. which is beyond its control and may prevent creating a file with
  67. the required access mode. So when the daemon context opens, the
  68. umask is set to an explicit known value.
  69. If the conventional value of 0 is too open, consider setting a
  70. value such as 0o022, 0o027, 0o077, or another specific value.
  71. Otherwise, ensure the daemon creates every file with an
  72. explicit access mode for the purpose.
  73. `pidfile`
  74. :Default: ``None``
  75. Context manager for a PID lock file. When the daemon context opens
  76. and closes, it enters and exits the `pidfile` context manager.
  77. `detach_process`
  78. :Default: ``None``
  79. If ``True``, detach the process context when opening the daemon
  80. context; if ``False``, do not detach.
  81. If unspecified (``None``) during initialisation of the instance,
  82. this will be set to ``True`` by default, and ``False`` only if
  83. detaching the process is determined to be redundant; for example,
  84. in the case when the process was started by `init`, by `initd`, or
  85. by `inetd`.
  86. `signal_map`
  87. :Default: system-dependent
  88. Mapping from operating system signals to callback actions.
  89. The mapping is used when the daemon context opens, and determines
  90. the action for each signal's signal handler:
  91. * A value of ``None`` will ignore the signal (by setting the
  92. signal action to ``signal.SIG_IGN``).
  93. * A string value will be used as the name of an attribute on the
  94. ``DaemonContext`` instance. The attribute's value will be used
  95. as the action for the signal handler.
  96. * Any other value will be used as the action for the
  97. signal handler. See the ``signal.signal`` documentation
  98. for details of the signal handler interface.
  99. The default value depends on which signals are defined on the
  100. running system. Each item from the list below whose signal is
  101. actually defined in the ``signal`` module will appear in the
  102. default map:
  103. * ``signal.SIGTTIN``: ``None``
  104. * ``signal.SIGTTOU``: ``None``
  105. * ``signal.SIGTSTP``: ``None``
  106. * ``signal.SIGTERM``: ``'terminate'``
  107. Depending on how the program will interact with its child
  108. processes, it may need to specify a signal map that
  109. includes the ``signal.SIGCHLD`` signal (received when a
  110. child process exits). See the specific operating system's
  111. documentation for more detail on how to determine what
  112. circumstances dictate the need for signal handlers.
  113. `uid`
  114. :Default: ``os.getuid()``
  115. `gid`
  116. :Default: ``os.getgid()``
  117. The user ID (“UID”) value and group ID (“GID”) value to switch
  118. the process to on daemon start.
  119. The default values, the real UID and GID of the process, will
  120. relinquish any effective privilege elevation inherited by the
  121. process.
  122. `initgroups`
  123. :Default: ``False``
  124. If true, set the daemon process's supplementary groups as
  125. determined by the specified `uid`.
  126. This will require that the current process UID has
  127. permission to change the process's owning GID.
  128. `prevent_core`
  129. :Default: ``True``
  130. If true, prevents the generation of core files, in order to avoid
  131. leaking sensitive information from daemons run as `root`.
  132. `stdin`
  133. :Default: ``None``
  134. `stdout`
  135. :Default: ``None``
  136. `stderr`
  137. :Default: ``None``
  138. Each of `stdin`, `stdout`, and `stderr` is a file-like object
  139. which will be used as the new file for the standard I/O stream
  140. `sys.stdin`, `sys.stdout`, and `sys.stderr` respectively. The file
  141. should therefore be open, with a minimum of mode 'r' in the case
  142. of `stdin`, and mimimum of mode 'w+' in the case of `stdout` and
  143. `stderr`.
  144. If the object has a `fileno()` method that returns a file
  145. descriptor, the corresponding file will be excluded from being
  146. closed during daemon start (that is, it will be treated as though
  147. it were listed in `files_preserve`).
  148. If ``None``, the corresponding system stream is re-bound to the
  149. file named by `os.devnull`.
  150. """
  151. def __init__(
  152. self,
  153. chroot_directory=None,
  154. working_directory="/",
  155. umask=0,
  156. uid=None,
  157. gid=None,
  158. initgroups=False,
  159. prevent_core=True,
  160. detach_process=None,
  161. files_preserve=None,
  162. pidfile=None,
  163. stdin=None,
  164. stdout=None,
  165. stderr=None,
  166. signal_map=None,
  167. ):
  168. """ Set up a new instance. """
  169. self.chroot_directory = chroot_directory
  170. self.working_directory = working_directory
  171. self.umask = umask
  172. self.prevent_core = prevent_core
  173. self.files_preserve = files_preserve
  174. self.pidfile = pidfile
  175. self.stdin = stdin
  176. self.stdout = stdout
  177. self.stderr = stderr
  178. if uid is None:
  179. uid = os.getuid()
  180. self.uid = uid
  181. if gid is None:
  182. gid = os.getgid()
  183. self.gid = gid
  184. self.initgroups = initgroups
  185. if detach_process is None:
  186. detach_process = is_detach_process_context_required()
  187. self.detach_process = detach_process
  188. if signal_map is None:
  189. signal_map = make_default_signal_map()
  190. self.signal_map = signal_map
  191. self._is_open = False
  192. @property
  193. def is_open(self):
  194. """ ``True`` if the instance is currently open. """
  195. return self._is_open
  196. def open(self):
  197. """ Become a daemon process.
  198. :return: ``None``.
  199. Open the daemon context, turning the current program into a daemon
  200. process. This performs the following steps:
  201. * If this instance's `is_open` property is true, return
  202. immediately. This makes it safe to call `open` multiple times on
  203. an instance.
  204. * If the `prevent_core` attribute is true, set the resource limits
  205. for the process to prevent any core dump from the process.
  206. * If the `chroot_directory` attribute is not ``None``, set the
  207. effective root directory of the process to that directory (via
  208. `os.chroot`).
  209. This allows running the daemon process inside a “chroot gaol”
  210. as a means of limiting the system's exposure to rogue behaviour
  211. by the process. Note that the specified directory needs to
  212. already be set up for this purpose.
  213. * Set the process owner (UID and GID) to the `uid` and `gid`
  214. attribute values.
  215. If the `initgroups` attribute is true, also set the process's
  216. supplementary groups to all the user's groups (i.e. those
  217. groups whose membership includes the username corresponding
  218. to `uid`).
  219. * Close all open file descriptors. This excludes those listed in
  220. the `files_preserve` attribute, and those that correspond to the
  221. `stdin`, `stdout`, or `stderr` attributes.
  222. * Change current working directory to the path specified by the
  223. `working_directory` attribute.
  224. * Reset the file access creation mask to the value specified by
  225. the `umask` attribute.
  226. * If the `detach_process` option is true, detach the current
  227. process into its own process group, and disassociate from any
  228. controlling terminal.
  229. * Set signal handlers as specified by the `signal_map` attribute.
  230. * If any of the attributes `stdin`, `stdout`, `stderr` are not
  231. ``None``, bind the system streams `sys.stdin`, `sys.stdout`,
  232. and/or `sys.stderr` to the files represented by the
  233. corresponding attributes. Where the attribute has a file
  234. descriptor, the descriptor is duplicated (instead of re-binding
  235. the name).
  236. * If the `pidfile` attribute is not ``None``, enter its context
  237. manager.
  238. * Mark this instance as open (for the purpose of future `open` and
  239. `close` calls).
  240. * Register the `close` method to be called during Python's exit
  241. processing.
  242. When the function returns, the running program is a daemon
  243. process.
  244. """
  245. if self.is_open:
  246. return
  247. if self.chroot_directory is not None:
  248. change_root_directory(self.chroot_directory)
  249. if self.prevent_core:
  250. prevent_core_dump()
  251. change_file_creation_mask(self.umask)
  252. change_working_directory(self.working_directory)
  253. change_process_owner(self.uid, self.gid, self.initgroups)
  254. if self.detach_process:
  255. detach_process_context()
  256. signal_handler_map = self._make_signal_handler_map()
  257. set_signal_handlers(signal_handler_map)
  258. exclude_fds = self._get_exclude_file_descriptors()
  259. close_all_open_files(exclude=exclude_fds)
  260. redirect_stream(sys.stdin, self.stdin)
  261. redirect_stream(sys.stdout, self.stdout)
  262. redirect_stream(sys.stderr, self.stderr)
  263. if self.pidfile is not None:
  264. self.pidfile.__enter__()
  265. self._is_open = True
  266. register_atexit_function(self.close)
  267. def __enter__(self):
  268. """ Context manager entry point. """
  269. self.open()
  270. return self
  271. def close(self):
  272. """ Exit the daemon process context.
  273. :return: ``None``.
  274. Close the daemon context. This performs the following steps:
  275. * If this instance's `is_open` property is false, return
  276. immediately. This makes it safe to call `close` multiple times
  277. on an instance.
  278. * If the `pidfile` attribute is not ``None``, exit its context
  279. manager.
  280. * Mark this instance as closed (for the purpose of future `open`
  281. and `close` calls).
  282. """
  283. if not self.is_open:
  284. return
  285. if self.pidfile is not None:
  286. # Follow the interface for telling a context manager to exit,
  287. # <URL:https://docs.python.org/3/library/stdtypes.html#typecontextmanager>.
  288. self.pidfile.__exit__(None, None, None)
  289. self._is_open = False
  290. def __exit__(self, exc_type, exc_value, traceback):
  291. """ Context manager exit point. """
  292. self.close()
  293. def terminate(self, signal_number, stack_frame):
  294. """ Signal handler for end-process signals.
  295. :param signal_number: The OS signal number received.
  296. :param stack_frame: The frame object at the point the
  297. signal was received.
  298. :return: ``None``.
  299. Signal handler for the ``signal.SIGTERM`` signal. Performs the
  300. following step:
  301. * Raise a ``SystemExit`` exception explaining the signal.
  302. """
  303. exception = SystemExit(
  304. "Terminating on signal {signal_number!r}".format(
  305. signal_number=signal_number))
  306. raise exception
  307. def _get_exclude_file_descriptors(self):
  308. """ Get the set of file descriptors to exclude closing.
  309. :return: A set containing the file descriptors for the
  310. files to be preserved.
  311. The file descriptors to be preserved are those from the
  312. items in `files_preserve`, and also each of `stdin`,
  313. `stdout`, and `stderr`. For each item:
  314. * If the item is ``None``, omit it from the return set.
  315. * If the item's `fileno` method returns a value, include
  316. that value in the return set.
  317. * Otherwise, include the item verbatim in the return set.
  318. """
  319. files_preserve = self.files_preserve
  320. if files_preserve is None:
  321. files_preserve = []
  322. files_preserve.extend(
  323. item for item in {self.stdin, self.stdout, self.stderr}
  324. if hasattr(item, 'fileno'))
  325. exclude_descriptors = set()
  326. for item in files_preserve:
  327. if item is None:
  328. continue
  329. file_descriptor = _get_file_descriptor(item)
  330. if file_descriptor is not None:
  331. exclude_descriptors.add(file_descriptor)
  332. else:
  333. exclude_descriptors.add(item)
  334. return exclude_descriptors
  335. def _make_signal_handler(self, target):
  336. """ Make the signal handler for a specified target object.
  337. :param target: A specification of the target for the
  338. handler; see below.
  339. :return: The value for use by `signal.signal()`.
  340. If `target` is ``None``, return ``signal.SIG_IGN``. If `target`
  341. is a text string, return the attribute of this instance named
  342. by that string. Otherwise, return `target` itself.
  343. """
  344. if target is None:
  345. result = signal.SIG_IGN
  346. elif isinstance(target, str):
  347. name = target
  348. result = getattr(self, name)
  349. else:
  350. result = target
  351. return result
  352. def _make_signal_handler_map(self):
  353. """ Make the map from signals to handlers for this instance.
  354. :return: The constructed signal map for this instance.
  355. Construct a map from signal numbers to handlers for this
  356. context instance, suitable for passing to
  357. `set_signal_handlers`.
  358. """
  359. signal_handler_map = {
  360. signal_number: self._make_signal_handler(target)
  361. for (signal_number, target) in self.signal_map.items()}
  362. return signal_handler_map
  363. def get_stream_file_descriptors(
  364. stdin=sys.stdin,
  365. stdout=sys.stdout,
  366. stderr=sys.stderr,
  367. ):
  368. """ Get the set of file descriptors for the process streams.
  369. :stdin: The input stream for the process (default:
  370. `sys.stdin`).
  371. :stdout: The ouput stream for the process (default:
  372. `sys.stdout`).
  373. :stderr: The diagnostic stream for the process (default:
  374. `sys.stderr`).
  375. :return: A `set` of each file descriptor (integer) for the
  376. streams.
  377. The standard streams are the files `sys.stdin`, `sys.stdout`,
  378. `sys.stderr`.
  379. Streams might in some circumstances be non-file objects.
  380. Include in the result only those streams that actually have a
  381. file descriptor (as returned by the `fileno` method).
  382. """
  383. file_descriptors = {
  384. fd for fd in {
  385. _get_file_descriptor(stream)
  386. for stream in {stdin, stdout, stderr}}
  387. if fd is not None}
  388. return file_descriptors
  389. def _get_file_descriptor(obj):
  390. """ Get the file descriptor, if the object has one.
  391. :param obj: The object expected to be a file-like object.
  392. :return: The file descriptor iff the file supports it; otherwise
  393. ``None``.
  394. The object may be a non-file object. It may also be a
  395. file-like object with no support for a file descriptor. In
  396. either case, return ``None``.
  397. """
  398. file_descriptor = None
  399. if hasattr(obj, 'fileno'):
  400. try:
  401. file_descriptor = obj.fileno()
  402. except ValueError:
  403. # The item doesn't support a file descriptor.
  404. pass
  405. return file_descriptor
  406. def change_working_directory(directory):
  407. """ Change the working directory of this process.
  408. :param directory: The target directory path.
  409. :return: ``None``.
  410. """
  411. try:
  412. os.chdir(directory)
  413. except Exception as exc:
  414. error = DaemonOSEnvironmentError(
  415. "Unable to change working directory ({exc})".format(exc=exc))
  416. raise error from exc
  417. def change_root_directory(directory):
  418. """ Change the root directory of this process.
  419. :param directory: The target directory path.
  420. :return: ``None``.
  421. Set the current working directory, then the process root directory,
  422. to the specified `directory`. Requires appropriate OS privileges
  423. for this process.
  424. """
  425. try:
  426. os.chdir(directory)
  427. os.chroot(directory)
  428. except Exception as exc:
  429. error = DaemonOSEnvironmentError(
  430. "Unable to change root directory ({exc})".format(exc=exc))
  431. raise error from exc
  432. def change_file_creation_mask(mask):
  433. """ Change the file creation mask for this process.
  434. :param mask: The numeric file creation mask to set.
  435. :return: ``None``.
  436. """
  437. try:
  438. os.umask(mask)
  439. except Exception as exc:
  440. error = DaemonOSEnvironmentError(
  441. "Unable to change file creation mask ({exc})".format(exc=exc))
  442. raise error from exc
  443. def get_username_for_uid(uid):
  444. """ Get the username for the specified UID. """
  445. passwd_entry = pwd.getpwuid(uid)
  446. username = passwd_entry.pw_name
  447. return username
  448. def change_process_owner(uid, gid, initgroups=False):
  449. """ Change the owning UID, GID, and groups of this process.
  450. :param uid: The target UID for the daemon process.
  451. :param gid: The target GID for the daemon process.
  452. :param initgroups: If true, initialise the supplementary
  453. groups of the process.
  454. :return: ``None``.
  455. Sets the owning GID and UID of the process (in that order, to
  456. avoid permission errors) to the specified `gid` and `uid`
  457. values.
  458. If `initgroups` is true, the supplementary groups of the
  459. process are also initialised, with those corresponding to the
  460. username for the target UID.
  461. All these operations require appropriate OS privileges. If
  462. permission is denied, a ``DaemonOSEnvironmentError`` is
  463. raised.
  464. """
  465. try:
  466. username = get_username_for_uid(uid)
  467. except KeyError:
  468. # We don't have a username to pass to ‘os.initgroups’.
  469. initgroups = False
  470. try:
  471. if initgroups:
  472. os.initgroups(username, gid)
  473. else:
  474. os.setgid(gid)
  475. os.setuid(uid)
  476. except Exception as exc:
  477. error = DaemonOSEnvironmentError(
  478. "Unable to change process owner ({exc})".format(exc=exc))
  479. raise error from exc
  480. def prevent_core_dump():
  481. """ Prevent this process from generating a core dump.
  482. :return: ``None``.
  483. Set the soft and hard limits for core dump size to zero. On Unix,
  484. this entirely prevents the process from creating core dump.
  485. """
  486. core_resource = resource.RLIMIT_CORE
  487. try:
  488. # Ensure the resource limit exists on this platform, by requesting
  489. # its current value.
  490. resource.getrlimit(core_resource)
  491. except ValueError as exc:
  492. error = DaemonOSEnvironmentError(
  493. "System does not support RLIMIT_CORE resource limit"
  494. " ({exc})".format(exc=exc))
  495. raise error from exc
  496. # Set hard and soft limits to zero, i.e. no core dump at all.
  497. core_limit = (0, 0)
  498. resource.setrlimit(core_resource, core_limit)
  499. def detach_process_context():
  500. """ Detach the process context from parent and session.
  501. :return: ``None``.
  502. Detach from the parent process and session group, allowing the
  503. parent to exit while this process continues running.
  504. Reference: “Advanced Programming in the Unix Environment”,
  505. section 13.3, by W. Richard Stevens, published 1993 by
  506. Addison-Wesley.
  507. """
  508. def fork_then_exit_parent(error_message):
  509. """ Fork a child process, then exit the parent process.
  510. :param error_message: Message for the exception in case of a
  511. detach failure.
  512. :return: ``None``.
  513. :raise DaemonProcessDetachError: If the fork fails.
  514. """
  515. try:
  516. pid = os.fork()
  517. if pid > 0:
  518. os._exit(0)
  519. except OSError as exc:
  520. error = DaemonProcessDetachError(
  521. "{message}: [{exc.errno:d}] {exc.strerror}".format(
  522. message=error_message, exc=exc))
  523. raise error from exc
  524. fork_then_exit_parent(error_message="Failed first fork")
  525. os.setsid()
  526. fork_then_exit_parent(error_message="Failed second fork")
  527. def is_process_started_by_init():
  528. """ Determine whether the current process is started by `init`.
  529. :return: ``True`` iff the parent process is `init`; otherwise
  530. ``False``.
  531. The `init` process is the one with process ID of 1.
  532. """
  533. result = False
  534. init_pid = 1
  535. if os.getppid() == init_pid:
  536. result = True
  537. return result
  538. def is_socket(fd):
  539. """ Determine whether the file descriptor is a socket.
  540. :param fd: The file descriptor to interrogate.
  541. :return: ``True`` iff the file descriptor is a socket; otherwise
  542. ``False``.
  543. Query the socket type of `fd`. If there is no error, the file is a
  544. socket.
  545. """
  546. warnings.warn(
  547. DeprecationWarning("migrate to `is_socket_file` instead"))
  548. result = False
  549. try:
  550. file_socket = socket.fromfd(fd, socket.AF_INET, socket.SOCK_RAW)
  551. file_socket.getsockopt(socket.SOL_SOCKET, socket.SO_TYPE)
  552. except socket.error as exc:
  553. exc_errno = exc.args[0]
  554. if exc_errno == errno.ENOTSOCK:
  555. # Socket operation on non-socket.
  556. pass
  557. else:
  558. # Some other socket error.
  559. result = True
  560. else:
  561. # No error getting socket type.
  562. result = True
  563. return result
  564. def is_socket_file(file):
  565. """ Determine whether the `file` is a socket.
  566. :param file: The file (an `io.IOBase` instance) to interrogate.
  567. :return: ``True`` iff `file` is a socket; otherwise ``False``.
  568. Query the socket type of the file descriptor of `file`. If there is no
  569. error, the file is a socket.
  570. """
  571. result = False
  572. try:
  573. file_fd = file.fileno()
  574. except ValueError:
  575. # The file doesn't have a file descriptor.
  576. file_fd = None
  577. try:
  578. file_socket = socket.fromfd(file_fd, socket.AF_INET, socket.SOCK_RAW)
  579. file_socket.getsockopt(socket.SOL_SOCKET, socket.SO_TYPE)
  580. except socket.error as exc:
  581. exc_errno = exc.args[0]
  582. if exc_errno == errno.ENOTSOCK:
  583. # Socket operation on non-socket.
  584. pass
  585. else:
  586. # Some other socket error.
  587. result = True
  588. else:
  589. # No error getting socket type.
  590. result = True
  591. return result
  592. def is_process_started_by_superserver():
  593. """ Determine whether the current process is started by the superserver.
  594. :return: ``True`` if this process was started by the internet
  595. superserver; otherwise ``False``.
  596. The internet superserver creates a network socket, and
  597. attaches it to the standard streams of the child process. If
  598. that is the case for this process, return ``True``, otherwise
  599. ``False``.
  600. """
  601. result = False
  602. if is_socket_file(sys.__stdin__):
  603. result = True
  604. return result
  605. def is_detach_process_context_required():
  606. """ Determine whether detaching the process context is required.
  607. :return: ``False`` iff the process is already detached;
  608. otherwise ``True``.
  609. The process environment is interrogated for the following:
  610. * Process was started by `init`; or
  611. * Process was started by `inetd`.
  612. If any of the above are true, the process is deemed to be already
  613. detached.
  614. """
  615. result = True
  616. if is_process_started_by_init() or is_process_started_by_superserver():
  617. result = False
  618. return result
  619. def close_file_descriptor_if_open(fd):
  620. """ Close a file descriptor if already open.
  621. :param fd: The file descriptor to close.
  622. :return: ``None``.
  623. Close the file descriptor `fd`, suppressing an error in the
  624. case the file was not open.
  625. """
  626. try:
  627. os.close(fd)
  628. except EnvironmentError as exc:
  629. if exc.errno == errno.EBADF:
  630. # File descriptor was not open.
  631. pass
  632. else:
  633. error = DaemonOSEnvironmentError(
  634. "Failed to close file descriptor {fd:d} ({exc})".format(
  635. fd=fd, exc=exc))
  636. raise error from exc
  637. MAXFD = 2048
  638. def get_maximum_file_descriptors():
  639. """ Get the maximum number of open file descriptors for this process.
  640. :return: The number (integer) to use as the maximum number of open
  641. files for this process.
  642. The maximum is the process hard resource limit of maximum number of
  643. open file descriptors. If the limit is “infinity”, a default value
  644. of ``MAXFD`` is returned.
  645. """
  646. (__, hard_limit) = resource.getrlimit(resource.RLIMIT_NOFILE)
  647. result = hard_limit
  648. if hard_limit == resource.RLIM_INFINITY:
  649. result = MAXFD
  650. return result
  651. _total_file_descriptor_range = range(0, get_maximum_file_descriptors())
  652. def _validate_fd_values(fds):
  653. """ Validate the collection of file descriptors `fds`.
  654. :param fds: A collection of file descriptors.
  655. :raise TypeError: When any of the `fds` are an invalid type.
  656. :return: ``None``.
  657. A valid file descriptor is an `int` value.
  658. """
  659. invalid_fds = set(filter((lambda fd: not isinstance(fd, int)), fds))
  660. if invalid_fds:
  661. value_to_complain_about = next(iter(invalid_fds))
  662. message = "not an integer file descriptor: {!r}".format(
  663. value_to_complain_about)
  664. raise TypeError(message)
  665. def _get_candidate_file_descriptor_ranges(exclude):
  666. """ Get the collection of candidate file descriptor ranges.
  667. :param exclude: A collection of file descriptors that should
  668. be excluded from the return ranges.
  669. :return: The collection (a `list`) of ranges that contain the
  670. file descriptors that are candidates for files that may be
  671. open in this process.
  672. Determine the ranges of all the candidate file descriptors.
  673. Each range is a pair of `int` values (`low`, `high`).
  674. A value is a candidate if it could be an open file descriptor
  675. in this process, excluding those integers in the `exclude`
  676. collection.
  677. """
  678. _validate_fd_values(exclude)
  679. ranges = []
  680. remaining_range = _total_file_descriptor_range
  681. for exclude_fd in sorted(exclude):
  682. if (exclude_fd > remaining_range.stop):
  683. # This and all later exclusions are higher than the remaining
  684. # range.
  685. break
  686. if (exclude_fd < remaining_range.start):
  687. # The remaining range does not include the current exclusion.
  688. continue
  689. if (exclude_fd != remaining_range.start):
  690. # There is a candidate range below the current exclusion.
  691. ranges.append((remaining_range.start, exclude_fd))
  692. # Narrow the remaining range to those above the current exclusion.
  693. remaining_range = range(exclude_fd + 1, remaining_range.stop)
  694. if (remaining_range.start < remaining_range.stop):
  695. # After excluding all the specified file descriptors, there is a
  696. # remaining range; append it as a candidate for closing file
  697. # descriptors.
  698. ranges.append((remaining_range.start, remaining_range.stop))
  699. return ranges
  700. def _close_file_descriptor_ranges(ranges):
  701. """ Close file descriptors described by `ranges`.
  702. :param ranges: A sequence of tuples `(low, high)`, each
  703. describing a range of file descriptors to close.
  704. :return: ``None``.
  705. Attempt to close each open file descriptor – starting from
  706. `low` and ending before `high` – from each range in `ranges`.
  707. """
  708. for range in ranges:
  709. os.closerange(range[0], range[1])
  710. def close_all_open_files(exclude=None):
  711. """ Close all open file descriptors.
  712. :param exclude: Collection of file descriptors to skip when closing
  713. files.
  714. :return: ``None``.
  715. Closes every file descriptor (if open) of this process. If
  716. specified, `exclude` is a set of file descriptors to *not*
  717. close.
  718. """
  719. if exclude is None:
  720. exclude = set()
  721. fd_ranges = _get_candidate_file_descriptor_ranges(exclude=exclude)
  722. _close_file_descriptor_ranges(ranges=fd_ranges)
  723. def redirect_stream(system_stream, target_stream):
  724. """ Redirect a system stream to a specified file.
  725. :param standard_stream: A file object representing a standard I/O
  726. stream.
  727. :param target_stream: The target file object for the redirected
  728. stream, or ``None`` to specify the null device.
  729. :return: ``None``.
  730. `system_stream` is a standard system stream such as
  731. ``sys.stdout``. `target_stream` is an open file object that
  732. should replace the corresponding system stream object.
  733. If `target_stream` is ``None``, defaults to opening the
  734. operating system's null device and using its file descriptor.
  735. """
  736. if target_stream is None:
  737. target_fd = os.open(os.devnull, os.O_RDWR)
  738. else:
  739. target_fd = target_stream.fileno()
  740. os.dup2(target_fd, system_stream.fileno())
  741. def make_default_signal_map():
  742. """ Make the default signal map for this system.
  743. :return: A mapping from signal number to handler object.
  744. The signals available differ by system. The map will not contain
  745. any signals not defined on the running system.
  746. """
  747. name_map = {
  748. 'SIGTSTP': None,
  749. 'SIGTTIN': None,
  750. 'SIGTTOU': None,
  751. 'SIGTERM': 'terminate',
  752. }
  753. signal_map = {
  754. getattr(signal, name): target
  755. for (name, target) in name_map.items()
  756. if hasattr(signal, name)}
  757. return signal_map
  758. def set_signal_handlers(signal_handler_map):
  759. """ Set the signal handlers as specified.
  760. :param signal_handler_map: A map from signal number to handler
  761. object.
  762. :return: ``None``.
  763. See the `signal` module for details on signal numbers and signal
  764. handlers.
  765. """
  766. for (signal_number, handler) in signal_handler_map.items():
  767. signal.signal(signal_number, handler)
  768. def register_atexit_function(func):
  769. """ Register a function for processing at program exit.
  770. :param func: A callable function expecting no arguments.
  771. :return: ``None``.
  772. The function `func` is registered for a call with no arguments
  773. at program exit.
  774. """
  775. atexit.register(func)
  776. # Copyright © 2008–2024 Ben Finney <ben+python@benfinney.id.au>
  777. # Copyright © 2007–2008 Robert Niederreiter, Jens Klein
  778. # Copyright © 2004–2005 Chad J. Schroeder
  779. # Copyright © 2003 Clark Evans
  780. # Copyright © 2002 Noah Spurrier
  781. # Copyright © 2001 Jürgen Hermann
  782. #
  783. # This is free software: you may copy, modify, and/or distribute this work
  784. # under the terms of the Apache License, version 2.0 as published by the
  785. # Apache Software Foundation.
  786. # No warranty expressed or implied. See the file ‘LICENSE.ASF-2’ for details.
  787. # Local variables:
  788. # coding: utf-8
  789. # mode: python
  790. # End:
  791. # vim: fileencoding=utf-8 filetype=python :