canvas.py 31 KB

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