canvas.py 31 KB

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