canvas.py 13 KB

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