platforms.py 19 KB

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