__init__.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. # -*- coding: utf-8 -*-
  2. """
  3. celery.utils
  4. ~~~~~~~~~~~~
  5. Utility functions.
  6. """
  7. from __future__ import absolute_import, print_function
  8. import os
  9. import sys
  10. import traceback
  11. import warnings
  12. import datetime
  13. from functools import partial, wraps
  14. from inspect import getargspec
  15. from pprint import pprint
  16. from kombu.entity import Exchange, Queue
  17. from celery.exceptions import CPendingDeprecationWarning, CDeprecationWarning
  18. from celery.five import StringIO, items, reraise, string_t
  19. __all__ = ['worker_direct', 'warn_deprecated', 'deprecated', 'lpmerge',
  20. 'is_iterable', 'isatty', 'cry', 'maybe_reraise', 'strtobool',
  21. 'jsonify', 'gen_task_name', 'nodename', 'nodesplit',
  22. 'cached_property']
  23. PENDING_DEPRECATION_FMT = """
  24. {description} is scheduled for deprecation in \
  25. version {deprecation} and removal in version v{removal}. \
  26. {alternative}
  27. """
  28. DEPRECATION_FMT = """
  29. {description} is deprecated and scheduled for removal in
  30. version {removal}. {alternative}
  31. """
  32. #: Billiard sets this when execv is enabled.
  33. #: We use it to find out the name of the original ``__main__``
  34. #: module, so that we can properly rewrite the name of the
  35. #: task to be that of ``App.main``.
  36. MP_MAIN_FILE = os.environ.get('MP_MAIN_FILE') or None
  37. #: Exchange for worker direct queues.
  38. WORKER_DIRECT_EXCHANGE = Exchange('C.dq')
  39. #: Format for worker direct queue names.
  40. WORKER_DIRECT_QUEUE_FORMAT = '{hostname}.dq'
  41. #: Separator for worker node name and hostname.
  42. NODENAME_SEP = '@'
  43. def worker_direct(hostname):
  44. """Return :class:`kombu.Queue` that is a direct route to
  45. a worker by hostname.
  46. :param hostname: The fully qualified node name of a worker
  47. (e.g. ``w1@example.com``). If passed a
  48. :class:`kombu.Queue` instance it will simply return
  49. that instead.
  50. """
  51. if isinstance(hostname, Queue):
  52. return hostname
  53. return Queue(WORKER_DIRECT_QUEUE_FORMAT.format(hostname=hostname),
  54. WORKER_DIRECT_EXCHANGE,
  55. hostname, auto_delete=True)
  56. def warn_deprecated(description=None, deprecation=None,
  57. removal=None, alternative=None):
  58. ctx = {'description': description,
  59. 'deprecation': deprecation, 'removal': removal,
  60. 'alternative': alternative}
  61. if deprecation is not None:
  62. w = CPendingDeprecationWarning(PENDING_DEPRECATION_FMT.format(**ctx))
  63. else:
  64. w = CDeprecationWarning(DEPRECATION_FMT.format(**ctx))
  65. warnings.warn(w)
  66. def deprecated(description=None, deprecation=None,
  67. removal=None, alternative=None):
  68. """Decorator for deprecated functions.
  69. A deprecation warning will be emitted when the function is called.
  70. :keyword description: Description of what is being deprecated.
  71. :keyword deprecation: Version that marks first deprecation, if this
  72. argument is not set a ``PendingDeprecationWarning`` will be emitted
  73. instead.
  74. :keyword removed: Future version when this feature will be removed.
  75. :keyword alternative: Instructions for an alternative solution (if any).
  76. """
  77. def _inner(fun):
  78. @wraps(fun)
  79. def __inner(*args, **kwargs):
  80. from .imports import qualname
  81. warn_deprecated(description=description or qualname(fun),
  82. deprecation=deprecation,
  83. removal=removal,
  84. alternative=alternative)
  85. return fun(*args, **kwargs)
  86. return __inner
  87. return _inner
  88. def lpmerge(L, R):
  89. """In place left precedent dictionary merge.
  90. Keeps values from `L`, if the value in `R` is :const:`None`."""
  91. set = L.__setitem__
  92. [set(k, v) for k, v in items(R) if v is not None]
  93. return L
  94. def is_iterable(obj):
  95. try:
  96. iter(obj)
  97. except TypeError:
  98. return False
  99. return True
  100. def fun_takes_kwargs(fun, kwlist=[]):
  101. """With a function, and a list of keyword arguments, returns arguments
  102. in the list which the function takes.
  103. If the object has an `argspec` attribute that is used instead
  104. of using the :meth:`inspect.getargspec` introspection.
  105. :param fun: The function to inspect arguments of.
  106. :param kwlist: The list of keyword arguments.
  107. Examples
  108. >>> def foo(self, x, y, logfile=None, loglevel=None):
  109. ... return x * y
  110. >>> fun_takes_kwargs(foo, ['logfile', 'loglevel', 'task_id'])
  111. ['logfile', 'loglevel']
  112. >>> def foo(self, x, y, **kwargs):
  113. >>> fun_takes_kwargs(foo, ['logfile', 'loglevel', 'task_id'])
  114. ['logfile', 'loglevel', 'task_id']
  115. """
  116. S = getattr(fun, 'argspec', getargspec(fun))
  117. if S.keywords is not None:
  118. return kwlist
  119. return [kw for kw in kwlist if kw in S.args]
  120. def isatty(fh):
  121. try:
  122. return fh.isatty()
  123. except AttributeError:
  124. pass
  125. def cry(out=None, sepchr='=', seplen=49): # pragma: no cover
  126. """Return stacktrace of all active threads.
  127. From https://gist.github.com/737056
  128. """
  129. import threading
  130. out = StringIO() if out is None else out
  131. P = partial(print, file=out)
  132. # get a map of threads by their ID so we can print their names
  133. # during the traceback dump
  134. tmap = dict((t.ident, t) for t in threading.enumerate())
  135. sep = sepchr * seplen
  136. for tid, frame in items(sys._current_frames()):
  137. thread = tmap.get(tid)
  138. if not thread:
  139. # skip old junk (left-overs from a fork)
  140. continue
  141. P('{0.name}'.format(thread))
  142. P(sep)
  143. traceback.print_stack(frame, file=out)
  144. P(sep)
  145. P('LOCAL VARIABLES')
  146. P(sep)
  147. pprint(frame.f_locals, stream=out)
  148. P('\n')
  149. return out.getvalue()
  150. def maybe_reraise():
  151. """Re-raise if an exception is currently being handled, or return
  152. otherwise."""
  153. exc_info = sys.exc_info()
  154. try:
  155. if exc_info[2]:
  156. reraise(exc_info[0], exc_info[1], exc_info[2])
  157. finally:
  158. # see http://docs.python.org/library/sys.html#sys.exc_info
  159. del(exc_info)
  160. def strtobool(term, table={'false': False, 'no': False, '0': False,
  161. 'true': True, 'yes': True, '1': True,
  162. 'on': True, 'off': False}):
  163. """Convert common terms for true/false to bool
  164. (true/false/yes/no/on/off/1/0)."""
  165. if isinstance(term, string_t):
  166. try:
  167. return table[term.lower()]
  168. except KeyError:
  169. raise TypeError('Cannot coerce {0!r} to type bool'.format(term))
  170. return term
  171. def jsonify(obj,
  172. builtin_types=(int, float, string_t), key=None,
  173. keyfilter=None,
  174. unknown_type_filter=None):
  175. """Transforms object making it suitable for json serialization"""
  176. from kombu.abstract import Object as KombuDictType
  177. _jsonify = partial(jsonify, builtin_types=builtin_types, key=key,
  178. keyfilter=keyfilter,
  179. unknown_type_filter=unknown_type_filter)
  180. if isinstance(obj, KombuDictType):
  181. obj = obj.as_dict(recurse=True)
  182. if obj is None or isinstance(obj, builtin_types):
  183. return obj
  184. elif isinstance(obj, (tuple, list)):
  185. return [_jsonify(v) for v in obj]
  186. elif isinstance(obj, dict):
  187. return dict((k, _jsonify(v, key=k))
  188. for k, v in items(obj)
  189. if (keyfilter(k) if keyfilter else 1))
  190. elif isinstance(obj, datetime.datetime):
  191. # See "Date Time String Format" in the ECMA-262 specification.
  192. r = obj.isoformat()
  193. if obj.microsecond:
  194. r = r[:23] + r[26:]
  195. if r.endswith('+00:00'):
  196. r = r[:-6] + 'Z'
  197. return r
  198. elif isinstance(obj, datetime.date):
  199. return obj.isoformat()
  200. elif isinstance(obj, datetime.time):
  201. r = obj.isoformat()
  202. if obj.microsecond:
  203. r = r[:12]
  204. return r
  205. elif isinstance(obj, datetime.timedelta):
  206. return str(obj)
  207. else:
  208. if unknown_type_filter is None:
  209. raise ValueError(
  210. 'Unsupported type: {0!r} {1!r} (parent: {2})'.format(
  211. type(obj), obj, key))
  212. return unknown_type_filter(obj)
  213. def gen_task_name(app, name, module_name):
  214. """Generate task name from name/module pair."""
  215. try:
  216. module = sys.modules[module_name]
  217. except KeyError:
  218. # Fix for manage.py shell_plus (Issue #366)
  219. module = None
  220. if module is not None:
  221. module_name = module.__name__
  222. # - If the task module is used as the __main__ script
  223. # - we need to rewrite the module part of the task name
  224. # - to match App.main.
  225. if MP_MAIN_FILE and module.__file__ == MP_MAIN_FILE:
  226. # - see comment about :envvar:`MP_MAIN_FILE` above.
  227. module_name = '__main__'
  228. if module_name == '__main__' and app.main:
  229. return '.'.join([app.main, name])
  230. return '.'.join(p for p in (module_name, name) if p)
  231. def nodename(name, hostname):
  232. """Create node name from name/hostname pair."""
  233. return NODENAME_SEP.join((name, hostname))
  234. def nodesplit(nodename):
  235. """Split node name into tuple of name/hostname."""
  236. parts = nodename.split(NODENAME_SEP, 1)
  237. if len(parts) == 1:
  238. return None, parts[0]
  239. return parts
  240. # ------------------------------------------------------------------------ #
  241. # > XXX Compat
  242. from .log import LOG_LEVELS # noqa
  243. from .imports import ( # noqa
  244. qualname as get_full_cls_name, symbol_by_name as get_cls_by_name,
  245. instantiate, import_from_cwd
  246. )
  247. from .functional import chunks, noop # noqa
  248. from kombu.utils import cached_property, kwdict, uuid # noqa
  249. gen_unique_id = uuid