bootsteps.py 11 KB

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