Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

bootsteps.py 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  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.replace('_', ' ')
  115. steps = reversed(parent.steps) if reverse else parent.steps
  116. for step in steps:
  117. if step:
  118. fun = getattr(step, method, None)
  119. if fun is not None:
  120. self._debug('%s %s...',
  121. description.capitalize(), step.alias)
  122. try:
  123. fun(parent, *args)
  124. except Exception as exc:
  125. if propagate:
  126. raise
  127. logger.error(
  128. 'Error on %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. for step in values(steps):
  189. step.requires = [symbol_by_name(dep) for dep in step.requires]
  190. stream = deque(step.requires for step in values(steps))
  191. while stream:
  192. for node in stream.popleft():
  193. node = symbol_by_name(node)
  194. if node.name not in self.steps:
  195. steps[node.name] = node
  196. stream.append(node.requires)
  197. def _finalize_steps(self, steps):
  198. last = self._find_last()
  199. self._firstpass(steps)
  200. it = ((C, C.requires) for C in values(steps))
  201. G = self.graph = DependencyGraph(
  202. it, formatter=self.GraphFormatter(root=last),
  203. )
  204. if last:
  205. for obj in G:
  206. if obj != last:
  207. G.add_edge(last, obj)
  208. try:
  209. return G.topsort()
  210. except KeyError as exc:
  211. raise KeyError('unknown bootstep: %s' % exc)
  212. def claim_steps(self):
  213. return dict(self.load_step(step) for step in self._all_steps())
  214. def _all_steps(self):
  215. return self.types | self.app.steps[self.name.lower()]
  216. def load_step(self, step):
  217. step = symbol_by_name(step)
  218. return step.name, step
  219. def _debug(self, msg, *args):
  220. return debug(_pre(self, msg), *args)
  221. @property
  222. def alias(self):
  223. return _label(self)
  224. class StepType(type):
  225. """Metaclass for steps."""
  226. def __new__(cls, name, bases, attrs):
  227. module = attrs.get('__module__')
  228. qname = '{0}.{1}'.format(module, name) if module else name
  229. attrs.update(
  230. __qualname__=qname,
  231. name=attrs.get('name') or qname,
  232. )
  233. return super(StepType, cls).__new__(cls, name, bases, attrs)
  234. def __str__(self):
  235. return self.name
  236. def __repr__(self):
  237. return 'step:{0.name}{{{0.requires!r}}}'.format(self)
  238. @with_metaclass(StepType)
  239. class Step(object):
  240. """A Bootstep.
  241. The :meth:`__init__` method is called when the step
  242. is bound to a parent object, and can as such be used
  243. to initialize attributes in the parent object at
  244. parent instantiation-time.
  245. """
  246. #: Optional step name, will use qualname if not specified.
  247. name = None
  248. #: Optional short name used for graph outputs and in logs.
  249. label = None
  250. #: Set this to true if the step is enabled based on some condition.
  251. conditional = False
  252. #: List of other steps that that must be started before this step.
  253. #: Note that all dependencies must be in the same blueprint.
  254. requires = ()
  255. #: This flag is reserved for the workers Consumer,
  256. #: since it is required to always be started last.
  257. #: There can only be one object marked last
  258. #: in every blueprint.
  259. last = False
  260. #: This provides the default for :meth:`include_if`.
  261. enabled = True
  262. def __init__(self, parent, **kwargs):
  263. pass
  264. def include_if(self, parent):
  265. """An optional predicate that decides whether this
  266. step should be created."""
  267. return self.enabled
  268. def instantiate(self, name, *args, **kwargs):
  269. return instantiate(name, *args, **kwargs)
  270. def _should_include(self, parent):
  271. if self.include_if(parent):
  272. return True, self.create(parent)
  273. return False, None
  274. def include(self, parent):
  275. return self._should_include(parent)[0]
  276. def create(self, parent):
  277. """Create the step."""
  278. pass
  279. def __repr__(self):
  280. return '<step: {0.alias}>'.format(self)
  281. @property
  282. def alias(self):
  283. return self.label or _label(self)
  284. def info(self, obj):
  285. pass
  286. class StartStopStep(Step):
  287. #: Optional obj created by the :meth:`create` method.
  288. #: This is used by :class:`StartStopStep` to keep the
  289. #: original service object.
  290. obj = None
  291. def start(self, parent):
  292. if self.obj:
  293. return self.obj.start()
  294. def stop(self, parent):
  295. if self.obj:
  296. return self.obj.stop()
  297. def close(self, parent):
  298. pass
  299. def terminate(self, parent):
  300. if self.obj:
  301. return getattr(self.obj, 'terminate', self.obj.stop)()
  302. def include(self, parent):
  303. inc, ret = self._should_include(parent)
  304. if inc:
  305. self.obj = ret
  306. parent.steps.append(self)
  307. return inc
  308. class ConsumerStep(StartStopStep):
  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)