canvas.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830
  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.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(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 not isinstance(items, MutableSequence):
  199. items = self.options[key] = [items]
  200. if value not in items:
  201. items.append(value)
  202. return value
  203. def link(self, callback):
  204. return self.append_to_list_option('link', callback)
  205. def link_error(self, errback):
  206. return self.append_to_list_option('link_error', errback)
  207. def flatten_links(self):
  208. return list(_chain.from_iterable(_chain(
  209. [[self]],
  210. (link.flatten_links()
  211. for link in maybe_list(self.options.get('link')) or [])
  212. )))
  213. def __or__(self, other):
  214. if isinstance(other, group):
  215. other = maybe_unroll_group(other)
  216. if not isinstance(self, chain) and isinstance(other, chain):
  217. return chain((self, ) + other.tasks, app=self._app)
  218. elif isinstance(other, chain):
  219. return chain(*self.tasks + other.tasks, app=self._app)
  220. elif isinstance(other, Signature):
  221. if isinstance(self, chain):
  222. return chain(*self.tasks + (other, ), app=self._app)
  223. return chain(self, other, app=self._app)
  224. return NotImplemented
  225. def __deepcopy__(self, memo):
  226. memo[id(self)] = self
  227. return dict(self)
  228. def __invert__(self):
  229. return self.apply_async().get()
  230. def __reduce__(self):
  231. # for serialization, the task type is lazily loaded,
  232. # and not stored in the dict itself.
  233. return signature, (dict(self), )
  234. def __json__(self):
  235. return dict(self)
  236. def reprcall(self, *args, **kwargs):
  237. args, kwargs, _ = self._merge(args, kwargs, {})
  238. return reprcall(self['task'], args, kwargs)
  239. def election(self):
  240. type = self.type
  241. app = type.app
  242. tid = self.options.get('task_id') or uuid()
  243. with app.producer_or_acquire(None) as P:
  244. props = type.backend.on_task_call(P, tid)
  245. app.control.election(tid, 'task', self.clone(task_id=tid, **props),
  246. connection=P.connection)
  247. return type.AsyncResult(tid)
  248. def __repr__(self):
  249. return self.reprcall()
  250. @cached_property
  251. def type(self):
  252. return self._type or self.app.tasks[self['task']]
  253. @cached_property
  254. def app(self):
  255. return self._app or current_app
  256. @cached_property
  257. def AsyncResult(self):
  258. try:
  259. return self.type.AsyncResult
  260. except KeyError: # task not registered
  261. return self.app.AsyncResult
  262. @cached_property
  263. def _apply_async(self):
  264. try:
  265. return self.type.apply_async
  266. except KeyError:
  267. return _partial(self.app.send_task, self['task'])
  268. id = _getitem_property('options.task_id')
  269. task = _getitem_property('task')
  270. args = _getitem_property('args')
  271. kwargs = _getitem_property('kwargs')
  272. options = _getitem_property('options')
  273. subtask_type = _getitem_property('subtask_type')
  274. immutable = _getitem_property('immutable')
  275. @Signature.register_type
  276. class chain(Signature):
  277. def __init__(self, *tasks, **options):
  278. tasks = (regen(tasks[0]) if len(tasks) == 1 and is_list(tasks[0])
  279. else tasks)
  280. Signature.__init__(
  281. self, 'celery.chain', (), {'tasks': tasks}, **options
  282. )
  283. self.tasks = tasks
  284. self.subtask_type = 'chain'
  285. def __call__(self, *args, **kwargs):
  286. if self.tasks:
  287. return self.apply_async(args, kwargs)
  288. def apply_async(self, args=(), kwargs={}, group_id=None, chord=None,
  289. task_id=None, link=None, link_error=None,
  290. publisher=None, root_id=None, **options):
  291. app = self.app
  292. if app.conf.CELERY_ALWAYS_EAGER:
  293. return self.apply(args, kwargs, **options)
  294. tasks, results = self.prepare_steps(
  295. args, self.tasks, root_id, link_error,
  296. )
  297. if not results:
  298. return
  299. result = results[-1]
  300. last_task = tasks[-1]
  301. if group_id:
  302. last_task.set(group_id=group_id)
  303. if chord:
  304. last_task.set(chord=chord)
  305. if task_id:
  306. last_task.set(task_id=task_id)
  307. result = last_task.type.AsyncResult(task_id)
  308. # make sure we can do a link() and link_error() on a chain object.
  309. if link:
  310. tasks[-1].set(link=link)
  311. tasks[0].apply_async(**options)
  312. return result
  313. def prepare_steps(self, args, tasks,
  314. root_id=None, link_error=None, app=None):
  315. app = app or self.app
  316. steps = deque(tasks)
  317. next_step = prev_task = prev_res = None
  318. tasks, results = [], []
  319. i = 0
  320. while steps:
  321. task = steps.popleft()
  322. if not i: # first task
  323. # first task gets partial args from chain
  324. task = task.clone(args)
  325. res = task.freeze(root_id=root_id)
  326. root_id = res.id if root_id is None else root_id
  327. else:
  328. task = task.clone()
  329. res = task.freeze(root_id=root_id)
  330. i += 1
  331. if isinstance(task, group):
  332. task = maybe_unroll_group(task)
  333. if isinstance(task, chain):
  334. # splice the chain
  335. steps.extendleft(reversed(task.tasks))
  336. continue
  337. elif isinstance(task, group) and steps and \
  338. not isinstance(steps[0], group):
  339. # automatically upgrade group(...) | s to chord(group, s)
  340. try:
  341. next_step = steps.popleft()
  342. # for chords we freeze by pretending it's a normal
  343. # signature instead of a group.
  344. res = Signature.freeze(next_step)
  345. task = chord(
  346. task, body=next_step,
  347. task_id=res.task_id, root_id=root_id,
  348. )
  349. except IndexError:
  350. pass # no callback, so keep as group.
  351. if prev_task:
  352. # link previous task to this task.
  353. prev_task.link(task)
  354. # set AsyncResult.parent
  355. if not res.parent:
  356. res.parent = prev_res
  357. if link_error:
  358. task.set(link_error=link_error)
  359. if not isinstance(prev_task, chord):
  360. results.append(res)
  361. tasks.append(task)
  362. prev_task, prev_res = task, res
  363. return tasks, results
  364. def apply(self, args=(), kwargs={}, **options):
  365. last, fargs = None, args
  366. for task in self.tasks:
  367. res = task.clone(fargs).apply(
  368. last and (last.get(), ), **options
  369. )
  370. res.parent, last, fargs = last, res, None
  371. return last
  372. @classmethod
  373. def from_dict(self, d, app=None):
  374. tasks = d['kwargs']['tasks']
  375. if d['args'] and tasks:
  376. # partial args passed on to first task in chain (Issue #1057).
  377. tasks[0]['args'] = tasks[0]._merge(d['args'])[0]
  378. return chain(*d['kwargs']['tasks'], app=app, **d['options'])
  379. @property
  380. def app(self):
  381. app = self._app
  382. if app is None:
  383. try:
  384. app = self.tasks[0]._app
  385. except (KeyError, IndexError):
  386. pass
  387. return app or current_app
  388. def __repr__(self):
  389. return ' | '.join(repr(t) for t in self.tasks)
  390. class _basemap(Signature):
  391. _task_name = None
  392. _unpack_args = itemgetter('task', 'it')
  393. def __init__(self, task, it, **options):
  394. Signature.__init__(
  395. self, self._task_name, (),
  396. {'task': task, 'it': regen(it)}, immutable=True, **options
  397. )
  398. def apply_async(self, args=(), kwargs={}, **opts):
  399. # need to evaluate generators
  400. task, it = self._unpack_args(self.kwargs)
  401. return self.type.apply_async(
  402. (), {'task': task, 'it': list(it)}, **opts
  403. )
  404. @classmethod
  405. def from_dict(cls, d, app=None):
  406. return cls(*cls._unpack_args(d['kwargs']), app=app, **d['options'])
  407. @Signature.register_type
  408. class xmap(_basemap):
  409. _task_name = 'celery.map'
  410. def __repr__(self):
  411. task, it = self._unpack_args(self.kwargs)
  412. return '[{0}(x) for x in {1}]'.format(task.task,
  413. truncate(repr(it), 100))
  414. @Signature.register_type
  415. class xstarmap(_basemap):
  416. _task_name = 'celery.starmap'
  417. def __repr__(self):
  418. task, it = self._unpack_args(self.kwargs)
  419. return '[{0}(*x) for x in {1}]'.format(task.task,
  420. truncate(repr(it), 100))
  421. @Signature.register_type
  422. class chunks(Signature):
  423. _unpack_args = itemgetter('task', 'it', 'n')
  424. def __init__(self, task, it, n, **options):
  425. Signature.__init__(
  426. self, 'celery.chunks', (),
  427. {'task': task, 'it': regen(it), 'n': n},
  428. immutable=True, **options
  429. )
  430. @classmethod
  431. def from_dict(self, d, app=None):
  432. return chunks(*self._unpack_args(d['kwargs']), app=app, **d['options'])
  433. def apply_async(self, args=(), kwargs={}, **opts):
  434. return self.group().apply_async(args, kwargs, **opts)
  435. def __call__(self, **options):
  436. return self.group()(**options)
  437. def group(self):
  438. # need to evaluate generators
  439. task, it, n = self._unpack_args(self.kwargs)
  440. return group((xstarmap(task, part, app=self._app)
  441. for part in _chunks(iter(it), n)),
  442. app=self._app)
  443. @classmethod
  444. def apply_chunks(cls, task, it, n, app=None):
  445. return cls(task, it, n, app=app)()
  446. def _maybe_group(tasks):
  447. if isinstance(tasks, group):
  448. tasks = list(tasks.tasks)
  449. elif isinstance(tasks, Signature):
  450. tasks = [tasks]
  451. else:
  452. tasks = regen(tasks)
  453. return tasks
  454. @Signature.register_type
  455. class group(Signature):
  456. def __init__(self, *tasks, **options):
  457. if len(tasks) == 1:
  458. tasks = _maybe_group(tasks[0])
  459. Signature.__init__(
  460. self, 'celery.group', (), {'tasks': tasks}, **options
  461. )
  462. self.tasks, self.subtask_type = tasks, 'group'
  463. @classmethod
  464. def from_dict(self, d, app=None):
  465. tasks = d['kwargs']['tasks']
  466. if d['args'] and tasks:
  467. # partial args passed on to all tasks in the group (Issue #1057).
  468. for task in tasks:
  469. task['args'] = task._merge(d['args'])[0]
  470. return group(tasks, app=app, **d['options'])
  471. def _prepared(self, tasks, partial_args, group_id, root_id, dict=dict,
  472. Signature=Signature, from_dict=Signature.from_dict):
  473. for task in tasks:
  474. if isinstance(task, dict):
  475. if isinstance(task, Signature):
  476. # local sigs are always of type Signature, and we
  477. # clone them to make sure we do not modify the originals.
  478. task = task.clone()
  479. else:
  480. # serialized sigs must be converted to Signature.
  481. task = from_dict(task)
  482. if partial_args and not task.immutable:
  483. task.args = tuple(partial_args) + tuple(task.args)
  484. yield task, task.freeze(group_id=group_id, root_id=root_id)
  485. def _apply_tasks(self, tasks, producer=None, app=None, **options):
  486. app = app or self.app
  487. with app.producer_or_acquire(producer) as producer:
  488. for sig, res in tasks:
  489. sig.apply_async(producer=producer, add_to_parent=False,
  490. **options)
  491. yield res
  492. def _freeze_gid(self, options):
  493. # remove task_id and use that as the group_id,
  494. # if we don't remove it then every task will have the same id...
  495. options = dict(self.options, **options)
  496. options['group_id'] = group_id = (
  497. options.pop('task_id', uuid()))
  498. return options, group_id, options.get('root_id')
  499. def apply_async(self, args=(), kwargs=None, add_to_parent=True,
  500. producer=None, **options):
  501. app = self.app
  502. if app.conf.CELERY_ALWAYS_EAGER:
  503. return self.apply(args, kwargs, **options)
  504. if not self.tasks:
  505. return self.freeze()
  506. options, group_id, root_id = self._freeze_gid(options)
  507. tasks = self._prepared(self.tasks, args, group_id, root_id)
  508. result = self.app.GroupResult(
  509. group_id, list(self._apply_tasks(tasks, producer, app, **options)),
  510. )
  511. parent_task = get_current_worker_task()
  512. if add_to_parent and parent_task:
  513. parent_task.add_trail(result)
  514. return result
  515. def apply(self, args=(), kwargs={}, **options):
  516. app = self.app
  517. if not self.tasks:
  518. return self.freeze() # empty group returns GroupResult
  519. options, group_id, root_id = self._freeze_gid(options)
  520. tasks = self._prepared(self.tasks, args, group_id, root_id)
  521. return app.GroupResult(group_id, [
  522. sig.apply(**options) for sig, _ in tasks
  523. ])
  524. def set_immutable(self, immutable):
  525. for task in self.tasks:
  526. task.set_immutable(immutable)
  527. def link(self, sig):
  528. # Simply link to first task
  529. sig = sig.clone().set(immutable=True)
  530. return self.tasks[0].link(sig)
  531. def link_error(self, sig):
  532. sig = sig.clone().set(immutable=True)
  533. return self.tasks[0].link_error(sig)
  534. def __call__(self, *partial_args, **options):
  535. return self.apply_async(partial_args, **options)
  536. def freeze(self, _id=None, group_id=None, chord=None, root_id=None):
  537. opts = self.options
  538. try:
  539. gid = opts['task_id']
  540. except KeyError:
  541. gid = opts['task_id'] = uuid()
  542. if group_id:
  543. opts['group_id'] = group_id
  544. if chord:
  545. opts['chord'] = group_id
  546. root_id = opts.setdefault('root_id', root_id)
  547. new_tasks, results = [], []
  548. for task in self.tasks:
  549. task = maybe_signature(task, app=self._app).clone()
  550. results.append(task.freeze(
  551. group_id=group_id, chord=chord, root_id=root_id,
  552. ))
  553. new_tasks.append(task)
  554. self.tasks = self.kwargs['tasks'] = new_tasks
  555. return self.app.GroupResult(gid, results)
  556. _freeze = freeze
  557. def skew(self, start=1.0, stop=None, step=1.0):
  558. it = fxrange(start, stop, step, repeatlast=True)
  559. for task in self.tasks:
  560. task.set(countdown=next(it))
  561. return self
  562. def __iter__(self):
  563. return iter(self.tasks)
  564. def __repr__(self):
  565. return repr(self.tasks)
  566. @property
  567. def app(self):
  568. app = self._app
  569. if app is None:
  570. try:
  571. app = self.tasks[0]._app
  572. except (KeyError, IndexError):
  573. pass
  574. return app if app is not None else current_app
  575. @Signature.register_type
  576. class chord(Signature):
  577. def __init__(self, header, body=None, task='celery.chord',
  578. args=(), kwargs={}, **options):
  579. Signature.__init__(
  580. self, task, args,
  581. dict(kwargs, header=_maybe_group(header),
  582. body=maybe_signature(body, app=self._app)), **options
  583. )
  584. self.subtask_type = 'chord'
  585. def freeze(self, *args, **kwargs):
  586. return self.body.freeze(*args, **kwargs)
  587. @classmethod
  588. def from_dict(self, d, app=None):
  589. args, d['kwargs'] = self._unpack_args(**d['kwargs'])
  590. return self(*args, app=app, **d)
  591. @staticmethod
  592. def _unpack_args(header=None, body=None, **kwargs):
  593. # Python signatures are better at extracting keys from dicts
  594. # than manually popping things off.
  595. return (header, body), kwargs
  596. @cached_property
  597. def app(self):
  598. app = self._app
  599. if app is None:
  600. app = self.tasks[0]._app
  601. if app is None:
  602. app = self.body._app
  603. return app if app is not None else current_app
  604. def apply_async(self, args=(), kwargs={}, task_id=None,
  605. producer=None, publisher=None, connection=None,
  606. router=None, result_cls=None, **options):
  607. body = kwargs.get('body') or self.kwargs['body']
  608. kwargs = dict(self.kwargs, **kwargs)
  609. body = body.clone(**options)
  610. app = self.app
  611. tasks = (self.tasks.clone() if isinstance(self.tasks, group)
  612. else group(self.tasks))
  613. if app.conf.CELERY_ALWAYS_EAGER:
  614. return self.apply((), kwargs,
  615. body=body, task_id=task_id, **options)
  616. return self.run(tasks, body, args, task_id=task_id, **options)
  617. def apply(self, args=(), kwargs={}, propagate=True, body=None, **options):
  618. body = self.body if body is None else body
  619. tasks = (self.tasks.clone() if isinstance(self.tasks, group)
  620. else group(self.tasks))
  621. return body.apply(
  622. args=(tasks.apply().get(propagate=propagate), ),
  623. )
  624. def run(self, header, body, partial_args, app=None, interval=None,
  625. countdown=1, max_retries=None, propagate=None, eager=False,
  626. task_id=None, **options):
  627. app = app or self.app
  628. propagate = (app.conf.CELERY_CHORD_PROPAGATES
  629. if propagate is None else propagate)
  630. group_id = uuid()
  631. root_id = body.options.get('root_id')
  632. body.setdefault('chord_size', len(header.tasks))
  633. results = header.freeze(
  634. group_id=group_id, chord=body, root_id=root_id).results
  635. bodyres = body.freeze(task_id, root_id=root_id)
  636. parent = app.backend.apply_chord(
  637. header, partial_args, group_id, body,
  638. interval=interval, countdown=countdown,
  639. max_retries=max_retries, propagate=propagate, result=results)
  640. bodyres.parent = parent
  641. return bodyres
  642. def __call__(self, body=None, **options):
  643. return self.apply_async((), {'body': body} if body else {}, **options)
  644. def clone(self, *args, **kwargs):
  645. s = Signature.clone(self, *args, **kwargs)
  646. # need to make copy of body
  647. try:
  648. s.kwargs['body'] = s.kwargs['body'].clone()
  649. except (AttributeError, KeyError):
  650. pass
  651. return s
  652. def link(self, callback):
  653. self.body.link(callback)
  654. return callback
  655. def link_error(self, errback):
  656. self.body.link_error(errback)
  657. return errback
  658. def set_immutable(self, immutable):
  659. # changes mutability of header only, not callback.
  660. for task in self.tasks:
  661. task.set_immutable(immutable)
  662. def __repr__(self):
  663. if self.body:
  664. return self.body.reprcall(self.tasks)
  665. return '<chord without body: {0.tasks!r}>'.format(self)
  666. tasks = _getitem_property('kwargs.header')
  667. body = _getitem_property('kwargs.body')
  668. def signature(varies, *args, **kwargs):
  669. if isinstance(varies, dict):
  670. if isinstance(varies, Signature):
  671. return varies.clone()
  672. return Signature.from_dict(varies)
  673. return Signature(varies, *args, **kwargs)
  674. subtask = signature # XXX compat
  675. def maybe_signature(d, app=None):
  676. if d is not None:
  677. if isinstance(d, dict):
  678. if not isinstance(d, Signature):
  679. d = signature(d)
  680. elif isinstance(d, list):
  681. return [maybe_signature(s, app=app) for s in d]
  682. if app is not None:
  683. d._app = app
  684. return d
  685. maybe_subtask = maybe_signature # XXX compat