__init__.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  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. # deprecated
  102. S = getattr(fun, 'argspec', getargspec(fun))
  103. if S.keywords is not None:
  104. return kwlist
  105. return [kw for kw in kwlist if kw in S.args]
  106. def isatty(fh):
  107. try:
  108. return fh.isatty()
  109. except AttributeError:
  110. pass
  111. def cry(out=None, sepchr='=', seplen=49): # pragma: no cover
  112. """Return stacktrace of all active threads,
  113. taken from https://gist.github.com/737056."""
  114. import threading
  115. out = StringIO() if out is None else out
  116. P = partial(print, file=out)
  117. # get a map of threads by their ID so we can print their names
  118. # during the traceback dump
  119. tmap = dict((t.ident, t) for t in threading.enumerate())
  120. sep = sepchr * seplen
  121. for tid, frame in items(sys._current_frames()):
  122. thread = tmap.get(tid)
  123. if not thread:
  124. # skip old junk (left-overs from a fork)
  125. continue
  126. P('{0.name}'.format(thread))
  127. P(sep)
  128. traceback.print_stack(frame, file=out)
  129. P(sep)
  130. P('LOCAL VARIABLES')
  131. P(sep)
  132. pprint(frame.f_locals, stream=out)
  133. P('\n')
  134. return out.getvalue()
  135. def maybe_reraise():
  136. """Re-raise if an exception is currently being handled, or return
  137. otherwise."""
  138. exc_info = sys.exc_info()
  139. try:
  140. if exc_info[2]:
  141. reraise(exc_info[0], exc_info[1], exc_info[2])
  142. finally:
  143. # see http://docs.python.org/library/sys.html#sys.exc_info
  144. del(exc_info)
  145. def strtobool(term, table={'false': False, 'no': False, '0': False,
  146. 'true': True, 'yes': True, '1': True,
  147. 'on': True, 'off': False}):
  148. """Convert common terms for true/false to bool
  149. (true/false/yes/no/on/off/1/0)."""
  150. if isinstance(term, string_t):
  151. try:
  152. return table[term.lower()]
  153. except KeyError:
  154. raise TypeError('Cannot coerce {0!r} to type bool'.format(term))
  155. return term
  156. def jsonify(obj,
  157. builtin_types=(int, float, string_t), key=None,
  158. keyfilter=None,
  159. unknown_type_filter=None):
  160. """Transforms object making it suitable for json serialization"""
  161. from kombu.abstract import Object as KombuDictType
  162. _jsonify = partial(jsonify, builtin_types=builtin_types, key=key,
  163. keyfilter=keyfilter,
  164. unknown_type_filter=unknown_type_filter)
  165. if isinstance(obj, KombuDictType):
  166. obj = obj.as_dict(recurse=True)
  167. if obj is None or isinstance(obj, builtin_types):
  168. return obj
  169. elif isinstance(obj, (tuple, list)):
  170. return [_jsonify(v) for v in obj]
  171. elif isinstance(obj, dict):
  172. return dict((k, _jsonify(v, key=k))
  173. for k, v in items(obj)
  174. if (keyfilter(k) if keyfilter else 1))
  175. elif isinstance(obj, datetime.datetime):
  176. # See "Date Time String Format" in the ECMA-262 specification.
  177. r = obj.isoformat()
  178. if obj.microsecond:
  179. r = r[:23] + r[26:]
  180. if r.endswith('+00:00'):
  181. r = r[:-6] + 'Z'
  182. return r
  183. elif isinstance(obj, datetime.date):
  184. return obj.isoformat()
  185. elif isinstance(obj, datetime.time):
  186. r = obj.isoformat()
  187. if obj.microsecond:
  188. r = r[:12]
  189. return r
  190. elif isinstance(obj, datetime.timedelta):
  191. return str(obj)
  192. else:
  193. if unknown_type_filter is None:
  194. raise ValueError(
  195. 'Unsupported type: {0!r} {1!r} (parent: {2})'.format(
  196. type(obj), obj, key))
  197. return unknown_type_filter(obj)
  198. def gen_task_name(app, name, module_name):
  199. """Generate task name from name/module pair."""
  200. try:
  201. module = sys.modules[module_name]
  202. except KeyError:
  203. # Fix for manage.py shell_plus (Issue #366)
  204. module = None
  205. if module is not None:
  206. module_name = module.__name__
  207. # - If the task module is used as the __main__ script
  208. # - we need to rewrite the module part of the task name
  209. # - to match App.main.
  210. if MP_MAIN_FILE and module.__file__ == MP_MAIN_FILE:
  211. # - see comment about :envvar:`MP_MAIN_FILE` above.
  212. module_name = '__main__'
  213. if module_name == '__main__' and app.main:
  214. return '.'.join([app.main, name])
  215. return '.'.join(p for p in (module_name, name) if p)
  216. def nodename(name, hostname):
  217. """Create node name from name/hostname pair."""
  218. return NODENAME_SEP.join((name, hostname))
  219. def nodesplit(nodename):
  220. """Split node name into tuple of name/hostname."""
  221. parts = nodename.split(NODENAME_SEP, 1)
  222. if len(parts) == 1:
  223. return None, parts[0]
  224. return parts
  225. # ------------------------------------------------------------------------ #
  226. # > XXX Compat
  227. from .log import LOG_LEVELS # noqa
  228. from .imports import ( # noqa
  229. qualname as get_full_cls_name, symbol_by_name as get_cls_by_name,
  230. instantiate, import_from_cwd
  231. )
  232. from .functional import chunks, noop # noqa
  233. from kombu.utils import cached_property, kwdict, uuid # noqa
  234. gen_unique_id = uuid