canvas.py 36 KB

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