canvas.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661
  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
  10. from copy import deepcopy
  11. from functools import partial as _partial, reduce
  12. from operator import itemgetter
  13. from itertools import chain as _chain
  14. from kombu.utils import cached_property, fxrange, kwdict, reprcall, uuid
  15. from celery._state import current_app
  16. from celery.utils.functional import (
  17. maybe_list, is_list, regen,
  18. chunks as _chunks,
  19. )
  20. from celery.utils.text import truncate
  21. __all__ = ['Signature', 'chain', 'xmap', 'xstarmap', 'chunks',
  22. 'group', 'chord', 'signature', 'maybe_signature']
  23. class _getitem_property(object):
  24. """Attribute -> dict key descriptor.
  25. The target object must support ``__getitem__``,
  26. and optionally ``__setitem__``.
  27. Example:
  28. >>> from collections import defaultdict
  29. >>> class Me(dict):
  30. ... deep = defaultdict(dict)
  31. ...
  32. ... foo = _getitem_property('foo')
  33. ... deep_thing = _getitem_property('deep.thing')
  34. >>> me = Me()
  35. >>> me.foo
  36. None
  37. >>> me.foo = 10
  38. >>> me.foo
  39. 10
  40. >>> me['foo']
  41. 10
  42. >>> me.deep_thing = 42
  43. >>> me.deep_thing
  44. 42
  45. >>> me.deep
  46. defaultdict(<type 'dict'>, {'thing': 42})
  47. """
  48. def __init__(self, keypath):
  49. path, _, self.key = keypath.rpartition('.')
  50. self.path = path.split('.') if path else None
  51. def _path(self, obj):
  52. return (reduce(lambda d, k: d[k], [obj] + self.path) if self.path
  53. else obj)
  54. def __get__(self, obj, type=None):
  55. if obj is None:
  56. return type
  57. return self._path(obj).get(self.key)
  58. def __set__(self, obj, value):
  59. self._path(obj)[self.key] = value
  60. def maybe_unroll_group(g):
  61. """Unroll group with only one member."""
  62. # Issue #1656
  63. try:
  64. size = len(g.tasks)
  65. except TypeError:
  66. try:
  67. size = g.tasks.__length_hint__()
  68. except (AttributeError, TypeError):
  69. pass
  70. else:
  71. return list(g.tasks)[0] if size == 1 else g
  72. else:
  73. return g.tasks[0] if size == 1 else g
  74. class Signature(dict):
  75. """Class that wraps the arguments and execution options
  76. for a single task invocation.
  77. Used as the parts in a :class:`group` and other constructs,
  78. or to pass tasks around as callbacks while being compatible
  79. with serializers with a strict type subset.
  80. :param task: Either a task class/instance, or the name of a task.
  81. :keyword args: Positional arguments to apply.
  82. :keyword kwargs: Keyword arguments to apply.
  83. :keyword options: Additional options to :meth:`Task.apply_async`.
  84. Note that if the first argument is a :class:`dict`, the other
  85. arguments will be ignored and the values in the dict will be used
  86. instead.
  87. >>> s = signature('tasks.add', args=(2, 2))
  88. >>> signature(s)
  89. {'task': 'tasks.add', args=(2, 2), kwargs={}, options={}}
  90. """
  91. TYPES = {}
  92. _app = _type = None
  93. @classmethod
  94. def register_type(cls, subclass, name=None):
  95. cls.TYPES[name or subclass.__name__] = subclass
  96. return subclass
  97. @classmethod
  98. def from_dict(self, d, app=None):
  99. typ = d.get('subtask_type')
  100. if typ:
  101. return self.TYPES[typ].from_dict(kwdict(d), app=app)
  102. return Signature(d, app=app)
  103. def __init__(self, task=None, args=None, kwargs=None, options=None,
  104. type=None, subtask_type=None, immutable=False,
  105. app=None, **ex):
  106. self._app = app
  107. init = dict.__init__
  108. if isinstance(task, dict):
  109. return init(self, task) # works like dict(d)
  110. # Also supports using task class/instance instead of string name.
  111. try:
  112. task_name = task.name
  113. except AttributeError:
  114. task_name = task
  115. else:
  116. self._type = task
  117. init(self,
  118. task=task_name, args=tuple(args or ()),
  119. kwargs=kwargs or {},
  120. options=dict(options or {}, **ex),
  121. subtask_type=subtask_type,
  122. immutable=immutable)
  123. def __call__(self, *partial_args, **partial_kwargs):
  124. args, kwargs, _ = self._merge(partial_args, partial_kwargs, None)
  125. return self.type(*args, **kwargs)
  126. def delay(self, *partial_args, **partial_kwargs):
  127. return self.apply_async(partial_args, partial_kwargs)
  128. def apply(self, args=(), kwargs={}, **options):
  129. """Apply this task locally."""
  130. # For callbacks: extra args are prepended to the stored args.
  131. args, kwargs, options = self._merge(args, kwargs, options)
  132. return self.type.apply(args, kwargs, **options)
  133. def _merge(self, args=(), kwargs={}, options={}):
  134. if self.immutable:
  135. return (self.args, self.kwargs,
  136. dict(self.options, **options) if options else self.options)
  137. return (tuple(args) + tuple(self.args) if args else self.args,
  138. dict(self.kwargs, **kwargs) if kwargs else self.kwargs,
  139. dict(self.options, **options) if options else self.options)
  140. def clone(self, args=(), kwargs={}, **opts):
  141. # need to deepcopy options so origins links etc. is not modified.
  142. if args or kwargs or opts:
  143. args, kwargs, opts = self._merge(args, kwargs, opts)
  144. else:
  145. args, kwargs, opts = self.args, self.kwargs, self.options
  146. s = Signature.from_dict({'task': self.task, 'args': tuple(args),
  147. 'kwargs': kwargs, 'options': deepcopy(opts),
  148. 'subtask_type': self.subtask_type,
  149. 'immutable': self.immutable}, app=self._app)
  150. s._type = self._type
  151. return s
  152. partial = clone
  153. def freeze(self, _id=None, group_id=None, chord=None):
  154. opts = self.options
  155. try:
  156. tid = opts['task_id']
  157. except KeyError:
  158. tid = opts['task_id'] = _id or uuid()
  159. if 'reply_to' not in opts:
  160. opts['reply_to'] = self.app.oid
  161. if group_id:
  162. opts['group_id'] = group_id
  163. if chord:
  164. opts['chord'] = chord
  165. return self.AsyncResult(tid)
  166. _freeze = freeze
  167. def replace(self, args=None, kwargs=None, options=None):
  168. s = self.clone()
  169. if args is not None:
  170. s.args = args
  171. if kwargs is not None:
  172. s.kwargs = kwargs
  173. if options is not None:
  174. s.options = options
  175. return s
  176. def set(self, immutable=None, **options):
  177. if immutable is not None:
  178. self.set_immutable(immutable)
  179. self.options.update(options)
  180. return self
  181. def set_immutable(self, immutable):
  182. self.immutable = immutable
  183. def apply_async(self, args=(), kwargs={}, **options):
  184. try:
  185. _apply = self._apply_async
  186. except IndexError: # no tasks for chain, etc to find type
  187. return
  188. # For callbacks: extra args are prepended to the stored args.
  189. if args or kwargs or options:
  190. args, kwargs, options = self._merge(args, kwargs, options)
  191. else:
  192. args, kwargs, options = self.args, self.kwargs, self.options
  193. return _apply(args, kwargs, **options)
  194. def append_to_list_option(self, key, value):
  195. items = self.options.setdefault(key, [])
  196. if value not in items:
  197. items.append(value)
  198. return value
  199. def link(self, callback):
  200. return self.append_to_list_option('link', callback)
  201. def link_error(self, errback):
  202. return self.append_to_list_option('link_error', errback)
  203. def flatten_links(self):
  204. return list(_chain.from_iterable(_chain(
  205. [[self]],
  206. (link.flatten_links()
  207. for link in maybe_list(self.options.get('link')) or [])
  208. )))
  209. def __or__(self, other):
  210. if isinstance(other, group):
  211. other = maybe_unroll_group(other)
  212. if not isinstance(self, chain) and isinstance(other, chain):
  213. return chain((self, ) + other.tasks, app=self._app)
  214. elif isinstance(other, chain):
  215. return chain(*self.tasks + other.tasks, app=self._app)
  216. elif isinstance(other, Signature):
  217. if isinstance(self, chain):
  218. return chain(*self.tasks + (other, ), app=self._app)
  219. return chain(self, other, app=self._app)
  220. return NotImplemented
  221. def __deepcopy__(self, memo):
  222. memo[id(self)] = self
  223. return dict(self)
  224. def __invert__(self):
  225. return self.apply_async().get()
  226. def __reduce__(self):
  227. # for serialization, the task type is lazily loaded,
  228. # and not stored in the dict itself.
  229. return subtask, (dict(self), )
  230. def reprcall(self, *args, **kwargs):
  231. args, kwargs, _ = self._merge(args, kwargs, {})
  232. return reprcall(self['task'], args, kwargs)
  233. def election(self):
  234. type = self.type
  235. app = type.app
  236. tid = self.options.get('task_id') or uuid()
  237. with app.producer_or_acquire(None) as P:
  238. props = type.backend.on_task_call(P, tid)
  239. app.control.election(tid, 'task', self.clone(task_id=tid, **props),
  240. connection=P.connection)
  241. return type.AsyncResult(tid)
  242. def __repr__(self):
  243. return self.reprcall()
  244. @cached_property
  245. def type(self):
  246. return self._type or self.app.tasks[self['task']]
  247. @cached_property
  248. def app(self):
  249. return self._app or current_app
  250. @cached_property
  251. def AsyncResult(self):
  252. try:
  253. return self.type.AsyncResult
  254. except KeyError: # task not registered
  255. return self.app.AsyncResult
  256. @cached_property
  257. def _apply_async(self):
  258. try:
  259. return self.type.apply_async
  260. except KeyError:
  261. return _partial(self.app.send_task, self['task'])
  262. id = _getitem_property('options.task_id')
  263. task = _getitem_property('task')
  264. args = _getitem_property('args')
  265. kwargs = _getitem_property('kwargs')
  266. options = _getitem_property('options')
  267. subtask_type = _getitem_property('subtask_type')
  268. immutable = _getitem_property('immutable')
  269. @Signature.register_type
  270. class chain(Signature):
  271. def __init__(self, *tasks, **options):
  272. tasks = (regen(tasks[0]) if len(tasks) == 1 and is_list(tasks[0])
  273. else tasks)
  274. Signature.__init__(
  275. self, 'celery.chain', (), {'tasks': tasks}, **options
  276. )
  277. self.tasks = tasks
  278. self.subtask_type = 'chain'
  279. def __call__(self, *args, **kwargs):
  280. if self.tasks:
  281. return self.apply_async(args, kwargs)
  282. @classmethod
  283. def from_dict(self, d, app=None):
  284. tasks = d['kwargs']['tasks']
  285. if d['args'] and tasks:
  286. # partial args passed on to first task in chain (Issue #1057).
  287. tasks[0]['args'] = tasks[0]._merge(d['args'])[0]
  288. return chain(*d['kwargs']['tasks'], app=app, **kwdict(d['options']))
  289. @property
  290. def type(self):
  291. try:
  292. return self._type or self.tasks[0].type.app.tasks['celery.chain']
  293. except KeyError:
  294. return self.app.tasks['celery.chain']
  295. def __repr__(self):
  296. return ' | '.join(repr(t) for t in self.tasks)
  297. class _basemap(Signature):
  298. _task_name = None
  299. _unpack_args = itemgetter('task', 'it')
  300. def __init__(self, task, it, **options):
  301. Signature.__init__(
  302. self, self._task_name, (),
  303. {'task': task, 'it': regen(it)}, immutable=True, **options
  304. )
  305. def apply_async(self, args=(), kwargs={}, **opts):
  306. # need to evaluate generators
  307. task, it = self._unpack_args(self.kwargs)
  308. return self.type.apply_async(
  309. (), {'task': task, 'it': list(it)}, **opts
  310. )
  311. @classmethod
  312. def from_dict(cls, d, app=None):
  313. return cls(*cls._unpack_args(d['kwargs']), app=app, **d['options'])
  314. @Signature.register_type
  315. class xmap(_basemap):
  316. _task_name = 'celery.map'
  317. def __repr__(self):
  318. task, it = self._unpack_args(self.kwargs)
  319. return '[{0}(x) for x in {1}]'.format(task.task,
  320. truncate(repr(it), 100))
  321. @Signature.register_type
  322. class xstarmap(_basemap):
  323. _task_name = 'celery.starmap'
  324. def __repr__(self):
  325. task, it = self._unpack_args(self.kwargs)
  326. return '[{0}(*x) for x in {1}]'.format(task.task,
  327. truncate(repr(it), 100))
  328. @Signature.register_type
  329. class chunks(Signature):
  330. _unpack_args = itemgetter('task', 'it', 'n')
  331. def __init__(self, task, it, n, **options):
  332. Signature.__init__(
  333. self, 'celery.chunks', (),
  334. {'task': task, 'it': regen(it), 'n': n},
  335. immutable=True, **options
  336. )
  337. @classmethod
  338. def from_dict(self, d, app=None):
  339. return chunks(*self._unpack_args(d['kwargs']), app=app, **d['options'])
  340. def apply_async(self, args=(), kwargs={}, **opts):
  341. return self.group().apply_async(args, kwargs, **opts)
  342. def __call__(self, **options):
  343. return self.group()(**options)
  344. def group(self):
  345. # need to evaluate generators
  346. task, it, n = self._unpack_args(self.kwargs)
  347. return group((xstarmap(task, part, app=self._app)
  348. for part in _chunks(iter(it), n)),
  349. app=self._app)
  350. @classmethod
  351. def apply_chunks(cls, task, it, n, app=None):
  352. return cls(task, it, n, app=app)()
  353. def _maybe_group(tasks):
  354. if isinstance(tasks, group):
  355. tasks = list(tasks.tasks)
  356. elif isinstance(tasks, Signature):
  357. tasks = [tasks]
  358. else:
  359. tasks = regen(tasks)
  360. return tasks
  361. def _maybe_clone(tasks, app):
  362. return [s.clone() if isinstance(s, Signature) else signature(s, app=app)
  363. for s in tasks]
  364. @Signature.register_type
  365. class group(Signature):
  366. def __init__(self, *tasks, **options):
  367. if len(tasks) == 1:
  368. tasks = _maybe_group(tasks[0])
  369. Signature.__init__(
  370. self, 'celery.group', (), {'tasks': tasks}, **options
  371. )
  372. self.tasks, self.subtask_type = tasks, 'group'
  373. @classmethod
  374. def from_dict(self, d, app=None):
  375. tasks = d['kwargs']['tasks']
  376. if d['args'] and tasks:
  377. # partial args passed on to all tasks in the group (Issue #1057).
  378. for task in tasks:
  379. task['args'] = task._merge(d['args'])[0]
  380. return group(tasks, app=app, **kwdict(d['options']))
  381. def apply_async(self, args=(), kwargs=None, **options):
  382. tasks = _maybe_clone(self.tasks, app=self._app)
  383. if not tasks:
  384. return self.freeze()
  385. type = self.type
  386. return type(*type.prepare(dict(self.options, **options),
  387. tasks, args))
  388. def set_immutable(self, immutable):
  389. for task in self.tasks:
  390. task.set_immutable(immutable)
  391. def link(self, sig):
  392. # Simply link to first task
  393. sig = sig.clone().set(immutable=True)
  394. return self.tasks[0].link(sig)
  395. def link_error(self, sig):
  396. sig = sig.clone().set(immutable=True)
  397. return self.tasks[0].link_error(sig)
  398. def apply(self, *args, **kwargs):
  399. if not self.tasks:
  400. return self.freeze() # empty group returns GroupResult
  401. return Signature.apply(self, *args, **kwargs)
  402. def __call__(self, *partial_args, **options):
  403. return self.apply_async(partial_args, **options)
  404. def freeze(self, _id=None, group_id=None, chord=None):
  405. opts = self.options
  406. try:
  407. gid = opts['task_id']
  408. except KeyError:
  409. gid = opts['task_id'] = uuid()
  410. if group_id:
  411. opts['group_id'] = group_id
  412. if chord:
  413. opts['chord'] = group_id
  414. new_tasks, results = [], []
  415. for task in self.tasks:
  416. task = maybe_signature(task, app=self._app).clone()
  417. results.append(task.freeze(group_id=group_id, chord=chord))
  418. new_tasks.append(task)
  419. self.tasks = self.kwargs['tasks'] = new_tasks
  420. return self.app.GroupResult(gid, results)
  421. _freeze = freeze
  422. def skew(self, start=1.0, stop=None, step=1.0):
  423. it = fxrange(start, stop, step, repeatlast=True)
  424. for task in self.tasks:
  425. task.set(countdown=next(it))
  426. return self
  427. def __iter__(self):
  428. return iter(self.tasks)
  429. def __repr__(self):
  430. return repr(self.tasks)
  431. @property
  432. def type(self):
  433. if self._type:
  434. return self._type
  435. # taking the app from the first task in the list, there may be a
  436. # better solution for this, e.g. to consolidate tasks with the same
  437. # app and apply them in batches.
  438. app = self._app if self._app else self.tasks[0].type.app
  439. return app.tasks[self['task']]
  440. @Signature.register_type
  441. class chord(Signature):
  442. def __init__(self, header, body=None, task='celery.chord',
  443. args=(), kwargs={}, **options):
  444. Signature.__init__(
  445. self, task, args,
  446. dict(kwargs, header=_maybe_group(header),
  447. body=maybe_signature(body, app=self._app)), **options
  448. )
  449. self.subtask_type = 'chord'
  450. def freeze(self, _id=None, group_id=None, chord=None):
  451. return self.body.freeze(_id, group_id=group_id, chord=chord)
  452. @classmethod
  453. def from_dict(self, d, app=None):
  454. args, d['kwargs'] = self._unpack_args(**kwdict(d['kwargs']))
  455. return self(*args, app=app, **kwdict(d))
  456. @staticmethod
  457. def _unpack_args(header=None, body=None, **kwargs):
  458. # Python signatures are better at extracting keys from dicts
  459. # than manually popping things off.
  460. return (header, body), kwargs
  461. @property
  462. def type(self):
  463. if self._type:
  464. return self._type
  465. # we will be able to fix this mess in 3.2 when we no longer
  466. # require an actual task implementation for chord/group
  467. if self._app:
  468. app = self._app
  469. else:
  470. try:
  471. app = self.tasks[0].type.app
  472. except IndexError:
  473. app = self.body.type.app
  474. return app.tasks['celery.chord']
  475. def apply_async(self, args=(), kwargs={}, task_id=None,
  476. producer=None, publisher=None, connection=None,
  477. router=None, result_cls=None, **options):
  478. body = kwargs.get('body') or self.kwargs['body']
  479. kwargs = dict(self.kwargs, **kwargs)
  480. body = body.clone(**options)
  481. _chord = self.type
  482. if _chord.app.conf.CELERY_ALWAYS_EAGER:
  483. return self.apply((), kwargs, task_id=task_id, **options)
  484. res = body.freeze(task_id)
  485. parent = _chord(self.tasks, body, args, **options)
  486. res.parent = parent
  487. return res
  488. def __call__(self, body=None, **options):
  489. return self.apply_async((), {'body': body} if body else {}, **options)
  490. def clone(self, *args, **kwargs):
  491. s = Signature.clone(self, *args, **kwargs)
  492. # need to make copy of body
  493. try:
  494. s.kwargs['body'] = s.kwargs['body'].clone()
  495. except (AttributeError, KeyError):
  496. pass
  497. return s
  498. def link(self, callback):
  499. self.body.link(callback)
  500. return callback
  501. def link_error(self, errback):
  502. self.body.link_error(errback)
  503. return errback
  504. def set_immutable(self, immutable):
  505. # changes mutability of header only, not callback.
  506. for task in self.tasks:
  507. task.set_immutable(immutable)
  508. def __repr__(self):
  509. if self.body:
  510. return self.body.reprcall(self.tasks)
  511. return '<chord without body: {0.tasks!r}>'.format(self)
  512. tasks = _getitem_property('kwargs.header')
  513. body = _getitem_property('kwargs.body')
  514. def signature(varies, *args, **kwargs):
  515. if not (args or kwargs) and isinstance(varies, dict):
  516. if isinstance(varies, Signature):
  517. return varies.clone()
  518. return Signature.from_dict(varies)
  519. return Signature(varies, *args, **kwargs)
  520. subtask = signature # XXX compat
  521. def maybe_signature(d, app=None):
  522. if d is not None:
  523. if isinstance(d, dict):
  524. if not isinstance(d, Signature):
  525. return signature(d, app=app)
  526. elif isinstance(d, list):
  527. return [maybe_signature(s, app=app) for s in d]
  528. if app is not None:
  529. d._app = app
  530. return d
  531. maybe_subtask = maybe_signature # XXX compat