platforms.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. import os
  2. import sys
  3. import pwd
  4. import grp
  5. import errno
  6. import atexit
  7. import signal
  8. try:
  9. from setproctitle import setproctitle as _setproctitle
  10. except ImportError:
  11. _setproctitle = None
  12. CAN_DETACH = True
  13. try:
  14. import resource
  15. except ImportError:
  16. CAN_DETACH = False
  17. DAEMON_UMASK = 0
  18. DAEMON_WORKDIR = "/"
  19. DAEMON_REDIRECT_TO = getattr(os, "devnull", "/dev/nulll")
  20. class LockFailed(Exception):
  21. pass
  22. def get_fdmax(default=None):
  23. fdmax = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
  24. if fdmax == resource.RLIM_INFINITY:
  25. return default
  26. return fdmax
  27. class PIDFile(object):
  28. def __init__(self, path):
  29. self.path = os.path.abspath(path)
  30. def write_pid(self):
  31. open_flags = (os.O_CREAT | os.O_EXCL | os.O_WRONLY)
  32. open_mode = (((os.R_OK | os.W_OK) << 6) |
  33. ((os.R_OK) << 3) |
  34. ((os.R_OK)))
  35. pidfile_fd = os.open(self.path, open_flags, open_mode)
  36. pidfile = os.fdopen(pidfile_fd, "w")
  37. pid = os.getpid()
  38. pidfile.write("%d\n" % (pid, ))
  39. pidfile.close()
  40. def acquire(self):
  41. try:
  42. self.write_pid()
  43. except OSError, exc:
  44. raise LockFailed(str(exc))
  45. return self
  46. def is_locked(self):
  47. return os.path.exists(self.path)
  48. def release(self):
  49. self.remove()
  50. def read_pid(self):
  51. try:
  52. fh = open(self.path, "r")
  53. except IOError, exc:
  54. if exc.errno == errno.ENOENT:
  55. return
  56. raise
  57. line = fh.readline().strip()
  58. fh.close()
  59. try:
  60. return int(line)
  61. except ValueError:
  62. raise ValueError("PID file %r contents invalid." % path)
  63. def remove(self):
  64. try:
  65. os.unlink(self.path)
  66. except OSError, exc:
  67. if exc.errno in (errno.ENOENT, errno.EACCES):
  68. return
  69. raise
  70. def remove_if_stale(self):
  71. try:
  72. pid = self.read_pid()
  73. except ValueError, exc:
  74. sys.stderr.write("Broken pidfile found. Removing it.\n")
  75. self.remove()
  76. return True
  77. if not pid:
  78. self.remove()
  79. return True
  80. try:
  81. os.kill(pid, 0)
  82. except os.error, exc:
  83. if exc.errno == errno.ESRCH:
  84. sys.stderr.write("Stale pidfile exists. Removing it.\n")
  85. self.remove()
  86. return True
  87. return False
  88. def create_pidlock(pidfile):
  89. """Create and verify pidfile.
  90. If the pidfile already exists the program exits with an error message,
  91. however if the process it refers to is not running anymore, the pidfile
  92. is just deleted.
  93. """
  94. pidlock = PIDFile(pidfile)
  95. if pidlock.is_locked() and not pidlock.remove_if_stale():
  96. raise SystemExit(
  97. "ERROR: Pidfile (%s) already exists.\n"
  98. "Seems we're already running? (PID: %s)" % (
  99. pidfile, pidlock.read_pid()))
  100. return pidlock
  101. class DaemonContext(object):
  102. _is_open = False
  103. def __init__(self, pidfile=None,
  104. working_directory=DAEMON_WORKDIR, umask=DAEMON_UMASK, **kwargs):
  105. self.working_directory = working_directory
  106. self.umask = umask
  107. def detach(self):
  108. if os.fork() == 0: # first child
  109. os.setsid() # create new session
  110. if os.fork() > 0: # second child
  111. os._exit(0)
  112. else:
  113. os._exit(0)
  114. def open(self):
  115. if self._is_open:
  116. return
  117. self.detach()
  118. os.chdir(self.working_directory)
  119. os.umask(self.umask)
  120. for fd in reversed(range(get_fdmax(default=2048))):
  121. try:
  122. os.close(fd)
  123. except OSError, exc:
  124. if exc.errno != errno.EBADF:
  125. raise
  126. os.open(DAEMON_REDIRECT_TO, os.O_RDWR)
  127. os.dup2(0, 1)
  128. os.dup2(0, 2)
  129. self._is_open = True
  130. def close(self):
  131. if self._is_open:
  132. self._is_open = False
  133. def create_daemon_context(logfile=None, pidfile=None, uid=None, gid=None,
  134. **options):
  135. if not CAN_DETACH:
  136. raise RuntimeError(
  137. "This platform does not support detach.")
  138. # Make sure SIGCLD is using the default handler.
  139. reset_signal("SIGCLD")
  140. set_effective_user(uid=uid, gid=gid)
  141. # Since without stderr any errors will be silently suppressed,
  142. # we need to know that we have access to the logfile.
  143. if logfile:
  144. open(logfile, "a").close()
  145. if pidfile:
  146. # Doesn't actually create the pidfile, but makes sure it's
  147. # not stale.
  148. create_pidlock(pidfile)
  149. defaults = {"umask": lambda: 0,
  150. "working_directory": lambda: os.getcwd()}
  151. for opt_name, opt_default_gen in defaults.items():
  152. if opt_name not in options or options[opt_name] is None:
  153. options[opt_name] = opt_default_gen()
  154. context = DaemonContext(**options)
  155. return context, context.close
  156. def parse_uid(uid):
  157. """Parse user id.
  158. uid can be an interger (uid) or a string (username), if a username
  159. the uid is taken from the password file.
  160. """
  161. try:
  162. return int(uid)
  163. except ValueError:
  164. return pwd.getpwnam(uid).pw_uid
  165. def parse_gid(gid):
  166. """Parse group id.
  167. gid can be an integer (gid) or a string (group name), if a group name
  168. the gid is taken from the password file.
  169. """
  170. try:
  171. return int(gid)
  172. except ValueError:
  173. return grp.getgrnam(gid).gr_gid
  174. def setegid(gid):
  175. """Set effective group id."""
  176. gid = parse_gid(gid)
  177. if gid != os.getgid():
  178. os.setegid
  179. def seteuid(uid):
  180. """Set effective user id."""
  181. uid = parse_uid(uid)
  182. if uid != os.getuid():
  183. os.seteuid(uid)
  184. def set_effective_user(uid=None, gid=None):
  185. """Change process privileges to new user/group.
  186. If uid and gid is set the effective user/group is set.
  187. If only uid is set, the effective uer is set, and the group is
  188. set to the users primary group.
  189. If only gid is set, the effective group is set.
  190. """
  191. uid = uid and parse_uid(uid)
  192. gid = gid and parse_gid(gid)
  193. if uid:
  194. # If gid isn't defined, get the primary gid of the uer.
  195. setegid(gid or pwd.getpwuid(uid).pw_gid)
  196. seteuid(uid)
  197. else:
  198. gid and setegid(gid)
  199. def reset_signal(signal_name):
  200. """Reset signal to the default signal handler.
  201. Does nothing if the platform doesn't support signals,
  202. or the specified signal in particular.
  203. """
  204. try:
  205. signum = getattr(signal, signal_name)
  206. signal.signal(signum, signal.SIG_DFL)
  207. except (AttributeError, ValueError):
  208. pass
  209. def ignore_signal(signal_name):
  210. """Ignore signal using :const:`SIG_IGN`.
  211. Does nothing if the platform doesn't support signals,
  212. or the specified signal in particular.
  213. """
  214. try:
  215. signum = getattr(signal, signal_name)
  216. signal.signal(signum, signal.SIG_IGN)
  217. except (AttributeError, ValueError):
  218. pass
  219. def install_signal_handler(signal_name, handler):
  220. """Install a handler.
  221. Does nothing if the current platform doesn't support signals,
  222. or the specified signal in particular.
  223. """
  224. try:
  225. signum = getattr(signal, signal_name)
  226. signal.signal(signum, handler)
  227. except (AttributeError, ValueError):
  228. pass
  229. def strargv(argv):
  230. arg_start = "manage" in argv[0] and 2 or 1
  231. if len(argv) > arg_start:
  232. return " ".join(argv[arg_start:])
  233. return ""
  234. def set_process_title(progname, info=None):
  235. """Set the ps name for the currently running process.
  236. Only works if :mod:`setproctitle` is installed.
  237. """
  238. proctitle = "[%s]" % progname
  239. proctitle = info and "%s %s" % (proctitle, info) or proctitle
  240. if _setproctitle:
  241. _setproctitle(proctitle)
  242. return proctitle
  243. def set_mp_process_title(progname, info=None, hostname=None):
  244. """Set the ps name using the multiprocessing process name.
  245. Only works if :mod:`setproctitle` is installed.
  246. """
  247. from multiprocessing.process import current_process
  248. if hostname:
  249. progname = "%s@%s" % (progname, hostname.split(".")[0])
  250. return set_process_title("%s:%s" % (progname, current_process().name),
  251. info=info)