platforms.py 20 KB

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