__init__.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  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. def domain(type):
  37. return type.split('-', 1)
  38. class EventDispatcher(object):
  39. """Send events as messages.
  40. :param connection: Connection to the broker.
  41. :keyword hostname: Hostname to identify ourselves as,
  42. by default uses the hostname returned by :func:`socket.gethostname`.
  43. :keyword domains: List of domains to send events for. :meth:`send` will
  44. ignore send requests to domains not in this list.
  45. If this is :const:`None`, all events will be sent.
  46. :keyword enabled: Set to :const:`False` to not actually publish any events,
  47. making :meth:`send` a noop operation.
  48. :keyword channel: Can be used instead of `connection` to specify
  49. an exact channel to use when sending events.
  50. :keyword buffer_while_offline: If enabled events will be buffered
  51. while the connection is down. :meth:`flush` must be called
  52. as soon as the connection is re-established.
  53. You need to :meth:`close` this after use.
  54. """
  55. DISABLED_TRANSPORTS = set(['sql'])
  56. def __init__(self, connection=None, hostname=None, enabled=True,
  57. channel=None, buffer_while_offline=True, app=None,
  58. serializer=None, domains=None):
  59. self.app = app_or_default(app or self.app)
  60. self.connection = connection
  61. self.channel = channel
  62. self.hostname = hostname or socket.gethostname()
  63. self.buffer_while_offline = buffer_while_offline
  64. self.mutex = threading.Lock()
  65. self.publisher = None
  66. self._outbound_buffer = deque()
  67. self.serializer = serializer or self.app.conf.CELERY_EVENT_SERIALIZER
  68. self.on_enabled = set()
  69. self.on_disabled = set()
  70. self.tzoffset = [-time.timezone, -time.altzone]
  71. self.domains = set(domains or [])
  72. if not connection and channel:
  73. self.connection = channel.connection.client
  74. self.enabled = enabled
  75. if self.connection.transport.driver_type in self.DISABLED_TRANSPORTS:
  76. self.enabled = False
  77. if self.enabled:
  78. self.enable()
  79. def __enter__(self):
  80. return self
  81. def __exit__(self, *exc_info):
  82. self.close()
  83. def get_exchange(self):
  84. if self.connection:
  85. return get_exchange(self.connection)
  86. else:
  87. return get_exchange(self.channel.connection.client)
  88. def enable(self):
  89. self.publisher = Producer(self.channel or self.connection,
  90. exchange=self.get_exchange(),
  91. serializer=self.serializer)
  92. self.enabled = True
  93. for callback in self.on_enabled:
  94. callback()
  95. def disable(self):
  96. if self.enabled:
  97. self.enabled = False
  98. self.close()
  99. for callback in self.on_disabled:
  100. callback()
  101. def send(self, type, **fields):
  102. """Send event.
  103. :param type: Kind of event.
  104. :keyword \*\*fields: Event arguments.
  105. """
  106. if self.enabled:
  107. domains = self.domains
  108. if domains and domain(type) not in domains:
  109. return
  110. with self.mutex:
  111. event = Event(type, hostname=self.hostname,
  112. clock=self.app.clock.forward(),
  113. tzoffset=self.tzoffset, **fields)
  114. try:
  115. self.publisher.publish(event,
  116. routing_key=type.replace('-', '.'))
  117. except Exception as exc:
  118. if not self.buffer_while_offline:
  119. raise
  120. self._outbound_buffer.append((type, fields, exc))
  121. def flush(self):
  122. while self._outbound_buffer:
  123. try:
  124. type, fields, _ = self._outbound_buffer.popleft()
  125. except IndexError:
  126. return
  127. self.send(type, **fields)
  128. def copy_buffer(self, other):
  129. self._outbound_buffer = other._outbound_buffer
  130. def close(self):
  131. """Close the event dispatcher."""
  132. self.mutex.locked() and self.mutex.release()
  133. self.publisher = None
  134. class EventReceiver(ConsumerMixin):
  135. """Capture events.
  136. :param connection: Connection to the broker.
  137. :keyword handlers: Event handlers.
  138. :attr:`handlers` is a dict of event types and their handlers,
  139. the special handler `"*"` captures all events that doesn't have a
  140. handler.
  141. """
  142. def __init__(self, connection, handlers=None, routing_key='#',
  143. node_id=None, app=None, queue_prefix='celeryev'):
  144. self.app = app_or_default(app)
  145. self.connection = connection
  146. self.handlers = {} if handlers is None else handlers
  147. self.routing_key = routing_key
  148. self.node_id = node_id or uuid()
  149. self.queue_prefix = queue_prefix
  150. self.queue = Queue('.'.join([self.queue_prefix, self.node_id]),
  151. exchange=self.get_exchange(),
  152. routing_key=self.routing_key,
  153. auto_delete=True,
  154. durable=False)
  155. def get_exchange(self):
  156. return get_exchange(self.connection)
  157. def process(self, type, event):
  158. """Process the received event by dispatching it to the appropriate
  159. handler."""
  160. handler = self.handlers.get(type) or self.handlers.get('*')
  161. handler and handler(event)
  162. def get_consumers(self, Consumer, channel):
  163. return [Consumer(queues=[self.queue],
  164. callbacks=[self._receive], no_ack=True)]
  165. def on_consume_ready(self, connection, channel, consumers,
  166. wakeup=True, **kwargs):
  167. if wakeup:
  168. self.wakeup_workers(channel=channel)
  169. def itercapture(self, limit=None, timeout=None, wakeup=True):
  170. return self.consume(limit=limit, timeout=timeout, wakeup=wakeup)
  171. def capture(self, limit=None, timeout=None, wakeup=True):
  172. """Open up a consumer capturing events.
  173. This has to run in the main process, and it will never
  174. stop unless forced via :exc:`KeyboardInterrupt` or :exc:`SystemExit`.
  175. """
  176. return list(self.consume(limit=limit, timeout=timeout, wakeup=wakeup))
  177. def wakeup_workers(self, channel=None):
  178. self.app.control.broadcast('heartbeat',
  179. connection=self.connection,
  180. channel=channel)
  181. def _receive(self, body, message):
  182. type = body.pop('type').lower()
  183. clock = body.get('clock')
  184. if clock:
  185. self.app.clock.adjust(clock)
  186. self.process(type, Event(type, body))
  187. class Events(object):
  188. def __init__(self, app=None):
  189. self.app = app
  190. @cached_property
  191. def Receiver(self):
  192. return self.app.subclass_with_self(EventReceiver,
  193. reverse='events.Receiver')
  194. @cached_property
  195. def Dispatcher(self):
  196. return self.app.subclass_with_self(EventDispatcher,
  197. reverse='events.Dispatcher')
  198. @cached_property
  199. def State(self):
  200. return self.app.subclass_with_self('celery.events.state:State',
  201. reverse='events.State')
  202. @contextmanager
  203. def default_dispatcher(self, hostname=None, enabled=True,
  204. buffer_while_offline=False):
  205. with self.app.amqp.producer_pool.acquire(block=True) as pub:
  206. with self.Dispatcher(pub.connection, hostname, enabled,
  207. pub.channel, buffer_while_offline) as d:
  208. yield d