base.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. # -*- coding: utf-8 -*-
  2. """
  3. celery.concurrency.base
  4. ~~~~~~~~~~~~~~~~~~~~~~~
  5. TaskPool interface.
  6. """
  7. from __future__ import absolute_import, unicode_literals
  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, forking_enable=True,
  60. callbacks_propagate=(), app=None, **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. self.app = app
  67. def on_start(self):
  68. pass
  69. def did_start_ok(self):
  70. return True
  71. def flush(self):
  72. pass
  73. def on_stop(self):
  74. pass
  75. def register_with_event_loop(self, loop):
  76. pass
  77. def on_apply(self, *args, **kwargs):
  78. pass
  79. def on_terminate(self):
  80. pass
  81. def on_soft_timeout(self, job):
  82. pass
  83. def on_hard_timeout(self, job):
  84. pass
  85. def maintain_pool(self, *args, **kwargs):
  86. pass
  87. def terminate_job(self, pid, signal=None):
  88. raise NotImplementedError(
  89. '{0} does not implement kill_job'.format(type(self)))
  90. def restart(self):
  91. raise NotImplementedError(
  92. '{0} does not implement restart'.format(type(self)))
  93. def stop(self):
  94. self.on_stop()
  95. self._state = self.TERMINATE
  96. def terminate(self):
  97. self._state = self.TERMINATE
  98. self.on_terminate()
  99. def start(self):
  100. self._does_debug = logger.isEnabledFor(logging.DEBUG)
  101. self.on_start()
  102. self._state = self.RUN
  103. def close(self):
  104. self._state = self.CLOSE
  105. self.on_close()
  106. def on_close(self):
  107. pass
  108. def apply_async(self, target, args=[], kwargs={}, **options):
  109. """Equivalent of the :func:`apply` built-in function.
  110. Callbacks should optimally return as soon as possible since
  111. otherwise the thread which handles the result will get blocked.
  112. """
  113. if self._does_debug:
  114. logger.debug('TaskPool: Apply %s (args:%s kwargs:%s)',
  115. target, truncate(safe_repr(args), 1024),
  116. truncate(safe_repr(kwargs), 1024))
  117. return self.on_apply(target, args, kwargs,
  118. waitforslot=self.putlocks,
  119. callbacks_propagate=self.callbacks_propagate,
  120. **options)
  121. def _get_info(self):
  122. return {
  123. 'max-concurrency': self.limit,
  124. }
  125. @property
  126. def info(self):
  127. return self._get_info()
  128. @property
  129. def active(self):
  130. return self._state == self.RUN
  131. @property
  132. def num_processes(self):
  133. return self.limit