Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.
 
 
 
 
 
 

143 Zeilen
4.9 KiB

  1. # Copyright (c) 2012, 2013, 2014 Ilya Otyutskiy <ilya.otyutskiy@icloud.com>
  2. # Copyright 2020 The Matrix.org Foundation C.I.C.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import atexit
  16. import fcntl
  17. import logging
  18. import os
  19. import signal
  20. import sys
  21. from types import FrameType, TracebackType
  22. from typing import NoReturn, Optional, Type
  23. def daemonize_process(pid_file: str, logger: logging.Logger, chdir: str = "/") -> None:
  24. """daemonize the current process
  25. This calls fork(), and has the main process exit. When it returns we will be
  26. running in the child process.
  27. """
  28. # If pidfile already exists, we should read pid from there; to overwrite it, if
  29. # locking will fail, because locking attempt somehow purges the file contents.
  30. if os.path.isfile(pid_file):
  31. with open(pid_file) as pid_fh:
  32. old_pid = pid_fh.read()
  33. # Create a lockfile so that only one instance of this daemon is running at any time.
  34. try:
  35. lock_fh = open(pid_file, "w")
  36. except OSError:
  37. print("Unable to create the pidfile.")
  38. sys.exit(1)
  39. try:
  40. # Try to get an exclusive lock on the file. This will fail if another process
  41. # has the file locked.
  42. fcntl.flock(lock_fh, fcntl.LOCK_EX | fcntl.LOCK_NB)
  43. except OSError:
  44. print("Unable to lock on the pidfile.")
  45. # We need to overwrite the pidfile if we got here.
  46. #
  47. # XXX better to avoid overwriting it, surely. this looks racey as the pid file
  48. # could be created between us trying to read it and us trying to lock it.
  49. with open(pid_file, "w") as pid_fh:
  50. pid_fh.write(old_pid)
  51. sys.exit(1)
  52. # Fork, creating a new process for the child.
  53. process_id = os.fork()
  54. if process_id != 0:
  55. # parent process: exit.
  56. # we use os._exit to avoid running the atexit handlers. In particular, that
  57. # means we don't flush the logs. This is important because if we are using
  58. # a MemoryHandler, we could have logs buffered which are now buffered in both
  59. # the main and the child process, so if we let the main process flush the logs,
  60. # we'll get two copies.
  61. os._exit(0)
  62. # This is the child process. Continue.
  63. # Stop listening for signals that the parent process receives.
  64. # This is done by getting a new process id.
  65. # setpgrp() is an alternative to setsid().
  66. # setsid puts the process in a new parent group and detaches its controlling
  67. # terminal.
  68. os.setsid()
  69. # point stdin, stdout, stderr at /dev/null
  70. devnull = "/dev/null"
  71. if hasattr(os, "devnull"):
  72. # Python has set os.devnull on this system, use it instead as it might be
  73. # different than /dev/null.
  74. devnull = os.devnull
  75. devnull_fd = os.open(devnull, os.O_RDWR)
  76. os.dup2(devnull_fd, 0)
  77. os.dup2(devnull_fd, 1)
  78. os.dup2(devnull_fd, 2)
  79. os.close(devnull_fd)
  80. # now that we have redirected stderr to /dev/null, any uncaught exceptions will
  81. # get sent to /dev/null, so make sure we log them.
  82. #
  83. # (we don't normally expect reactor.run to raise any exceptions, but this will
  84. # also catch any other uncaught exceptions before we get that far.)
  85. def excepthook(
  86. type_: Type[BaseException],
  87. value: BaseException,
  88. traceback: Optional[TracebackType],
  89. ) -> None:
  90. logger.critical("Unhanded exception", exc_info=(type_, value, traceback))
  91. sys.excepthook = excepthook
  92. # Set umask to default to safe file permissions when running as a root daemon. 027
  93. # is an octal number which we are typing as 0o27 for Python3 compatibility.
  94. os.umask(0o27)
  95. # Change to a known directory. If this isn't done, starting a daemon in a
  96. # subdirectory that needs to be deleted results in "directory busy" errors.
  97. os.chdir(chdir)
  98. try:
  99. lock_fh.write("%s" % (os.getpid()))
  100. lock_fh.flush()
  101. except OSError:
  102. logger.error("Unable to write pid to the pidfile.")
  103. print("Unable to write pid to the pidfile.")
  104. sys.exit(1)
  105. # write a log line on SIGTERM.
  106. def sigterm(signum: int, frame: Optional[FrameType]) -> NoReturn:
  107. logger.warning("Caught signal %s. Stopping daemon." % signum)
  108. sys.exit(0)
  109. signal.signal(signal.SIGTERM, sigterm)
  110. # Cleanup pid file at exit.
  111. def exit() -> None:
  112. logger.warning("Stopping daemon.")
  113. os.remove(pid_file)
  114. sys.exit(0)
  115. atexit.register(exit)
  116. logger.warning("Starting daemon.")