__init__.py 9.7 KB

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