platforms.py 16 KB

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