base.py 4.2 KB

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