bootsteps.py 12 KB

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