snapshot.py 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. # -*- coding: utf-8 -*-
  2. """Periodically store events in a database.
  3. Consuming the events as a stream isn't always suitable
  4. so this module implements a system to take snapshots of the
  5. state of a cluster at regular intervals. There's a full
  6. implementation of this writing the snapshots to a database
  7. in :mod:`djcelery.snapshots` in the `django-celery` distribution.
  8. """
  9. from kombu.utils.limits import TokenBucket
  10. from celery import platforms
  11. from celery.app import app_or_default
  12. from celery.utils.timer2 import Timer
  13. from celery.utils.dispatch import Signal
  14. from celery.utils.imports import instantiate
  15. from celery.utils.log import get_logger
  16. from celery.utils.time import rate
  17. __all__ = ['Polaroid', 'evcam']
  18. logger = get_logger('celery.evcam')
  19. class Polaroid:
  20. """Record event snapshots."""
  21. timer = None
  22. shutter_signal = Signal(providing_args=('state',))
  23. cleanup_signal = Signal()
  24. clear_after = False
  25. _tref = None
  26. _ctref = None
  27. def __init__(self, state, freq=1.0, maxrate=None,
  28. cleanup_freq=3600.0, timer=None, app=None):
  29. self.app = app_or_default(app)
  30. self.state = state
  31. self.freq = freq
  32. self.cleanup_freq = cleanup_freq
  33. self.timer = timer or self.timer or Timer()
  34. self.logger = logger
  35. self.maxrate = maxrate and TokenBucket(rate(maxrate))
  36. def install(self):
  37. self._tref = self.timer.call_repeatedly(self.freq, self.capture)
  38. self._ctref = self.timer.call_repeatedly(
  39. self.cleanup_freq, self.cleanup,
  40. )
  41. def on_shutter(self, state):
  42. pass
  43. def on_cleanup(self):
  44. pass
  45. def cleanup(self):
  46. logger.debug('Cleanup: Running...')
  47. self.cleanup_signal.send(None)
  48. self.on_cleanup()
  49. def shutter(self):
  50. if self.maxrate is None or self.maxrate.can_consume():
  51. logger.debug('Shutter: %s', self.state)
  52. self.shutter_signal.send(self.state)
  53. self.on_shutter(self.state)
  54. def capture(self):
  55. self.state.freeze_while(self.shutter, clear_after=self.clear_after)
  56. def cancel(self):
  57. if self._tref:
  58. self._tref() # flush all received events.
  59. self._tref.cancel()
  60. if self._ctref:
  61. self._ctref.cancel()
  62. def __enter__(self):
  63. self.install()
  64. return self
  65. def __exit__(self, *exc_info):
  66. self.cancel()
  67. def evcam(camera, freq=1.0, maxrate=None, loglevel=0,
  68. logfile=None, pidfile=None, timer=None, app=None):
  69. """Start snapshot recorder."""
  70. app = app_or_default(app)
  71. if pidfile:
  72. platforms.create_pidlock(pidfile)
  73. app.log.setup_logging_subsystem(loglevel, logfile)
  74. print('-> evcam: Taking snapshots with {0} (every {1} secs.)'.format(
  75. camera, freq))
  76. state = app.events.State()
  77. cam = instantiate(camera, state, app=app, freq=freq,
  78. maxrate=maxrate, timer=timer)
  79. cam.install()
  80. conn = app.connection_for_read()
  81. recv = app.events.Receiver(conn, handlers={'*': state.event})
  82. try:
  83. try:
  84. recv.capture(limit=None)
  85. except KeyboardInterrupt:
  86. raise SystemExit
  87. finally:
  88. cam.cancel()
  89. conn.close()