base.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. # -*- coding: utf-8 -*-
  2. """
  3. celery.concurrency.base
  4. ~~~~~~~~~~~~~~~~~~~~~~~
  5. TaskPool interface.
  6. """
  7. from __future__ import absolute_import
  8. import logging
  9. import os
  10. import sys
  11. from billiard.einfo import ExceptionInfo
  12. from billiard.exceptions import WorkerLostError
  13. from kombu.utils.encoding import safe_repr
  14. from celery.exceptions import WorkerShutdown, WorkerTerminate
  15. from celery.five import monotonic, reraise
  16. from celery.utils import timer2
  17. from celery.utils.text import truncate
  18. from celery.utils.log import get_logger
  19. __all__ = ['BasePool', 'apply_target']
  20. logger = get_logger('celery.pool')
  21. def apply_target(target, args=(), kwargs={}, callback=None,
  22. accept_callback=None, pid=None, getpid=os.getpid,
  23. propagate=(), monotonic=monotonic, **_):
  24. if accept_callback:
  25. accept_callback(pid or getpid(), monotonic())
  26. try:
  27. ret = target(*args, **kwargs)
  28. except propagate:
  29. raise
  30. except Exception:
  31. raise
  32. except (WorkerShutdown, WorkerTerminate):
  33. raise
  34. except BaseException as exc:
  35. try:
  36. reraise(WorkerLostError, WorkerLostError(repr(exc)),
  37. sys.exc_info()[2])
  38. except WorkerLostError:
  39. callback(ExceptionInfo())
  40. else:
  41. callback(ret)
  42. class BasePool(object):
  43. RUN = 0x1
  44. CLOSE = 0x2
  45. TERMINATE = 0x3
  46. Timer = timer2.Timer
  47. #: set to true if the pool can be shutdown from within
  48. #: a signal handler.
  49. signal_safe = True
  50. #: set to true if pool uses greenlets.
  51. is_green = False
  52. _state = None
  53. _pool = None
  54. _does_debug = True
  55. #: only used by multiprocessing pool
  56. uses_semaphore = False
  57. task_join_will_block = True
  58. body_can_be_buffer = False
  59. def __init__(self, limit=None, putlocks=True,
  60. forking_enable=True, callbacks_propagate=(), **options):
  61. self.limit = limit
  62. self.putlocks = putlocks
  63. self.options = options
  64. self.forking_enable = forking_enable
  65. self.callbacks_propagate = callbacks_propagate
  66. def on_start(self):
  67. pass
  68. def did_start_ok(self):
  69. return True
  70. def flush(self):
  71. pass
  72. def on_stop(self):
  73. pass
  74. def register_with_event_loop(self, loop):
  75. pass
  76. def on_apply(self, *args, **kwargs):
  77. pass
  78. def on_terminate(self):
  79. pass
  80. def on_soft_timeout(self, job):
  81. pass
  82. def on_hard_timeout(self, job):
  83. pass
  84. def maintain_pool(self, *args, **kwargs):
  85. pass
  86. def terminate_job(self, pid, signal=None):
  87. raise NotImplementedError(
  88. '{0} does not implement kill_job'.format(type(self)))
  89. def restart(self):
  90. raise NotImplementedError(
  91. '{0} does not implement restart'.format(type(self)))
  92. def stop(self):
  93. self.on_stop()
  94. self._state = self.TERMINATE
  95. def terminate(self):
  96. self._state = self.TERMINATE
  97. self.on_terminate()
  98. def start(self):
  99. self._does_debug = logger.isEnabledFor(logging.DEBUG)
  100. self.on_start()
  101. self._state = self.RUN
  102. def close(self):
  103. self._state = self.CLOSE
  104. self.on_close()
  105. def on_close(self):
  106. pass
  107. def apply_async(self, target, args=[], kwargs={}, **options):
  108. """Equivalent of the :func:`apply` built-in function.
  109. Callbacks should optimally return as soon as possible since
  110. otherwise the thread which handles the result will get blocked.
  111. """
  112. if self._does_debug:
  113. logger.debug('TaskPool: Apply %s (args:%s kwargs:%s)',
  114. target, truncate(safe_repr(args), 1024),
  115. truncate(safe_repr(kwargs), 1024))
  116. return self.on_apply(target, args, kwargs,
  117. waitforslot=self.putlocks,
  118. callbacks_propagate=self.callbacks_propagate,
  119. **options)
  120. def _get_info(self):
  121. return {}
  122. @property
  123. def info(self):
  124. return self._get_info()
  125. @property
  126. def active(self):
  127. return self._state == self.RUN
  128. @property
  129. def num_processes(self):
  130. return self.limit