canvas.py 34 KB

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