canvas.py 34 KB

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