platforms.py 17 KB

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