buckets.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. import time
  2. from Queue import Queue, Empty as QueueEmpty
  3. from itertools import chain
  4. from celery.utils import all
  5. from celery.utils import timeutils
  6. from celery.utils.compat import izip_longest
  7. class RateLimitExceeded(Exception):
  8. """The token buckets rate limit has been exceeded."""
  9. class TaskBucket(object):
  10. """This is a collection of token buckets, each task type having
  11. its own token bucket. If the task type doesn't have a rate limit,
  12. it will have a plain Queue object instead of a token bucket queue.
  13. The :meth:`put` operation forwards the task to its appropriate bucket,
  14. while the :meth:`get` operation iterates over the buckets and retrieves
  15. the first available item.
  16. Say we have three types of tasks in the registry: ``celery.ping``,
  17. ``feed.refresh`` and ``video.compress``, the TaskBucket will consist
  18. of the following items::
  19. {"celery.ping": TokenBucketQueue(fill_rate=300),
  20. "feed.refresh": Queue(),
  21. "video.compress": TokenBucketQueue(fill_rate=2)}
  22. The get operation will iterate over these until one of the buckets
  23. is able to return an item. The underlying datastructure is a ``dict``,
  24. so the order is ignored here.
  25. :param task_registry: The task registry used to get the task
  26. type class for a given task name.
  27. """
  28. min_wait = 0.0
  29. def __init__(self, task_registry):
  30. self.task_registry = task_registry
  31. self.buckets = {}
  32. self.init_with_registry()
  33. self.immediate = Queue()
  34. def put(self, job):
  35. """Put a task into the appropiate bucket."""
  36. if job.task_name not in self.buckets:
  37. self.add_bucket_for_type(job.task_name)
  38. self.buckets[job.task_name].put_nowait(job)
  39. put_nowait = put
  40. def _get(self):
  41. # If the first bucket is always returning items, we would never
  42. # get to fetch items from the other buckets. So we always iterate over
  43. # all the buckets and put any ready items into a queue called
  44. # "immediate". This queue is always checked for cached items first.
  45. if self.immediate:
  46. try:
  47. return 0, self.immediate.get_nowait()
  48. except QueueEmpty:
  49. pass
  50. remaining_times = []
  51. for bucket in self.buckets.values():
  52. remaining = bucket.expected_time()
  53. if not remaining:
  54. try:
  55. # Just put any ready items into the immediate queue.
  56. self.immediate.put_nowait(bucket.get_nowait())
  57. except QueueEmpty:
  58. pass
  59. except RateLimitExceeded:
  60. remaining_times.append(bucket.expected_time())
  61. else:
  62. remaining_times.append(remaining)
  63. # Try the immediate queue again.
  64. try:
  65. return 0, self.immediate.get_nowait()
  66. except QueueEmpty:
  67. if not remaining_times:
  68. # No items in any of the buckets.
  69. raise
  70. # There's items, but have to wait before we can retrieve them,
  71. # return the shortest remaining time.
  72. return min(remaining_times), None
  73. def get(self, block=True, timeout=None):
  74. """Retrive the task from the first available bucket.
  75. Available as in, there is an item in the queue and you can
  76. consume tokens from it.
  77. """
  78. time_start = time.time()
  79. did_timeout = lambda: timeout and time.time() - time_start > timeout
  80. while True:
  81. remaining_time, item = self._get()
  82. if remaining_time:
  83. if not block or did_timeout():
  84. raise QueueEmpty
  85. time.sleep(min(remaining_time, timeout or 1))
  86. else:
  87. return item
  88. def get_nowait(self):
  89. return self.get(block=False)
  90. def init_with_registry(self):
  91. """Initialize with buckets for all the task types in the registry."""
  92. map(self.add_bucket_for_type, self.task_registry.keys())
  93. def refresh(self):
  94. """Refresh rate limits for all task types in the registry."""
  95. map(self.update_bucket_for_type, self.task_registry.keys())
  96. def get_bucket_for_type(self, task_name):
  97. """Get the bucket for a particular task type."""
  98. if task_name not in self.buckets:
  99. return self.add_bucket_for_type(task_name)
  100. return self.buckets[task_name]
  101. def _get_queue_for_type(self, task_name):
  102. bucket = self.buckets[task_name]
  103. if isinstance(bucket, TokenBucketQueue):
  104. return bucket.queue
  105. return bucket
  106. def update_bucket_for_type(self, task_name):
  107. task_type = self.task_registry[task_name]
  108. rate_limit = getattr(task_type, "rate_limit", None)
  109. rate_limit = timeutils.rate(rate_limit)
  110. if task_name in self.buckets:
  111. task_queue = self._get_queue_for_type(task_name)
  112. else:
  113. task_queue = FastQueue()
  114. if rate_limit:
  115. task_queue = TokenBucketQueue(rate_limit, queue=task_queue)
  116. self.buckets[task_name] = task_queue
  117. return task_queue
  118. def add_bucket_for_type(self, task_name):
  119. """Add a bucket for a task type.
  120. Will read the tasks rate limit and create a :class:`TokenBucketQueue`
  121. if it has one. If the task doesn't have a rate limit a regular Queue
  122. will be used.
  123. """
  124. if task_name not in self.buckets:
  125. return self.update_bucket_for_type(task_name)
  126. def qsize(self):
  127. """Get the total size of all the queues."""
  128. return sum(bucket.qsize() for bucket in self.buckets.values())
  129. def empty(self):
  130. return all(bucket.empty() for bucket in self.buckets.values())
  131. def clear(self):
  132. for bucket in self.buckets.values():
  133. bucket.clear()
  134. @property
  135. def items(self):
  136. # for queues with contents [(1, 2), (3, 4), (5, 6), (7, 8)]
  137. # zips and flattens to [1, 3, 5, 7, 2, 4, 6, 8]
  138. return filter(None, chain.from_iterable(izip_longest(*[bucket.items
  139. for bucket in self.buckets.values()])))
  140. class FastQueue(Queue):
  141. """:class:`Queue.Queue` supporting the interface of
  142. :class:`TokenBucketQueue`."""
  143. def clear(self):
  144. return self.queue.clear()
  145. def expected_time(self, tokens=1):
  146. return 0
  147. def can_consume(self, tokens=1):
  148. return True
  149. def wait(self, block=True):
  150. return self.get(block=block)
  151. @property
  152. def items(self):
  153. return self.queue
  154. class TokenBucketQueue(object):
  155. """Queue with rate limited get operations.
  156. This uses the token bucket algorithm to rate limit the queue on get
  157. operations.
  158. See http://en.wikipedia.org/wiki/Token_Bucket
  159. Most of this code was stolen from an entry in the ASPN Python Cookbook:
  160. http://code.activestate.com/recipes/511490/
  161. :param fill_rate: see :attr:`fill_rate`.
  162. :keyword capacity: see :attr:`capacity`.
  163. .. attribute:: fill_rate
  164. The rate in tokens/second that the bucket will be refilled.
  165. .. attribute:: capacity
  166. Maximum number of tokens in the bucket. Default is ``1``.
  167. .. attribute:: timestamp
  168. Timestamp of the last time a token was taken out of the bucket.
  169. """
  170. RateLimitExceeded = RateLimitExceeded
  171. def __init__(self, fill_rate, queue=None, capacity=1):
  172. self.capacity = float(capacity)
  173. self._tokens = self.capacity
  174. self.queue = queue
  175. if not self.queue:
  176. self.queue = Queue()
  177. self.fill_rate = float(fill_rate)
  178. self.timestamp = time.time()
  179. def put(self, item, block=True):
  180. """Put an item into the queue.
  181. Also see :meth:`Queue.Queue.put`.
  182. """
  183. put = block and self.queue.put or self.queue.put_nowait
  184. put(item)
  185. def put_nowait(self, item):
  186. """Put an item into the queue without blocking.
  187. :raises Queue.Full: If a free slot is not immediately available.
  188. Also see :meth:`Queue.Queue.put_nowait`
  189. """
  190. return self.put(item, block=False)
  191. def get(self, block=True):
  192. """Remove and return an item from the queue.
  193. :raises RateLimitExceeded: If a token could not be consumed from the
  194. token bucket (consuming from the queue too fast).
  195. :raises Queue.Empty: If an item is not immediately available.
  196. Also see :meth:`Queue.Queue.get`.
  197. """
  198. get = block and self.queue.get or self.queue.get_nowait
  199. if not self.can_consume(1):
  200. raise RateLimitExceeded
  201. return get()
  202. def get_nowait(self):
  203. """Remove and return an item from the queue without blocking.
  204. :raises RateLimitExceeded: If a token could not be consumed from the
  205. token bucket (consuming from the queue too fast).
  206. :raises Queue.Empty: If an item is not immediately available.
  207. Also see :meth:`Queue.Queue.get_nowait`.
  208. """
  209. return self.get(block=False)
  210. def qsize(self):
  211. """Returns the size of the queue.
  212. See :meth:`Queue.Queue.qsize`.
  213. """
  214. return self.queue.qsize()
  215. def empty(self):
  216. return self.queue.empty()
  217. def clear(self):
  218. return self.items.clear()
  219. def wait(self, block=False):
  220. """Wait until a token can be retrieved from the bucket and return
  221. the next item."""
  222. while True:
  223. remaining = self.expected_time()
  224. if not remaining:
  225. return self.get(block=block)
  226. time.sleep(remaining)
  227. def can_consume(self, tokens=1):
  228. """Consume tokens from the bucket. Returns True if there were
  229. sufficient tokens otherwise False."""
  230. if tokens <= self._get_tokens():
  231. self._tokens -= tokens
  232. return True
  233. return False
  234. def expected_time(self, tokens=1):
  235. """Returns the expected time in seconds when a new token should be
  236. available."""
  237. tokens = max(tokens, self._get_tokens())
  238. return (tokens - self._get_tokens()) / self.fill_rate
  239. def _get_tokens(self):
  240. if self._tokens < self.capacity:
  241. now = time.time()
  242. delta = self.fill_rate * (now - self.timestamp)
  243. self._tokens = min(self.capacity, self._tokens + delta)
  244. self.timestamp = now
  245. return self._tokens
  246. @property
  247. def items(self):
  248. return self.queue.queue