buckets.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. import threading
  2. from collections import deque
  3. from time import time, sleep
  4. from Queue import Queue, Empty
  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.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:
  53. raise Empty()
  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 Empty:
  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 Empty:
  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 Empty:
  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()
  92. did_timeout = lambda: timeout and time() - time_start > timeout
  93. self.not_empty.acquire()
  94. try:
  95. while True:
  96. try:
  97. remaining_time, item = self._get()
  98. except Empty:
  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 Empty()
  106. 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
  148. :class:`FastQueue` will be used instead.
  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. """Returns :const:`True` if all of the buckets are empty."""
  157. return all(bucket.empty() for bucket in self.buckets.values())
  158. def clear(self):
  159. """Delete the data in all of the buckets."""
  160. for bucket in self.buckets.values():
  161. bucket.clear()
  162. @property
  163. def items(self):
  164. """Flattens the data in all of the buckets into a single list."""
  165. # for queues with contents [(1, 2), (3, 4), (5, 6), (7, 8)]
  166. # zips and flattens to [1, 3, 5, 7, 2, 4, 6, 8]
  167. return filter(None, chain_from_iterable(izip_longest(*[bucket.items
  168. for bucket in self.buckets.values()])))
  169. class FastQueue(Queue):
  170. """:class:`Queue.Queue` supporting the interface of
  171. :class:`TokenBucketQueue`."""
  172. def clear(self):
  173. return self.queue.clear()
  174. def expected_time(self, tokens=1):
  175. return 0
  176. def wait(self, block=True):
  177. return self.get(block=block)
  178. @property
  179. def items(self):
  180. return self.queue
  181. class TokenBucketQueue(object):
  182. """Queue with rate limited get operations.
  183. This uses the token bucket algorithm to rate limit the queue on get
  184. operations.
  185. :param fill_rate: The rate in tokens/second that the bucket will
  186. be refilled.
  187. :keyword capacity: Maximum number of tokens in the bucket.
  188. Default is 1.
  189. """
  190. RateLimitExceeded = RateLimitExceeded
  191. def __init__(self, fill_rate, queue=None, capacity=1):
  192. self._bucket = TokenBucket(fill_rate, capacity)
  193. self.queue = queue
  194. if not self.queue:
  195. self.queue = Queue()
  196. def put(self, item, block=True):
  197. """Put an item onto the queue."""
  198. self.queue.put(item, block=block)
  199. def put_nowait(self, item):
  200. """Put an item into the queue without blocking.
  201. :raises Queue.Full: If a free slot is not immediately available.
  202. """
  203. return self.put(item, block=False)
  204. def get(self, block=True):
  205. """Remove and return an item from the queue.
  206. :raises RateLimitExceeded: If a token could not be consumed from the
  207. token bucket (consuming from the queue
  208. too fast).
  209. :raises Queue.Empty: If an item is not immediately available.
  210. """
  211. get = block and self.queue.get or self.queue.get_nowait
  212. if not self._bucket.can_consume(1):
  213. raise RateLimitExceeded()
  214. return get()
  215. def get_nowait(self):
  216. """Remove and return an item from the queue without blocking.
  217. :raises RateLimitExceeded: If a token could not be consumed from the
  218. token bucket (consuming from the queue
  219. too fast).
  220. :raises Queue.Empty: If an item is not immediately available.
  221. """
  222. return self.get(block=False)
  223. def qsize(self):
  224. """Returns the size of the queue."""
  225. return self.queue.qsize()
  226. def empty(self):
  227. """Returns :const:`True` if the queue is empty."""
  228. return self.queue.empty()
  229. def clear(self):
  230. """Delete all data in the queue."""
  231. return self.items.clear()
  232. def wait(self, block=False):
  233. """Wait until a token can be retrieved from the bucket and return
  234. the next item."""
  235. while True:
  236. remaining = self.expected_time()
  237. if not remaining:
  238. return self.get(block=block)
  239. sleep(remaining)
  240. def expected_time(self, tokens=1):
  241. """Returns the expected time in seconds of when a new token should be
  242. available."""
  243. return self._bucket.expected_time(tokens)
  244. @property
  245. def items(self):
  246. """Underlying data. Do not modify."""
  247. return self.queue.queue