bootsteps.py 11 KB

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