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.

__init__.py 14KB

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