__init__.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. from __future__ import generators
  2. import time
  3. import operator
  4. try:
  5. import ctypes
  6. except ImportError:
  7. ctypes = None
  8. import importlib
  9. import logging
  10. from datetime import datetime
  11. from uuid import UUID, uuid4, _uuid_generate_random
  12. from inspect import getargspec
  13. from itertools import islice
  14. from carrot.utils import rpartition
  15. from dateutil.parser import parse as parse_iso8601
  16. from celery.utils.compat import all, any, defaultdict
  17. from celery.utils.timeutils import timedelta_seconds # was here before
  18. from celery.utils.functional import curry
  19. LOG_LEVELS = dict(logging._levelNames)
  20. LOG_LEVELS["FATAL"] = logging.FATAL
  21. LOG_LEVELS[logging.FATAL] = "FATAL"
  22. class promise(object):
  23. """A promise.
  24. Evaluated when called or if the :meth:`evaluate` method is called.
  25. The function is evaluated on every access, so the value is not
  26. memoized (see :class:`mpromise`).
  27. Overloaded operations that will evaluate the promise:
  28. :meth:`__str__`, :meth:`__repr__`, :meth:`__cmp__`.
  29. """
  30. def __init__(self, fun, *args, **kwargs):
  31. self._fun = fun
  32. self._args = args
  33. self._kwargs = kwargs
  34. def __call__(self):
  35. return self.evaluate()
  36. def evaluate(self):
  37. return self._fun(*self._args, **self._kwargs)
  38. def __str__(self):
  39. return str(self())
  40. def __repr__(self):
  41. return repr(self())
  42. def __cmp__(self, rhs):
  43. if isinstance(rhs, self.__class__):
  44. return -cmp(rhs, self())
  45. return cmp(self(), rhs)
  46. def __deepcopy__(self, memo):
  47. memo[id(self)] = self
  48. return self
  49. def __reduce__(self):
  50. return (self.__class__, (self._fun, ), {"_args": self._args,
  51. "_kwargs": self._kwargs})
  52. class mpromise(promise):
  53. """Memoized promise.
  54. The function is only evaluated once, every subsequent access
  55. will return the same value.
  56. .. attribute:: evaluated
  57. Set to to :const:`True` after the promise has been evaluated.
  58. """
  59. evaluated = False
  60. _value = None
  61. def evaluate(self):
  62. if not self.evaluated:
  63. self._value = super(mpromise, self).evaluate()
  64. self.evaluated = True
  65. return self._value
  66. def maybe_promise(value):
  67. """Evaluates if the value is a promise."""
  68. if isinstance(value, promise):
  69. return value.evaluate()
  70. return value
  71. def noop(*args, **kwargs):
  72. """No operation.
  73. Takes any arguments/keyword arguments and does nothing.
  74. """
  75. pass
  76. def maybe_iso8601(dt):
  77. """``Either datetime | str -> datetime or None -> None``"""
  78. if not dt:
  79. return
  80. if isinstance(dt, datetime):
  81. return dt
  82. return parse_iso8601(dt)
  83. def kwdict(kwargs):
  84. """Make sure keyword arguments are not in unicode.
  85. This should be fixed in newer Python versions,
  86. see: http://bugs.python.org/issue4978.
  87. """
  88. return dict((key.encode("utf-8"), value)
  89. for key, value in kwargs.items())
  90. def first(predicate, iterable):
  91. """Returns the first element in ``iterable`` that ``predicate`` returns a
  92. :const:`True` value for."""
  93. for item in iterable:
  94. if predicate(item):
  95. return item
  96. def firstmethod(method):
  97. """Returns a functions that with a list of instances,
  98. finds the first instance that returns a value for the given method.
  99. The list can also contain promises (:class:`promise`.)
  100. """
  101. def _matcher(seq, *args, **kwargs):
  102. for cls in seq:
  103. try:
  104. answer = getattr(maybe_promise(cls), method)(*args, **kwargs)
  105. if answer is not None:
  106. return answer
  107. except AttributeError:
  108. pass
  109. return _matcher
  110. def chunks(it, n):
  111. """Split an iterator into chunks with ``n`` elements each.
  112. Examples
  113. # n == 2
  114. >>> x = chunks(iter([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]), 2)
  115. >>> list(x)
  116. [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9], [10]]
  117. # n == 3
  118. >>> x = chunks(iter([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]), 3)
  119. >>> list(x)
  120. [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10]]
  121. """
  122. for first in it:
  123. yield [first] + list(islice(it, n - 1))
  124. def gen_unique_id():
  125. """Generate a unique id, having - hopefully - a very small chance of
  126. collission.
  127. For now this is provided by :func:`uuid.uuid4`.
  128. """
  129. # Workaround for http://bugs.python.org/issue4607
  130. if ctypes and _uuid_generate_random:
  131. buffer = ctypes.create_string_buffer(16)
  132. _uuid_generate_random(buffer)
  133. return str(UUID(bytes=buffer.raw))
  134. return str(uuid4())
  135. def padlist(container, size, default=None):
  136. """Pad list with default elements.
  137. Examples:
  138. >>> first, last, city = padlist(["George", "Costanza", "NYC"], 3)
  139. ("George", "Costanza", "NYC")
  140. >>> first, last, city = padlist(["George", "Costanza"], 3)
  141. ("George", "Costanza", None)
  142. >>> first, last, city, planet = padlist(["George", "Costanza",
  143. "NYC"], 4, default="Earth")
  144. ("George", "Costanza", "NYC", "Earth")
  145. """
  146. return list(container)[:size] + [default] * (size - len(container))
  147. def is_iterable(obj):
  148. try:
  149. iter(obj)
  150. except TypeError:
  151. return False
  152. return True
  153. def mitemgetter(*items):
  154. """Like :func:`operator.itemgetter` but returns :const:`None`
  155. on missing items instead of raising :exc:`KeyError`."""
  156. return lambda container: map(container.get, items)
  157. def mattrgetter(*attrs):
  158. """Like :func:`operator.itemgetter` but returns :const:`None` on missing
  159. attributes instead of raising :exc:`AttributeError`."""
  160. return lambda obj: dict((attr, getattr(obj, attr, None))
  161. for attr in attrs)
  162. def get_full_cls_name(cls):
  163. """With a class, get its full module and class name."""
  164. return ".".join([cls.__module__,
  165. cls.__name__])
  166. def repeatlast(it):
  167. """Iterate over all elements in the iterator, and when its exhausted
  168. yield the last value infinitely."""
  169. for item in it:
  170. yield item
  171. while 1: # pragma: no cover
  172. yield item
  173. def retry_over_time(fun, catch, args=[], kwargs={}, errback=noop,
  174. max_retries=None, interval_start=2, interval_step=2, interval_max=30):
  175. """Retry the function over and over until max retries is exceeded.
  176. For each retry we sleep a for a while before we try again, this interval
  177. is increased for every retry until the max seconds is reached.
  178. :param fun: The function to try
  179. :param catch: Exceptions to catch, can be either tuple or a single
  180. exception class.
  181. :keyword args: Positional arguments passed on to the function.
  182. :keyword kwargs: Keyword arguments passed on to the function.
  183. :keyword errback: Callback for when an exception in ``catch`` is raised.
  184. The callback must take two arguments: ``exc`` and ``interval``, where
  185. ``exc`` is the exception instance, and ``interval`` is the time in
  186. seconds to sleep next..
  187. :keyword max_retries: Maximum number of retries before we give up.
  188. If this is not set, we will retry forever.
  189. :keyword interval_start: How long (in seconds) we start sleeping between
  190. retries.
  191. :keyword interval_step: By how much the interval is increased for each
  192. retry.
  193. :keyword interval_max: Maximum number of seconds to sleep between retries.
  194. """
  195. retries = 0
  196. interval_range = xrange(interval_start,
  197. interval_max + interval_start,
  198. interval_step)
  199. for interval in repeatlast(interval_range):
  200. try:
  201. retval = fun(*args, **kwargs)
  202. except catch, exc:
  203. if max_retries and retries > max_retries:
  204. raise
  205. errback(exc, interval)
  206. retries += 1
  207. time.sleep(interval)
  208. else:
  209. return retval
  210. def fun_takes_kwargs(fun, kwlist=[]):
  211. """With a function, and a list of keyword arguments, returns arguments
  212. in the list which the function takes.
  213. If the object has an ``argspec`` attribute that is used instead
  214. of using the :meth:`inspect.getargspec`` introspection.
  215. :param fun: The function to inspect arguments of.
  216. :param kwlist: The list of keyword arguments.
  217. Examples
  218. >>> def foo(self, x, y, logfile=None, loglevel=None):
  219. ... return x * y
  220. >>> fun_takes_kwargs(foo, ["logfile", "loglevel", "task_id"])
  221. ["logfile", "loglevel"]
  222. >>> def foo(self, x, y, **kwargs):
  223. >>> fun_takes_kwargs(foo, ["logfile", "loglevel", "task_id"])
  224. ["logfile", "loglevel", "task_id"]
  225. """
  226. argspec = getattr(fun, "argspec", getargspec(fun))
  227. args, _varargs, keywords, _defaults = argspec
  228. if keywords != None:
  229. return kwlist
  230. return filter(curry(operator.contains, args), kwlist)
  231. def get_cls_by_name(name, aliases={}):
  232. """Get class by name.
  233. The name should be the full dot-separated path to the class::
  234. modulename.ClassName
  235. Example::
  236. celery.concurrency.processes.TaskPool
  237. ^- class name
  238. If ``aliases`` is provided, a dict containing short name/long name
  239. mappings, the name is looked up in the aliases first.
  240. Examples:
  241. >>> get_cls_by_name("celery.concurrency.processes.TaskPool")
  242. <class 'celery.concurrency.processes.TaskPool'>
  243. >>> get_cls_by_name("default", {
  244. ... "default": "celery.concurrency.processes.TaskPool"})
  245. <class 'celery.concurrency.processes.TaskPool'>
  246. # Does not try to look up non-string names.
  247. >>> from celery.concurrency.processes import TaskPool
  248. >>> get_cls_by_name(TaskPool) is TaskPool
  249. True
  250. """
  251. if not isinstance(name, basestring):
  252. return name # already a class
  253. name = aliases.get(name) or name
  254. module_name, _, cls_name = rpartition(name, ".")
  255. module = importlib.import_module(module_name)
  256. return getattr(module, cls_name)
  257. def instantiate(name, *args, **kwargs):
  258. """Instantiate class by name.
  259. See :func:`get_cls_by_name`.
  260. """
  261. return get_cls_by_name(name)(*args, **kwargs)
  262. def truncate_text(text, maxlen=128, suffix="..."):
  263. """Truncates text to a maximum number of characters."""
  264. if len(text) >= maxlen:
  265. return text[:maxlen].rsplit(" ", 1)[0] + suffix
  266. return text
  267. def abbr(S, max, ellipsis="..."):
  268. if S is None:
  269. return "???"
  270. if len(S) > max:
  271. return ellipsis and (S[:max - len(ellipsis)] + ellipsis) or S[:max]
  272. return S
  273. def abbrtask(S, max):
  274. if S is None:
  275. return "???"
  276. if len(S) > max:
  277. module, _, cls = rpartition(S, ".")
  278. module = abbr(module, max - len(cls), False)
  279. return module + "[.]" + cls
  280. return S