platforms.py 17 KB

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