bootsteps.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. # -*- coding: utf-8 -*-
  2. """
  3. celery.bootsteps
  4. ~~~~~~~~~~~~~~~~
  5. A directed acyclic graph of reusable components.
  6. """
  7. from __future__ import absolute_import, unicode_literals
  8. from collections import deque
  9. from threading import Event
  10. from kombu.common import ignore_errors
  11. from kombu.utils import symbol_by_name
  12. from .datastructures import DependencyGraph, GraphFormatter
  13. from .five import values, with_metaclass
  14. from .utils.imports import instantiate, qualname
  15. from .utils.log import get_logger
  16. from .utils.threads import default_socket_timeout
  17. try:
  18. from greenlet import GreenletExit
  19. IGNORE_ERRORS = (GreenletExit, )
  20. except ImportError: # pragma: no cover
  21. IGNORE_ERRORS = ()
  22. #: Default socket timeout at shutdown.
  23. SHUTDOWN_SOCKET_TIMEOUT = 5.0
  24. #: States
  25. RUN = 0x1
  26. CLOSE = 0x2
  27. TERMINATE = 0x3
  28. logger = get_logger(__name__)
  29. debug = logger.debug
  30. def _pre(ns, fmt):
  31. return '| {0}: {1}'.format(ns.alias, fmt)
  32. def _label(s):
  33. return s.name.rsplit('.', 1)[-1]
  34. class StepFormatter(GraphFormatter):
  35. """Graph formatter for :class:`Blueprint`."""
  36. blueprint_prefix = '⧉'
  37. conditional_prefix = '∘'
  38. blueprint_scheme = {
  39. 'shape': 'parallelogram',
  40. 'color': 'slategray4',
  41. 'fillcolor': 'slategray3',
  42. }
  43. def label(self, step):
  44. return step and '{0}{1}'.format(
  45. self._get_prefix(step),
  46. (step.label or _label(step)).encode('utf-8', 'ignore'),
  47. )
  48. def _get_prefix(self, step):
  49. if step.last:
  50. return self.blueprint_prefix
  51. if step.conditional:
  52. return self.conditional_prefix
  53. return ''
  54. def node(self, obj, **attrs):
  55. scheme = self.blueprint_scheme if obj.last else self.node_scheme
  56. return self.draw_node(obj, scheme, attrs)
  57. def edge(self, a, b, **attrs):
  58. if a.last:
  59. attrs.update(arrowhead='none', color='darkseagreen3')
  60. return self.draw_edge(a, b, self.edge_scheme, attrs)
  61. class Blueprint(object):
  62. """Blueprint containing bootsteps that can be applied to objects.
  63. :keyword steps: List of steps.
  64. :keyword name: Set explicit name for this blueprint.
  65. :keyword app: Set the Celery app for this blueprint.
  66. :keyword on_start: Optional callback applied after blueprint start.
  67. :keyword on_close: Optional callback applied before blueprint close.
  68. :keyword on_stopped: Optional callback applied after blueprint stopped.
  69. """
  70. GraphFormatter = StepFormatter
  71. name = None
  72. state = None
  73. started = 0
  74. default_steps = set()
  75. def __init__(self, steps=None, name=None, app=None,
  76. on_start=None, on_close=None, on_stopped=None):
  77. self.app = app
  78. self.name = name or self.name or qualname(type(self))
  79. self.types = set(steps or []) | set(self.default_steps)
  80. self.on_start = on_start
  81. self.on_close = on_close
  82. self.on_stopped = on_stopped
  83. self.shutdown_complete = Event()
  84. self.steps = {}
  85. def start(self, parent):
  86. self.state = RUN
  87. if self.on_start:
  88. self.on_start()
  89. for i, step in enumerate(s for s in parent.steps if s is not None):
  90. self._debug('Starting %s', step.alias)
  91. self.started = i + 1
  92. step.start(parent)
  93. debug('^-- substep ok')
  94. def info(self, parent):
  95. info = {}
  96. for step in parent.steps:
  97. info.update(step.info(parent) or {})
  98. return info
  99. def close(self, parent):
  100. if self.on_close:
  101. self.on_close()
  102. self.send_all(parent, 'close', 'Closing', reverse=False)
  103. def restart(self, parent, method='stop', description='Restarting'):
  104. self.send_all(parent, method, description)
  105. def send_all(self, parent, method, description=None, reverse=True):
  106. description = description or method.capitalize()
  107. steps = reversed(parent.steps) if reverse else parent.steps
  108. with default_socket_timeout(SHUTDOWN_SOCKET_TIMEOUT): # Issue 975
  109. for step in steps:
  110. if step:
  111. self._debug('%s %s...', description, step.alias)
  112. fun = getattr(step, method, None)
  113. if fun:
  114. fun(parent)
  115. def stop(self, parent, close=True, terminate=False):
  116. what = 'Terminating' if terminate else 'Stopping'
  117. if self.state in (CLOSE, TERMINATE):
  118. return
  119. if self.state != RUN or self.started != len(parent.steps):
  120. # Not fully started, can safely exit.
  121. self.state = TERMINATE
  122. self.shutdown_complete.set()
  123. return
  124. self.close(parent)
  125. self.state = CLOSE
  126. self.restart(parent, 'terminate' if terminate else 'stop', what)
  127. if self.on_stopped:
  128. self.on_stopped()
  129. self.state = TERMINATE
  130. self.shutdown_complete.set()
  131. def join(self, timeout=None):
  132. try:
  133. # Will only get here if running green,
  134. # makes sure all greenthreads have exited.
  135. self.shutdown_complete.wait(timeout=timeout)
  136. except IGNORE_ERRORS:
  137. pass
  138. def apply(self, parent, **kwargs):
  139. """Apply the steps in this blueprint to an object.
  140. This will apply the ``__init__`` and ``include`` methods
  141. of each step, with the object as argument::
  142. step = Step(obj)
  143. ...
  144. step.include(obj)
  145. For :class:`StartStopStep` the services created
  146. will also be added to the objects ``steps`` attribute.
  147. """
  148. self._debug('Preparing bootsteps.')
  149. order = self.order = []
  150. steps = self.steps = self.claim_steps()
  151. self._debug('Building graph...')
  152. for S in self._finalize_steps(steps):
  153. step = S(parent, **kwargs)
  154. steps[step.name] = step
  155. order.append(step)
  156. self._debug('New boot order: {%s}',
  157. ', '.join(s.alias for s in self.order))
  158. for step in order:
  159. step.include(parent)
  160. return self
  161. def connect_with(self, other):
  162. self.graph.adjacent.update(other.graph.adjacent)
  163. self.graph.add_edge(type(other.order[0]), type(self.order[-1]))
  164. def __getitem__(self, name):
  165. return self.steps[name]
  166. def _find_last(self):
  167. for C in values(self.steps):
  168. if C.last:
  169. return C
  170. def _firstpass(self, steps):
  171. stream = deque(step.requires for step in values(steps))
  172. while stream:
  173. for node in stream.popleft():
  174. node = symbol_by_name(node)
  175. if node.name not in self.steps:
  176. steps[node.name] = node
  177. stream.append(node.requires)
  178. def _finalize_steps(self, steps):
  179. last = self._find_last()
  180. self._firstpass(steps)
  181. it = ((C, C.requires) for C in values(steps))
  182. G = self.graph = DependencyGraph(
  183. it, formatter=self.GraphFormatter(root=last),
  184. )
  185. if last:
  186. for obj in G:
  187. if obj != last:
  188. G.add_edge(last, obj)
  189. try:
  190. return G.topsort()
  191. except KeyError as exc:
  192. raise KeyError('unknown bootstep: %s' % exc)
  193. def claim_steps(self):
  194. return dict(self.load_step(step) for step in self._all_steps())
  195. def _all_steps(self):
  196. return self.types | self.app.steps[self.name.lower()]
  197. def load_step(self, step):
  198. step = symbol_by_name(step)
  199. return step.name, step
  200. def _debug(self, msg, *args):
  201. return debug(_pre(self, msg), *args)
  202. @property
  203. def alias(self):
  204. return _label(self)
  205. class StepType(type):
  206. """Metaclass for steps."""
  207. def __new__(cls, name, bases, attrs):
  208. module = attrs.get('__module__')
  209. qname = '{0}.{1}'.format(module, name) if module else name
  210. attrs.update(
  211. __qualname__=qname,
  212. name=attrs.get('name') or qname,
  213. requires=attrs.get('requires', ()),
  214. )
  215. return super(StepType, cls).__new__(cls, name, bases, attrs)
  216. def __str__(self):
  217. return self.name
  218. def __repr__(self):
  219. return 'step:{0.name}{{{0.requires!r}}}'.format(self)
  220. @with_metaclass(StepType)
  221. class Step(object):
  222. """A Bootstep.
  223. The :meth:`__init__` method is called when the step
  224. is bound to a parent object, and can as such be used
  225. to initialize attributes in the parent object at
  226. parent instantiation-time.
  227. """
  228. #: Optional step name, will use qualname if not specified.
  229. name = None
  230. #: Optional short name used for graph outputs and in logs.
  231. label = None
  232. #: Set this to true if the step is enabled based on some condition.
  233. conditional = False
  234. #: List of other steps that that must be started before this step.
  235. #: Note that all dependencies must be in the same blueprint.
  236. requires = ()
  237. #: This flag is reserved for the workers Consumer,
  238. #: since it is required to always be started last.
  239. #: There can only be one object marked last
  240. #: in every blueprint.
  241. last = False
  242. #: This provides the default for :meth:`include_if`.
  243. enabled = True
  244. def __init__(self, parent, **kwargs):
  245. pass
  246. def include_if(self, parent):
  247. """An optional predicate that decided whether this
  248. step should be created."""
  249. return self.enabled
  250. def instantiate(self, name, *args, **kwargs):
  251. return instantiate(name, *args, **kwargs)
  252. def _should_include(self, parent):
  253. if self.include_if(parent):
  254. return True, self.create(parent)
  255. return False, None
  256. def include(self, parent):
  257. return self._should_include(parent)[0]
  258. def create(self, parent):
  259. """Create the step."""
  260. pass
  261. def __repr__(self):
  262. return '<step: {0.alias}>'.format(self)
  263. @property
  264. def alias(self):
  265. return self.label or _label(self)
  266. def info(self, obj):
  267. pass
  268. class StartStopStep(Step):
  269. #: Optional obj created by the :meth:`create` method.
  270. #: This is used by :class:`StartStopStep` to keep the
  271. #: original service object.
  272. obj = None
  273. def start(self, parent):
  274. if self.obj:
  275. return self.obj.start()
  276. def stop(self, parent):
  277. if self.obj:
  278. return self.obj.stop()
  279. def close(self, parent):
  280. pass
  281. def terminate(self, parent):
  282. self.stop(parent)
  283. def include(self, parent):
  284. inc, ret = self._should_include(parent)
  285. if inc:
  286. self.obj = ret
  287. parent.steps.append(self)
  288. return inc
  289. class ConsumerStep(StartStopStep):
  290. requires = ('Connection', )
  291. consumers = None
  292. def get_consumers(self, channel):
  293. raise NotImplementedError('missing get_consumers')
  294. def start(self, c):
  295. self.consumers = self.get_consumers(c.connection)
  296. for consumer in self.consumers or []:
  297. consumer.consume()
  298. def stop(self, c):
  299. for consumer in self.consumers or []:
  300. ignore_errors(c.connection, consumer.cancel)
  301. def shutdown(self, c):
  302. self.stop(c)
  303. for consumer in self.consumers or []:
  304. if consumer.channel:
  305. ignore_errors(c.connection, consumer.channel.close)