__init__.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  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 os
  11. import time
  12. import threading
  13. import warnings
  14. from collections import deque
  15. from contextlib import contextmanager
  16. from copy import copy
  17. from operator import itemgetter
  18. from kombu import Exchange, Queue, Producer
  19. from kombu.connection import maybe_channel
  20. from kombu.mixins import ConsumerMixin
  21. from kombu.utils import cached_property
  22. from celery.app import app_or_default
  23. from celery.utils import anon_nodename, uuid
  24. from celery.utils.functional import dictfilter
  25. from celery.utils.timeutils import adjust_timestamp, utcoffset, maybe_s_to_ms
  26. __all__ = ['Events', 'Event', 'EventDispatcher', 'EventReceiver']
  27. event_exchange = Exchange('celeryev', type='topic')
  28. _TZGETTER = itemgetter('utcoffset', 'timestamp')
  29. W_YAJL = """
  30. anyjson is currently using the yajl library.
  31. This json implementation is broken, it severely truncates floats
  32. so timestamps will not work.
  33. Please uninstall yajl or force anyjson to use a different library.
  34. """
  35. def get_exchange(conn):
  36. ex = copy(event_exchange)
  37. if conn.transport.driver_type == 'redis':
  38. # quick hack for Issue #436
  39. ex.type = 'fanout'
  40. return ex
  41. def Event(type, _fields=None, __dict__=dict, __now__=time.time, **fields):
  42. """Create an event.
  43. An event is a dictionary, the only required field is ``type``.
  44. A ``timestamp`` field will be set to the current time if not provided.
  45. """
  46. event = __dict__(_fields, **fields) if _fields else fields
  47. if 'timestamp' not in event:
  48. event.update(timestamp=__now__(), type=type)
  49. else:
  50. event['type'] = type
  51. return event
  52. def group_from(type):
  53. """Get the group part of an event type name.
  54. E.g.::
  55. >>> group_from('task-sent')
  56. 'task'
  57. >>> group_from('custom-my-event')
  58. 'custom'
  59. """
  60. return type.split('-', 1)[0]
  61. class EventDispatcher(object):
  62. """Dispatches event messages.
  63. :param connection: Connection to the broker.
  64. :keyword hostname: Hostname to identify ourselves as,
  65. by default uses the hostname returned by
  66. :func:`~celery.utils.anon_nodename`.
  67. :keyword groups: List of groups to send events for. :meth:`send` will
  68. ignore send requests to groups not in this list.
  69. If this is :const:`None`, all events will be sent. Example groups
  70. include ``"task"`` and ``"worker"``.
  71. :keyword enabled: Set to :const:`False` to not actually publish any events,
  72. making :meth:`send` a noop operation.
  73. :keyword channel: Can be used instead of `connection` to specify
  74. an exact channel to use when sending events.
  75. :keyword buffer_while_offline: If enabled events will be buffered
  76. while the connection is down. :meth:`flush` must be called
  77. as soon as the connection is re-established.
  78. You need to :meth:`close` this after use.
  79. """
  80. DISABLED_TRANSPORTS = set(['sql'])
  81. app = None
  82. # set of callbacks to be called when :meth:`enabled`.
  83. on_enabled = None
  84. # set of callbacks to be called when :meth:`disabled`.
  85. on_disabled = None
  86. def __init__(self, connection=None, hostname=None, enabled=True,
  87. channel=None, buffer_while_offline=True, app=None,
  88. serializer=None, groups=None):
  89. self.app = app_or_default(app or self.app)
  90. self.connection = connection
  91. self.channel = channel
  92. self.hostname = hostname or anon_nodename()
  93. self.buffer_while_offline = buffer_while_offline
  94. self.mutex = threading.Lock()
  95. self.producer = None
  96. self._outbound_buffer = deque()
  97. self.serializer = serializer or self.app.conf.CELERY_EVENT_SERIALIZER
  98. self.on_enabled = set()
  99. self.on_disabled = set()
  100. self.groups = set(groups or [])
  101. self.tzoffset = [-time.timezone, -time.altzone]
  102. self.clock = self.app.clock
  103. if not connection and channel:
  104. self.connection = channel.connection.client
  105. self.enabled = enabled
  106. conninfo = self.connection or self.app.connection()
  107. self.exchange = get_exchange(conninfo)
  108. if conninfo.transport.driver_type in self.DISABLED_TRANSPORTS:
  109. self.enabled = False
  110. if self.enabled:
  111. self.enable()
  112. self.headers = {'hostname': self.hostname}
  113. self.pid = os.getpid()
  114. self.warn_if_yajl()
  115. def warn_if_yajl(self):
  116. import anyjson
  117. if anyjson.implementation.name == 'yajl':
  118. warnings.warn(UserWarning(W_YAJL))
  119. def __enter__(self):
  120. return self
  121. def __exit__(self, *exc_info):
  122. self.close()
  123. def enable(self):
  124. self.producer = Producer(self.channel or self.connection,
  125. exchange=self.exchange,
  126. serializer=self.serializer)
  127. self.enabled = True
  128. for callback in self.on_enabled:
  129. callback()
  130. def disable(self):
  131. if self.enabled:
  132. self.enabled = False
  133. self.close()
  134. for callback in self.on_disabled:
  135. callback()
  136. def publish(self, type, fields, producer, retry=False,
  137. retry_policy=None, blind=False, utcoffset=utcoffset,
  138. Event=Event):
  139. """Publish event using a custom :class:`~kombu.Producer`
  140. instance.
  141. :param type: Event type name, with group separated by dash (`-`).
  142. :param fields: Dictionary of event fields, must be json serializable.
  143. :param producer: :class:`~kombu.Producer` instance to use,
  144. only the ``publish`` method will be called.
  145. :keyword retry: Retry in the event of connection failure.
  146. :keyword retry_policy: Dict of custom retry policy, see
  147. :meth:`~kombu.Connection.ensure`.
  148. :keyword blind: Don't set logical clock value (also do not forward
  149. the internal logical clock).
  150. :keyword Event: Event type used to create event,
  151. defaults to :func:`Event`.
  152. :keyword utcoffset: Function returning the current utcoffset in hours.
  153. """
  154. with self.mutex:
  155. clock = None if blind else self.clock.forward()
  156. event = Event(type, hostname=self.hostname, utcoffset=utcoffset(),
  157. pid=self.pid, clock=clock, **fields)
  158. exchange = self.exchange
  159. producer.publish(
  160. event,
  161. routing_key=type.replace('-', '.'),
  162. exchange=exchange.name,
  163. retry=retry,
  164. retry_policy=retry_policy,
  165. declare=[exchange],
  166. serializer=self.serializer,
  167. headers=self.headers,
  168. )
  169. def send(self, type, blind=False, **fields):
  170. """Send event.
  171. :param type: Event type name, with group separated by dash (`-`).
  172. :keyword retry: Retry in the event of connection failure.
  173. :keyword retry_policy: Dict of custom retry policy, see
  174. :meth:`~kombu.Connection.ensure`.
  175. :keyword blind: Don't set logical clock value (also do not forward
  176. the internal logical clock).
  177. :keyword Event: Event type used to create event,
  178. defaults to :func:`Event`.
  179. :keyword utcoffset: Function returning the current utcoffset in hours.
  180. :keyword \*\*fields: Event fields, must be json serializable.
  181. """
  182. if self.enabled:
  183. groups = self.groups
  184. if groups and group_from(type) not in groups:
  185. return
  186. try:
  187. self.publish(type, fields, self.producer, blind)
  188. except Exception as exc:
  189. if not self.buffer_while_offline:
  190. raise
  191. self._outbound_buffer.append((type, fields, exc))
  192. def flush(self):
  193. """Flushes the outbound buffer."""
  194. while self._outbound_buffer:
  195. try:
  196. type, fields, _ = self._outbound_buffer.popleft()
  197. except IndexError:
  198. return
  199. self.send(type, **fields)
  200. def extend_buffer(self, other):
  201. """Copies the outbound buffer of another instance."""
  202. self._outbound_buffer.extend(other._outbound_buffer)
  203. def close(self):
  204. """Close the event dispatcher."""
  205. self.mutex.locked() and self.mutex.release()
  206. self.producer = None
  207. def _get_publisher(self):
  208. return self.producer
  209. def _set_publisher(self, producer):
  210. self.producer = producer
  211. publisher = property(_get_publisher, _set_publisher) # XXX compat
  212. class EventReceiver(ConsumerMixin):
  213. """Capture events.
  214. :param connection: Connection to the broker.
  215. :keyword handlers: Event handlers.
  216. :attr:`handlers` is a dict of event types and their handlers,
  217. the special handler `"*"` captures all events that doesn't have a
  218. handler.
  219. """
  220. app = None
  221. def __init__(self, channel, handlers=None, routing_key='#',
  222. node_id=None, app=None, queue_prefix='celeryev'):
  223. self.app = app_or_default(app or self.app)
  224. self.channel = maybe_channel(channel)
  225. self.handlers = {} if handlers is None else handlers
  226. self.routing_key = routing_key
  227. self.node_id = node_id or uuid()
  228. self.queue_prefix = queue_prefix
  229. self.exchange = get_exchange(self.connection or self.app.connection())
  230. self.queue = Queue('.'.join([self.queue_prefix, self.node_id]),
  231. exchange=self.exchange,
  232. routing_key=self.routing_key,
  233. auto_delete=True,
  234. durable=False,
  235. queue_arguments=self._get_queue_arguments())
  236. self.adjust_clock = self.app.clock.adjust
  237. def _get_queue_arguments(self):
  238. conf = self.app.conf
  239. return dictfilter({
  240. 'x-message-ttl': maybe_s_to_ms(conf.CELERY_EVENT_QUEUE_TTL),
  241. 'x-expires': maybe_s_to_ms(conf.CELERY_EVENT_QUEUE_EXPIRES),
  242. })
  243. def process(self, type, event):
  244. """Process the received event by dispatching it to the appropriate
  245. handler."""
  246. handler = self.handlers.get(type) or self.handlers.get('*')
  247. handler and handler(event)
  248. def get_consumers(self, Consumer, channel):
  249. return [Consumer(queues=[self.queue],
  250. callbacks=[self._receive], no_ack=True,
  251. accept=['application/json'])]
  252. def on_consume_ready(self, connection, channel, consumers,
  253. wakeup=True, **kwargs):
  254. if wakeup:
  255. self.wakeup_workers(channel=channel)
  256. def itercapture(self, limit=None, timeout=None, wakeup=True):
  257. return self.consume(limit=limit, timeout=timeout, wakeup=wakeup)
  258. def capture(self, limit=None, timeout=None, wakeup=True):
  259. """Open up a consumer capturing events.
  260. This has to run in the main process, and it will never
  261. stop unless forced via :exc:`KeyboardInterrupt` or :exc:`SystemExit`.
  262. """
  263. return list(self.consume(limit=limit, timeout=timeout, wakeup=wakeup))
  264. def wakeup_workers(self, channel=None):
  265. self.app.control.broadcast('heartbeat',
  266. connection=self.connection,
  267. channel=channel)
  268. def event_from_message(self, body, localize=True,
  269. now=time.time, tzfields=_TZGETTER,
  270. adjust_timestamp=adjust_timestamp):
  271. type = body.get('type', '').lower()
  272. clock = body.get('clock')
  273. if clock:
  274. self.adjust_clock(clock)
  275. if localize:
  276. try:
  277. offset, timestamp = tzfields(body)
  278. except KeyError:
  279. pass
  280. else:
  281. body['timestamp'] = adjust_timestamp(timestamp, offset)
  282. return type, Event(type, body, local_received=now())
  283. def _receive(self, body, message):
  284. self.process(*self.event_from_message(body))
  285. @property
  286. def connection(self):
  287. return self.channel.connection.client if self.channel else None
  288. class Events(object):
  289. def __init__(self, app=None):
  290. self.app = app
  291. @cached_property
  292. def Receiver(self):
  293. return self.app.subclass_with_self(EventReceiver,
  294. reverse='events.Receiver')
  295. @cached_property
  296. def Dispatcher(self):
  297. return self.app.subclass_with_self(EventDispatcher,
  298. reverse='events.Dispatcher')
  299. @cached_property
  300. def State(self):
  301. return self.app.subclass_with_self('celery.events.state:State',
  302. reverse='events.State')
  303. @contextmanager
  304. def default_dispatcher(self, hostname=None, enabled=True,
  305. buffer_while_offline=False):
  306. with self.app.amqp.producer_pool.acquire(block=True) as prod:
  307. with self.Dispatcher(prod.connection, hostname, enabled,
  308. prod.channel, buffer_while_offline) as d:
  309. yield d