bootsteps.py 12 KB

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