platforms.py 16 KB

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