platforms.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681
  1. # -*- coding: utf-8 -*-
  2. """
  3. celery.platforms
  4. ~~~~~~~~~~~~~~~~
  5. Utilities dealing with platform specifics: signals, daemonization,
  6. users, groups, and so on.
  7. """
  8. from __future__ import absolute_import
  9. from __future__ import with_statement
  10. import atexit
  11. import errno
  12. import os
  13. import platform as _platform
  14. import shlex
  15. import signal as _signal
  16. import sys
  17. from billiard import current_process
  18. from contextlib import contextmanager
  19. from .local import try_import
  20. _setproctitle = try_import('setproctitle')
  21. resource = try_import('resource')
  22. pwd = try_import('pwd')
  23. grp = try_import('grp')
  24. # exitcodes
  25. EX_OK = getattr(os, 'EX_OK', 0)
  26. EX_FAILURE = 1
  27. EX_UNAVAILABLE = getattr(os, 'EX_UNAVAILABLE', 69)
  28. EX_USAGE = getattr(os, 'EX_USAGE', 64)
  29. SYSTEM = _platform.system()
  30. IS_OSX = SYSTEM == 'Darwin'
  31. IS_WINDOWS = SYSTEM == 'Windows'
  32. DAEMON_UMASK = 0
  33. DAEMON_WORKDIR = '/'
  34. PIDFILE_FLAGS = os.O_CREAT | os.O_EXCL | os.O_WRONLY
  35. PIDFILE_MODE = ((os.R_OK | os.W_OK) << 6) | ((os.R_OK) << 3) | ((os.R_OK))
  36. PIDLOCKED = """ERROR: Pidfile (%s) already exists.
  37. Seems we're already running? (pid: %s)"""
  38. def pyimplementation():
  39. """Returns string identifying the current Python implementation."""
  40. if hasattr(_platform, 'python_implementation'):
  41. return _platform.python_implementation()
  42. elif sys.platform.startswith('java'):
  43. return 'Jython ' + sys.platform
  44. elif hasattr(sys, 'pypy_version_info'):
  45. v = '.'.join(map(str, sys.pypy_version_info[:3]))
  46. if sys.pypy_version_info[3:]:
  47. v += '-' + ''.join(map(str, sys.pypy_version_info[3:]))
  48. return 'PyPy ' + v
  49. else:
  50. return 'CPython'
  51. def _find_option_with_arg(argv, short_opts=None, long_opts=None):
  52. """Search argv for option specifying its short and longopt
  53. alternatives.
  54. Returns the value of the option if found.
  55. """
  56. for i, arg in enumerate(argv):
  57. if arg.startswith('-'):
  58. if long_opts and arg.startswith('--'):
  59. name, _, val = arg.partition('=')
  60. if name in long_opts:
  61. return val
  62. if short_opts and arg in short_opts:
  63. return argv[i + 1]
  64. raise KeyError('|'.join(short_opts or [] + long_opts or []))
  65. def maybe_patch_concurrency(argv, short_opts=None, long_opts=None):
  66. """With short and long opt alternatives that specify the command line
  67. option to set the pool, this makes sure that anything that needs
  68. to be patched is completed as early as possible.
  69. (e.g. eventlet/gevent monkey patches)."""
  70. try:
  71. pool = _find_option_with_arg(argv, short_opts, long_opts)
  72. except KeyError:
  73. pass
  74. else:
  75. # set up eventlet/gevent environments ASAP.
  76. from celery import concurrency
  77. concurrency.get_implementation(pool)
  78. class LockFailed(Exception):
  79. """Raised if a pidlock can't be acquired."""
  80. def get_fdmax(default=None):
  81. """Returns the maximum number of open file descriptors
  82. on this system.
  83. :keyword default: Value returned if there's no file
  84. descriptor limit.
  85. """
  86. fdmax = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
  87. if fdmax == resource.RLIM_INFINITY:
  88. return default
  89. return fdmax
  90. class Pidfile(object):
  91. """Pidfile
  92. This is the type returned by :func:`create_pidlock`.
  93. TIP: Use the :func:`create_pidlock` function instead,
  94. which is more convenient and also removes stale pidfiles (when
  95. the process holding the lock is no longer running).
  96. """
  97. #: Path to the pid lock file.
  98. path = None
  99. def __init__(self, path):
  100. self.path = os.path.abspath(path)
  101. def acquire(self):
  102. """Acquire lock."""
  103. try:
  104. self.write_pid()
  105. except OSError, exc:
  106. raise LockFailed, LockFailed(str(exc)), sys.exc_info()[2]
  107. return self
  108. __enter__ = acquire
  109. def is_locked(self):
  110. """Returns true if the pid lock exists."""
  111. return os.path.exists(self.path)
  112. def release(self, *args):
  113. """Release lock."""
  114. self.remove()
  115. __exit__ = release
  116. def read_pid(self):
  117. """Reads and returns the current pid."""
  118. with ignore_errno('ENOENT'):
  119. with open(self.path, 'r') as fh:
  120. line = fh.readline()
  121. if line.strip() == line: # must contain '\n'
  122. raise ValueError(
  123. 'Partially written or invalid pidfile %r' % self.path)
  124. try:
  125. return int(line.strip())
  126. except ValueError:
  127. raise ValueError(
  128. 'pidfile %r contents invalid.' % self.path)
  129. def remove(self):
  130. """Removes the lock."""
  131. with ignore_errno(errno.ENOENT, errno.EACCES):
  132. os.unlink(self.path)
  133. def remove_if_stale(self):
  134. """Removes the lock if the process is not running.
  135. (does not respond to signals)."""
  136. try:
  137. pid = self.read_pid()
  138. except ValueError, exc:
  139. sys.stderr.write('Broken pidfile found. Removing it.\n')
  140. self.remove()
  141. return True
  142. if not pid:
  143. self.remove()
  144. return True
  145. try:
  146. os.kill(pid, 0)
  147. except os.error, exc:
  148. if exc.errno == errno.ESRCH:
  149. sys.stderr.write('Stale pidfile exists. Removing it.\n')
  150. self.remove()
  151. return True
  152. return False
  153. def write_pid(self):
  154. pid = os.getpid()
  155. content = '%d\n' % (pid, )
  156. pidfile_fd = os.open(self.path, PIDFILE_FLAGS, PIDFILE_MODE)
  157. pidfile = os.fdopen(pidfile_fd, 'w')
  158. try:
  159. pidfile.write(content)
  160. # flush and sync so that the re-read below works.
  161. pidfile.flush()
  162. try:
  163. os.fsync(pidfile_fd)
  164. except AttributeError: # pragma: no cover
  165. pass
  166. finally:
  167. pidfile.close()
  168. rfh = open(self.path)
  169. try:
  170. if rfh.read() != content:
  171. raise LockFailed(
  172. "Inconsistency: Pidfile content doesn't match at re-read")
  173. finally:
  174. rfh.close()
  175. PIDFile = Pidfile # compat alias
  176. def create_pidlock(pidfile):
  177. """Create and verify pidfile.
  178. If the pidfile already exists the program exits with an error message,
  179. however if the process it refers to is not running anymore, the pidfile
  180. is deleted and the program continues.
  181. This function will automatically install an :mod:`atexit` handler
  182. to release the lock at exit, you can skip this by calling
  183. :func:`_create_pidlock` instead.
  184. :returns: :class:`Pidfile`.
  185. **Example**:
  186. .. code-block:: python
  187. pidlock = create_pidlock('/var/run/app.pid')
  188. """
  189. pidlock = _create_pidlock(pidfile)
  190. atexit.register(pidlock.release)
  191. return pidlock
  192. def _create_pidlock(pidfile):
  193. pidlock = Pidfile(pidfile)
  194. if pidlock.is_locked() and not pidlock.remove_if_stale():
  195. raise SystemExit(PIDLOCKED % (pidfile, pidlock.read_pid()))
  196. pidlock.acquire()
  197. return pidlock
  198. def fileno(f):
  199. """Get object fileno, or :const:`None` if not defined."""
  200. try:
  201. return f.fileno()
  202. except AttributeError:
  203. pass
  204. class DaemonContext(object):
  205. _is_open = False
  206. def __init__(self, pidfile=None, workdir=None, umask=None,
  207. fake=False, after_chdir=None, **kwargs):
  208. self.workdir = workdir or DAEMON_WORKDIR
  209. self.umask = DAEMON_UMASK if umask is None else umask
  210. self.fake = fake
  211. self.after_chdir = after_chdir
  212. self.stdfds = (sys.stdin, sys.stdout, sys.stderr)
  213. def redirect_to_null(self, fd):
  214. if fd:
  215. dest = os.open(os.devnull, os.O_RDWR)
  216. os.dup2(dest, fd)
  217. def open(self):
  218. if not self._is_open:
  219. if not self.fake:
  220. self._detach()
  221. os.chdir(self.workdir)
  222. os.umask(self.umask)
  223. if self.after_chdir:
  224. self.after_chdir()
  225. preserve = [fileno(f) for f in self.stdfds if fileno(f)]
  226. for fd in reversed(range(get_fdmax(default=2048))):
  227. if fd not in preserve:
  228. with ignore_errno(errno.EBADF):
  229. os.close(fd)
  230. for fd in self.stdfds:
  231. self.redirect_to_null(fileno(fd))
  232. self._is_open = True
  233. __enter__ = open
  234. def close(self, *args):
  235. if self._is_open:
  236. self._is_open = False
  237. __exit__ = close
  238. def _detach(self):
  239. if os.fork() == 0: # first child
  240. os.setsid() # create new session
  241. if os.fork() > 0: # second child
  242. os._exit(0)
  243. else:
  244. os._exit(0)
  245. return self
  246. def detached(logfile=None, pidfile=None, uid=None, gid=None, umask=0,
  247. workdir=None, fake=False, **opts):
  248. """Detach the current process in the background (daemonize).
  249. :keyword logfile: Optional log file. The ability to write to this file
  250. will be verified before the process is detached.
  251. :keyword pidfile: Optional pidfile. The pidfile will not be created,
  252. as this is the responsibility of the child. But the process will
  253. exit if the pid lock exists and the pid written is still running.
  254. :keyword uid: Optional user id or user name to change
  255. effective privileges to.
  256. :keyword gid: Optional group id or group name to change effective
  257. privileges to.
  258. :keyword umask: Optional umask that will be effective in the child process.
  259. :keyword workdir: Optional new working directory.
  260. :keyword fake: Don't actually detach, intented for debugging purposes.
  261. :keyword \*\*opts: Ignored.
  262. **Example**:
  263. .. code-block:: python
  264. from celery.platforms import detached, create_pidlock
  265. with detached(logfile='/var/log/app.log', pidfile='/var/run/app.pid',
  266. uid='nobody'):
  267. # Now in detached child process with effective user set to nobody,
  268. # and we know that our logfile can be written to, and that
  269. # the pidfile is not locked.
  270. pidlock = create_pidlock('/var/run/app.pid')
  271. # Run the program
  272. program.run(logfile='/var/log/app.log')
  273. """
  274. if not resource:
  275. raise RuntimeError('This platform does not support detach.')
  276. workdir = os.getcwd() if workdir is None else workdir
  277. signals.reset('SIGCLD') # Make sure SIGCLD is using the default handler.
  278. if not os.geteuid():
  279. # no point trying to setuid unless we're root.
  280. maybe_drop_privileges(uid=uid, gid=gid)
  281. def after_chdir_do():
  282. # Since without stderr any errors will be silently suppressed,
  283. # we need to know that we have access to the logfile.
  284. logfile and open(logfile, 'a').close()
  285. # Doesn't actually create the pidfile, but makes sure it's not stale.
  286. if pidfile:
  287. _create_pidlock(pidfile).release()
  288. return DaemonContext(
  289. umask=umask, workdir=workdir, fake=fake, after_chdir=after_chdir_do,
  290. )
  291. def parse_uid(uid):
  292. """Parse user id.
  293. uid can be an integer (uid) or a string (user name), if a user name
  294. the uid is taken from the password file.
  295. """
  296. try:
  297. return int(uid)
  298. except ValueError:
  299. try:
  300. return pwd.getpwnam(uid).pw_uid
  301. except (AttributeError, KeyError):
  302. raise KeyError('User does not exist: %r' % (uid, ))
  303. def parse_gid(gid):
  304. """Parse group id.
  305. gid can be an integer (gid) or a string (group name), if a group name
  306. the gid is taken from the password file.
  307. """
  308. try:
  309. return int(gid)
  310. except ValueError:
  311. try:
  312. return grp.getgrnam(gid).gr_gid
  313. except (AttributeError, KeyError):
  314. raise KeyError('Group does not exist: %r' % (gid, ))
  315. def _setgroups_hack(groups):
  316. """:fun:`setgroups` may have a platform-dependent limit,
  317. and it is not always possible to know in advance what this limit
  318. is, so we use this ugly hack stolen from glibc."""
  319. groups = groups[:]
  320. while 1:
  321. try:
  322. return os.setgroups(groups)
  323. except ValueError: # error from Python's check.
  324. if len(groups) <= 1:
  325. raise
  326. groups[:] = groups[:-1]
  327. except OSError, exc: # error from the OS.
  328. if exc.errno != errno.EINVAL or len(groups) <= 1:
  329. raise
  330. groups[:] = groups[:-1]
  331. def setgroups(groups):
  332. """Set active groups from a list of group ids."""
  333. max_groups = None
  334. try:
  335. max_groups = os.sysconf('SC_NGROUPS_MAX')
  336. except Exception:
  337. pass
  338. try:
  339. return _setgroups_hack(groups[:max_groups])
  340. except OSError, exc:
  341. if exc.errno != errno.EPERM:
  342. raise
  343. if any(group not in groups for group in os.getgroups()):
  344. # we shouldn't be allowed to change to this group.
  345. raise
  346. def initgroups(uid, gid):
  347. """Compat version of :func:`os.initgroups` which was first
  348. added to Python 2.7."""
  349. if not pwd: # pragma: no cover
  350. return
  351. username = pwd.getpwuid(uid)[0]
  352. if hasattr(os, 'initgroups'): # Python 2.7+
  353. return os.initgroups(username, gid)
  354. groups = [gr.gr_gid for gr in grp.getgrall()
  355. if username in gr.gr_mem]
  356. setgroups(groups)
  357. def setgid(gid):
  358. """Version of :func:`os.setgid` supporting group names."""
  359. os.setgid(parse_gid(gid))
  360. def setuid(uid):
  361. """Version of :func:`os.setuid` supporting usernames."""
  362. os.setuid(parse_uid(uid))
  363. def maybe_drop_privileges(uid=None, gid=None):
  364. """Change process privileges to new user/group.
  365. If UID and GID is specified, the real user/group is changed.
  366. If only UID is specified, the real user is changed, and the group is
  367. changed to the users primary group.
  368. If only GID is specified, only the group is changed.
  369. """
  370. uid = uid and parse_uid(uid)
  371. gid = gid and parse_gid(gid)
  372. if uid:
  373. # If GID isn't defined, get the primary GID of the user.
  374. if not gid and pwd:
  375. gid = pwd.getpwuid(uid).pw_gid
  376. # Must set the GID before initgroups(), as setgid()
  377. # is known to zap the group list on some platforms.
  378. setgid(gid)
  379. initgroups(uid, gid)
  380. # at last:
  381. setuid(uid)
  382. else:
  383. gid and setgid(gid)
  384. class Signals(object):
  385. """Convenience interface to :mod:`signals`.
  386. If the requested signal is not supported on the current platform,
  387. the operation will be ignored.
  388. **Examples**:
  389. .. code-block:: python
  390. >>> from celery.platforms import signals
  391. >>> signals['INT'] = my_handler
  392. >>> signals['INT']
  393. my_handler
  394. >>> signals.supported('INT')
  395. True
  396. >>> signals.signum('INT')
  397. 2
  398. >>> signals.ignore('USR1')
  399. >>> signals['USR1'] == signals.ignored
  400. True
  401. >>> signals.reset('USR1')
  402. >>> signals['USR1'] == signals.default
  403. True
  404. >>> signals.update(INT=exit_handler,
  405. ... TERM=exit_handler,
  406. ... HUP=hup_handler)
  407. """
  408. ignored = _signal.SIG_IGN
  409. default = _signal.SIG_DFL
  410. def supported(self, signal_name):
  411. """Returns true value if ``signal_name`` exists on this platform."""
  412. try:
  413. return self.signum(signal_name)
  414. except AttributeError:
  415. pass
  416. def signum(self, signal_name):
  417. """Get signal number from signal name."""
  418. if isinstance(signal_name, int):
  419. return signal_name
  420. if not isinstance(signal_name, basestring) \
  421. or not signal_name.isupper():
  422. raise TypeError('signal name must be uppercase string.')
  423. if not signal_name.startswith('SIG'):
  424. signal_name = 'SIG' + signal_name
  425. return getattr(_signal, signal_name)
  426. def reset(self, *signal_names):
  427. """Reset signals to the default signal handler.
  428. Does nothing if the platform doesn't support signals,
  429. or the specified signal in particular.
  430. """
  431. self.update((sig, self.default) for sig in signal_names)
  432. def ignore(self, *signal_names):
  433. """Ignore signal using :const:`SIG_IGN`.
  434. Does nothing if the platform doesn't support signals,
  435. or the specified signal in particular.
  436. """
  437. self.update((sig, self.ignored) for sig in signal_names)
  438. def __getitem__(self, signal_name):
  439. return _signal.getsignal(self.signum(signal_name))
  440. def __setitem__(self, signal_name, handler):
  441. """Install signal handler.
  442. Does nothing if the current platform doesn't support signals,
  443. or the specified signal in particular.
  444. """
  445. try:
  446. _signal.signal(self.signum(signal_name), handler)
  447. except (AttributeError, ValueError):
  448. pass
  449. def update(self, _d_=None, **sigmap):
  450. """Set signal handlers from a mapping."""
  451. for signal_name, handler in dict(_d_ or {}, **sigmap).iteritems():
  452. self[signal_name] = handler
  453. signals = Signals()
  454. get_signal = signals.signum # compat
  455. install_signal_handler = signals.__setitem__ # compat
  456. reset_signal = signals.reset # compat
  457. ignore_signal = signals.ignore # compat
  458. def strargv(argv):
  459. arg_start = 2 if 'manage' in argv[0] else 1
  460. if len(argv) > arg_start:
  461. return ' '.join(argv[arg_start:])
  462. return ''
  463. def set_process_title(progname, info=None):
  464. """Set the ps name for the currently running process.
  465. Only works if :mod:`setproctitle` is installed.
  466. """
  467. proctitle = '[%s]' % progname
  468. proctitle = '%s %s' % (proctitle, info) if info else proctitle
  469. if _setproctitle:
  470. _setproctitle.setproctitle(proctitle)
  471. return proctitle
  472. if os.environ.get('NOSETPS'): # pragma: no cover
  473. def set_mp_process_title(*a, **k):
  474. pass
  475. else:
  476. def set_mp_process_title(progname, info=None, hostname=None): # noqa
  477. """Set the ps name using the multiprocessing process name.
  478. Only works if :mod:`setproctitle` is installed.
  479. """
  480. if hostname:
  481. progname = '%s@%s' % (progname, hostname.split('.')[0])
  482. return set_process_title(
  483. '%s:%s' % (progname, current_process().name), info=info)
  484. def shellsplit(s):
  485. """Compat. version of :func:`shlex.split` that supports
  486. the ``posix`` option which was first added in Python 2.6.
  487. Posix behavior will be disabled if running under Windows.
  488. """
  489. lexer = shlex.shlex(s, posix=not IS_WINDOWS)
  490. lexer.whitespace_split = True
  491. lexer.commenters = ''
  492. return list(lexer)
  493. def get_errno(n):
  494. """Get errno for string, e.g. ``ENOENT``."""
  495. if isinstance(n, basestring):
  496. return getattr(errno, n)
  497. return n
  498. @contextmanager
  499. def ignore_errno(*errnos, **kwargs):
  500. """Context manager to ignore specific POSIX error codes.
  501. Takes a list of error codes to ignore, which can be either
  502. the name of the code, or the code integer itself::
  503. >>> with ignore_errno('ENOENT'):
  504. ... with open('foo', 'r'):
  505. ... return r.read()
  506. >>> with ignore_errno(errno.ENOENT, errno.EPERM):
  507. ... pass
  508. :keyword types: A tuple of exceptions to ignore (when the errno matches),
  509. defaults to :exc:`Exception`.
  510. """
  511. types = kwargs.get('types') or (Exception, )
  512. errnos = [get_errno(errno) for errno in errnos]
  513. try:
  514. yield
  515. except types, exc:
  516. if not hasattr(exc, 'errno'):
  517. raise
  518. if exc.errno not in errnos:
  519. raise