dumper.py 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. # -*- coding: utf-8 -*-
  2. """Utility to dump events to screen.
  3. This is a simple program that dumps events to the console
  4. as they happen. Think of it like a `tcpdump` for Celery events.
  5. """
  6. from __future__ import absolute_import, print_function, unicode_literals
  7. import sys
  8. from datetime import datetime
  9. from celery.app import app_or_default
  10. from celery.utils.functional import LRUCache
  11. from celery.utils.time import humanize_seconds
  12. __all__ = ['Dumper', 'evdump']
  13. TASK_NAMES = LRUCache(limit=0xFFF)
  14. HUMAN_TYPES = {
  15. 'worker-offline': 'shutdown',
  16. 'worker-online': 'started',
  17. 'worker-heartbeat': 'heartbeat',
  18. }
  19. CONNECTION_ERROR = """\
  20. -> Cannot connect to %s: %s.
  21. Trying again %s
  22. """
  23. def humanize_type(type):
  24. try:
  25. return HUMAN_TYPES[type.lower()]
  26. except KeyError:
  27. return type.lower().replace('-', ' ')
  28. class Dumper(object):
  29. """Monitor events."""
  30. def __init__(self, out=sys.stdout):
  31. self.out = out
  32. def say(self, msg):
  33. print(msg, file=self.out)
  34. # need to flush so that output can be piped.
  35. try:
  36. self.out.flush()
  37. except AttributeError: # pragma: no cover
  38. pass
  39. def on_event(self, ev):
  40. timestamp = datetime.utcfromtimestamp(ev.pop('timestamp'))
  41. type = ev.pop('type').lower()
  42. hostname = ev.pop('hostname')
  43. if type.startswith('task-'):
  44. uuid = ev.pop('uuid')
  45. if type in ('task-received', 'task-sent'):
  46. task = TASK_NAMES[uuid] = '{0}({1}) args={2} kwargs={3}' \
  47. .format(ev.pop('name'), uuid,
  48. ev.pop('args'),
  49. ev.pop('kwargs'))
  50. else:
  51. task = TASK_NAMES.get(uuid, '')
  52. return self.format_task_event(hostname, timestamp,
  53. type, task, ev)
  54. fields = ', '.join(
  55. '{0}={1}'.format(key, ev[key]) for key in sorted(ev)
  56. )
  57. sep = fields and ':' or ''
  58. self.say('{0} [{1}] {2}{3} {4}'.format(
  59. hostname, timestamp, humanize_type(type), sep, fields),
  60. )
  61. def format_task_event(self, hostname, timestamp, type, task, event):
  62. fields = ', '.join(
  63. '{0}={1}'.format(key, event[key]) for key in sorted(event)
  64. )
  65. sep = fields and ':' or ''
  66. self.say('{0} [{1}] {2}{3} {4} {5}'.format(
  67. hostname, timestamp, humanize_type(type), sep, task, fields),
  68. )
  69. def evdump(app=None, out=sys.stdout):
  70. """Start event dump."""
  71. app = app_or_default(app)
  72. dumper = Dumper(out=out)
  73. dumper.say('-> evdump: starting capture...')
  74. conn = app.connection_for_read().clone()
  75. def _error_handler(exc, interval):
  76. dumper.say(CONNECTION_ERROR % (
  77. conn.as_uri(), exc, humanize_seconds(interval, 'in', ' ')
  78. ))
  79. while 1:
  80. try:
  81. conn.ensure_connection(_error_handler)
  82. recv = app.events.Receiver(conn, handlers={'*': dumper.on_event})
  83. recv.capture()
  84. except (KeyboardInterrupt, SystemExit):
  85. return conn and conn.close()
  86. except conn.connection_errors + conn.channel_errors:
  87. dumper.say('-> Connection lost, attempting reconnect')
  88. if __name__ == '__main__': # pragma: no cover
  89. evdump()