canvas.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874
  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. tasks = _getitem_property('kwargs.tasks')
  278. def __init__(self, *tasks, **options):
  279. tasks = (regen(tasks[0]) if len(tasks) == 1 and is_list(tasks[0])
  280. else tasks)
  281. Signature.__init__(
  282. self, 'celery.chain', (), {'tasks': tasks}, **options
  283. )
  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={}, **options):
  289. # python is best at unpacking kwargs, so .run is here to do that.
  290. app = self.app
  291. if app.conf.CELERY_ALWAYS_EAGER:
  292. return self.apply(args, kwargs, **options)
  293. return self.run(args, kwargs, app=app, **(
  294. dict(self.options, **options) if options else self.options))
  295. def run(self, args=(), kwargs={}, group_id=None, chord=None,
  296. task_id=None, link=None, link_error=None,
  297. publisher=None, producer=None, root_id=None, app=None, **options):
  298. app = app or self.app
  299. tasks, results = self.prepare_steps(
  300. args, self.tasks, root_id, link_error,
  301. )
  302. if not results:
  303. return
  304. result = results[-1]
  305. last_task = tasks[-1]
  306. if group_id:
  307. last_task.set(group_id=group_id)
  308. if chord:
  309. last_task.set(chord=chord)
  310. if task_id:
  311. last_task.set(task_id=task_id)
  312. result = last_task.type.AsyncResult(task_id)
  313. # make sure we can do a link() and link_error() on a chain object.
  314. if link:
  315. tasks[-1].set(link=link)
  316. tasks[0].apply_async(**options)
  317. return result
  318. def prepare_steps(self, args, tasks,
  319. root_id=None, link_error=None, app=None):
  320. app = app or self.app
  321. steps = deque(tasks)
  322. next_step = prev_task = prev_res = None
  323. tasks, results = [], []
  324. i = 0
  325. while steps:
  326. task = steps.popleft()
  327. if not i: # first task
  328. # first task gets partial args from chain
  329. task = task.clone(args)
  330. res = task.freeze(root_id=root_id)
  331. root_id = res.id if root_id is None else root_id
  332. else:
  333. task = task.clone()
  334. res = task.freeze(root_id=root_id)
  335. i += 1
  336. if isinstance(task, group):
  337. task = maybe_unroll_group(task)
  338. if isinstance(task, chain):
  339. # splice the chain
  340. steps.extendleft(reversed(task.tasks))
  341. continue
  342. elif isinstance(task, group) and steps and \
  343. not isinstance(steps[0], group):
  344. # automatically upgrade group(...) | s to chord(group, s)
  345. try:
  346. next_step = steps.popleft()
  347. # for chords we freeze by pretending it's a normal
  348. # signature instead of a group.
  349. res = Signature.freeze(next_step)
  350. task = chord(
  351. task, body=next_step,
  352. task_id=res.task_id, root_id=root_id,
  353. )
  354. except IndexError:
  355. pass # no callback, so keep as group.
  356. if prev_task:
  357. # link previous task to this task.
  358. prev_task.link(task)
  359. # set AsyncResult.parent
  360. if not res.parent:
  361. res.parent = prev_res
  362. if link_error:
  363. task.set(link_error=link_error)
  364. if not isinstance(prev_task, chord):
  365. results.append(res)
  366. tasks.append(task)
  367. prev_task, prev_res = task, res
  368. return tasks, results
  369. def apply(self, args=(), kwargs={}, **options):
  370. last, fargs = None, args
  371. for task in self.tasks:
  372. res = task.clone(fargs).apply(
  373. last and (last.get(), ), **dict(self.options, **options))
  374. res.parent, last, fargs = last, res, None
  375. return last
  376. @classmethod
  377. def from_dict(self, d, app=None):
  378. tasks = d['kwargs']['tasks']
  379. if d['args'] and tasks:
  380. # partial args passed on to first task in chain (Issue #1057).
  381. tasks[0]['args'] = tasks[0]._merge(d['args'])[0]
  382. return chain(*d['kwargs']['tasks'], app=app, **d['options'])
  383. @property
  384. def app(self):
  385. app = self._app
  386. if app is None:
  387. try:
  388. app = self.tasks[0]._app
  389. except (KeyError, IndexError):
  390. pass
  391. return app or current_app
  392. def __repr__(self):
  393. return ' | '.join(repr(t) for t in self.tasks)
  394. class _basemap(Signature):
  395. _task_name = None
  396. _unpack_args = itemgetter('task', 'it')
  397. def __init__(self, task, it, **options):
  398. Signature.__init__(
  399. self, self._task_name, (),
  400. {'task': task, 'it': regen(it)}, immutable=True, **options
  401. )
  402. def apply_async(self, args=(), kwargs={}, **opts):
  403. # need to evaluate generators
  404. task, it = self._unpack_args(self.kwargs)
  405. return self.type.apply_async(
  406. (), {'task': task, 'it': list(it)}, **opts
  407. )
  408. @classmethod
  409. def from_dict(cls, d, app=None):
  410. return cls(*cls._unpack_args(d['kwargs']), app=app, **d['options'])
  411. @Signature.register_type
  412. class xmap(_basemap):
  413. _task_name = 'celery.map'
  414. def __repr__(self):
  415. task, it = self._unpack_args(self.kwargs)
  416. return '[{0}(x) for x in {1}]'.format(task.task,
  417. truncate(repr(it), 100))
  418. @Signature.register_type
  419. class xstarmap(_basemap):
  420. _task_name = 'celery.starmap'
  421. def __repr__(self):
  422. task, it = self._unpack_args(self.kwargs)
  423. return '[{0}(*x) for x in {1}]'.format(task.task,
  424. truncate(repr(it), 100))
  425. @Signature.register_type
  426. class chunks(Signature):
  427. _unpack_args = itemgetter('task', 'it', 'n')
  428. def __init__(self, task, it, n, **options):
  429. Signature.__init__(
  430. self, 'celery.chunks', (),
  431. {'task': task, 'it': regen(it), 'n': n},
  432. immutable=True, **options
  433. )
  434. @classmethod
  435. def from_dict(self, d, app=None):
  436. return chunks(*self._unpack_args(d['kwargs']), app=app, **d['options'])
  437. def apply_async(self, args=(), kwargs={}, **opts):
  438. return self.group().apply_async(args, kwargs, **opts)
  439. def __call__(self, **options):
  440. return self.group()(**options)
  441. def group(self):
  442. # need to evaluate generators
  443. task, it, n = self._unpack_args(self.kwargs)
  444. return group((xstarmap(task, part, app=self._app)
  445. for part in _chunks(iter(it), n)),
  446. app=self._app)
  447. @classmethod
  448. def apply_chunks(cls, task, it, n, app=None):
  449. return cls(task, it, n, app=app)()
  450. def _maybe_group(tasks):
  451. if isinstance(tasks, group):
  452. tasks = list(tasks.tasks)
  453. elif isinstance(tasks, Signature):
  454. tasks = [tasks]
  455. else:
  456. tasks = regen(tasks)
  457. return tasks
  458. @Signature.register_type
  459. class group(Signature):
  460. tasks = _getitem_property('kwargs.tasks')
  461. def __init__(self, *tasks, **options):
  462. if len(tasks) == 1:
  463. tasks = _maybe_group(tasks[0])
  464. Signature.__init__(
  465. self, 'celery.group', (), {'tasks': tasks}, **options
  466. )
  467. self.subtask_type = 'group'
  468. @classmethod
  469. def from_dict(self, d, app=None):
  470. tasks = d['kwargs']['tasks']
  471. if d['args'] and tasks:
  472. # partial args passed on to all tasks in the group (Issue #1057).
  473. for task in tasks:
  474. task['args'] = task._merge(d['args'])[0]
  475. return group(tasks, app=app, **d['options'])
  476. def _prepared(self, tasks, partial_args, group_id, root_id, dict=dict,
  477. Signature=Signature, from_dict=Signature.from_dict):
  478. for task in tasks:
  479. if isinstance(task, dict):
  480. if isinstance(task, Signature):
  481. # local sigs are always of type Signature, and we
  482. # clone them to make sure we do not modify the originals.
  483. task = task.clone()
  484. else:
  485. # serialized sigs must be converted to Signature.
  486. task = from_dict(task)
  487. if isinstance(task, group):
  488. # needs yield_from :(
  489. unroll = task._prepared(
  490. task.tasks, partial_args, group_id, root_id,
  491. )
  492. for taskN, resN in unroll:
  493. yield taskN, resN
  494. else:
  495. if partial_args and not task.immutable:
  496. task.args = tuple(partial_args) + tuple(task.args)
  497. yield task, task.freeze(group_id=group_id, root_id=root_id)
  498. def _apply_tasks(self, tasks, producer=None, app=None, **options):
  499. app = app or self.app
  500. with app.producer_or_acquire(producer) as producer:
  501. for sig, res in tasks:
  502. sig.apply_async(producer=producer, add_to_parent=False,
  503. **options)
  504. yield res
  505. def _freeze_gid(self, options):
  506. # remove task_id and use that as the group_id,
  507. # if we don't remove it then every task will have the same id...
  508. options = dict(self.options, **options)
  509. options['group_id'] = group_id = (
  510. options.pop('task_id', uuid()))
  511. return options, group_id, options.get('root_id')
  512. def apply_async(self, args=(), kwargs=None, add_to_parent=True,
  513. producer=None, **options):
  514. app = self.app
  515. if app.conf.CELERY_ALWAYS_EAGER:
  516. return self.apply(args, kwargs, **options)
  517. if not self.tasks:
  518. return self.freeze()
  519. options, group_id, root_id = self._freeze_gid(options)
  520. tasks = self._prepared(self.tasks, args, group_id, root_id)
  521. result = self.app.GroupResult(
  522. group_id, list(self._apply_tasks(tasks, producer, app, **options)),
  523. )
  524. parent_task = get_current_worker_task()
  525. if add_to_parent and parent_task:
  526. parent_task.add_trail(result)
  527. return result
  528. def apply(self, args=(), kwargs={}, **options):
  529. app = self.app
  530. if not self.tasks:
  531. return self.freeze() # empty group returns GroupResult
  532. options, group_id, root_id = self._freeze_gid(options)
  533. tasks = self._prepared(self.tasks, args, group_id, root_id)
  534. return app.GroupResult(group_id, [
  535. sig.apply(**options) for sig, _ in tasks
  536. ])
  537. def set_immutable(self, immutable):
  538. for task in self.tasks:
  539. task.set_immutable(immutable)
  540. def link(self, sig):
  541. # Simply link to first task
  542. sig = sig.clone().set(immutable=True)
  543. return self.tasks[0].link(sig)
  544. def link_error(self, sig):
  545. sig = sig.clone().set(immutable=True)
  546. return self.tasks[0].link_error(sig)
  547. def __call__(self, *partial_args, **options):
  548. return self.apply_async(partial_args, **options)
  549. def _freeze_unroll(self, new_tasks, group_id, chord, root_id):
  550. stack = deque(self.tasks)
  551. while stack:
  552. task = maybe_signature(stack.popleft(), app=self._app).clone()
  553. if isinstance(task, group):
  554. stack.extendleft(task.tasks)
  555. else:
  556. new_tasks.append(task)
  557. yield task.freeze(group_id=group_id,
  558. chord=chord, root_id=root_id)
  559. def freeze(self, _id=None, group_id=None, chord=None, root_id=None):
  560. opts = self.options
  561. try:
  562. gid = opts['task_id']
  563. except KeyError:
  564. gid = opts['task_id'] = uuid()
  565. if group_id:
  566. opts['group_id'] = group_id
  567. if chord:
  568. opts['chord'] = chord
  569. root_id = opts.setdefault('root_id', root_id)
  570. new_tasks = []
  571. # Need to unroll subgroups early so that chord gets the
  572. # right result instance for chord_unlock etc.
  573. results = list(self._freeze_unroll(
  574. new_tasks, group_id, chord, root_id,
  575. ))
  576. if isinstance(self.tasks, MutableSequence):
  577. self.tasks[:] = new_tasks
  578. else:
  579. self.tasks = new_tasks
  580. return self.app.GroupResult(gid, results)
  581. _freeze = freeze
  582. def skew(self, start=1.0, stop=None, step=1.0):
  583. it = fxrange(start, stop, step, repeatlast=True)
  584. for task in self.tasks:
  585. task.set(countdown=next(it))
  586. return self
  587. def __iter__(self):
  588. return iter(self.tasks)
  589. def __repr__(self):
  590. return repr(self.tasks)
  591. @property
  592. def app(self):
  593. app = self._app
  594. if app is None:
  595. try:
  596. app = self.tasks[0].app
  597. except (KeyError, IndexError):
  598. pass
  599. return app if app is not None else current_app
  600. @Signature.register_type
  601. class chord(Signature):
  602. def __init__(self, header, body=None, task='celery.chord',
  603. args=(), kwargs={}, **options):
  604. Signature.__init__(
  605. self, task, args,
  606. dict(kwargs, header=_maybe_group(header),
  607. body=maybe_signature(body, app=self._app)), **options
  608. )
  609. self.subtask_type = 'chord'
  610. def freeze(self, *args, **kwargs):
  611. return self.body.freeze(*args, **kwargs)
  612. @classmethod
  613. def from_dict(self, d, app=None):
  614. args, d['kwargs'] = self._unpack_args(**d['kwargs'])
  615. return self(*args, app=app, **d)
  616. @staticmethod
  617. def _unpack_args(header=None, body=None, **kwargs):
  618. # Python signatures are better at extracting keys from dicts
  619. # than manually popping things off.
  620. return (header, body), kwargs
  621. @cached_property
  622. def app(self):
  623. return self._get_app(self.body)
  624. def _get_app(self, body=None):
  625. app = self._app
  626. if app is None:
  627. app = self.tasks[0]._app
  628. if app is None and body is not None:
  629. app = body._app
  630. return app if app is not None else current_app
  631. def apply_async(self, args=(), kwargs={}, task_id=None,
  632. producer=None, publisher=None, connection=None,
  633. router=None, result_cls=None, **options):
  634. body = kwargs.get('body') or self.kwargs['body']
  635. kwargs = dict(self.kwargs, **kwargs)
  636. body = body.clone(**options)
  637. app = self._get_app(body)
  638. tasks = (self.tasks.clone() if isinstance(self.tasks, group)
  639. else group(self.tasks))
  640. if app.conf.CELERY_ALWAYS_EAGER:
  641. return self.apply((), kwargs,
  642. body=body, task_id=task_id, **options)
  643. return self.run(tasks, body, args, task_id=task_id, **options)
  644. def apply(self, args=(), kwargs={}, propagate=True, body=None, **options):
  645. body = self.body if body is None else body
  646. tasks = (self.tasks.clone() if isinstance(self.tasks, group)
  647. else group(self.tasks))
  648. return body.apply(
  649. args=(tasks.apply().get(propagate=propagate), ),
  650. )
  651. def _traverse_tasks(self, tasks, value=None):
  652. stack = deque(tasks)
  653. while stack:
  654. task = stack.popleft()
  655. if isinstance(task, group):
  656. stack.extend(task.tasks)
  657. else:
  658. yield task if value is None else value
  659. def __length_hint__(self):
  660. return sum(self._traverse_tasks(self.tasks, 1))
  661. def run(self, header, body, partial_args, app=None, interval=None,
  662. countdown=1, max_retries=None, propagate=None, eager=False,
  663. task_id=None, **options):
  664. app = app or self._get_app(body)
  665. propagate = (app.conf.CELERY_CHORD_PROPAGATES
  666. if propagate is None else propagate)
  667. group_id = uuid()
  668. root_id = body.options.get('root_id')
  669. if 'chord_size' not in body:
  670. body['chord_size'] = self.__length_hint__()
  671. results = header.freeze(
  672. group_id=group_id, chord=body, root_id=root_id).results
  673. bodyres = body.freeze(task_id, root_id=root_id)
  674. parent = app.backend.apply_chord(
  675. header, partial_args, group_id, body,
  676. interval=interval, countdown=countdown,
  677. max_retries=max_retries, propagate=propagate, result=results)
  678. bodyres.parent = parent
  679. return bodyres
  680. def __call__(self, body=None, **options):
  681. return self.apply_async((), {'body': body} if body else {}, **options)
  682. def clone(self, *args, **kwargs):
  683. s = Signature.clone(self, *args, **kwargs)
  684. # need to make copy of body
  685. try:
  686. s.kwargs['body'] = s.kwargs['body'].clone()
  687. except (AttributeError, KeyError):
  688. pass
  689. return s
  690. def link(self, callback):
  691. self.body.link(callback)
  692. return callback
  693. def link_error(self, errback):
  694. self.body.link_error(errback)
  695. return errback
  696. def set_immutable(self, immutable):
  697. # changes mutability of header only, not callback.
  698. for task in self.tasks:
  699. task.set_immutable(immutable)
  700. def __repr__(self):
  701. if self.body:
  702. return self.body.reprcall(self.tasks)
  703. return '<chord without body: {0.tasks!r}>'.format(self)
  704. tasks = _getitem_property('kwargs.header')
  705. body = _getitem_property('kwargs.body')
  706. def signature(varies, *args, **kwargs):
  707. if isinstance(varies, dict):
  708. if isinstance(varies, Signature):
  709. return varies.clone()
  710. return Signature.from_dict(varies)
  711. return Signature(varies, *args, **kwargs)
  712. subtask = signature # XXX compat
  713. def maybe_signature(d, app=None):
  714. if d is not None:
  715. if isinstance(d, dict):
  716. if not isinstance(d, Signature):
  717. d = signature(d)
  718. elif isinstance(d, list):
  719. return [maybe_signature(s, app=app) for s in d]
  720. if app is not None:
  721. d._app = app
  722. return d
  723. maybe_subtask = maybe_signature # XXX compat