canvas.py 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033
  1. # -*- coding: utf-8 -*-
  2. """
  3. celery.canvas
  4. ~~~~~~~~~~~~~
  5. Composing task workflows.
  6. Documentation for some of these types are in :mod:`celery`.
  7. You should import these from :mod:`celery` and not this module.
  8. """
  9. from __future__ import absolute_import, unicode_literals
  10. import sys
  11. from collections import MutableSequence, deque
  12. from copy import deepcopy
  13. from functools import partial as _partial, reduce
  14. from operator import itemgetter
  15. from itertools import chain as _chain
  16. from kombu.utils import cached_property, fxrange, reprcall, uuid
  17. from celery._state import current_app
  18. from celery.local import try_import
  19. from celery.result import GroupResult
  20. from celery.utils import abstract
  21. from celery.utils.functional import (
  22. maybe_list, is_list, _regen, regen, chunks as _chunks,
  23. )
  24. from celery.utils.text import truncate
  25. __all__ = ['Signature', 'chain', 'xmap', 'xstarmap', 'chunks',
  26. 'group', 'chord', 'signature', 'maybe_signature']
  27. PY3 = sys.version_info[0] == 3
  28. # json in Python 2.7 borks if dict contains byte keys.
  29. JSON_NEEDS_UNICODE_KEYS = PY3 and not try_import('simplejson')
  30. class _getitem_property(object):
  31. """Attribute -> dict key descriptor.
  32. The target object must support ``__getitem__``,
  33. and optionally ``__setitem__``.
  34. Example:
  35. >>> from collections import defaultdict
  36. >>> class Me(dict):
  37. ... deep = defaultdict(dict)
  38. ...
  39. ... foo = _getitem_property('foo')
  40. ... deep_thing = _getitem_property('deep.thing')
  41. >>> me = Me()
  42. >>> me.foo
  43. None
  44. >>> me.foo = 10
  45. >>> me.foo
  46. 10
  47. >>> me['foo']
  48. 10
  49. >>> me.deep_thing = 42
  50. >>> me.deep_thing
  51. 42
  52. >>> me.deep
  53. defaultdict(<type 'dict'>, {'thing': 42})
  54. """
  55. def __init__(self, keypath):
  56. path, _, self.key = keypath.rpartition('.')
  57. self.path = path.split('.') if path else None
  58. def _path(self, obj):
  59. return (reduce(lambda d, k: d[k], [obj] + self.path) if self.path
  60. else obj)
  61. def __get__(self, obj, type=None):
  62. if obj is None:
  63. return type
  64. return self._path(obj).get(self.key)
  65. def __set__(self, obj, value):
  66. self._path(obj)[self.key] = value
  67. def maybe_unroll_group(g):
  68. """Unroll group with only one member."""
  69. # Issue #1656
  70. try:
  71. size = len(g.tasks)
  72. except TypeError:
  73. try:
  74. size = g.tasks.__length_hint__()
  75. except (AttributeError, TypeError):
  76. return g
  77. else:
  78. return list(g.tasks)[0] if size == 1 else g
  79. else:
  80. return g.tasks[0] if size == 1 else g
  81. def task_name_from(task):
  82. return getattr(task, 'name', task)
  83. def _upgrade(fields, sig):
  84. """Used by custom signatures in .from_dict, to keep common fields."""
  85. sig.update(chord_size=fields.get('chord_size'))
  86. return sig
  87. class Signature(dict):
  88. """Class that wraps the arguments and execution options
  89. for a single task invocation.
  90. Used as the parts in a :class:`group` and other constructs,
  91. or to pass tasks around as callbacks while being compatible
  92. with serializers with a strict type subset.
  93. :param task: Either a task class/instance, or the name of a task.
  94. :keyword args: Positional arguments to apply.
  95. :keyword kwargs: Keyword arguments to apply.
  96. :keyword options: Additional options to :meth:`Task.apply_async`.
  97. Note that if the first argument is a :class:`dict`, the other
  98. arguments will be ignored and the values in the dict will be used
  99. instead.
  100. >>> s = signature('tasks.add', args=(2, 2))
  101. >>> signature(s)
  102. {'task': 'tasks.add', args=(2, 2), kwargs={}, options={}}
  103. """
  104. TYPES = {}
  105. _app = _type = None
  106. @classmethod
  107. def register_type(cls, subclass, name=None):
  108. cls.TYPES[name or subclass.__name__] = subclass
  109. return subclass
  110. @classmethod
  111. def from_dict(self, d, app=None):
  112. typ = d.get('subtask_type')
  113. if typ:
  114. return self.TYPES[typ].from_dict(d, app=app)
  115. return Signature(d, app=app)
  116. def __init__(self, task=None, args=None, kwargs=None, options=None,
  117. type=None, subtask_type=None, immutable=False,
  118. app=None, **ex):
  119. self._app = app
  120. init = dict.__init__
  121. if isinstance(task, dict):
  122. return init(self, task) # works like dict(d)
  123. # Also supports using task class/instance instead of string name.
  124. try:
  125. task_name = task.name
  126. except AttributeError:
  127. task_name = task
  128. else:
  129. self._type = task
  130. init(self,
  131. task=task_name, args=tuple(args or ()),
  132. kwargs=kwargs or {},
  133. options=dict(options or {}, **ex),
  134. subtask_type=subtask_type,
  135. immutable=immutable,
  136. chord_size=None)
  137. def __call__(self, *partial_args, **partial_kwargs):
  138. args, kwargs, _ = self._merge(partial_args, partial_kwargs, None)
  139. return self.type(*args, **kwargs)
  140. def delay(self, *partial_args, **partial_kwargs):
  141. return self.apply_async(partial_args, partial_kwargs)
  142. def apply(self, args=(), kwargs={}, **options):
  143. """Apply this task locally."""
  144. # For callbacks: extra args are prepended to the stored args.
  145. args, kwargs, options = self._merge(args, kwargs, options)
  146. return self.type.apply(args, kwargs, **options)
  147. def _merge(self, args=(), kwargs={}, options={}, force=False):
  148. if self.immutable and not force:
  149. return (self.args, self.kwargs,
  150. dict(self.options, **options) if options else self.options)
  151. return (tuple(args) + tuple(self.args) if args else self.args,
  152. dict(self.kwargs, **kwargs) if kwargs else self.kwargs,
  153. dict(self.options, **options) if options else self.options)
  154. def clone(self, args=(), kwargs={}, **opts):
  155. # need to deepcopy options so origins links etc. is not modified.
  156. if args or kwargs or opts:
  157. args, kwargs, opts = self._merge(args, kwargs, opts)
  158. else:
  159. args, kwargs, opts = self.args, self.kwargs, self.options
  160. s = Signature.from_dict({'task': self.task, 'args': tuple(args),
  161. 'kwargs': kwargs, 'options': deepcopy(opts),
  162. 'subtask_type': self.subtask_type,
  163. 'chord_size': self.chord_size,
  164. 'immutable': self.immutable}, app=self._app)
  165. s._type = self._type
  166. return s
  167. partial = clone
  168. def freeze(self, _id=None, group_id=None, chord=None,
  169. root_id=None, parent_id=None):
  170. opts = self.options
  171. try:
  172. tid = opts['task_id']
  173. except KeyError:
  174. tid = opts['task_id'] = _id or uuid()
  175. if root_id:
  176. opts['root_id'] = root_id
  177. if parent_id:
  178. opts['parent_id'] = parent_id
  179. if 'reply_to' not in opts:
  180. opts['reply_to'] = self.app.oid
  181. if group_id:
  182. opts['group_id'] = group_id
  183. if chord:
  184. opts['chord'] = chord
  185. return self.AsyncResult(tid)
  186. _freeze = freeze
  187. def replace(self, args=None, kwargs=None, options=None):
  188. s = self.clone()
  189. if args is not None:
  190. s.args = args
  191. if kwargs is not None:
  192. s.kwargs = kwargs
  193. if options is not None:
  194. s.options = options
  195. return s
  196. def set(self, immutable=None, **options):
  197. if immutable is not None:
  198. self.set_immutable(immutable)
  199. self.options.update(options)
  200. return self
  201. def set_immutable(self, immutable):
  202. self.immutable = immutable
  203. def set_parent_id(self, parent_id):
  204. self.parent_id = parent_id
  205. def apply_async(self, args=(), kwargs={}, route_name=None, **options):
  206. try:
  207. _apply = self._apply_async
  208. except IndexError: # pragma: no cover
  209. # no tasks for chain, etc to find type
  210. return
  211. # For callbacks: extra args are prepended to the stored args.
  212. if args or kwargs or options:
  213. args, kwargs, options = self._merge(args, kwargs, options)
  214. else:
  215. args, kwargs, options = self.args, self.kwargs, self.options
  216. return _apply(args, kwargs, **options)
  217. def append_to_list_option(self, key, value):
  218. items = self.options.setdefault(key, [])
  219. if not isinstance(items, MutableSequence):
  220. items = self.options[key] = [items]
  221. if value not in items:
  222. items.append(value)
  223. return value
  224. def link(self, callback):
  225. return self.append_to_list_option('link', callback)
  226. def link_error(self, errback):
  227. return self.append_to_list_option('link_error', errback)
  228. def flatten_links(self):
  229. return list(_chain.from_iterable(_chain(
  230. [[self]],
  231. (link.flatten_links()
  232. for link in maybe_list(self.options.get('link')) or [])
  233. )))
  234. def __or__(self, other):
  235. if isinstance(self, group):
  236. if isinstance(other, group):
  237. return group(_chain(self.tasks, other.tasks), app=self.app)
  238. return chord(self, body=other, app=self._app)
  239. elif isinstance(other, group):
  240. other = maybe_unroll_group(other)
  241. if not isinstance(self, chain) and isinstance(other, chain):
  242. return chain((self,) + other.tasks, app=self._app)
  243. elif isinstance(other, chain):
  244. return chain(*self.tasks + other.tasks, app=self._app)
  245. elif isinstance(other, Signature):
  246. if isinstance(self, chain):
  247. return chain(*self.tasks + (other,), app=self._app)
  248. return chain(self, other, app=self._app)
  249. return NotImplemented
  250. def __deepcopy__(self, memo):
  251. memo[id(self)] = self
  252. return dict(self)
  253. def __invert__(self):
  254. return self.apply_async().get()
  255. def __reduce__(self):
  256. # for serialization, the task type is lazily loaded,
  257. # and not stored in the dict itself.
  258. return signature, (dict(self),)
  259. def __json__(self):
  260. return dict(self)
  261. def reprcall(self, *args, **kwargs):
  262. args, kwargs, _ = self._merge(args, kwargs, {}, force=True)
  263. return reprcall(self['task'], args, kwargs)
  264. def election(self):
  265. type = self.type
  266. app = type.app
  267. tid = self.options.get('task_id') or uuid()
  268. with app.producer_or_acquire(None) as P:
  269. props = type.backend.on_task_call(P, tid)
  270. app.control.election(tid, 'task', self.clone(task_id=tid, **props),
  271. connection=P.connection)
  272. return type.AsyncResult(tid)
  273. def __repr__(self):
  274. return self.reprcall()
  275. if JSON_NEEDS_UNICODE_KEYS: # pragma: no cover
  276. def items(self):
  277. for k, v in dict.items(self):
  278. yield k.decode() if isinstance(k, bytes) else k, v
  279. @property
  280. def name(self):
  281. # for duck typing compatibility with Task.name
  282. return self.task
  283. @cached_property
  284. def type(self):
  285. return self._type or self.app.tasks[self['task']]
  286. @cached_property
  287. def app(self):
  288. return self._app or current_app
  289. @cached_property
  290. def AsyncResult(self):
  291. try:
  292. return self.type.AsyncResult
  293. except KeyError: # task not registered
  294. return self.app.AsyncResult
  295. @cached_property
  296. def _apply_async(self):
  297. try:
  298. return self.type.apply_async
  299. except KeyError:
  300. return _partial(self.app.send_task, self['task'])
  301. id = _getitem_property('options.task_id')
  302. parent_id = _getitem_property('options.parent_id')
  303. root_id = _getitem_property('options.root_id')
  304. task = _getitem_property('task')
  305. args = _getitem_property('args')
  306. kwargs = _getitem_property('kwargs')
  307. options = _getitem_property('options')
  308. subtask_type = _getitem_property('subtask_type')
  309. chord_size = _getitem_property('chord_size')
  310. immutable = _getitem_property('immutable')
  311. abstract.CallableSignature.register(Signature)
  312. @Signature.register_type
  313. class chain(Signature):
  314. tasks = _getitem_property('kwargs.tasks')
  315. def __init__(self, *tasks, **options):
  316. tasks = (regen(tasks[0]) if len(tasks) == 1 and is_list(tasks[0])
  317. else tasks)
  318. Signature.__init__(
  319. self, 'celery.chain', (), {'tasks': tasks}, **options
  320. )
  321. self._use_link = options.pop('use_link', None)
  322. self.subtask_type = 'chain'
  323. self._frozen = None
  324. def __call__(self, *args, **kwargs):
  325. if self.tasks:
  326. return self.apply_async(args, kwargs)
  327. def apply_async(self, args=(), kwargs={}, **options):
  328. # python is best at unpacking kwargs, so .run is here to do that.
  329. app = self.app
  330. if app.conf.task_always_eager:
  331. return self.apply(args, kwargs, **options)
  332. return self.run(args, kwargs, app=app, **(
  333. dict(self.options, **options) if options else self.options))
  334. def run(self, args=(), kwargs={}, group_id=None, chord=None,
  335. task_id=None, link=None, link_error=None, publisher=None,
  336. producer=None, root_id=None, parent_id=None, app=None, **options):
  337. app = app or self.app
  338. use_link = self._use_link
  339. args = (tuple(args) + tuple(self.args)
  340. if args and not self.immutable else self.args)
  341. if self._frozen:
  342. tasks, results = self._frozen
  343. else:
  344. tasks, results = self.prepare_steps(
  345. args, self.tasks, root_id, parent_id, link_error, app,
  346. task_id, group_id, chord,
  347. )
  348. if results:
  349. if link:
  350. tasks[0].set(link=link)
  351. first_task = tasks.pop()
  352. first_task.apply_async(
  353. chain=tasks if not use_link else None, **options)
  354. return results[0]
  355. def freeze(self, _id=None, group_id=None, chord=None,
  356. root_id=None, parent_id=None):
  357. _, results = self._frozen = self.prepare_steps(
  358. self.args, self.tasks, root_id, parent_id, None,
  359. self.app, _id, group_id, chord, clone=False,
  360. )
  361. return results[-1]
  362. def prepare_steps(self, args, tasks,
  363. root_id=None, parent_id=None, link_error=None, app=None,
  364. last_task_id=None, group_id=None, chord_body=None,
  365. clone=True, from_dict=Signature.from_dict):
  366. app = app or self.app
  367. # use chain message field for protocol 2 and later.
  368. # this avoids pickle blowing the stack on the recursion
  369. # required by linking task together in a tree structure.
  370. # (why is pickle using recursion? or better yet why cannot python
  371. # do tail call optimization making recursion actually useful?)
  372. use_link = self._use_link
  373. if use_link is None and app.conf.task_protocol > 1:
  374. use_link = False
  375. steps = deque(tasks)
  376. steps_pop = steps.pop
  377. steps_extend = steps.extend
  378. prev_task = None
  379. prev_res = prev_prev_res = None
  380. tasks, results = [], []
  381. i = 0
  382. while steps:
  383. task = steps_pop()
  384. is_first_task, is_last_task = not steps, not i
  385. if not isinstance(task, abstract.CallableSignature):
  386. task = from_dict(task, app=app)
  387. if isinstance(task, group):
  388. task = maybe_unroll_group(task)
  389. # first task gets partial args from chain
  390. if clone:
  391. task = task.clone(args) if is_first_task else task.clone()
  392. elif is_first_task:
  393. task.args = tuple(args) + tuple(task.args)
  394. if isinstance(task, chain):
  395. # splice the chain
  396. steps_extend(task.tasks)
  397. continue
  398. if isinstance(task, group) and prev_task:
  399. # automatically upgrade group(...) | s to chord(group, s)
  400. # for chords we freeze by pretending it's a normal
  401. # signature instead of a group.
  402. tasks.pop()
  403. results.pop()
  404. task = chord(
  405. task, body=prev_task,
  406. task_id=prev_res.task_id, root_id=root_id, app=app,
  407. )
  408. prev_res = prev_prev_res
  409. if is_last_task:
  410. # chain(task_id=id) means task id is set for the last task
  411. # in the chain. If the chord is part of a chord/group
  412. # then that chord/group must synchronize based on the
  413. # last task in the chain, so we only set the group_id and
  414. # chord callback for the last task.
  415. res = task.freeze(
  416. last_task_id,
  417. root_id=root_id, group_id=group_id, chord=chord_body,
  418. )
  419. else:
  420. res = task.freeze(root_id=root_id)
  421. i += 1
  422. if prev_task:
  423. prev_task.set_parent_id(task.id)
  424. if use_link:
  425. # link previous task to this task.
  426. task.link(prev_task)
  427. if not res.parent and prev_res:
  428. prev_res.parent = res.parent
  429. elif prev_res:
  430. prev_res.parent = res
  431. if is_first_task and parent_id is not None:
  432. task.set_parent_id(parent_id)
  433. if link_error:
  434. task.set(link_error=link_error)
  435. tasks.append(task)
  436. results.append(res)
  437. prev_task, prev_prev_res, prev_res = (
  438. task, prev_res, res,
  439. )
  440. if root_id is None and tasks:
  441. root_id = tasks[-1].id
  442. for task in reversed(tasks):
  443. task.options['root_id'] = root_id
  444. return tasks, results
  445. def apply(self, args=(), kwargs={}, **options):
  446. last, fargs = None, args
  447. for task in self.tasks:
  448. res = task.clone(fargs).apply(
  449. last and (last.get(),), **dict(self.options, **options))
  450. res.parent, last, fargs = last, res, None
  451. return last
  452. @classmethod
  453. def from_dict(self, d, app=None):
  454. tasks = d['kwargs']['tasks']
  455. if tasks:
  456. if isinstance(tasks, tuple): # aaaargh
  457. tasks = d['kwargs']['tasks'] = list(tasks)
  458. # First task must be signature object to get app
  459. tasks[0] = maybe_signature(tasks[0], app=app)
  460. return _upgrade(d, chain(*tasks, app=app, **d['options']))
  461. @property
  462. def app(self):
  463. app = self._app
  464. if app is None:
  465. try:
  466. app = self.tasks[0]._app
  467. except (KeyError, IndexError):
  468. pass
  469. return app or current_app
  470. def __repr__(self):
  471. return ' | '.join(repr(t) for t in self.tasks)
  472. class _basemap(Signature):
  473. _task_name = None
  474. _unpack_args = itemgetter('task', 'it')
  475. def __init__(self, task, it, **options):
  476. Signature.__init__(
  477. self, self._task_name, (),
  478. {'task': task, 'it': regen(it)}, immutable=True, **options
  479. )
  480. def apply_async(self, args=(), kwargs={}, **opts):
  481. # need to evaluate generators
  482. task, it = self._unpack_args(self.kwargs)
  483. return self.type.apply_async(
  484. (), {'task': task, 'it': list(it)},
  485. route_name=task_name_from(self.kwargs.get('task')), **opts
  486. )
  487. @classmethod
  488. def from_dict(cls, d, app=None):
  489. return _upgrade(
  490. d, cls(*cls._unpack_args(d['kwargs']), app=app, **d['options']),
  491. )
  492. @Signature.register_type
  493. class xmap(_basemap):
  494. _task_name = 'celery.map'
  495. def __repr__(self):
  496. task, it = self._unpack_args(self.kwargs)
  497. return '[{0}(x) for x in {1}]'.format(task.task,
  498. truncate(repr(it), 100))
  499. @Signature.register_type
  500. class xstarmap(_basemap):
  501. _task_name = 'celery.starmap'
  502. def __repr__(self):
  503. task, it = self._unpack_args(self.kwargs)
  504. return '[{0}(*x) for x in {1}]'.format(task.task,
  505. truncate(repr(it), 100))
  506. @Signature.register_type
  507. class chunks(Signature):
  508. _unpack_args = itemgetter('task', 'it', 'n')
  509. def __init__(self, task, it, n, **options):
  510. Signature.__init__(
  511. self, 'celery.chunks', (),
  512. {'task': task, 'it': regen(it), 'n': n},
  513. immutable=True, **options
  514. )
  515. @classmethod
  516. def from_dict(self, d, app=None):
  517. return _upgrade(
  518. d, chunks(*self._unpack_args(
  519. d['kwargs']), app=app, **d['options']),
  520. )
  521. def apply_async(self, args=(), kwargs={}, **opts):
  522. return self.group().apply_async(
  523. args, kwargs,
  524. route_name=task_name_from(self.kwargs.get('task')), **opts
  525. )
  526. def __call__(self, **options):
  527. return self.apply_async(**options)
  528. def group(self):
  529. # need to evaluate generators
  530. task, it, n = self._unpack_args(self.kwargs)
  531. return group((xstarmap(task, part, app=self._app)
  532. for part in _chunks(iter(it), n)),
  533. app=self._app)
  534. @classmethod
  535. def apply_chunks(cls, task, it, n, app=None):
  536. return cls(task, it, n, app=app)()
  537. def _maybe_group(tasks, app):
  538. if isinstance(tasks, dict):
  539. tasks = signature(tasks, app=app)
  540. if isinstance(tasks, group):
  541. tasks = tasks.tasks
  542. elif isinstance(tasks, abstract.CallableSignature):
  543. tasks = [tasks]
  544. else:
  545. tasks = [signature(t, app=app) for t in tasks]
  546. return tasks
  547. @Signature.register_type
  548. class group(Signature):
  549. tasks = _getitem_property('kwargs.tasks')
  550. def __init__(self, *tasks, **options):
  551. if len(tasks) == 1:
  552. tasks = tasks[0]
  553. if isinstance(tasks, group):
  554. tasks = tasks.tasks
  555. if not isinstance(tasks, _regen):
  556. tasks = regen(tasks)
  557. Signature.__init__(
  558. self, 'celery.group', (), {'tasks': tasks}, **options
  559. )
  560. self.subtask_type = 'group'
  561. @classmethod
  562. def from_dict(self, d, app=None):
  563. return _upgrade(
  564. d, group(d['kwargs']['tasks'], app=app, **d['options']),
  565. )
  566. def __len__(self):
  567. return len(self.tasks)
  568. def _prepared(self, tasks, partial_args, group_id, root_id, app, dict=dict,
  569. CallableSignature=abstract.CallableSignature,
  570. from_dict=Signature.from_dict):
  571. for task in tasks:
  572. if isinstance(task, CallableSignature):
  573. # local sigs are always of type Signature, and we
  574. # clone them to make sure we do not modify the originals.
  575. task = task.clone()
  576. else:
  577. # serialized sigs must be converted to Signature.
  578. task = from_dict(task, app=app)
  579. if isinstance(task, group):
  580. # needs yield_from :(
  581. unroll = task._prepared(
  582. task.tasks, partial_args, group_id, root_id, app,
  583. )
  584. for taskN, resN in unroll:
  585. yield taskN, resN
  586. else:
  587. if partial_args and not task.immutable:
  588. task.args = tuple(partial_args) + tuple(task.args)
  589. yield task, task.freeze(group_id=group_id, root_id=root_id)
  590. def _apply_tasks(self, tasks, producer=None, app=None,
  591. add_to_parent=None, chord=None, **options):
  592. app = app or self.app
  593. with app.producer_or_acquire(producer) as producer:
  594. for sig, res in tasks:
  595. sig.apply_async(producer=producer, add_to_parent=False,
  596. chord=sig.options.get('chord') or chord,
  597. **options)
  598. yield res # <-- r.parent, etc set in the frozen result.
  599. def _freeze_gid(self, options):
  600. # remove task_id and use that as the group_id,
  601. # if we don't remove it then every task will have the same id...
  602. options = dict(self.options, **options)
  603. options['group_id'] = group_id = (
  604. options.pop('task_id', uuid()))
  605. return options, group_id, options.get('root_id')
  606. def set_parent_id(self, parent_id):
  607. for task in self.tasks:
  608. task.set_parent_id(parent_id)
  609. def apply_async(self, args=(), kwargs=None, add_to_parent=True,
  610. producer=None, **options):
  611. app = self.app
  612. if app.conf.task_always_eager:
  613. return self.apply(args, kwargs, **options)
  614. if not self.tasks:
  615. return self.freeze()
  616. options, group_id, root_id = self._freeze_gid(options)
  617. tasks = self._prepared(self.tasks, args, group_id, root_id, app)
  618. result = self.app.GroupResult(
  619. group_id, list(self._apply_tasks(tasks, producer, app, **options)),
  620. )
  621. # - Special case of group(A.s() | group(B.s(), C.s()))
  622. # That is, group with single item that is a chain but the
  623. # last task in that chain is a group.
  624. #
  625. # We cannot actually support arbitrary GroupResults in chains,
  626. # but this special case we can.
  627. if len(result) == 1 and isinstance(result[0], GroupResult):
  628. result = result[0]
  629. parent_task = app.current_worker_task
  630. if add_to_parent and parent_task:
  631. parent_task.add_trail(result)
  632. return result
  633. def apply(self, args=(), kwargs={}, **options):
  634. app = self.app
  635. if not self.tasks:
  636. return self.freeze() # empty group returns GroupResult
  637. options, group_id, root_id = self._freeze_gid(options)
  638. tasks = self._prepared(self.tasks, args, group_id, root_id, app)
  639. return app.GroupResult(group_id, [
  640. sig.apply(**options) for sig, _ in tasks
  641. ])
  642. def set_immutable(self, immutable):
  643. for task in self.tasks:
  644. task.set_immutable(immutable)
  645. def link(self, sig):
  646. # Simply link to first task
  647. sig = sig.clone().set(immutable=True)
  648. return self.tasks[0].link(sig)
  649. def link_error(self, sig):
  650. sig = sig.clone().set(immutable=True)
  651. return self.tasks[0].link_error(sig)
  652. def __call__(self, *partial_args, **options):
  653. return self.apply_async(partial_args, **options)
  654. def _freeze_unroll(self, new_tasks, group_id, chord, root_id, parent_id):
  655. stack = deque(self.tasks)
  656. while stack:
  657. task = maybe_signature(stack.popleft(), app=self._app).clone()
  658. if isinstance(task, group):
  659. stack.extendleft(task.tasks)
  660. else:
  661. new_tasks.append(task)
  662. yield task.freeze(group_id=group_id,
  663. chord=chord, root_id=root_id,
  664. parent_id=parent_id)
  665. def freeze(self, _id=None, group_id=None, chord=None,
  666. root_id=None, parent_id=None):
  667. opts = self.options
  668. try:
  669. gid = opts['task_id']
  670. except KeyError:
  671. gid = opts['task_id'] = uuid()
  672. if group_id:
  673. opts['group_id'] = group_id
  674. if chord:
  675. opts['chord'] = chord
  676. root_id = opts.setdefault('root_id', root_id)
  677. parent_id = opts.setdefault('parent_id', parent_id)
  678. new_tasks = []
  679. # Need to unroll subgroups early so that chord gets the
  680. # right result instance for chord_unlock etc.
  681. results = list(self._freeze_unroll(
  682. new_tasks, group_id, chord, root_id, parent_id,
  683. ))
  684. if isinstance(self.tasks, MutableSequence):
  685. self.tasks[:] = new_tasks
  686. else:
  687. self.tasks = new_tasks
  688. return self.app.GroupResult(gid, results)
  689. _freeze = freeze
  690. def skew(self, start=1.0, stop=None, step=1.0):
  691. it = fxrange(start, stop, step, repeatlast=True)
  692. for task in self.tasks:
  693. task.set(countdown=next(it))
  694. return self
  695. def __iter__(self):
  696. return iter(self.tasks)
  697. def __repr__(self):
  698. return 'group({0.tasks!r})'.format(self)
  699. @property
  700. def app(self):
  701. app = self._app
  702. if app is None:
  703. try:
  704. app = self.tasks[0].app
  705. except (KeyError, IndexError):
  706. pass
  707. return app if app is not None else current_app
  708. @Signature.register_type
  709. class chord(Signature):
  710. def __init__(self, header, body=None, task='celery.chord',
  711. args=(), kwargs={}, app=None, **options):
  712. Signature.__init__(
  713. self, task, args,
  714. dict(kwargs, header=_maybe_group(header, app),
  715. body=maybe_signature(body, app=app)), app=app, **options
  716. )
  717. self.subtask_type = 'chord'
  718. def freeze(self, _id=None, group_id=None, chord=None,
  719. root_id=None, parent_id=None):
  720. if not isinstance(self.tasks, group):
  721. self.tasks = group(self.tasks, app=self.app)
  722. bodyres = self.body.freeze(_id, parent_id=self.id, root_id=root_id)
  723. self.tasks.freeze(
  724. parent_id=parent_id, root_id=root_id, chord=self.body)
  725. self.id = self.tasks.id
  726. self.body.set_parent_id(self.id)
  727. return bodyres
  728. def set_parent_id(self, parent_id):
  729. tasks = self.tasks
  730. if isinstance(tasks, group):
  731. tasks = tasks.tasks
  732. for task in tasks:
  733. task.set_parent_id(parent_id)
  734. self.parent_id = parent_id
  735. @classmethod
  736. def from_dict(self, d, app=None):
  737. args, d['kwargs'] = self._unpack_args(**d['kwargs'])
  738. return _upgrade(d, self(*args, app=app, **d))
  739. @staticmethod
  740. def _unpack_args(header=None, body=None, **kwargs):
  741. # Python signatures are better at extracting keys from dicts
  742. # than manually popping things off.
  743. return (header, body), kwargs
  744. @cached_property
  745. def app(self):
  746. return self._get_app(self.body)
  747. def _get_app(self, body=None):
  748. app = self._app
  749. if app is None:
  750. try:
  751. tasks = self.tasks.tasks # is a group
  752. except AttributeError:
  753. tasks = self.tasks
  754. app = tasks[0]._app
  755. if app is None and body is not None:
  756. app = body._app
  757. return app if app is not None else current_app
  758. def apply_async(self, args=(), kwargs={}, task_id=None,
  759. producer=None, publisher=None, connection=None,
  760. router=None, result_cls=None, **options):
  761. args = (tuple(args) + tuple(self.args)
  762. if args and not self.immutable else self.args)
  763. body = kwargs.get('body') or self.kwargs['body']
  764. kwargs = dict(self.kwargs, **kwargs)
  765. body = body.clone(**options)
  766. app = self._get_app(body)
  767. tasks = (self.tasks.clone() if isinstance(self.tasks, group)
  768. else group(self.tasks, app=app))
  769. if app.conf.task_always_eager:
  770. return self.apply((), kwargs,
  771. body=body, task_id=task_id, **options)
  772. return self.run(tasks, body, args, task_id=task_id, **options)
  773. def apply(self, args=(), kwargs={}, propagate=True, body=None, **options):
  774. body = self.body if body is None else body
  775. tasks = (self.tasks.clone() if isinstance(self.tasks, group)
  776. else group(self.tasks, app=self.app))
  777. return body.apply(
  778. args=(tasks.apply().get(propagate=propagate),),
  779. )
  780. def _traverse_tasks(self, tasks, value=None):
  781. stack = deque(list(tasks))
  782. while stack:
  783. task = stack.popleft()
  784. if isinstance(task, group):
  785. stack.extend(task.tasks)
  786. else:
  787. yield task if value is None else value
  788. def __length_hint__(self):
  789. return sum(self._traverse_tasks(self.tasks, 1))
  790. def run(self, header, body, partial_args, app=None, interval=None,
  791. countdown=1, max_retries=None, eager=False,
  792. task_id=None, **options):
  793. app = app or self._get_app(body)
  794. group_id = uuid()
  795. root_id = body.options.get('root_id')
  796. body.chord_size = self.__length_hint__()
  797. options = dict(self.options, **options) if options else self.options
  798. if options:
  799. options.pop('task_id', None)
  800. body.options.update(options)
  801. results = header.freeze(
  802. group_id=group_id, chord=body, root_id=root_id).results
  803. bodyres = body.freeze(task_id, root_id=root_id)
  804. parent = app.backend.apply_chord(
  805. header, partial_args, group_id, body,
  806. interval=interval, countdown=countdown,
  807. options=options, max_retries=max_retries,
  808. result=results)
  809. bodyres.parent = parent
  810. return bodyres
  811. def __call__(self, body=None, **options):
  812. return self.apply_async((), {'body': body} if body else {}, **options)
  813. def clone(self, *args, **kwargs):
  814. s = Signature.clone(self, *args, **kwargs)
  815. # need to make copy of body
  816. try:
  817. s.kwargs['body'] = s.kwargs['body'].clone()
  818. except (AttributeError, KeyError):
  819. pass
  820. return s
  821. def link(self, callback):
  822. self.body.link(callback)
  823. return callback
  824. def link_error(self, errback):
  825. self.body.link_error(errback)
  826. return errback
  827. def set_immutable(self, immutable):
  828. # changes mutability of header only, not callback.
  829. for task in self.tasks:
  830. task.set_immutable(immutable)
  831. def __repr__(self):
  832. if self.body:
  833. return self.body.reprcall(self.tasks)
  834. return '<chord without body: {0.tasks!r}>'.format(self)
  835. tasks = _getitem_property('kwargs.header')
  836. body = _getitem_property('kwargs.body')
  837. def signature(varies, *args, **kwargs):
  838. app = kwargs.get('app')
  839. if isinstance(varies, dict):
  840. if isinstance(varies, abstract.CallableSignature):
  841. return varies.clone()
  842. return Signature.from_dict(varies, app=app)
  843. return Signature(varies, *args, **kwargs)
  844. subtask = signature # XXX compat
  845. def maybe_signature(d, app=None):
  846. if d is not None:
  847. if isinstance(d, dict):
  848. if not isinstance(d, abstract.CallableSignature):
  849. d = signature(d)
  850. elif isinstance(d, list):
  851. return [maybe_signature(s, app=app) for s in d]
  852. if app is not None:
  853. d._app = app
  854. return d
  855. maybe_subtask = maybe_signature # XXX compat