canvas.py 12 KB

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