buckets.py 10 KB

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