threads.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. # -*- coding: utf-8 -*-
  2. """
  3. celery.utils.threads
  4. ~~~~~~~~~~~~~~~~~~~~
  5. Threading utilities.
  6. """
  7. from __future__ import absolute_import, print_function
  8. import os
  9. import socket
  10. import sys
  11. import threading
  12. import traceback
  13. from contextlib import contextmanager
  14. from celery.local import Proxy
  15. from celery.five import THREAD_TIMEOUT_MAX, items
  16. __all__ = ['bgThread', 'Local', 'LocalStack', 'LocalManager',
  17. 'get_ident', 'default_socket_timeout']
  18. USE_FAST_LOCALS = os.environ.get('USE_FAST_LOCALS')
  19. PY3 = sys.version_info[0] == 3
  20. @contextmanager
  21. def default_socket_timeout(timeout):
  22. prev = socket.getdefaulttimeout()
  23. socket.setdefaulttimeout(timeout)
  24. yield
  25. socket.setdefaulttimeout(prev)
  26. class bgThread(threading.Thread):
  27. def __init__(self, name=None, **kwargs):
  28. super(bgThread, self).__init__()
  29. self._is_shutdown = threading.Event()
  30. self._is_stopped = threading.Event()
  31. self.daemon = True
  32. self.name = name or self.__class__.__name__
  33. def body(self):
  34. raise NotImplementedError('subclass responsibility')
  35. def on_crash(self, msg, *fmt, **kwargs):
  36. print(msg.format(*fmt), file=sys.stderr)
  37. exc_info = sys.exc_info()
  38. try:
  39. traceback.print_exception(exc_info[0], exc_info[1], exc_info[2],
  40. None, sys.stderr)
  41. finally:
  42. del(exc_info)
  43. def run(self):
  44. body = self.body
  45. shutdown_set = self._is_shutdown.is_set
  46. try:
  47. while not shutdown_set():
  48. try:
  49. body()
  50. except Exception as exc:
  51. try:
  52. self.on_crash('{0!r} crashed: {1!r}', self.name, exc)
  53. self._set_stopped()
  54. finally:
  55. os._exit(1) # exiting by normal means won't work
  56. finally:
  57. self._set_stopped()
  58. def _set_stopped(self):
  59. try:
  60. self._is_stopped.set()
  61. except TypeError: # pragma: no cover
  62. # we lost the race at interpreter shutdown,
  63. # so gc collected built-in modules.
  64. pass
  65. def stop(self):
  66. """Graceful shutdown."""
  67. self._is_shutdown.set()
  68. self._is_stopped.wait()
  69. if self.is_alive():
  70. self.join(THREAD_TIMEOUT_MAX)
  71. try:
  72. from greenlet import getcurrent as get_ident
  73. except ImportError: # pragma: no cover
  74. try:
  75. from _thread import get_ident # noqa
  76. except ImportError:
  77. try:
  78. from thread import get_ident # noqa
  79. except ImportError: # pragma: no cover
  80. try:
  81. from _dummy_thread import get_ident # noqa
  82. except ImportError:
  83. from dummy_thread import get_ident # noqa
  84. def release_local(local):
  85. """Releases the contents of the local for the current context.
  86. This makes it possible to use locals without a manager.
  87. Example::
  88. >>> loc = Local()
  89. >>> loc.foo = 42
  90. >>> release_local(loc)
  91. >>> hasattr(loc, 'foo')
  92. False
  93. With this function one can release :class:`Local` objects as well
  94. as :class:`StackLocal` objects. However it is not possible to
  95. release data held by proxies that way, one always has to retain
  96. a reference to the underlying local object in order to be able
  97. to release it.
  98. .. versionadded:: 0.6.1
  99. """
  100. local.__release_local__()
  101. class Local(object):
  102. __slots__ = ('__storage__', '__ident_func__')
  103. def __init__(self):
  104. object.__setattr__(self, '__storage__', {})
  105. object.__setattr__(self, '__ident_func__', get_ident)
  106. def __iter__(self):
  107. return iter(items(self.__storage__))
  108. def __call__(self, proxy):
  109. """Create a proxy for a name."""
  110. return Proxy(self, proxy)
  111. def __release_local__(self):
  112. self.__storage__.pop(self.__ident_func__(), None)
  113. def __getattr__(self, name):
  114. try:
  115. return self.__storage__[self.__ident_func__()][name]
  116. except KeyError:
  117. raise AttributeError(name)
  118. def __setattr__(self, name, value):
  119. ident = self.__ident_func__()
  120. storage = self.__storage__
  121. try:
  122. storage[ident][name] = value
  123. except KeyError:
  124. storage[ident] = {name: value}
  125. def __delattr__(self, name):
  126. try:
  127. del self.__storage__[self.__ident_func__()][name]
  128. except KeyError:
  129. raise AttributeError(name)
  130. class _LocalStack(object):
  131. """This class works similar to a :class:`Local` but keeps a stack
  132. of objects instead. This is best explained with an example::
  133. >>> ls = LocalStack()
  134. >>> ls.push(42)
  135. >>> ls.top
  136. 42
  137. >>> ls.push(23)
  138. >>> ls.top
  139. 23
  140. >>> ls.pop()
  141. 23
  142. >>> ls.top
  143. 42
  144. They can be force released by using a :class:`LocalManager` or with
  145. the :func:`release_local` function but the correct way is to pop the
  146. item from the stack after using. When the stack is empty it will
  147. no longer be bound to the current context (and as such released).
  148. By calling the stack without arguments it will return a proxy that
  149. resolves to the topmost item on the stack.
  150. """
  151. def __init__(self):
  152. self._local = Local()
  153. def __release_local__(self):
  154. self._local.__release_local__()
  155. def _get__ident_func__(self):
  156. return self._local.__ident_func__
  157. def _set__ident_func__(self, value):
  158. object.__setattr__(self._local, '__ident_func__', value)
  159. __ident_func__ = property(_get__ident_func__, _set__ident_func__)
  160. del _get__ident_func__, _set__ident_func__
  161. def __call__(self):
  162. def _lookup():
  163. rv = self.top
  164. if rv is None:
  165. raise RuntimeError('object unbound')
  166. return rv
  167. return Proxy(_lookup)
  168. def push(self, obj):
  169. """Pushes a new item to the stack"""
  170. rv = getattr(self._local, 'stack', None)
  171. if rv is None:
  172. self._local.stack = rv = []
  173. rv.append(obj)
  174. return rv
  175. def pop(self):
  176. """Remove the topmost item from the stack, will return the
  177. old value or `None` if the stack was already empty.
  178. """
  179. stack = getattr(self._local, 'stack', None)
  180. if stack is None:
  181. return None
  182. elif len(stack) == 1:
  183. release_local(self._local)
  184. return stack[-1]
  185. else:
  186. return stack.pop()
  187. def __len__(self):
  188. stack = getattr(self._local, 'stack', None)
  189. return len(stack) if stack else 0
  190. @property
  191. def stack(self):
  192. """get_current_worker_task uses this to find
  193. the original task that was executed by the worker."""
  194. stack = getattr(self._local, 'stack', None)
  195. if stack is not None:
  196. return stack
  197. return []
  198. @property
  199. def top(self):
  200. """The topmost item on the stack. If the stack is empty,
  201. `None` is returned.
  202. """
  203. try:
  204. return self._local.stack[-1]
  205. except (AttributeError, IndexError):
  206. return None
  207. class LocalManager(object):
  208. """Local objects cannot manage themselves. For that you need a local
  209. manager. You can pass a local manager multiple locals or add them
  210. later by appending them to `manager.locals`. Everytime the manager
  211. cleans up it, will clean up all the data left in the locals for this
  212. context.
  213. The `ident_func` parameter can be added to override the default ident
  214. function for the wrapped locals.
  215. """
  216. def __init__(self, locals=None, ident_func=None):
  217. if locals is None:
  218. self.locals = []
  219. elif isinstance(locals, Local):
  220. self.locals = [locals]
  221. else:
  222. self.locals = list(locals)
  223. if ident_func is not None:
  224. self.ident_func = ident_func
  225. for local in self.locals:
  226. object.__setattr__(local, '__ident_func__', ident_func)
  227. else:
  228. self.ident_func = get_ident
  229. def get_ident(self):
  230. """Return the context identifier the local objects use internally
  231. for this context. You cannot override this method to change the
  232. behavior but use it to link other context local objects (such as
  233. SQLAlchemy's scoped sessions) to the Werkzeug locals."""
  234. return self.ident_func()
  235. def cleanup(self):
  236. """Manually clean up the data in the locals for this context.
  237. Call this at the end of the request or use `make_middleware()`.
  238. """
  239. for local in self.locals:
  240. release_local(local)
  241. def __repr__(self):
  242. return '<{0} storages: {1}>'.format(
  243. self.__class__.__name__, len(self.locals))
  244. class _FastLocalStack(threading.local):
  245. def __init__(self):
  246. self.stack = []
  247. self.push = self.stack.append
  248. self.pop = self.stack.pop
  249. @property
  250. def top(self):
  251. try:
  252. return self.stack[-1]
  253. except (AttributeError, IndexError):
  254. return None
  255. def __len__(self):
  256. return len(self.stack)
  257. if USE_FAST_LOCALS: # pragma: no cover
  258. LocalStack = _FastLocalStack
  259. else:
  260. # - See #706
  261. # since each thread has its own greenlet we can just use those as
  262. # identifiers for the context. If greenlets are not available we
  263. # fall back to the current thread ident.
  264. LocalStack = _LocalStack # noqa