__init__.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. # -*- coding: utf-8 -*-
  2. """
  3. celery.utils
  4. ~~~~~~~~~~~~
  5. Utility functions.
  6. """
  7. from __future__ import absolute_import, print_function
  8. import numbers
  9. import os
  10. import re
  11. import socket
  12. import sys
  13. import traceback
  14. import warnings
  15. import datetime
  16. from collections import Callable
  17. from functools import partial, wraps
  18. from pprint import pprint
  19. from kombu.entity import Exchange, Queue
  20. from celery.exceptions import CPendingDeprecationWarning, CDeprecationWarning
  21. from celery.five import WhateverIO, items, reraise, string_t
  22. __all__ = ['worker_direct', 'warn_deprecated', 'deprecated', 'lpmerge',
  23. 'is_iterable', 'isatty', 'cry', 'maybe_reraise', 'strtobool',
  24. 'jsonify', 'gen_task_name', 'nodename', 'nodesplit',
  25. 'cached_property']
  26. PY3 = sys.version_info[0] == 3
  27. PENDING_DEPRECATION_FMT = """
  28. {description} is scheduled for deprecation in \
  29. version {deprecation} and removal in version v{removal}. \
  30. {alternative}
  31. """
  32. DEPRECATION_FMT = """
  33. {description} is deprecated and scheduled for removal in
  34. version {removal}. {alternative}
  35. """
  36. #: Billiard sets this when execv is enabled.
  37. #: We use it to find out the name of the original ``__main__``
  38. #: module, so that we can properly rewrite the name of the
  39. #: task to be that of ``App.main``.
  40. MP_MAIN_FILE = os.environ.get('MP_MAIN_FILE') or None
  41. #: Exchange for worker direct queues.
  42. WORKER_DIRECT_EXCHANGE = Exchange('C.dq')
  43. #: Format for worker direct queue names.
  44. WORKER_DIRECT_QUEUE_FORMAT = '{hostname}.dq'
  45. #: Separator for worker node name and hostname.
  46. NODENAME_SEP = '@'
  47. NODENAME_DEFAULT = 'celery'
  48. RE_FORMAT = re.compile(r'%(\w)')
  49. def worker_direct(hostname):
  50. """Return :class:`kombu.Queue` that is a direct route to
  51. a worker by hostname.
  52. :param hostname: The fully qualified node name of a worker
  53. (e.g. ``w1@example.com``). If passed a
  54. :class:`kombu.Queue` instance it will simply return
  55. that instead.
  56. """
  57. if isinstance(hostname, Queue):
  58. return hostname
  59. return Queue(WORKER_DIRECT_QUEUE_FORMAT.format(hostname=hostname),
  60. WORKER_DIRECT_EXCHANGE,
  61. hostname, auto_delete=True)
  62. def warn_deprecated(description=None, deprecation=None,
  63. removal=None, alternative=None, stacklevel=2):
  64. ctx = {'description': description,
  65. 'deprecation': deprecation, 'removal': removal,
  66. 'alternative': alternative}
  67. if deprecation is not None:
  68. w = CPendingDeprecationWarning(PENDING_DEPRECATION_FMT.format(**ctx))
  69. else:
  70. w = CDeprecationWarning(DEPRECATION_FMT.format(**ctx))
  71. warnings.warn(w, stacklevel=stacklevel)
  72. def deprecated(deprecation=None, removal=None,
  73. alternative=None, description=None):
  74. """Decorator for deprecated functions.
  75. A deprecation warning will be emitted when the function is called.
  76. :keyword deprecation: Version that marks first deprecation, if this
  77. argument is not set a ``PendingDeprecationWarning`` will be emitted
  78. instead.
  79. :keyword removal: Future version when this feature will be removed.
  80. :keyword alternative: Instructions for an alternative solution (if any).
  81. :keyword description: Description of what is being deprecated.
  82. """
  83. def _inner(fun):
  84. @wraps(fun)
  85. def __inner(*args, **kwargs):
  86. from .imports import qualname
  87. warn_deprecated(description=description or qualname(fun),
  88. deprecation=deprecation,
  89. removal=removal,
  90. alternative=alternative,
  91. stacklevel=3)
  92. return fun(*args, **kwargs)
  93. return __inner
  94. return _inner
  95. def deprecated_property(deprecation=None, removal=None,
  96. alternative=None, description=None):
  97. def _inner(fun):
  98. return _deprecated_property(
  99. fun, deprecation=deprecation, removal=removal,
  100. alternative=alternative, description=description or fun.__name__)
  101. return _inner
  102. class _deprecated_property(object):
  103. def __init__(self, fget=None, fset=None, fdel=None, doc=None, **depreinfo):
  104. self.__get = fget
  105. self.__set = fset
  106. self.__del = fdel
  107. self.__name__, self.__module__, self.__doc__ = (
  108. fget.__name__, fget.__module__, fget.__doc__,
  109. )
  110. self.depreinfo = depreinfo
  111. self.depreinfo.setdefault('stacklevel', 3)
  112. def __get__(self, obj, type=None):
  113. if obj is None:
  114. return self
  115. warn_deprecated(**self.depreinfo)
  116. return self.__get(obj)
  117. def __set__(self, obj, value):
  118. if obj is None:
  119. return self
  120. if self.__set is None:
  121. raise AttributeError('cannot set attribute')
  122. warn_deprecated(**self.depreinfo)
  123. self.__set(obj, value)
  124. def __delete__(self, obj):
  125. if obj is None:
  126. return self
  127. if self.__del is None:
  128. raise AttributeError('cannot delete attribute')
  129. warn_deprecated(**self.depreinfo)
  130. self.__del(obj)
  131. def setter(self, fset):
  132. return self.__class__(self.__get, fset, self.__del, **self.depreinfo)
  133. def deleter(self, fdel):
  134. return self.__class__(self.__get, self.__set, fdel, **self.depreinfo)
  135. def lpmerge(L, R):
  136. """In place left precedent dictionary merge.
  137. Keeps values from `L`, if the value in `R` is :const:`None`."""
  138. setitem = L.__setitem__
  139. [setitem(k, v) for k, v in items(R) if v is not None]
  140. return L
  141. def is_iterable(obj):
  142. try:
  143. iter(obj)
  144. except TypeError:
  145. return False
  146. return True
  147. def isatty(fh):
  148. try:
  149. return fh.isatty()
  150. except AttributeError:
  151. pass
  152. def cry(out=None, sepchr='=', seplen=49): # pragma: no cover
  153. """Return stacktrace of all active threads,
  154. taken from https://gist.github.com/737056."""
  155. import threading
  156. out = WhateverIO() if out is None else out
  157. P = partial(print, file=out)
  158. # get a map of threads by their ID so we can print their names
  159. # during the traceback dump
  160. tmap = {t.ident: t for t in threading.enumerate()}
  161. sep = sepchr * seplen
  162. for tid, frame in items(sys._current_frames()):
  163. thread = tmap.get(tid)
  164. if not thread:
  165. # skip old junk (left-overs from a fork)
  166. continue
  167. P('{0.name}'.format(thread))
  168. P(sep)
  169. traceback.print_stack(frame, file=out)
  170. P(sep)
  171. P('LOCAL VARIABLES')
  172. P(sep)
  173. pprint(frame.f_locals, stream=out)
  174. P('\n')
  175. return out.getvalue()
  176. def maybe_reraise():
  177. """Re-raise if an exception is currently being handled, or return
  178. otherwise."""
  179. exc_info = sys.exc_info()
  180. try:
  181. if exc_info[2]:
  182. reraise(exc_info[0], exc_info[1], exc_info[2])
  183. finally:
  184. # see http://docs.python.org/library/sys.html#sys.exc_info
  185. del(exc_info)
  186. def strtobool(term, table={'false': False, 'no': False, '0': False,
  187. 'true': True, 'yes': True, '1': True,
  188. 'on': True, 'off': False}):
  189. """Convert common terms for true/false to bool
  190. (true/false/yes/no/on/off/1/0)."""
  191. if isinstance(term, string_t):
  192. try:
  193. return table[term.lower()]
  194. except KeyError:
  195. raise TypeError('Cannot coerce {0!r} to type bool'.format(term))
  196. return term
  197. def jsonify(obj,
  198. builtin_types=(numbers.Real, string_t), key=None,
  199. keyfilter=None,
  200. unknown_type_filter=None):
  201. """Transforms object making it suitable for json serialization"""
  202. from kombu.abstract import Object as KombuDictType
  203. _jsonify = partial(jsonify, builtin_types=builtin_types, key=key,
  204. keyfilter=keyfilter,
  205. unknown_type_filter=unknown_type_filter)
  206. if isinstance(obj, KombuDictType):
  207. obj = obj.as_dict(recurse=True)
  208. if obj is None or isinstance(obj, builtin_types):
  209. return obj
  210. elif isinstance(obj, (tuple, list)):
  211. return [_jsonify(v) for v in obj]
  212. elif isinstance(obj, dict):
  213. return {
  214. k: _jsonify(v, key=k) for k, v in items(obj)
  215. if (keyfilter(k) if keyfilter else 1)
  216. }
  217. elif isinstance(obj, datetime.datetime):
  218. # See "Date Time String Format" in the ECMA-262 specification.
  219. r = obj.isoformat()
  220. if obj.microsecond:
  221. r = r[:23] + r[26:]
  222. if r.endswith('+00:00'):
  223. r = r[:-6] + 'Z'
  224. return r
  225. elif isinstance(obj, datetime.date):
  226. return obj.isoformat()
  227. elif isinstance(obj, datetime.time):
  228. r = obj.isoformat()
  229. if obj.microsecond:
  230. r = r[:12]
  231. return r
  232. elif isinstance(obj, datetime.timedelta):
  233. return str(obj)
  234. else:
  235. if unknown_type_filter is None:
  236. raise ValueError(
  237. 'Unsupported type: {0!r} {1!r} (parent: {2})'.format(
  238. type(obj), obj, key))
  239. return unknown_type_filter(obj)
  240. def gen_task_name(app, name, module_name):
  241. """Generate task name from name/module pair."""
  242. try:
  243. module = sys.modules[module_name]
  244. except KeyError:
  245. # Fix for manage.py shell_plus (Issue #366)
  246. module = None
  247. if module is not None:
  248. module_name = module.__name__
  249. # - If the task module is used as the __main__ script
  250. # - we need to rewrite the module part of the task name
  251. # - to match App.main.
  252. if MP_MAIN_FILE and module.__file__ == MP_MAIN_FILE:
  253. # - see comment about :envvar:`MP_MAIN_FILE` above.
  254. module_name = '__main__'
  255. if module_name == '__main__' and app.main:
  256. return '.'.join([app.main, name])
  257. return '.'.join(p for p in (module_name, name) if p)
  258. def nodename(name, hostname):
  259. """Create node name from name/hostname pair."""
  260. return NODENAME_SEP.join((name, hostname))
  261. def anon_nodename(hostname=None, prefix='gen'):
  262. return nodename(''.join([prefix, str(os.getpid())]),
  263. hostname or socket.gethostname())
  264. def nodesplit(nodename):
  265. """Split node name into tuple of name/hostname."""
  266. parts = nodename.split(NODENAME_SEP, 1)
  267. if len(parts) == 1:
  268. return None, parts[0]
  269. return parts
  270. def default_nodename(hostname):
  271. name, host = nodesplit(hostname or '')
  272. return nodename(name or NODENAME_DEFAULT, host or socket.gethostname())
  273. def node_format(s, nodename, **extra):
  274. name, host = nodesplit(nodename)
  275. return host_format(
  276. s, host, name or NODENAME_DEFAULT, **extra)
  277. def _fmt_process_index(prefix='', default='0'):
  278. from .log import current_process_index
  279. index = current_process_index()
  280. return '{0}{1}'.format(prefix, index) if index else default
  281. _fmt_process_index_with_prefix = partial(_fmt_process_index, '-', '')
  282. def host_format(s, host=None, name=None, **extra):
  283. host = host or socket.gethostname()
  284. hname, _, domain = host.partition('.')
  285. name = name or hname
  286. keys = dict({
  287. 'h': host, 'n': name, 'd': domain,
  288. 'i': _fmt_process_index, 'I': _fmt_process_index_with_prefix,
  289. }, **extra)
  290. return simple_format(s, keys)
  291. def simple_format(s, keys, pattern=RE_FORMAT, expand=r'\1'):
  292. if s:
  293. keys.setdefault('%', '%')
  294. def resolve(match):
  295. resolver = keys[match.expand(expand)]
  296. if isinstance(resolver, Callable):
  297. return resolver()
  298. return resolver
  299. return pattern.sub(resolve, s)
  300. return s
  301. # ------------------------------------------------------------------------ #
  302. # > XXX Compat
  303. from .log import LOG_LEVELS # noqa
  304. from .imports import ( # noqa
  305. qualname as get_full_cls_name, symbol_by_name as get_cls_by_name,
  306. instantiate, import_from_cwd
  307. )
  308. from .functional import chunks, noop # noqa
  309. from kombu.utils import cached_property, kwdict, uuid # noqa
  310. gen_unique_id = uuid