canvas.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. # -*- coding: utf-8 -*-
  2. """
  3. celery.canvas
  4. ~~~~~~~~~~~~~
  5. Composing task workflows.
  6. Documentation for these functions are in :mod:`celery`.
  7. You should not import from this module directly.
  8. """
  9. from __future__ import absolute_import
  10. from future_builtins import map
  11. from operator import itemgetter
  12. from itertools import chain as _chain
  13. from kombu.utils import fxrange, kwdict, reprcall
  14. from celery import current_app
  15. from celery.local import Proxy
  16. from celery.utils import cached_property, uuid
  17. from celery.utils.functional import (
  18. maybe_list, is_list, regen,
  19. chunks as _chunks,
  20. )
  21. from celery.utils.text import truncate
  22. Chord = Proxy(lambda: current_app.tasks['celery.chord'])
  23. class _getitem_property(object):
  24. def __init__(self, key):
  25. self.key = key
  26. def __get__(self, obj, type=None):
  27. if obj is None:
  28. return type
  29. return obj.get(self.key)
  30. def __set__(self, obj, value):
  31. obj[self.key] = value
  32. class Signature(dict):
  33. """Class that wraps the arguments and execution options
  34. for a single task invocation.
  35. Used as the parts in a :class:`group` or to safely
  36. pass tasks around as callbacks.
  37. :param task: Either a task class/instance, or the name of a task.
  38. :keyword args: Positional arguments to apply.
  39. :keyword kwargs: Keyword arguments to apply.
  40. :keyword options: Additional options to :meth:`Task.apply_async`.
  41. Note that if the first argument is a :class:`dict`, the other
  42. arguments will be ignored and the values in the dict will be used
  43. instead.
  44. >>> s = subtask('tasks.add', args=(2, 2))
  45. >>> subtask(s)
  46. {'task': 'tasks.add', args=(2, 2), kwargs={}, options={}}
  47. """
  48. TYPES = {}
  49. _type = None
  50. @classmethod
  51. def register_type(cls, subclass, name=None):
  52. cls.TYPES[name or subclass.__name__] = subclass
  53. return subclass
  54. @classmethod
  55. def from_dict(self, d):
  56. typ = d.get('subtask_type')
  57. if typ:
  58. return self.TYPES[typ].from_dict(kwdict(d))
  59. return Signature(d)
  60. def __init__(self, task=None, args=None, kwargs=None, options=None,
  61. type=None, subtask_type=None, immutable=False, **ex):
  62. init = dict.__init__
  63. if isinstance(task, dict):
  64. return init(self, task) # works like dict(d)
  65. # Also supports using task class/instance instead of string name.
  66. try:
  67. task_name = task.name
  68. except AttributeError:
  69. task_name = task
  70. else:
  71. self._type = task
  72. init(self, task=task_name, args=tuple(args or ()),
  73. kwargs=kwargs or {},
  74. options=dict(options or {}, **ex),
  75. subtask_type=subtask_type,
  76. immutable=immutable)
  77. def __call__(self, *partial_args, **partial_kwargs):
  78. return self.apply_async(partial_args, partial_kwargs)
  79. delay = __call__
  80. def apply(self, args=(), kwargs={}, **options):
  81. """Apply this task locally."""
  82. # For callbacks: extra args are prepended to the stored args.
  83. args, kwargs, options = self._merge(args, kwargs, options)
  84. return self.type.apply(args, kwargs, **options)
  85. def _merge(self, args=(), kwargs={}, options={}):
  86. if self.immutable:
  87. return self.args, self.kwargs, dict(self.options, **options)
  88. return (tuple(args) + tuple(self.args) if args else self.args,
  89. dict(self.kwargs, **kwargs) if kwargs else self.kwargs,
  90. dict(self.options, **options) if options else self.options)
  91. def clone(self, args=(), kwargs={}, **options):
  92. args, kwargs, options = self._merge(args, kwargs, options)
  93. s = Signature.from_dict({'task': self.task, 'args': args,
  94. 'kwargs': kwargs, 'options': options,
  95. 'subtask_type': self.subtask_type,
  96. 'immutable': self.immutable})
  97. s._type = self._type
  98. return s
  99. partial = clone
  100. def replace(self, args=None, kwargs=None, options=None):
  101. s = self.clone()
  102. if args is not None:
  103. s.args = args
  104. if kwargs is not None:
  105. s.kwargs = kwargs
  106. if options is not None:
  107. s.options = options
  108. return s
  109. def set(self, immutable=None, **options):
  110. if immutable is not None:
  111. self.immutable = immutable
  112. self.options.update(options)
  113. return self
  114. def apply_async(self, args=(), kwargs={}, **options):
  115. # For callbacks: extra args are prepended to the stored args.
  116. args, kwargs, options = self._merge(args, kwargs, options)
  117. return self.type.apply_async(args, kwargs, **options)
  118. def append_to_list_option(self, key, value):
  119. items = self.options.setdefault(key, [])
  120. if value not in items:
  121. items.append(value)
  122. return value
  123. def link(self, callback):
  124. return self.append_to_list_option('link', callback)
  125. def link_error(self, errback):
  126. return self.append_to_list_option('link_error', errback)
  127. def flatten_links(self):
  128. return list(_chain.from_iterable(_chain([[self]],
  129. (link.flatten_links()
  130. for link in maybe_list(self.options.get('link')) or []))))
  131. def __or__(self, other):
  132. if isinstance(other, chain):
  133. return chain(*self.tasks + other.tasks)
  134. elif isinstance(other, Signature):
  135. if isinstance(self, chain):
  136. return chain(*self.tasks + (other, ))
  137. return chain(self, other)
  138. return NotImplemented
  139. def __invert__(self):
  140. return self.apply_async().get()
  141. def __reduce__(self):
  142. # for serialization, the task type is lazily loaded,
  143. # and not stored in the dict itself.
  144. return subtask, (dict(self), )
  145. def reprcall(self, *args, **kwargs):
  146. args, kwargs, _ = self._merge(args, kwargs, {})
  147. return reprcall(self['task'], args, kwargs)
  148. def __repr__(self):
  149. return self.reprcall()
  150. @cached_property
  151. def type(self):
  152. return self._type or current_app.tasks[self['task']]
  153. task = _getitem_property('task')
  154. args = _getitem_property('args')
  155. kwargs = _getitem_property('kwargs')
  156. options = _getitem_property('options')
  157. subtask_type = _getitem_property('subtask_type')
  158. immutable = _getitem_property('immutable')
  159. class chain(Signature):
  160. def __init__(self, *tasks, **options):
  161. tasks = tasks[0] if len(tasks) == 1 and is_list(tasks[0]) else tasks
  162. Signature.__init__(self,
  163. 'celery.chain', (), {'tasks': tasks}, **options)
  164. self.tasks = tasks
  165. self.subtask_type = 'chain'
  166. def __call__(self, *args, **kwargs):
  167. return self.apply_async(args, kwargs)
  168. @classmethod
  169. def from_dict(self, d):
  170. return chain(*d['kwargs']['tasks'], **kwdict(d['options']))
  171. def __repr__(self):
  172. return ' | '.join(map(repr, self.tasks))
  173. Signature.register_type(chain)
  174. class _basemap(Signature):
  175. _task_name = None
  176. _unpack_args = itemgetter('task', 'it')
  177. def __init__(self, task, it, **options):
  178. Signature.__init__(self, self._task_name, (),
  179. {'task': task, 'it': regen(it)}, immutable=True, **options)
  180. def apply_async(self, args=(), kwargs={}, **opts):
  181. # need to evaluate generators
  182. task, it = self._unpack_args(self.kwargs)
  183. return self.type.apply_async((),
  184. {'task': task, 'it': list(it)}, **opts)
  185. @classmethod
  186. def from_dict(self, d):
  187. return chunks(*self._unpack_args(d['kwargs']), **d['options'])
  188. class xmap(_basemap):
  189. _task_name = 'celery.map'
  190. def __repr__(self):
  191. task, it = self._unpack_args(self.kwargs)
  192. return '[{0}(x) for x in {1}]'.format(task.task,
  193. truncate(repr(it), 100))
  194. Signature.register_type(xmap)
  195. class xstarmap(_basemap):
  196. _task_name = 'celery.starmap'
  197. def __repr__(self):
  198. task, it = self._unpack_args(self.kwargs)
  199. return '[{0}(*x) for x in {1}]'.format(task.task,
  200. truncate(repr(it), 100))
  201. Signature.register_type(xstarmap)
  202. class chunks(Signature):
  203. _unpack_args = itemgetter('task', 'it', 'n')
  204. def __init__(self, task, it, n, **options):
  205. Signature.__init__(self, 'celery.chunks', (),
  206. {'task': task, 'it': regen(it), 'n': n},
  207. immutable=True, **options)
  208. @classmethod
  209. def from_dict(self, d):
  210. return chunks(*self._unpack_args(d['kwargs']), **d['options'])
  211. def apply_async(self, args=(), kwargs={}, **opts):
  212. return self.group().apply_async(args, kwargs, **opts)
  213. def __call__(self, **options):
  214. return self.group()(**options)
  215. def group(self):
  216. # need to evaluate generators
  217. task, it, n = self._unpack_args(self.kwargs)
  218. return group(xstarmap(task, part) for part in _chunks(iter(it), n))
  219. @classmethod
  220. def apply_chunks(cls, task, it, n):
  221. return cls(task, it, n)()
  222. Signature.register_type(chunks)
  223. def _maybe_group(tasks):
  224. if isinstance(tasks, group):
  225. tasks = list(tasks.tasks)
  226. else:
  227. tasks = regen(tasks if is_list(tasks) else tasks)
  228. return tasks
  229. class group(Signature):
  230. def __init__(self, *tasks, **options):
  231. if len(tasks) == 1:
  232. tasks = _maybe_group(tasks[0])
  233. Signature.__init__(self,
  234. 'celery.group', (), {'tasks': tasks}, **options)
  235. self.tasks, self.subtask_type = tasks, 'group'
  236. @classmethod
  237. def from_dict(self, d):
  238. return group(d['kwargs']['tasks'], **kwdict(d['options']))
  239. def __call__(self, *partial_args, **options):
  240. tasks, result, gid, args = self.type.prepare(options,
  241. [Signature.clone(t) for t in self.tasks], partial_args)
  242. return self.type(tasks, result, gid, args)
  243. def skew(self, start=1.0, stop=None, step=1.0):
  244. _next_skew = fxrange(start, stop, step, repeatlast=True).next
  245. for task in self.tasks:
  246. task.set(countdown=_next_skew())
  247. return self
  248. def __iter__(self):
  249. return iter(self.tasks)
  250. def __repr__(self):
  251. return repr(self.tasks)
  252. Signature.register_type(group)
  253. class chord(Signature):
  254. Chord = Chord
  255. def __init__(self, header, body=None, task='celery.chord',
  256. args=(), kwargs={}, **options):
  257. Signature.__init__(self, task, args, dict(kwargs,
  258. header=_maybe_group(header), body=maybe_subtask(body)), **options)
  259. self.subtask_type = 'chord'
  260. @classmethod
  261. def from_dict(self, d):
  262. args, d['kwargs'] = self._unpack_args(**kwdict(d['kwargs']))
  263. return self(*args, **kwdict(d))
  264. @staticmethod
  265. def _unpack_args(header=None, body=None, **kwargs):
  266. # Python signatures are better at extracting keys from dicts
  267. # than manually popping things off.
  268. return (header, body), kwargs
  269. def __call__(self, body=None, **kwargs):
  270. _chord = self.Chord
  271. body = self.kwargs['body'] = body or self.kwargs['body']
  272. if _chord.app.conf.CELERY_ALWAYS_EAGER:
  273. return self.apply((), kwargs)
  274. callback_id = body.options.setdefault('task_id', uuid())
  275. _chord(**dict(self.kwargs, **kwargs))
  276. return _chord.AsyncResult(callback_id)
  277. def clone(self, *args, **kwargs):
  278. s = Signature.clone(self, *args, **kwargs)
  279. # need to make copy of body
  280. try:
  281. s.kwargs['body'] = s.kwargs['body'].clone()
  282. except (AttributeError, KeyError):
  283. pass
  284. return s
  285. def link(self, callback):
  286. self.body.link(callback)
  287. return callback
  288. def link_error(self, errback):
  289. self.body.link_error(errback)
  290. return errback
  291. def __repr__(self):
  292. if self.body:
  293. return self.body.reprcall(self.tasks)
  294. return '<chord without body: {0.tasks!r}>'.format(self)
  295. @property
  296. def tasks(self):
  297. return self.kwargs['header']
  298. @property
  299. def body(self):
  300. return self.kwargs.get('body')
  301. Signature.register_type(chord)
  302. def subtask(varies, *args, **kwargs):
  303. if not (args or kwargs) and isinstance(varies, dict):
  304. if isinstance(varies, Signature):
  305. return varies.clone()
  306. return Signature.from_dict(varies)
  307. return Signature(varies, *args, **kwargs)
  308. def maybe_subtask(d):
  309. if d is not None and isinstance(d, dict) and not isinstance(d, Signature):
  310. return subtask(d)
  311. return d