__init__.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  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. from __future__ import with_statement
  11. import time
  12. import socket
  13. import threading
  14. from collections import deque
  15. from contextlib import contextmanager
  16. from copy import copy
  17. from kombu.common import eventloop
  18. from kombu.entity import Exchange, Queue
  19. from kombu.messaging import Consumer, Producer
  20. from kombu.utils import cached_property
  21. from celery.app import app_or_default
  22. from celery.utils import uuid
  23. event_exchange = Exchange('celeryev', type='topic')
  24. def get_exchange(conn):
  25. ex = copy(event_exchange)
  26. if conn.transport.driver_type == 'redis':
  27. # quick hack for Issue #436
  28. ex.type = 'fanout'
  29. return ex
  30. def Event(type, _fields=None, **fields):
  31. """Create an event.
  32. An event is a dictionary, the only required field is ``type``.
  33. """
  34. event = dict(_fields or {}, type=type, **fields)
  35. if 'timestamp' not in event:
  36. event['timestamp'] = time.time()
  37. return event
  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 enabled: Set to :const:`False` to not actually publish any events,
  44. making :meth:`send` a noop operation.
  45. :keyword channel: Can be used instead of `connection` to specify
  46. an exact channel to use when sending events.
  47. :keyword buffer_while_offline: If enabled events will be buffered
  48. while the connection is down. :meth:`flush` must be called
  49. as soon as the connection is re-established.
  50. You need to :meth:`close` this after use.
  51. """
  52. def __init__(self, connection=None, hostname=None, enabled=True,
  53. channel=None, buffer_while_offline=True, app=None,
  54. serializer=None):
  55. self.app = app_or_default(app or self.app)
  56. self.connection = connection
  57. self.channel = channel
  58. self.hostname = hostname or socket.gethostname()
  59. self.buffer_while_offline = buffer_while_offline
  60. self.mutex = threading.Lock()
  61. self.publisher = None
  62. self._outbound_buffer = deque()
  63. self.serializer = serializer or self.app.conf.CELERY_EVENT_SERIALIZER
  64. self.on_enabled = set()
  65. self.on_disabled = set()
  66. self.enabled = enabled
  67. if not connection and channel:
  68. self.connection = channel.connection.client
  69. if self.enabled:
  70. self.enable()
  71. def __enter__(self):
  72. return self
  73. def __exit__(self, *exc_info):
  74. self.close()
  75. def get_exchange(self):
  76. if self.connection:
  77. return get_exchange(self.connection)
  78. else:
  79. return get_exchange(self.channel.connection.client)
  80. def enable(self):
  81. self.publisher = Producer(self.channel or self.connection,
  82. exchange=self.get_exchange(),
  83. serializer=self.serializer)
  84. self.enabled = True
  85. for callback in self.on_enabled:
  86. callback()
  87. def disable(self):
  88. if self.enabled:
  89. self.enabled = False
  90. self.close()
  91. for callback in self.on_disabled:
  92. callback()
  93. def send(self, type, **fields):
  94. """Send event.
  95. :param type: Kind of event.
  96. :keyword \*\*fields: Event arguments.
  97. """
  98. if self.enabled:
  99. with self.mutex:
  100. event = Event(type, hostname=self.hostname,
  101. clock=self.app.clock.forward(), **fields)
  102. try:
  103. self.publisher.publish(event,
  104. routing_key=type.replace('-', '.'))
  105. except Exception, 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(object):
  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. handlers = {}
  131. def __init__(self, connection, handlers=None, routing_key='#',
  132. node_id=None, app=None, queue_prefix='celeryev'):
  133. self.app = app_or_default(app)
  134. self.connection = connection
  135. if handlers is not None:
  136. self.handlers = handlers
  137. self.routing_key = routing_key
  138. self.node_id = node_id or uuid()
  139. self.queue_prefix = queue_prefix
  140. self.queue = Queue('.'.join([self.queue_prefix, self.node_id]),
  141. exchange=self.get_exchange(),
  142. routing_key=self.routing_key,
  143. auto_delete=True,
  144. durable=False)
  145. def get_exchange(self):
  146. return get_exchange(self.connection)
  147. def process(self, type, event):
  148. """Process the received event by dispatching it to the appropriate
  149. handler."""
  150. handler = self.handlers.get(type) or self.handlers.get('*')
  151. handler and handler(event)
  152. @contextmanager
  153. def consumer(self, wakeup=True):
  154. """Create event consumer."""
  155. consumer = Consumer(self.connection,
  156. queues=[self.queue], no_ack=True)
  157. consumer.register_callback(self._receive)
  158. with consumer:
  159. if wakeup:
  160. self.wakeup_workers(channel=consumer.channel)
  161. yield consumer
  162. def itercapture(self, limit=None, timeout=None, wakeup=True):
  163. with self.consumer(wakeup=wakeup) as consumer:
  164. yield consumer
  165. self.drain_events(limit=limit, timeout=timeout)
  166. def capture(self, limit=None, timeout=None, wakeup=True):
  167. """Open up a consumer capturing events.
  168. This has to run in the main process, and it will never
  169. stop unless forced via :exc:`KeyboardInterrupt` or :exc:`SystemExit`.
  170. """
  171. list(self.itercapture(limit=limit, timeout=timeout, wakeup=wakeup))
  172. def wakeup_workers(self, channel=None):
  173. self.app.control.broadcast('heartbeat',
  174. connection=self.connection,
  175. channel=channel)
  176. def drain_events(self, **kwargs):
  177. for _ in eventloop(self.connection, **kwargs):
  178. pass
  179. def _receive(self, body, message):
  180. type = body.pop('type').lower()
  181. clock = body.get('clock')
  182. if clock:
  183. self.app.clock.adjust(clock)
  184. self.process(type, Event(type, body))
  185. class Events(object):
  186. def __init__(self, app=None):
  187. self.app = app
  188. @cached_property
  189. def Receiver(self):
  190. return self.app.subclass_with_self(EventReceiver,
  191. reverse='events.Receiver')
  192. @cached_property
  193. def Dispatcher(self):
  194. return self.app.subclass_with_self(EventDispatcher,
  195. reverse='events.Dispatcher')
  196. @cached_property
  197. def State(self):
  198. return self.app.subclass_with_self('celery.events.state:State',
  199. reverse='events.State')
  200. @contextmanager
  201. def default_dispatcher(self, hostname=None, enabled=True,
  202. buffer_while_offline=False):
  203. with self.app.amqp.producer_pool.acquire(block=True) as pub:
  204. with self.Dispatcher(pub.connection, hostname, enabled,
  205. pub.channel, buffer_while_offline) as d:
  206. yield d