buckets.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. from __future__ import absolute_import
  2. from __future__ import with_statement
  3. import threading
  4. from collections import deque
  5. from time import time, sleep
  6. from Queue import Queue, Empty
  7. from celery.datastructures import TokenBucket
  8. from celery.utils import timeutils
  9. from celery.utils.compat import izip_longest, chain_from_iterable
  10. class RateLimitExceeded(Exception):
  11. """The token buckets rate limit has been exceeded."""
  12. class TaskBucket(object):
  13. """This is a collection of token buckets, each task type having
  14. its own token bucket. If the task type doesn't have a rate limit,
  15. it will have a plain :class:`~Queue.Queue` object instead of a
  16. :class:`TokenBucketQueue`.
  17. The :meth:`put` operation forwards the task to its appropriate bucket,
  18. while the :meth:`get` operation iterates over the buckets and retrieves
  19. the first available item.
  20. Say we have three types of tasks in the registry: `celery.ping`,
  21. `feed.refresh` and `video.compress`, the TaskBucket will consist
  22. of the following items::
  23. {"celery.ping": TokenBucketQueue(fill_rate=300),
  24. "feed.refresh": Queue(),
  25. "video.compress": TokenBucketQueue(fill_rate=2)}
  26. The get operation will iterate over these until one of the buckets
  27. is able to return an item. The underlying datastructure is a `dict`,
  28. so the order is ignored here.
  29. :param task_registry: The task registry used to get the task
  30. type class for a given task name.
  31. """
  32. def __init__(self, task_registry):
  33. self.task_registry = task_registry
  34. self.buckets = {}
  35. self.init_with_registry()
  36. self.immediate = deque()
  37. self.mutex = threading.Lock()
  38. self.not_empty = threading.Condition(self.mutex)
  39. def put(self, request):
  40. """Put a :class:`~celery.worker.job.TaskRequest` into
  41. the appropiate bucket."""
  42. with self.mutex:
  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. put_nowait = put
  48. def _get_immediate(self):
  49. try:
  50. return self.immediate.popleft()
  51. except IndexError:
  52. raise Empty()
  53. def _get(self):
  54. # If the first bucket is always returning items, we would never
  55. # get to fetch items from the other buckets. So we always iterate over
  56. # all the buckets and put any ready items into a queue called
  57. # "immediate". This queue is always checked for cached items first.
  58. try:
  59. return 0, self._get_immediate()
  60. except Empty:
  61. pass
  62. remaining_times = []
  63. for bucket in self.buckets.values():
  64. remaining = bucket.expected_time()
  65. if not remaining:
  66. try:
  67. # Just put any ready items into the immediate queue.
  68. self.immediate.append(bucket.get_nowait())
  69. except Empty:
  70. pass
  71. except RateLimitExceeded:
  72. remaining_times.append(bucket.expected_time())
  73. else:
  74. remaining_times.append(remaining)
  75. # Try the immediate queue again.
  76. try:
  77. return 0, self._get_immediate()
  78. except Empty:
  79. if not remaining_times:
  80. # No items in any of the buckets.
  81. raise
  82. # There's items, but have to wait before we can retrieve them,
  83. # return the shortest remaining time.
  84. return min(remaining_times), None
  85. def get(self, block=True, timeout=None):
  86. """Retrive the task from the first available bucket.
  87. Available as in, there is an item in the queue and you can
  88. consume tokens from it.
  89. """
  90. time_start = time()
  91. did_timeout = lambda: timeout and time() - time_start > timeout
  92. with self.not_empty:
  93. while True:
  94. try:
  95. remaining_time, item = self._get()
  96. except Empty:
  97. if not block or did_timeout():
  98. raise
  99. self.not_empty.wait(timeout)
  100. continue
  101. if remaining_time:
  102. if not block or did_timeout():
  103. raise Empty()
  104. sleep(min(remaining_time, timeout or 1))
  105. else:
  106. return item
  107. def get_nowait(self):
  108. return self.get(block=False)
  109. def init_with_registry(self):
  110. """Initialize with buckets for all the task types in the registry."""
  111. for task in self.task_registry.keys():
  112. self.add_bucket_for_type(task)
  113. def refresh(self):
  114. """Refresh rate limits for all task types in the registry."""
  115. for task in self.task_registry.keys():
  116. self.update_bucket_for_type(task)
  117. def get_bucket_for_type(self, task_name):
  118. """Get the bucket for a particular task type."""
  119. if task_name not in self.buckets:
  120. return self.add_bucket_for_type(task_name)
  121. return self.buckets[task_name]
  122. def _get_queue_for_type(self, task_name):
  123. bucket = self.buckets[task_name]
  124. if isinstance(bucket, TokenBucketQueue):
  125. return bucket.queue
  126. return bucket
  127. def update_bucket_for_type(self, task_name):
  128. task_type = self.task_registry[task_name]
  129. rate_limit = getattr(task_type, "rate_limit", None)
  130. rate_limit = timeutils.rate(rate_limit)
  131. task_queue = FastQueue()
  132. if task_name in self.buckets:
  133. task_queue = self._get_queue_for_type(task_name)
  134. else:
  135. task_queue = FastQueue()
  136. if rate_limit:
  137. task_queue = TokenBucketQueue(rate_limit, queue=task_queue)
  138. self.buckets[task_name] = task_queue
  139. return task_queue
  140. def add_bucket_for_type(self, task_name):
  141. """Add a bucket for a task type.
  142. Will read the tasks rate limit and create a :class:`TokenBucketQueue`
  143. if it has one. If the task doesn't have a rate limit
  144. :class:`FastQueue` will be used instead.
  145. """
  146. if task_name not in self.buckets:
  147. return self.update_bucket_for_type(task_name)
  148. def qsize(self):
  149. """Get the total size of all the queues."""
  150. return sum(bucket.qsize() for bucket in self.buckets.values())
  151. def empty(self):
  152. """Returns :const:`True` if all of the buckets are empty."""
  153. return all(bucket.empty() for bucket in self.buckets.values())
  154. def clear(self):
  155. """Delete the data in all of the buckets."""
  156. for bucket in self.buckets.values():
  157. bucket.clear()
  158. @property
  159. def items(self):
  160. """Flattens the data in all of the buckets into a single list."""
  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.
  184. 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 onto the queue."""
  194. self.queue.put(item, block=block)
  195. def put_nowait(self, item):
  196. """Put an item into the queue without blocking.
  197. :raises Queue.Full: If a free slot is not immediately available.
  198. """
  199. return self.put(item, block=False)
  200. def get(self, block=True):
  201. """Remove and return an item from the queue.
  202. :raises RateLimitExceeded: If a token could not be consumed from the
  203. token bucket (consuming from the queue
  204. too fast).
  205. :raises Queue.Empty: If an item is not immediately available.
  206. """
  207. get = block and self.queue.get or self.queue.get_nowait
  208. if not block and not self.items:
  209. raise Empty()
  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
  217. too fast).
  218. :raises Queue.Empty: If an item is not immediately available.
  219. """
  220. return self.get(block=False)
  221. def qsize(self):
  222. """Returns the size of the queue."""
  223. return self.queue.qsize()
  224. def empty(self):
  225. """Returns :const:`True` if the queue is empty."""
  226. return self.queue.empty()
  227. def clear(self):
  228. """Delete all data in the queue."""
  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. get = self.get
  234. expected_time = self.expected_time
  235. while 1:
  236. remaining = expected_time()
  237. if not remaining:
  238. return 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. if not self.items:
  244. return 0
  245. return self._bucket.expected_time(tokens)
  246. @property
  247. def items(self):
  248. """Underlying data. Do not modify."""
  249. return self.queue.queue