platforms.py 20 KB

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