canvas.py 35 KB

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