platforms.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  1. # -*- coding: utf-8 -*-
  2. """
  3. celery.platforms
  4. ~~~~~~~~~~~~~~~~
  5. Utilities dealing with platform specifics: signals, daemonization,
  6. users, groups, and so on.
  7. :copyright: (c) 2009 - 2011 by Ask Solem.
  8. :license: BSD, see LICENSE for more details.
  9. """
  10. from __future__ import absolute_import
  11. import errno
  12. import os
  13. import platform as _platform
  14. import shlex
  15. import signal as _signal
  16. import sys
  17. from .local import try_import
  18. _setproctitle = try_import("setproctitle")
  19. resource = try_import("resource")
  20. pwd = try_import("pwd")
  21. grp = try_import("grp")
  22. SYSTEM = _platform.system()
  23. IS_OSX = SYSTEM == "Darwin"
  24. IS_WINDOWS = SYSTEM == "Windows"
  25. DAEMON_UMASK = 0
  26. DAEMON_WORKDIR = "/"
  27. DAEMON_REDIRECT_TO = getattr(os, "devnull", "/dev/null")
  28. def pyimplementation():
  29. if hasattr(_platform, "python_implementation"):
  30. return _platform.python_implementation()
  31. elif sys.platform.startswith("java"):
  32. return "Jython %s" % (sys.platform, )
  33. elif hasattr(sys, "pypy_version_info"):
  34. v = ".".join(map(str, sys.pypy_version_info[:3]))
  35. if sys.pypy_version_info[3:]:
  36. v += "-" + "".join(map(str, sys.pypy_version_info[3:]))
  37. return "PyPy %s" % (v, )
  38. else:
  39. return "CPython"
  40. class LockFailed(Exception):
  41. """Raised if a pidlock can't be acquired."""
  42. pass
  43. def get_fdmax(default=None):
  44. """Returns the maximum number of open file descriptors
  45. on this system.
  46. :keyword default: Value returned if there's no file
  47. descriptor limit.
  48. """
  49. fdmax = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
  50. if fdmax == resource.RLIM_INFINITY:
  51. return default
  52. return fdmax
  53. class PIDFile(object):
  54. """PID lock file.
  55. This is the type returned by :func:`create_pidlock`.
  56. **Should not be used directly, use the :func:`create_pidlock`
  57. context instead**
  58. """
  59. #: Path to the pid lock file.
  60. path = None
  61. def __init__(self, path):
  62. self.path = os.path.abspath(path)
  63. def acquire(self):
  64. """Acquire lock."""
  65. try:
  66. self.write_pid()
  67. except OSError, exc:
  68. raise LockFailed(str(exc))
  69. return self
  70. __enter__ = acquire
  71. def is_locked(self):
  72. """Returns true if the pid lock exists."""
  73. return os.path.exists(self.path)
  74. def release(self, *args):
  75. """Release lock."""
  76. self.remove()
  77. __exit__ = release
  78. def read_pid(self):
  79. """Reads and returns the current pid."""
  80. try:
  81. fh = open(self.path, "r")
  82. except IOError, exc:
  83. if exc.errno == errno.ENOENT:
  84. return
  85. raise
  86. line = fh.readline().strip()
  87. fh.close()
  88. try:
  89. return int(line)
  90. except ValueError:
  91. raise ValueError("PID file %r contents invalid." % self.path)
  92. def remove(self):
  93. """Removes the lock."""
  94. try:
  95. os.unlink(self.path)
  96. except OSError, exc:
  97. if exc.errno in (errno.ENOENT, errno.EACCES):
  98. return
  99. raise
  100. def remove_if_stale(self):
  101. """Removes the lock if the process is not running.
  102. (does not respond to signals)."""
  103. try:
  104. pid = self.read_pid()
  105. except ValueError, exc:
  106. sys.stderr.write("Broken pidfile found. Removing it.\n")
  107. self.remove()
  108. return True
  109. if not pid:
  110. self.remove()
  111. return True
  112. try:
  113. os.kill(pid, 0)
  114. except os.error, exc:
  115. if exc.errno == errno.ESRCH:
  116. sys.stderr.write("Stale pidfile exists. Removing it.\n")
  117. self.remove()
  118. return True
  119. return False
  120. def write_pid(self):
  121. open_flags = (os.O_CREAT | os.O_EXCL | os.O_WRONLY)
  122. open_mode = (((os.R_OK | os.W_OK) << 6) |
  123. ((os.R_OK) << 3) |
  124. ((os.R_OK)))
  125. pidfile_fd = os.open(self.path, open_flags, open_mode)
  126. pidfile = os.fdopen(pidfile_fd, "w")
  127. try:
  128. pid = os.getpid()
  129. pidfile.write("%d\n" % (pid, ))
  130. finally:
  131. pidfile.close()
  132. def create_pidlock(pidfile):
  133. """Create and verify pid file.
  134. If the pid file already exists the program exits with an error message,
  135. however if the process it refers to is not running anymore, the pid file
  136. is deleted and the program continues.
  137. The caller is responsible for releasing the lock before the program
  138. exits.
  139. :returns: :class:`PIDFile`.
  140. **Example**:
  141. .. code-block:: python
  142. import atexit
  143. pidlock = create_pidlock("/var/run/app.pid").acquire()
  144. atexit.register(pidlock.release)
  145. """
  146. pidlock = PIDFile(pidfile)
  147. if pidlock.is_locked() and not pidlock.remove_if_stale():
  148. raise SystemExit(
  149. "ERROR: Pidfile (%s) already exists.\n"
  150. "Seems we're already running? (PID: %s)" % (
  151. pidfile, pidlock.read_pid()))
  152. return pidlock
  153. class DaemonContext(object):
  154. _is_open = False
  155. workdir = DAEMON_WORKDIR
  156. umask = DAEMON_UMASK
  157. def __init__(self, pidfile=None, workdir=None,
  158. umask=None, **kwargs):
  159. self.workdir = workdir or self.workdir
  160. self.umask = self.umask if umask is None else umask
  161. def open(self):
  162. if not self._is_open:
  163. self._detach()
  164. os.chdir(self.workdir)
  165. os.umask(self.umask)
  166. for fd in reversed(range(get_fdmax(default=2048))):
  167. try:
  168. os.close(fd)
  169. except OSError, exc:
  170. if exc.errno != errno.EBADF:
  171. raise
  172. os.open(DAEMON_REDIRECT_TO, os.O_RDWR)
  173. os.dup2(0, 1)
  174. os.dup2(0, 2)
  175. self._is_open = True
  176. __enter__ = open
  177. def close(self, *args):
  178. if self._is_open:
  179. self._is_open = False
  180. __exit__ = close
  181. def _detach(self):
  182. if os.fork() == 0: # first child
  183. os.setsid() # create new session
  184. if os.fork() > 0: # second child
  185. os._exit(0)
  186. else:
  187. os._exit(0)
  188. return self
  189. def detached(logfile=None, pidfile=None, uid=None, gid=None, umask=0,
  190. workdir=None, **opts):
  191. """Detach the current process in the background (daemonize).
  192. :keyword logfile: Optional log file. The ability to write to this file
  193. will be verified before the process is detached.
  194. :keyword pidfile: Optional pid file. The pid file will not be created,
  195. as this is the responsibility of the child. But the process will
  196. exit if the pid lock exists and the pid written is still running.
  197. :keyword uid: Optional user id or user name to change
  198. effective privileges to.
  199. :keyword gid: Optional group id or group name to change effective
  200. privileges to.
  201. :keyword umask: Optional umask that will be effective in the child process.
  202. :keyword workdir: Optional new working directory.
  203. :keyword \*\*opts: Ignored.
  204. **Example**:
  205. .. code-block:: python
  206. import atexit
  207. from celery.platforms import detached, create_pidlock
  208. with detached(logfile="/var/log/app.log", pidfile="/var/run/app.pid",
  209. uid="nobody"):
  210. # Now in detached child process with effective user set to nobody,
  211. # and we know that our logfile can be written to, and that
  212. # the pidfile is not locked.
  213. pidlock = create_pidlock("/var/run/app.pid").acquire()
  214. atexit.register(pidlock.release)
  215. # Run the program
  216. program.run(logfile="/var/log/app.log")
  217. """
  218. if not resource:
  219. raise RuntimeError("This platform does not support detach.")
  220. workdir = os.getcwd() if workdir is None else workdir
  221. signals.reset("SIGCLD") # Make sure SIGCLD is using the default handler.
  222. if not os.geteuid():
  223. # no point trying to setuid unless we're root.
  224. maybe_drop_privileges(uid=uid, gid=gid)
  225. # Since without stderr any errors will be silently suppressed,
  226. # we need to know that we have access to the logfile.
  227. logfile and open(logfile, "a").close()
  228. # Doesn't actually create the pidfile, but makes sure it's not stale.
  229. pidfile and create_pidlock(pidfile)
  230. return DaemonContext(umask=umask, workdir=workdir)
  231. def parse_uid(uid):
  232. """Parse user id.
  233. uid can be an integer (uid) or a string (user name), if a user name
  234. the uid is taken from the password file.
  235. """
  236. try:
  237. return int(uid)
  238. except ValueError:
  239. if pwd:
  240. try:
  241. return pwd.getpwnam(uid).pw_uid
  242. except KeyError:
  243. raise KeyError("User does not exist: %r" % (uid, ))
  244. raise
  245. def parse_gid(gid):
  246. """Parse group id.
  247. gid can be an integer (gid) or a string (group name), if a group name
  248. the gid is taken from the password file.
  249. """
  250. try:
  251. return int(gid)
  252. except ValueError:
  253. if grp:
  254. try:
  255. return grp.getgrnam(gid).gr_gid
  256. except KeyError:
  257. raise KeyError("Group does not exist: %r" % (gid, ))
  258. raise
  259. def _setgroups_hack(groups):
  260. """:fun:`setgroups` may have a platform-dependent limit,
  261. and it is not always possible to know in advance what this limit
  262. is, so we use this ugly hack stolen from glibc."""
  263. groups = groups[:]
  264. while 1:
  265. try:
  266. return os.setgroups(groups)
  267. except ValueError: # error from Python's check.
  268. if len(groups) <= 1:
  269. raise
  270. groups[:] = groups[:-1]
  271. except OSError, exc: # error from the OS.
  272. if exc.errno != errno.EINVAL or len(groups) <= 1:
  273. raise
  274. groups[:] = groups[:-1]
  275. def setgroups(groups):
  276. max_groups = None
  277. try:
  278. max_groups = os.sysconf("SC_NGROUPS_MAX")
  279. except:
  280. pass
  281. try:
  282. return _setgroups_hack(groups[:max_groups])
  283. except OSError, exc:
  284. if exc.errno != errno.EPERM:
  285. raise
  286. if any(group not in groups for group in os.getgroups()):
  287. # we shouldn't be allowed to change to this group.
  288. raise
  289. def initgroups(uid, gid):
  290. if grp and pwd:
  291. username = pwd.getpwuid(uid)[0]
  292. if hasattr(os, "initgroups"): # Python 2.7+
  293. return os.initgroups(username, gid)
  294. groups = [gr.gr_gid for gr in grp.getgrall()
  295. if username in gr.gr_mem]
  296. setgroups(groups)
  297. def setegid(gid):
  298. """Set effective group id."""
  299. gid = parse_gid(gid)
  300. if gid != os.getegid():
  301. os.setegid(gid)
  302. def seteuid(uid):
  303. """Set effective user id."""
  304. uid = parse_uid(uid)
  305. if uid != os.geteuid():
  306. os.seteuid(uid)
  307. def setgid(gid):
  308. os.setgid(parse_gid(gid))
  309. def setuid(uid):
  310. os.setuid(parse_uid(uid))
  311. def maybe_drop_privileges(uid=None, gid=None):
  312. """Change process privileges to new user/group.
  313. If UID and GID is specified, the real user/group is changed.
  314. If only UID is specified, the real user is changed, and the group is
  315. changed to the users primary group.
  316. If only GID is specified, only the group is changed.
  317. """
  318. uid = uid and parse_uid(uid)
  319. gid = gid and parse_gid(gid)
  320. if uid:
  321. # If GID isn't defined, get the primary GID of the user.
  322. if not gid and pwd:
  323. gid = pwd.getpwuid(uid).pw_gid
  324. # Must set the GID before initgroups(), as setgid()
  325. # is known to zap the group list on some platforms.
  326. setgid(gid)
  327. initgroups(uid, gid)
  328. # at last:
  329. setuid(uid)
  330. else:
  331. gid and setgid(gid)
  332. class Signals(object):
  333. """Convenience interface to :mod:`signals`.
  334. If the requested signal is not supported on the current platform,
  335. the operation will be ignored.
  336. **Examples**:
  337. .. code-block:: python
  338. >>> from celery.platforms import signals
  339. >>> signals["INT"] = my_handler
  340. >>> signals["INT"]
  341. my_handler
  342. >>> signals.supported("INT")
  343. True
  344. >>> signals.signum("INT")
  345. 2
  346. >>> signals.ignore("USR1")
  347. >>> signals["USR1"] == signals.ignored
  348. True
  349. >>> signals.reset("USR1")
  350. >>> signals["USR1"] == signals.default
  351. True
  352. >>> signals.update(INT=exit_handler,
  353. ... TERM=exit_handler,
  354. ... HUP=hup_handler)
  355. """
  356. ignored = _signal.SIG_IGN
  357. default = _signal.SIG_DFL
  358. def supported(self, signal_name):
  359. """Returns true value if ``signal_name`` exists on this platform."""
  360. try:
  361. return self.signum(signal_name)
  362. except AttributeError:
  363. pass
  364. def signum(self, signal_name):
  365. """Get signal number from signal name."""
  366. if isinstance(signal_name, int):
  367. return signal_name
  368. if not isinstance(signal_name, basestring) \
  369. or not signal_name.isupper():
  370. raise TypeError("signal name must be uppercase string.")
  371. if not signal_name.startswith("SIG"):
  372. signal_name = "SIG" + signal_name
  373. return getattr(_signal, signal_name)
  374. def reset(self, *signal_names):
  375. """Reset signals to the default signal handler.
  376. Does nothing if the platform doesn't support signals,
  377. or the specified signal in particular.
  378. """
  379. self.update((sig, self.default) for sig in signal_names)
  380. def ignore(self, *signal_names):
  381. """Ignore signal using :const:`SIG_IGN`.
  382. Does nothing if the platform doesn't support signals,
  383. or the specified signal in particular.
  384. """
  385. self.update((sig, self.ignored) for sig in signal_names)
  386. def __getitem__(self, signal_name):
  387. return _signal.getsignal(self.signum(signal_name))
  388. def __setitem__(self, signal_name, handler):
  389. """Install signal handler.
  390. Does nothing if the current platform doesn't support signals,
  391. or the specified signal in particular.
  392. """
  393. try:
  394. _signal.signal(self.signum(signal_name), handler)
  395. except (AttributeError, ValueError):
  396. pass
  397. def update(self, _d_=None, **sigmap):
  398. """Set signal handlers from a mapping."""
  399. for signal_name, handler in dict(_d_ or {}, **sigmap).iteritems():
  400. self[signal_name] = handler
  401. signals = Signals()
  402. get_signal = signals.signum # compat
  403. install_signal_handler = signals.__setitem__ # compat
  404. reset_signal = signals.reset # compat
  405. ignore_signal = signals.ignore # compat
  406. def strargv(argv):
  407. arg_start = 2 if "manage" in argv[0] else 1
  408. if len(argv) > arg_start:
  409. return " ".join(argv[arg_start:])
  410. return ""
  411. def set_process_title(progname, info=None):
  412. """Set the ps name for the currently running process.
  413. Only works if :mod:`setproctitle` is installed.
  414. """
  415. proctitle = "[%s]" % progname
  416. proctitle = "%s %s" % (proctitle, info) if info else proctitle
  417. if _setproctitle:
  418. _setproctitle.setproctitle(proctitle)
  419. return proctitle
  420. def set_mp_process_title(progname, info=None, hostname=None):
  421. """Set the ps name using the multiprocessing process name.
  422. Only works if :mod:`setproctitle` is installed.
  423. """
  424. if hostname:
  425. progname = "%s@%s" % (progname, hostname.split(".")[0])
  426. try:
  427. from multiprocessing.process import current_process
  428. except ImportError:
  429. return set_process_title(progname, info=info)
  430. else:
  431. return set_process_title("%s:%s" % (progname,
  432. current_process().name), info=info)
  433. def shellsplit(s, posix=True):
  434. # posix= option to shlex.split first available in Python 2.6+
  435. lexer = shlex.shlex(s, posix=not IS_WINDOWS)
  436. lexer.whitespace_split = True
  437. lexer.commenters = ''
  438. return list(lexer)