canvas.py 32 KB

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