canvas.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020
  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, get_current_worker_task
  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, noop, 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 Python2.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: # no tasks for chain, etc to find type
  209. return
  210. # For callbacks: extra args are prepended to the stored args.
  211. if args or kwargs or options:
  212. args, kwargs, options = self._merge(args, kwargs, options)
  213. else:
  214. args, kwargs, options = self.args, self.kwargs, self.options
  215. return _apply(args, kwargs, **options)
  216. def append_to_list_option(self, key, value):
  217. items = self.options.setdefault(key, [])
  218. if not isinstance(items, MutableSequence):
  219. items = self.options[key] = [items]
  220. if value not in items:
  221. items.append(value)
  222. return value
  223. def link(self, callback):
  224. return self.append_to_list_option('link', callback)
  225. def link_error(self, errback):
  226. return self.append_to_list_option('link_error', errback)
  227. def flatten_links(self):
  228. return list(_chain.from_iterable(_chain(
  229. [[self]],
  230. (link.flatten_links()
  231. for link in maybe_list(self.options.get('link')) or [])
  232. )))
  233. def __or__(self, other):
  234. if isinstance(other, group):
  235. other = maybe_unroll_group(other)
  236. if not isinstance(self, chain) and isinstance(other, chain):
  237. return chain((self,) + other.tasks, app=self._app)
  238. elif isinstance(other, chain):
  239. return chain(*self.tasks + other.tasks, app=self._app)
  240. elif isinstance(other, Signature):
  241. if isinstance(self, chain):
  242. return chain(*self.tasks + (other,), app=self._app)
  243. return chain(self, other, app=self._app)
  244. return NotImplemented
  245. def __deepcopy__(self, memo):
  246. memo[id(self)] = self
  247. return dict(self)
  248. def __invert__(self):
  249. return self.apply_async().get()
  250. def __reduce__(self):
  251. # for serialization, the task type is lazily loaded,
  252. # and not stored in the dict itself.
  253. return signature, (dict(self),)
  254. def __json__(self):
  255. return dict(self)
  256. def reprcall(self, *args, **kwargs):
  257. args, kwargs, _ = self._merge(args, kwargs, {})
  258. return reprcall(self['task'], args, kwargs)
  259. def election(self):
  260. type = self.type
  261. app = type.app
  262. tid = self.options.get('task_id') or uuid()
  263. with app.producer_or_acquire(None) as P:
  264. props = type.backend.on_task_call(P, tid)
  265. app.control.election(tid, 'task', self.clone(task_id=tid, **props),
  266. connection=P.connection)
  267. return type.AsyncResult(tid)
  268. def __repr__(self):
  269. return self.reprcall()
  270. if JSON_NEEDS_UNICODE_KEYS:
  271. def items(self):
  272. for k, v in dict.items(self):
  273. yield k.decode() if isinstance(k, bytes) else k, v
  274. @property
  275. def name(self):
  276. # for duck typing compatibility with Task.name
  277. return self.task
  278. @cached_property
  279. def type(self):
  280. return self._type or self.app.tasks[self['task']]
  281. @cached_property
  282. def app(self):
  283. return self._app or current_app
  284. @cached_property
  285. def AsyncResult(self):
  286. try:
  287. return self.type.AsyncResult
  288. except KeyError: # task not registered
  289. return self.app.AsyncResult
  290. @cached_property
  291. def _apply_async(self):
  292. try:
  293. return self.type.apply_async
  294. except KeyError:
  295. return _partial(self.app.send_task, self['task'])
  296. id = _getitem_property('options.task_id')
  297. parent_id = _getitem_property('options.parent_id')
  298. root_id = _getitem_property('options.root_id')
  299. task = _getitem_property('task')
  300. args = _getitem_property('args')
  301. kwargs = _getitem_property('kwargs')
  302. options = _getitem_property('options')
  303. subtask_type = _getitem_property('subtask_type')
  304. chord_size = _getitem_property('chord_size')
  305. immutable = _getitem_property('immutable')
  306. abstract.CallableSignature.register(Signature)
  307. @Signature.register_type
  308. class chain(Signature):
  309. tasks = _getitem_property('kwargs.tasks')
  310. def __init__(self, *tasks, **options):
  311. tasks = (regen(tasks[0]) if len(tasks) == 1 and is_list(tasks[0])
  312. else tasks)
  313. Signature.__init__(
  314. self, 'celery.chain', (), {'tasks': tasks}, **options
  315. )
  316. self._use_link = options.pop('use_link', None)
  317. self.subtask_type = 'chain'
  318. self._frozen = None
  319. def __call__(self, *args, **kwargs):
  320. if self.tasks:
  321. return self.apply_async(args, kwargs)
  322. def apply_async(self, args=(), kwargs={}, **options):
  323. # python is best at unpacking kwargs, so .run is here to do that.
  324. app = self.app
  325. if app.conf.task_always_eager:
  326. return self.apply(args, kwargs, **options)
  327. return self.run(args, kwargs, app=app, **(
  328. dict(self.options, **options) if options else self.options))
  329. def run(self, args=(), kwargs={}, group_id=None, chord=None,
  330. task_id=None, link=None, link_error=None, publisher=None,
  331. producer=None, root_id=None, parent_id=None, app=None, **options):
  332. app = app or self.app
  333. use_link = self._use_link
  334. args = (tuple(args) + tuple(self.args)
  335. if args and not self.immutable else self.args)
  336. if self._frozen:
  337. tasks, results = self._frozen
  338. else:
  339. tasks, results = self.prepare_steps(
  340. args, self.tasks, root_id, parent_id, link_error, app,
  341. task_id, group_id, chord,
  342. )
  343. if results:
  344. if link:
  345. tasks[0].set(link=link)
  346. first_task = tasks.pop()
  347. first_task.apply_async(
  348. chain=tasks if not use_link else None, **options)
  349. return results[0]
  350. def freeze(self, _id=None, group_id=None, chord=None,
  351. root_id=None, parent_id=None):
  352. _, results = self._frozen = self.prepare_steps(
  353. self.args, self.tasks, root_id, parent_id, None,
  354. self.app, _id, group_id, chord, clone=False,
  355. )
  356. return results[-1]
  357. def prepare_steps(self, args, tasks,
  358. root_id=None, parent_id=None, link_error=None, app=None,
  359. last_task_id=None, group_id=None, chord_body=None,
  360. clone=True, from_dict=Signature.from_dict):
  361. app = app or self.app
  362. # use chain message field for protocol 2 and later.
  363. # this avoids pickle blowing the stack on the recursion
  364. # required by linking task together in a tree structure.
  365. # (why is pickle using recursion? or better yet why cannot python
  366. # do tail call optimization making recursion actually useful?)
  367. use_link = self._use_link
  368. if use_link is None and app.conf.task_protocol > 1:
  369. use_link = False
  370. steps = deque(tasks)
  371. steps_pop = steps.pop
  372. steps_extend = steps.extend
  373. next_step = prev_task = prev_prev_task = None
  374. prev_res = prev_prev_res = None
  375. tasks, results = [], []
  376. i = 0
  377. while steps:
  378. task = steps_pop()
  379. is_first_task, is_last_task = not steps, not i
  380. if not isinstance(task, abstract.CallableSignature):
  381. task = from_dict(task, app=app)
  382. if isinstance(task, group):
  383. task = maybe_unroll_group(task)
  384. # first task gets partial args from chain
  385. if clone:
  386. task = task.clone(args) if is_first_task else task.clone()
  387. elif is_first_task:
  388. task.args = tuple(args) + tuple(task.args)
  389. if isinstance(task, chain):
  390. # splice the chain
  391. steps_extend(task.tasks)
  392. continue
  393. if isinstance(task, group) and prev_task:
  394. # automatically upgrade group(...) | s to chord(group, s)
  395. # for chords we freeze by pretending it's a normal
  396. # signature instead of a group.
  397. tasks.pop()
  398. results.pop()
  399. prev_res = prev_prev_res
  400. task = chord(
  401. task, body=prev_task,
  402. task_id=res.task_id, root_id=root_id, app=app,
  403. )
  404. if is_last_task:
  405. # chain(task_id=id) means task id is set for the last task
  406. # in the chain. If the chord is part of a chord/group
  407. # then that chord/group must synchronize based on the
  408. # last task in the chain, so we only set the group_id and
  409. # chord callback for the last task.
  410. res = task.freeze(
  411. last_task_id,
  412. root_id=root_id, group_id=group_id, chord=chord_body,
  413. )
  414. else:
  415. res = task.freeze(root_id=root_id)
  416. i += 1
  417. if prev_task:
  418. prev_task.set_parent_id(task.id)
  419. if use_link:
  420. # link previous task to this task.
  421. task.link(prev_task)
  422. if not res.parent and prev_res:
  423. prev_res.parent = res.parent
  424. elif prev_res:
  425. prev_res.parent = res
  426. if is_first_task and parent_id is not None:
  427. task.set_parent_id(parent_id)
  428. if link_error:
  429. task.set(link_error=link_error)
  430. tasks.append(task)
  431. results.append(res)
  432. prev_prev_task, prev_task, prev_prev_res, prev_res = (
  433. prev_task, task, prev_res, res,
  434. )
  435. if root_id is None and tasks:
  436. root_id = tasks[-1].id
  437. for task in reversed(tasks):
  438. task.options['root_id'] = root_id
  439. return tasks, results
  440. def apply(self, args=(), kwargs={}, **options):
  441. last, fargs = None, args
  442. for task in self.tasks:
  443. res = task.clone(fargs).apply(
  444. last and (last.get(),), **dict(self.options, **options))
  445. res.parent, last, fargs = last, res, None
  446. return last
  447. @classmethod
  448. def from_dict(self, d, app=None):
  449. tasks = d['kwargs']['tasks']
  450. if tasks:
  451. if isinstance(tasks, tuple): # aaaargh
  452. tasks = d['kwargs']['tasks'] = list(tasks)
  453. # First task must be signature object to get app
  454. tasks[0] = maybe_signature(tasks[0], app=app)
  455. return _upgrade(d, chain(*tasks, app=app, **d['options']))
  456. @property
  457. def app(self):
  458. app = self._app
  459. if app is None:
  460. try:
  461. app = self.tasks[0]._app
  462. except (KeyError, IndexError):
  463. pass
  464. return app or current_app
  465. def __repr__(self):
  466. return ' | '.join(repr(t) for t in self.tasks)
  467. class _basemap(Signature):
  468. _task_name = None
  469. _unpack_args = itemgetter('task', 'it')
  470. def __init__(self, task, it, **options):
  471. Signature.__init__(
  472. self, self._task_name, (),
  473. {'task': task, 'it': regen(it)}, immutable=True, **options
  474. )
  475. def apply_async(self, args=(), kwargs={}, **opts):
  476. # need to evaluate generators
  477. task, it = self._unpack_args(self.kwargs)
  478. return self.type.apply_async(
  479. (), {'task': task, 'it': list(it)},
  480. route_name=task_name_from(self.kwargs.get('task')), **opts
  481. )
  482. @classmethod
  483. def from_dict(cls, d, app=None):
  484. return _upgrade(
  485. d, cls(*cls._unpack_args(d['kwargs']), app=app, **d['options']),
  486. )
  487. @Signature.register_type
  488. class xmap(_basemap):
  489. _task_name = 'celery.map'
  490. def __repr__(self):
  491. task, it = self._unpack_args(self.kwargs)
  492. return '[{0}(x) for x in {1}]'.format(task.task,
  493. truncate(repr(it), 100))
  494. @Signature.register_type
  495. class xstarmap(_basemap):
  496. _task_name = 'celery.starmap'
  497. def __repr__(self):
  498. task, it = self._unpack_args(self.kwargs)
  499. return '[{0}(*x) for x in {1}]'.format(task.task,
  500. truncate(repr(it), 100))
  501. @Signature.register_type
  502. class chunks(Signature):
  503. _unpack_args = itemgetter('task', 'it', 'n')
  504. def __init__(self, task, it, n, **options):
  505. Signature.__init__(
  506. self, 'celery.chunks', (),
  507. {'task': task, 'it': regen(it), 'n': n},
  508. immutable=True, **options
  509. )
  510. @classmethod
  511. def from_dict(self, d, app=None):
  512. return _upgrade(
  513. d, chunks(*self._unpack_args(
  514. d['kwargs']), app=app, **d['options']),
  515. )
  516. def apply_async(self, args=(), kwargs={}, **opts):
  517. return self.group().apply_async(
  518. args, kwargs,
  519. route_name=task_name_from(self.kwargs.get('task')), **opts
  520. )
  521. def __call__(self, **options):
  522. return self.apply_async(**options)
  523. def group(self):
  524. # need to evaluate generators
  525. task, it, n = self._unpack_args(self.kwargs)
  526. return group((xstarmap(task, part, app=self._app)
  527. for part in _chunks(iter(it), n)),
  528. app=self._app)
  529. @classmethod
  530. def apply_chunks(cls, task, it, n, app=None):
  531. return cls(task, it, n, app=app)()
  532. def _maybe_group(tasks, app):
  533. if isinstance(tasks, dict):
  534. tasks = signature(tasks, app=app)
  535. if isinstance(tasks, group):
  536. tasks = tasks.tasks
  537. elif isinstance(tasks, abstract.CallableSignature):
  538. tasks = [tasks]
  539. else:
  540. tasks = [signature(t, app=app) for t in regen(tasks)]
  541. return tasks
  542. @Signature.register_type
  543. class group(Signature):
  544. tasks = _getitem_property('kwargs.tasks')
  545. def __init__(self, *tasks, **options):
  546. app = options.get('app')
  547. if len(tasks) == 1:
  548. tasks = _maybe_group(tasks[0], app)
  549. Signature.__init__(
  550. self, 'celery.group', (), {'tasks': tasks}, **options
  551. )
  552. self.subtask_type = 'group'
  553. @classmethod
  554. def from_dict(self, d, app=None):
  555. return _upgrade(
  556. d, group(d['kwargs']['tasks'], app=app, **d['options']),
  557. )
  558. def __len__(self):
  559. return len(self.tasks)
  560. def _prepared(self, tasks, partial_args, group_id, root_id, app, dict=dict,
  561. CallableSignature=abstract.CallableSignature,
  562. from_dict=Signature.from_dict):
  563. for task in tasks:
  564. if isinstance(task, dict):
  565. if isinstance(task, CallableSignature):
  566. # local sigs are always of type Signature, and we
  567. # clone them to make sure we do not modify the originals.
  568. task = task.clone()
  569. else:
  570. # serialized sigs must be converted to Signature.
  571. task = from_dict(task, app=app)
  572. if isinstance(task, group):
  573. # needs yield_from :(
  574. unroll = task_prepared(
  575. task.tasks, partial_args, group_id, root_id, app,
  576. )
  577. for taskN, resN in unroll:
  578. yield taskN, resN
  579. else:
  580. if partial_args and not task.immutable:
  581. task.args = tuple(partial_args) + tuple(task.args)
  582. yield task, task.freeze(group_id=group_id, root_id=root_id)
  583. def _apply_tasks(self, tasks, producer=None, app=None,
  584. add_to_parent=None, **options):
  585. app = app or self.app
  586. with app.producer_or_acquire(producer) as producer:
  587. for sig, res in tasks:
  588. sig.apply_async(producer=producer, add_to_parent=False,
  589. **options)
  590. yield res # <-- r.parent, etc set in the frozen result.
  591. def _freeze_gid(self, options):
  592. # remove task_id and use that as the group_id,
  593. # if we don't remove it then every task will have the same id...
  594. options = dict(self.options, **options)
  595. options['group_id'] = group_id = (
  596. options.pop('task_id', uuid()))
  597. return options, group_id, options.get('root_id')
  598. def set_parent_id(self, parent_id):
  599. for task in self.tasks:
  600. task.set_parent_id(parent_id)
  601. def apply_async(self, args=(), kwargs=None, add_to_parent=True,
  602. producer=None, **options):
  603. app = self.app
  604. if app.conf.task_always_eager:
  605. return self.apply(args, kwargs, **options)
  606. if not self.tasks:
  607. return self.freeze()
  608. options, group_id, root_id = self._freeze_gid(options)
  609. tasks = self._prepared(self.tasks, args, group_id, root_id, app)
  610. result = self.app.GroupResult(
  611. group_id, list(self._apply_tasks(tasks, producer, app, **options)),
  612. )
  613. # - Special case of group(A.s() | group(B.s(), C.s()))
  614. # That is, group with single item that is a chain but the
  615. # last task in that chain is a group.
  616. #
  617. # We cannot actually support arbitrary GroupResults in chains,
  618. # but this special case we can.
  619. if len(result) == 1 and isinstance(result[0], GroupResult):
  620. result = result[0]
  621. parent_task = get_current_worker_task()
  622. if add_to_parent and parent_task:
  623. parent_task.add_trail(result)
  624. return result
  625. def apply(self, args=(), kwargs={}, **options):
  626. app = self.app
  627. if not self.tasks:
  628. return self.freeze() # empty group returns GroupResult
  629. options, group_id, root_id = self._freeze_gid(options)
  630. tasks = self._prepared(self.tasks, args, group_id, root_id, app)
  631. return app.GroupResult(group_id, [
  632. sig.apply(**options) for sig, _ in tasks
  633. ])
  634. def set_immutable(self, immutable):
  635. for task in self.tasks:
  636. task.set_immutable(immutable)
  637. def link(self, sig):
  638. # Simply link to first task
  639. sig = sig.clone().set(immutable=True)
  640. return self.tasks[0].link(sig)
  641. def link_error(self, sig):
  642. sig = sig.clone().set(immutable=True)
  643. return self.tasks[0].link_error(sig)
  644. def __call__(self, *partial_args, **options):
  645. return self.apply_async(partial_args, **options)
  646. def _freeze_unroll(self, new_tasks, group_id, chord, root_id, parent_id):
  647. stack = deque(self.tasks)
  648. while stack:
  649. task = maybe_signature(stack.popleft(), app=self._app).clone()
  650. if isinstance(task, group):
  651. stack.extendleft(task.tasks)
  652. else:
  653. new_tasks.append(task)
  654. yield task.freeze(group_id=group_id,
  655. chord=chord, root_id=root_id,
  656. parent_id=parent_id)
  657. def freeze(self, _id=None, group_id=None, chord=None,
  658. root_id=None, parent_id=None):
  659. opts = self.options
  660. try:
  661. gid = opts['task_id']
  662. except KeyError:
  663. gid = opts['task_id'] = uuid()
  664. if group_id:
  665. opts['group_id'] = group_id
  666. if chord:
  667. opts['chord'] = chord
  668. root_id = opts.setdefault('root_id', root_id)
  669. parent_id = opts.setdefault('parent_id', parent_id)
  670. new_tasks = []
  671. # Need to unroll subgroups early so that chord gets the
  672. # right result instance for chord_unlock etc.
  673. results = list(self._freeze_unroll(
  674. new_tasks, group_id, chord, root_id, parent_id,
  675. ))
  676. if isinstance(self.tasks, MutableSequence):
  677. self.tasks[:] = new_tasks
  678. else:
  679. self.tasks = new_tasks
  680. return self.app.GroupResult(gid, results)
  681. _freeze = freeze
  682. def skew(self, start=1.0, stop=None, step=1.0):
  683. it = fxrange(start, stop, step, repeatlast=True)
  684. for task in self.tasks:
  685. task.set(countdown=next(it))
  686. return self
  687. def __iter__(self):
  688. return iter(self.tasks)
  689. def __repr__(self):
  690. return repr(self.tasks)
  691. @property
  692. def app(self):
  693. app = self._app
  694. if app is None:
  695. try:
  696. app = self.tasks[0].app
  697. except (KeyError, IndexError):
  698. pass
  699. return app if app is not None else current_app
  700. @Signature.register_type
  701. class chord(Signature):
  702. def __init__(self, header, body=None, task='celery.chord',
  703. args=(), kwargs={}, app=None, **options):
  704. Signature.__init__(
  705. self, task, args,
  706. dict(kwargs, header=_maybe_group(header, app),
  707. body=maybe_signature(body, app=self._app)), **options
  708. )
  709. self.subtask_type = 'chord'
  710. def freeze(self, _id=None, group_id=None, chord=None,
  711. root_id=None, parent_id=None):
  712. if not isinstance(self.tasks, group):
  713. self.tasks = group(self.tasks)
  714. self.tasks.freeze(parent_id=parent_id, root_id=root_id)
  715. self.id = self.tasks.id
  716. return self.body.freeze(_id, parent_id=self.id, root_id=root_id)
  717. def set_parent_id(self, parent_id):
  718. tasks = self.tasks
  719. if isinstance(tasks, group):
  720. tasks = tasks.tasks
  721. for task in tasks:
  722. task.set_parent_id(parent_id)
  723. self.parent_id = parent_id
  724. @classmethod
  725. def from_dict(self, d, app=None):
  726. args, d['kwargs'] = self._unpack_args(**d['kwargs'])
  727. return _upgrade(d, self(*args, app=app, **d))
  728. @staticmethod
  729. def _unpack_args(header=None, body=None, **kwargs):
  730. # Python signatures are better at extracting keys from dicts
  731. # than manually popping things off.
  732. return (header, body), kwargs
  733. @cached_property
  734. def app(self):
  735. return self._get_app(self.body)
  736. def _get_app(self, body=None):
  737. app = self._app
  738. if app is None:
  739. try:
  740. tasks = self.tasks.tasks # is a group
  741. except AttributeError:
  742. tasks = self.tasks
  743. app = tasks[0]._app
  744. if app is None and body is not None:
  745. app = body._app
  746. return app if app is not None else current_app
  747. def apply_async(self, args=(), kwargs={}, task_id=None,
  748. producer=None, publisher=None, connection=None,
  749. router=None, result_cls=None, **options):
  750. args = (tuple(args) + tuple(self.args)
  751. if args and not self.immutable else self.args)
  752. body = kwargs.get('body') or self.kwargs['body']
  753. kwargs = dict(self.kwargs, **kwargs)
  754. body = body.clone(**options)
  755. app = self._get_app(body)
  756. tasks = (self.tasks.clone() if isinstance(self.tasks, group)
  757. else group(self.tasks))
  758. if app.conf.task_always_eager:
  759. return self.apply((), kwargs,
  760. body=body, task_id=task_id, **options)
  761. return self.run(tasks, body, args, task_id=task_id, **options)
  762. def apply(self, args=(), kwargs={}, propagate=True, body=None, **options):
  763. body = self.body if body is None else body
  764. tasks = (self.tasks.clone() if isinstance(self.tasks, group)
  765. else group(self.tasks))
  766. return body.apply(
  767. args=(tasks.apply().get(propagate=propagate),),
  768. )
  769. def _traverse_tasks(self, tasks, value=None):
  770. stack = deque(tasks)
  771. while stack:
  772. task = stack.popleft()
  773. if isinstance(task, group):
  774. stack.extend(task.tasks)
  775. else:
  776. yield task if value is None else value
  777. def __length_hint__(self):
  778. return sum(self._traverse_tasks(self.tasks, 1))
  779. def run(self, header, body, partial_args, app=None, interval=None,
  780. countdown=1, max_retries=None, eager=False,
  781. task_id=None, **options):
  782. app = app or self._get_app(body)
  783. group_id = uuid()
  784. root_id = body.options.get('root_id')
  785. body.chord_size = self.__length_hint__()
  786. options = dict(self.options, **options) if options else self.options
  787. if options:
  788. options.pop('task_id', None)
  789. body.options.update(options)
  790. results = header.freeze(
  791. group_id=group_id, chord=body, root_id=root_id).results
  792. bodyres = body.freeze(task_id, root_id=root_id)
  793. parent = app.backend.apply_chord(
  794. header, partial_args, group_id, body,
  795. interval=interval, countdown=countdown,
  796. options=options, max_retries=max_retries,
  797. result=results)
  798. bodyres.parent = parent
  799. return bodyres
  800. def __call__(self, body=None, **options):
  801. return self.apply_async((), {'body': body} if body else {}, **options)
  802. def clone(self, *args, **kwargs):
  803. s = Signature.clone(self, *args, **kwargs)
  804. # need to make copy of body
  805. try:
  806. s.kwargs['body'] = s.kwargs['body'].clone()
  807. except (AttributeError, KeyError):
  808. pass
  809. return s
  810. def link(self, callback):
  811. self.body.link(callback)
  812. return callback
  813. def link_error(self, errback):
  814. self.body.link_error(errback)
  815. return errback
  816. def set_immutable(self, immutable):
  817. # changes mutability of header only, not callback.
  818. for task in self.tasks:
  819. task.set_immutable(immutable)
  820. def __repr__(self):
  821. if self.body:
  822. return self.body.reprcall(self.tasks)
  823. return '<chord without body: {0.tasks!r}>'.format(self)
  824. tasks = _getitem_property('kwargs.header')
  825. body = _getitem_property('kwargs.body')
  826. def signature(varies, *args, **kwargs):
  827. if isinstance(varies, dict):
  828. if isinstance(varies, abstract.CallableSignature):
  829. return varies.clone()
  830. return Signature.from_dict(varies)
  831. return Signature(varies, *args, **kwargs)
  832. subtask = signature # XXX compat
  833. def maybe_signature(d, app=None):
  834. if d is not None:
  835. if isinstance(d, dict):
  836. if not isinstance(d, abstract.CallableSignature):
  837. d = signature(d)
  838. elif isinstance(d, list):
  839. return [maybe_signature(s, app=app) for s in d]
  840. if app is not None:
  841. d._app = app
  842. return d
  843. maybe_subtask = maybe_signature # XXX compat