buckets.py 10 KB

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