platforms.py 19 KB

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