platforms.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  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 contextlib import contextmanager
  18. from .local import try_import
  19. from billiard import current_process
  20. from kombu.utils.limits import TokenBucket
  21. _setproctitle = try_import('setproctitle')
  22. resource = try_import('resource')
  23. pwd = try_import('pwd')
  24. grp = try_import('grp')
  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. DAEMON_REDIRECT_TO = getattr(os, 'devnull', '/dev/null')
  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. _setps_bucket = TokenBucket(0.5) # 30/m, every 2 seconds
  38. PIDLOCKED = """ERROR: Pidfile (%s) already exists.
  39. Seems we're already running? (PID: %s)"""
  40. def pyimplementation():
  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. class LockFailed(Exception):
  53. """Raised if a pidlock can't be acquired."""
  54. pass
  55. def get_fdmax(default=None):
  56. """Returns the maximum number of open file descriptors
  57. on this system.
  58. :keyword default: Value returned if there's no file
  59. descriptor limit.
  60. """
  61. fdmax = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
  62. if fdmax == resource.RLIM_INFINITY:
  63. return default
  64. return fdmax
  65. class PIDFile(object):
  66. """PID lock file.
  67. This is the type returned by :func:`create_pidlock`.
  68. **Should not be used directly, use the :func:`create_pidlock`
  69. context instead**
  70. """
  71. #: Path to the pid lock file.
  72. path = None
  73. def __init__(self, path):
  74. self.path = os.path.abspath(path)
  75. def acquire(self):
  76. """Acquire lock."""
  77. try:
  78. self.write_pid()
  79. except OSError, exc:
  80. raise LockFailed, LockFailed(str(exc)), sys.exc_info()[2]
  81. return self
  82. __enter__ = acquire
  83. def is_locked(self):
  84. """Returns true if the pid lock exists."""
  85. return os.path.exists(self.path)
  86. def release(self, *args):
  87. """Release lock."""
  88. self.remove()
  89. __exit__ = release
  90. def read_pid(self):
  91. """Reads and returns the current pid."""
  92. try:
  93. fh = open(self.path, 'r')
  94. except IOError, exc:
  95. if exc.errno == errno.ENOENT:
  96. return
  97. raise
  98. try:
  99. line = fh.readline()
  100. if line.strip() == line: # must contain '\n'
  101. raise ValueError(
  102. 'Partially written or invalid pidfile %r' % (self.path))
  103. finally:
  104. fh.close()
  105. try:
  106. return int(line.strip())
  107. except ValueError:
  108. raise ValueError('PID file %r contents invalid.' % self.path)
  109. def remove(self):
  110. """Removes the lock."""
  111. try:
  112. os.unlink(self.path)
  113. except OSError, exc:
  114. if exc.errno in (errno.ENOENT, errno.EACCES):
  115. return
  116. raise
  117. def remove_if_stale(self):
  118. """Removes the lock if the process is not running.
  119. (does not respond to signals)."""
  120. try:
  121. pid = self.read_pid()
  122. except ValueError, exc:
  123. sys.stderr.write('Broken pidfile found. Removing it.\n')
  124. self.remove()
  125. return True
  126. if not pid:
  127. self.remove()
  128. return True
  129. try:
  130. os.kill(pid, 0)
  131. except os.error, exc:
  132. if exc.errno == errno.ESRCH:
  133. sys.stderr.write('Stale pidfile exists. Removing it.\n')
  134. self.remove()
  135. return True
  136. return False
  137. def write_pid(self):
  138. pid = os.getpid()
  139. content = '%d\n' % (pid, )
  140. pidfile_fd = os.open(self.path, PIDFILE_FLAGS, PIDFILE_MODE)
  141. pidfile = os.fdopen(pidfile_fd, 'w')
  142. try:
  143. pidfile.write(content)
  144. # flush and sync so that the re-read below works.
  145. pidfile.flush()
  146. try:
  147. os.fsync(pidfile_fd)
  148. except AttributeError: # pragma: no cover
  149. pass
  150. finally:
  151. pidfile.close()
  152. rfh = open(self.path)
  153. try:
  154. if rfh.read() != content:
  155. raise LockFailed(
  156. "Inconsistency: Pidfile content doesn't match at re-read")
  157. finally:
  158. rfh.close()
  159. def create_pidlock(pidfile):
  160. """Create and verify pid file.
  161. If the pid file already exists the program exits with an error message,
  162. however if the process it refers to is not running anymore, the pid file
  163. is deleted and the program continues.
  164. The caller is responsible for releasing the lock before the program
  165. exits.
  166. :returns: :class:`PIDFile`.
  167. **Example**:
  168. .. code-block:: python
  169. pidlock = create_pidlock('/var/run/app.pid')
  170. """
  171. pidlock = PIDFile(pidfile)
  172. if pidlock.is_locked() and not pidlock.remove_if_stale():
  173. raise SystemExit(PIDLOCKED % (pidfile, pidlock.read_pid()))
  174. pidlock.acquire()
  175. atexit.register(pidlock.release)
  176. return pidlock
  177. class DaemonContext(object):
  178. _is_open = False
  179. workdir = DAEMON_WORKDIR
  180. umask = DAEMON_UMASK
  181. def __init__(self, pidfile=None, workdir=None, umask=None,
  182. fake=False, **kwargs):
  183. self.workdir = workdir or self.workdir
  184. self.umask = self.umask if umask is None else umask
  185. self.fake = fake
  186. def open(self):
  187. if not self._is_open:
  188. if not self.fake:
  189. self._detach()
  190. os.chdir(self.workdir)
  191. os.umask(self.umask)
  192. for fd in reversed(range(get_fdmax(default=2048))):
  193. with ignore_EBADF():
  194. os.close(fd)
  195. os.open(DAEMON_REDIRECT_TO, os.O_RDWR)
  196. os.dup2(0, 1)
  197. os.dup2(0, 2)
  198. self._is_open = True
  199. __enter__ = open
  200. def close(self, *args):
  201. if self._is_open:
  202. self._is_open = False
  203. __exit__ = close
  204. def _detach(self):
  205. if os.fork() == 0: # first child
  206. os.setsid() # create new session
  207. if os.fork() > 0: # second child
  208. os._exit(0)
  209. else:
  210. os._exit(0)
  211. return self
  212. def detached(logfile=None, pidfile=None, uid=None, gid=None, umask=0,
  213. workdir=None, fake=False, **opts):
  214. """Detach the current process in the background (daemonize).
  215. :keyword logfile: Optional log file. The ability to write to this file
  216. will be verified before the process is detached.
  217. :keyword pidfile: Optional pid file. The pid file will not be created,
  218. as this is the responsibility of the child. But the process will
  219. exit if the pid lock exists and the pid written is still running.
  220. :keyword uid: Optional user id or user name to change
  221. effective privileges to.
  222. :keyword gid: Optional group id or group name to change effective
  223. privileges to.
  224. :keyword umask: Optional umask that will be effective in the child process.
  225. :keyword workdir: Optional new working directory.
  226. :keyword fake: Don't actually detach, intented for debugging purposes.
  227. :keyword \*\*opts: Ignored.
  228. **Example**:
  229. .. code-block:: python
  230. import atexit
  231. from celery.platforms import detached, create_pidlock
  232. with detached(logfile='/var/log/app.log', pidfile='/var/run/app.pid',
  233. uid='nobody'):
  234. # Now in detached child process with effective user set to nobody,
  235. # and we know that our logfile can be written to, and that
  236. # the pidfile is not locked.
  237. pidlock = create_pidlock('/var/run/app.pid').acquire()
  238. atexit.register(pidlock.release)
  239. # Run the program
  240. program.run(logfile='/var/log/app.log')
  241. """
  242. if not resource:
  243. raise RuntimeError('This platform does not support detach.')
  244. workdir = os.getcwd() if workdir is None else workdir
  245. signals.reset('SIGCLD') # Make sure SIGCLD is using the default handler.
  246. if not os.geteuid():
  247. # no point trying to setuid unless we're root.
  248. maybe_drop_privileges(uid=uid, gid=gid)
  249. # Since without stderr any errors will be silently suppressed,
  250. # we need to know that we have access to the logfile.
  251. logfile and open(logfile, 'a').close()
  252. # Doesn't actually create the pidfile, but makes sure it's not stale.
  253. pidfile and create_pidlock(pidfile)
  254. return DaemonContext(umask=umask, workdir=workdir, fake=fake)
  255. def parse_uid(uid):
  256. """Parse user id.
  257. uid can be an integer (uid) or a string (user name), if a user name
  258. the uid is taken from the password file.
  259. """
  260. try:
  261. return int(uid)
  262. except ValueError:
  263. try:
  264. return pwd.getpwnam(uid).pw_uid
  265. except (AttributeError, KeyError):
  266. raise KeyError('User does not exist: %r' % (uid, ))
  267. def parse_gid(gid):
  268. """Parse group id.
  269. gid can be an integer (gid) or a string (group name), if a group name
  270. the gid is taken from the password file.
  271. """
  272. try:
  273. return int(gid)
  274. except ValueError:
  275. try:
  276. return grp.getgrnam(gid).gr_gid
  277. except (AttributeError, KeyError):
  278. raise KeyError('Group does not exist: %r' % (gid, ))
  279. def _setgroups_hack(groups):
  280. """:fun:`setgroups` may have a platform-dependent limit,
  281. and it is not always possible to know in advance what this limit
  282. is, so we use this ugly hack stolen from glibc."""
  283. groups = groups[:]
  284. while 1:
  285. try:
  286. return os.setgroups(groups)
  287. except ValueError: # error from Python's check.
  288. if len(groups) <= 1:
  289. raise
  290. groups[:] = groups[:-1]
  291. except OSError, exc: # error from the OS.
  292. if exc.errno != errno.EINVAL or len(groups) <= 1:
  293. raise
  294. groups[:] = groups[:-1]
  295. def setgroups(groups):
  296. max_groups = None
  297. try:
  298. max_groups = os.sysconf('SC_NGROUPS_MAX')
  299. except Exception:
  300. pass
  301. try:
  302. return _setgroups_hack(groups[:max_groups])
  303. except OSError, exc:
  304. if exc.errno != errno.EPERM:
  305. raise
  306. if any(group not in groups for group in os.getgroups()):
  307. # we shouldn't be allowed to change to this group.
  308. raise
  309. def initgroups(uid, gid):
  310. if not pwd: # pragma: no cover
  311. return
  312. username = pwd.getpwuid(uid)[0]
  313. if hasattr(os, 'initgroups'): # Python 2.7+
  314. return os.initgroups(username, gid)
  315. groups = [gr.gr_gid for gr in grp.getgrall()
  316. if username in gr.gr_mem]
  317. setgroups(groups)
  318. def setegid(gid):
  319. """Set effective group id."""
  320. gid = parse_gid(gid)
  321. if gid != os.getegid():
  322. os.setegid(gid)
  323. def seteuid(uid):
  324. """Set effective user id."""
  325. uid = parse_uid(uid)
  326. if uid != os.geteuid():
  327. os.seteuid(uid)
  328. def setgid(gid):
  329. os.setgid(parse_gid(gid))
  330. def setuid(uid):
  331. os.setuid(parse_uid(uid))
  332. def maybe_drop_privileges(uid=None, gid=None):
  333. """Change process privileges to new user/group.
  334. If UID and GID is specified, the real user/group is changed.
  335. If only UID is specified, the real user is changed, and the group is
  336. changed to the users primary group.
  337. If only GID is specified, only the group is changed.
  338. """
  339. uid = uid and parse_uid(uid)
  340. gid = gid and parse_gid(gid)
  341. if uid:
  342. # If GID isn't defined, get the primary GID of the user.
  343. if not gid and pwd:
  344. gid = pwd.getpwuid(uid).pw_gid
  345. # Must set the GID before initgroups(), as setgid()
  346. # is known to zap the group list on some platforms.
  347. setgid(gid)
  348. initgroups(uid, gid)
  349. # at last:
  350. setuid(uid)
  351. else:
  352. gid and setgid(gid)
  353. class Signals(object):
  354. """Convenience interface to :mod:`signals`.
  355. If the requested signal is not supported on the current platform,
  356. the operation will be ignored.
  357. **Examples**:
  358. .. code-block:: python
  359. >>> from celery.platforms import signals
  360. >>> signals['INT'] = my_handler
  361. >>> signals['INT']
  362. my_handler
  363. >>> signals.supported('INT')
  364. True
  365. >>> signals.signum('INT')
  366. 2
  367. >>> signals.ignore('USR1')
  368. >>> signals['USR1'] == signals.ignored
  369. True
  370. >>> signals.reset('USR1')
  371. >>> signals['USR1'] == signals.default
  372. True
  373. >>> signals.update(INT=exit_handler,
  374. ... TERM=exit_handler,
  375. ... HUP=hup_handler)
  376. """
  377. ignored = _signal.SIG_IGN
  378. default = _signal.SIG_DFL
  379. def supported(self, signal_name):
  380. """Returns true value if ``signal_name`` exists on this platform."""
  381. try:
  382. return self.signum(signal_name)
  383. except AttributeError:
  384. pass
  385. def signum(self, signal_name):
  386. """Get signal number from signal name."""
  387. if isinstance(signal_name, int):
  388. return signal_name
  389. if not isinstance(signal_name, basestring) \
  390. or not signal_name.isupper():
  391. raise TypeError('signal name must be uppercase string.')
  392. if not signal_name.startswith('SIG'):
  393. signal_name = 'SIG' + signal_name
  394. return getattr(_signal, signal_name)
  395. def reset(self, *signal_names):
  396. """Reset signals to the default signal handler.
  397. Does nothing if the platform doesn't support signals,
  398. or the specified signal in particular.
  399. """
  400. self.update((sig, self.default) for sig in signal_names)
  401. def ignore(self, *signal_names):
  402. """Ignore signal using :const:`SIG_IGN`.
  403. Does nothing if the platform doesn't support signals,
  404. or the specified signal in particular.
  405. """
  406. self.update((sig, self.ignored) for sig in signal_names)
  407. def __getitem__(self, signal_name):
  408. return _signal.getsignal(self.signum(signal_name))
  409. def __setitem__(self, signal_name, handler):
  410. """Install signal handler.
  411. Does nothing if the current platform doesn't support signals,
  412. or the specified signal in particular.
  413. """
  414. try:
  415. _signal.signal(self.signum(signal_name), handler)
  416. except (AttributeError, ValueError):
  417. pass
  418. def update(self, _d_=None, **sigmap):
  419. """Set signal handlers from a mapping."""
  420. for signal_name, handler in dict(_d_ or {}, **sigmap).iteritems():
  421. self[signal_name] = handler
  422. signals = Signals()
  423. get_signal = signals.signum # compat
  424. install_signal_handler = signals.__setitem__ # compat
  425. reset_signal = signals.reset # compat
  426. ignore_signal = signals.ignore # compat
  427. def strargv(argv):
  428. arg_start = 2 if 'manage' in argv[0] else 1
  429. if len(argv) > arg_start:
  430. return ' '.join(argv[arg_start:])
  431. return ''
  432. def set_process_title(progname, info=None):
  433. """Set the ps name for the currently running process.
  434. Only works if :mod:`setproctitle` is installed.
  435. """
  436. proctitle = '[%s]' % progname
  437. proctitle = '%s %s' % (proctitle, info) if info else proctitle
  438. if _setproctitle:
  439. _setproctitle.setproctitle(proctitle)
  440. return proctitle
  441. if os.environ.get('NOSETPS'): # pragma: no cover
  442. def set_mp_process_title(*a, **k):
  443. pass
  444. else:
  445. def set_mp_process_title(progname, info=None, hostname=None, # noqa
  446. rate_limit=False):
  447. """Set the ps name using the multiprocessing process name.
  448. Only works if :mod:`setproctitle` is installed.
  449. """
  450. if not rate_limit or _setps_bucket.can_consume(1):
  451. if hostname:
  452. progname = '%s@%s' % (progname, hostname.split('.')[0])
  453. return set_process_title(
  454. '%s:%s' % (progname, current_process().name), info=info)
  455. def shellsplit(s, posix=True):
  456. # posix= option to shlex.split first available in Python 2.6+
  457. lexer = shlex.shlex(s, posix=not IS_WINDOWS)
  458. lexer.whitespace_split = True
  459. lexer.commenters = ''
  460. return list(lexer)
  461. @contextmanager
  462. def ignore_EBADF():
  463. try:
  464. yield
  465. except OSError, exc:
  466. if exc.errno != errno.EBADF:
  467. raise