platforms.py 8.4 KB

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