Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

mixins.py 7.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. # -*- coding: utf-8 -*-
  2. """
  3. kombu.mixins
  4. ============
  5. Useful mixin classes.
  6. """
  7. from __future__ import absolute_import
  8. import socket
  9. from contextlib import contextmanager
  10. from functools import partial
  11. from itertools import count
  12. from time import sleep
  13. from .common import ignore_errors
  14. from .five import range
  15. from .messaging import Consumer
  16. from .log import get_logger
  17. from .utils import cached_property, nested
  18. from .utils.encoding import safe_repr
  19. from .utils.limits import TokenBucket
  20. __all__ = ['ConsumerMixin']
  21. logger = get_logger(__name__)
  22. debug, info, warn, error = logger.debug, logger.info, logger.warn, logger.error
  23. W_CONN_LOST = """\
  24. Connection to broker lost, trying to re-establish connection...\
  25. """
  26. W_CONN_ERROR = """\
  27. Broker connection error, trying again in %s seconds: %r.\
  28. """
  29. class ConsumerMixin(object):
  30. """Convenience mixin for implementing consumer programs.
  31. It can be used outside of threads, with threads, or greenthreads
  32. (eventlet/gevent) too.
  33. The basic class would need a :attr:`connection` attribute
  34. which must be a :class:`~kombu.Connection` instance,
  35. and define a :meth:`get_consumers` method that returns a list
  36. of :class:`kombu.Consumer` instances to use.
  37. Supporting multiple consumers is important so that multiple
  38. channels can be used for different QoS requirements.
  39. **Example**:
  40. .. code-block:: python
  41. class Worker(ConsumerMixin):
  42. task_queue = Queue('tasks', Exchange('tasks'), 'tasks'))
  43. def __init__(self, connection):
  44. self.connection = None
  45. def get_consumers(self, Consumer, channel):
  46. return [Consumer(queues=[self.task_queue],
  47. callbacks=[self.on_task])]
  48. def on_task(self, body, message):
  49. print('Got task: {0!r}'.format(body))
  50. message.ack()
  51. **Additional handler methods**:
  52. * :meth:`extra_context`
  53. Optional extra context manager that will be entered
  54. after the connection and consumers have been set up.
  55. Takes arguments ``(connection, channel)``.
  56. * :meth:`on_connection_error`
  57. Handler called if the connection is lost/ or
  58. is unavailable.
  59. Takes arguments ``(exc, interval)``, where interval
  60. is the time in seconds when the connection will be retried.
  61. The default handler will log the exception.
  62. * :meth:`on_connection_revived`
  63. Handler called as soon as the connection is re-established
  64. after connection failure.
  65. Takes no arguments.
  66. * :meth:`on_consume_ready`
  67. Handler called when the consumer is ready to accept
  68. messages.
  69. Takes arguments ``(connection, channel, consumers)``.
  70. Also keyword arguments to ``consume`` are forwarded
  71. to this handler.
  72. * :meth:`on_consume_end`
  73. Handler called after the consumers are cancelled.
  74. Takes arguments ``(connection, channel)``.
  75. * :meth:`on_iteration`
  76. Handler called for every iteration while draining
  77. events.
  78. Takes no arguments.
  79. * :meth:`on_decode_error`
  80. Handler called if a consumer was unable to decode
  81. the body of a message.
  82. Takes arguments ``(message, exc)`` where message is the
  83. original message object.
  84. The default handler will log the error and
  85. acknowledge the message, so if you override make
  86. sure to call super, or perform these steps yourself.
  87. """
  88. #: maximum number of retries trying to re-establish the connection,
  89. #: if the connection is lost/unavailable.
  90. connect_max_retries = None
  91. #: When this is set to true the consumer should stop consuming
  92. #: and return, so that it can be joined if it is the implementation
  93. #: of a thread.
  94. should_stop = False
  95. def get_consumers(self, Consumer, channel):
  96. raise NotImplementedError('Subclass responsibility')
  97. def on_connection_revived(self):
  98. pass
  99. def on_consume_ready(self, connection, channel, consumers, **kwargs):
  100. pass
  101. def on_consume_end(self, connection, channel):
  102. pass
  103. def on_iteration(self):
  104. pass
  105. def on_decode_error(self, message, exc):
  106. error("Can't decode message body: %r (type:%r encoding:%r raw:%r')",
  107. exc, message.content_type, message.content_encoding,
  108. safe_repr(message.body))
  109. message.ack()
  110. def on_connection_error(self, exc, interval):
  111. warn(W_CONN_ERROR, interval, exc, exc_info=1)
  112. @contextmanager
  113. def extra_context(self, connection, channel):
  114. yield
  115. def run(self, _tokens=1):
  116. restart_limit = self.restart_limit
  117. errors = (self.connection.connection_errors +
  118. self.connection.channel_errors)
  119. while not self.should_stop:
  120. try:
  121. if restart_limit.can_consume(_tokens):
  122. for _ in self.consume(limit=None): # pragma: no cover
  123. pass
  124. else:
  125. sleep(restart_limit.expected_time(_tokens))
  126. except errors:
  127. warn(W_CONN_LOST, exc_info=1)
  128. @contextmanager
  129. def consumer_context(self, **kwargs):
  130. with self.Consumer() as (connection, channel, consumers):
  131. with self.extra_context(connection, channel):
  132. self.on_consume_ready(connection, channel, consumers, **kwargs)
  133. yield connection, channel, consumers
  134. def consume(self, limit=None, timeout=None, safety_interval=1, **kwargs):
  135. elapsed = 0
  136. with self.consumer_context(**kwargs) as (conn, channel, consumers):
  137. for i in limit and range(limit) or count():
  138. if self.should_stop:
  139. break
  140. self.on_iteration()
  141. try:
  142. conn.drain_events(timeout=safety_interval)
  143. except socket.timeout:
  144. conn.heartbeat_check()
  145. elapsed += safety_interval
  146. if timeout and elapsed >= timeout:
  147. raise
  148. except socket.error:
  149. if not self.should_stop:
  150. raise
  151. else:
  152. yield
  153. elapsed = 0
  154. debug('consume exiting')
  155. def maybe_conn_error(self, fun):
  156. """Use :func:`kombu.common.ignore_errors` instead."""
  157. return ignore_errors(self, fun)
  158. def create_connection(self):
  159. return self.connection.clone()
  160. @contextmanager
  161. def establish_connection(self):
  162. with self.create_connection() as conn:
  163. conn.ensure_connection(self.on_connection_error,
  164. self.connect_max_retries)
  165. yield conn
  166. @contextmanager
  167. def Consumer(self):
  168. with self.establish_connection() as conn:
  169. self.on_connection_revived()
  170. info('Connected to %s', conn.as_uri())
  171. channel = conn.default_channel
  172. cls = partial(Consumer, channel,
  173. on_decode_error=self.on_decode_error)
  174. with self._consume_from(*self.get_consumers(cls, channel)) as c:
  175. yield conn, channel, c
  176. debug('Consumers cancelled')
  177. self.on_consume_end(conn, channel)
  178. debug('Connection closed')
  179. def _consume_from(self, *consumers):
  180. return nested(*consumers)
  181. @cached_property
  182. def restart_limit(self):
  183. # the AttributeError that can be catched from amqplib
  184. # poses problems for the too often restarts protection
  185. # in Connection.ensure_connection
  186. return TokenBucket(1)
  187. @cached_property
  188. def connection_errors(self):
  189. return self.connection.connection_errors
  190. @cached_property
  191. def channel_errors(self):
  192. return self.connection.channel_errors