__init__.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. # -*- coding: utf-8 -*-
  2. """
  3. celery.events
  4. ~~~~~~~~~~~~~
  5. Events is a stream of messages sent for certain actions occurring
  6. in the worker (and clients if :setting:`CELERY_SEND_TASK_SENT_EVENT`
  7. is enabled), used for monitoring purposes.
  8. """
  9. from __future__ import absolute_import
  10. import time
  11. import socket
  12. import threading
  13. from collections import deque
  14. from contextlib import contextmanager
  15. from copy import copy
  16. from kombu import Exchange, Queue, Producer
  17. from kombu.mixins import ConsumerMixin
  18. from kombu.utils import cached_property
  19. from celery.app import app_or_default
  20. from celery.utils import uuid
  21. event_exchange = Exchange('celeryev', type='topic')
  22. def get_exchange(conn):
  23. ex = copy(event_exchange)
  24. if conn.transport.driver_type == 'redis':
  25. # quick hack for Issue #436
  26. ex.type = 'fanout'
  27. return ex
  28. def Event(type, _fields=None, **fields):
  29. """Create an event.
  30. An event is a dictionary, the only required field is ``type``.
  31. """
  32. event = dict(_fields or {}, type=type, **fields)
  33. if 'timestamp' not in event:
  34. event['timestamp'] = time.time()
  35. return event
  36. class EventDispatcher(object):
  37. """Send events as messages.
  38. :param connection: Connection to the broker.
  39. :keyword hostname: Hostname to identify ourselves as,
  40. by default uses the hostname returned by :func:`socket.gethostname`.
  41. :keyword enabled: Set to :const:`False` to not actually publish any events,
  42. making :meth:`send` a noop operation.
  43. :keyword channel: Can be used instead of `connection` to specify
  44. an exact channel to use when sending events.
  45. :keyword buffer_while_offline: If enabled events will be buffered
  46. while the connection is down. :meth:`flush` must be called
  47. as soon as the connection is re-established.
  48. You need to :meth:`close` this after use.
  49. """
  50. def __init__(self, connection=None, hostname=None, enabled=True,
  51. channel=None, buffer_while_offline=True, app=None,
  52. serializer=None):
  53. self.app = app_or_default(app or self.app)
  54. self.connection = connection
  55. self.channel = channel
  56. self.hostname = hostname or socket.gethostname()
  57. self.buffer_while_offline = buffer_while_offline
  58. self.mutex = threading.Lock()
  59. self.publisher = None
  60. self._outbound_buffer = deque()
  61. self.serializer = serializer or self.app.conf.CELERY_EVENT_SERIALIZER
  62. self.on_enabled = set()
  63. self.on_disabled = set()
  64. self.tzoffset = [-time.timezone, -time.altzone]
  65. self.enabled = enabled
  66. if not connection and channel:
  67. self.connection = channel.connection.client
  68. if self.enabled:
  69. self.enable()
  70. def __enter__(self):
  71. return self
  72. def __exit__(self, *exc_info):
  73. self.close()
  74. def get_exchange(self):
  75. if self.connection:
  76. return get_exchange(self.connection)
  77. else:
  78. return get_exchange(self.channel.connection.client)
  79. def enable(self):
  80. self.publisher = Producer(self.channel or self.connection,
  81. exchange=self.get_exchange(),
  82. serializer=self.serializer)
  83. self.enabled = True
  84. for callback in self.on_enabled:
  85. callback()
  86. def disable(self):
  87. if self.enabled:
  88. self.enabled = False
  89. self.close()
  90. for callback in self.on_disabled:
  91. callback()
  92. def send(self, type, **fields):
  93. """Send event.
  94. :param type: Kind of event.
  95. :keyword \*\*fields: Event arguments.
  96. """
  97. if self.enabled:
  98. with self.mutex:
  99. event = Event(type, hostname=self.hostname,
  100. clock=self.app.clock.forward(),
  101. tzoffset=self.tzoffset, **fields)
  102. try:
  103. self.publisher.publish(event,
  104. routing_key=type.replace('-', '.'))
  105. except Exception as exc:
  106. if not self.buffer_while_offline:
  107. raise
  108. self._outbound_buffer.append((type, fields, exc))
  109. def flush(self):
  110. while self._outbound_buffer:
  111. try:
  112. type, fields, _ = self._outbound_buffer.popleft()
  113. except IndexError:
  114. return
  115. self.send(type, **fields)
  116. def copy_buffer(self, other):
  117. self._outbound_buffer = other._outbound_buffer
  118. def close(self):
  119. """Close the event dispatcher."""
  120. self.mutex.locked() and self.mutex.release()
  121. self.publisher = None
  122. class EventReceiver(ConsumerMixin):
  123. """Capture events.
  124. :param connection: Connection to the broker.
  125. :keyword handlers: Event handlers.
  126. :attr:`handlers` is a dict of event types and their handlers,
  127. the special handler `"*"` captures all events that doesn't have a
  128. handler.
  129. """
  130. def __init__(self, connection, handlers=None, routing_key='#',
  131. node_id=None, app=None, queue_prefix='celeryev'):
  132. self.app = app_or_default(app)
  133. self.connection = connection
  134. self.handlers = {} if handlers is None else handlers
  135. self.routing_key = routing_key
  136. self.node_id = node_id or uuid()
  137. self.queue_prefix = queue_prefix
  138. self.queue = Queue('.'.join([self.queue_prefix, self.node_id]),
  139. exchange=self.get_exchange(),
  140. routing_key=self.routing_key,
  141. auto_delete=True,
  142. durable=False)
  143. def get_exchange(self):
  144. return get_exchange(self.connection)
  145. def process(self, type, event):
  146. """Process the received event by dispatching it to the appropriate
  147. handler."""
  148. handler = self.handlers.get(type) or self.handlers.get('*')
  149. handler and handler(event)
  150. def get_consumers(self, Consumer, channel):
  151. return [Consumer(queues=[self.queue],
  152. callbacks=[self._receive], no_ack=True)]
  153. def on_consume_ready(self, connection, channel, consumers,
  154. wakeup=True, **kwargs):
  155. if wakeup:
  156. self.wakeup_workers(channel=channel)
  157. def itercapture(self, limit=None, timeout=None, wakeup=True):
  158. return self.consume(limit=limit, timeout=timeout, wakeup=wakeup)
  159. def capture(self, limit=None, timeout=None, wakeup=True):
  160. """Open up a consumer capturing events.
  161. This has to run in the main process, and it will never
  162. stop unless forced via :exc:`KeyboardInterrupt` or :exc:`SystemExit`.
  163. """
  164. return list(self.consume(limit=limit, timeout=timeout, wakeup=wakeup))
  165. def wakeup_workers(self, channel=None):
  166. self.app.control.broadcast('heartbeat',
  167. connection=self.connection,
  168. channel=channel)
  169. def _receive(self, body, message):
  170. type = body.pop('type').lower()
  171. clock = body.get('clock')
  172. if clock:
  173. self.app.clock.adjust(clock)
  174. self.process(type, Event(type, body))
  175. class Events(object):
  176. def __init__(self, app=None):
  177. self.app = app
  178. @cached_property
  179. def Receiver(self):
  180. return self.app.subclass_with_self(EventReceiver,
  181. reverse='events.Receiver')
  182. @cached_property
  183. def Dispatcher(self):
  184. return self.app.subclass_with_self(EventDispatcher,
  185. reverse='events.Dispatcher')
  186. @cached_property
  187. def State(self):
  188. return self.app.subclass_with_self('celery.events.state:State',
  189. reverse='events.State')
  190. @contextmanager
  191. def default_dispatcher(self, hostname=None, enabled=True,
  192. buffer_while_offline=False):
  193. with self.app.amqp.producer_pool.acquire(block=True) as pub:
  194. with self.Dispatcher(pub.connection, hostname, enabled,
  195. pub.channel, buffer_while_offline) as d:
  196. yield d