canvas.py 35 KB

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