bootsteps.py 12 KB

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