daemon.py 2.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. from sqlalchemy.orm import collections
  2. from tracim_backend.lib.utils.logger import logger
  3. from tracim_backend.lib.utils.utils import get_rq_queue
  4. from tracim_backend.lib.utils.utils import get_redis_connection
  5. from rq.dummy import do_nothing
  6. from rq.worker import StopRequested
  7. from rq import Connection as RQConnection
  8. from rq import Worker as BaseRQWorker
  9. class FakeDaemon(object):
  10. """
  11. Temporary class for transition between tracim 1 and tracim 2
  12. """
  13. def __init__(self, config, *args, **kwargs):
  14. pass
  15. class MailSenderDaemon(FakeDaemon):
  16. # NOTE: use *args and **kwargs because parent __init__ use strange
  17. # * parameter
  18. def __init__(self, config, *args, **kwargs):
  19. super().__init__(*args, **kwargs)
  20. self.config = config
  21. self.worker = None # type: RQWorker
  22. def append_thread_callback(self, callback: collections.Callable) -> None:
  23. logger.warning('MailSenderDaemon not implement append_thread_callback')
  24. pass
  25. def stop(self) -> None:
  26. # When _stop_requested at False, tracim.lib.daemons.RQWorker
  27. # will raise StopRequested exception in worker thread after receive a
  28. # job.
  29. self.worker._stop_requested = True
  30. redis_connection = get_redis_connection(self.config)
  31. queue = get_rq_queue(redis_connection, 'mail_sender')
  32. queue.enqueue(do_nothing)
  33. def run(self) -> None:
  34. with RQConnection(get_redis_connection(self.config)):
  35. self.worker = RQWorker(['mail_sender'])
  36. self.worker.work()
  37. class RQWorker(BaseRQWorker):
  38. def _install_signal_handlers(self):
  39. # RQ Worker is designed to work in main thread
  40. # So we have to disable these signals (we implement server stop in
  41. # MailSenderDaemon.stop method).
  42. pass
  43. def dequeue_job_and_maintain_ttl(self, timeout):
  44. # RQ Worker is designed to work in main thread, so we add behaviour
  45. # here: if _stop_requested has been set to True, raise the standard way
  46. # StopRequested exception to stop worker.
  47. if self._stop_requested:
  48. raise StopRequested()
  49. return super().dequeue_job_and_maintain_ttl(timeout)