platforms.py 19 KB

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