platforms.py 20 KB

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