canvas.py 27 KB

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