canvas.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648
  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):
  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. return self.AsyncResult(tid)
  162. _freeze = freeze
  163. def replace(self, args=None, kwargs=None, options=None):
  164. s = self.clone()
  165. if args is not None:
  166. s.args = args
  167. if kwargs is not None:
  168. s.kwargs = kwargs
  169. if options is not None:
  170. s.options = options
  171. return s
  172. def set(self, immutable=None, **options):
  173. if immutable is not None:
  174. self.set_immutable(immutable)
  175. self.options.update(options)
  176. return self
  177. def set_immutable(self, immutable):
  178. self.immutable = immutable
  179. def apply_async(self, args=(), kwargs={}, **options):
  180. try:
  181. _apply = self._apply_async
  182. except IndexError: # no tasks for chain, etc to find type
  183. return
  184. # For callbacks: extra args are prepended to the stored args.
  185. if args or kwargs or options:
  186. args, kwargs, options = self._merge(args, kwargs, options)
  187. else:
  188. args, kwargs, options = self.args, self.kwargs, self.options
  189. return _apply(args, kwargs, **options)
  190. def append_to_list_option(self, key, value):
  191. items = self.options.setdefault(key, [])
  192. if value not in items:
  193. items.append(value)
  194. return value
  195. def link(self, callback):
  196. return self.append_to_list_option('link', callback)
  197. def link_error(self, errback):
  198. return self.append_to_list_option('link_error', errback)
  199. def flatten_links(self):
  200. return list(_chain.from_iterable(_chain(
  201. [[self]],
  202. (link.flatten_links()
  203. for link in maybe_list(self.options.get('link')) or [])
  204. )))
  205. def __or__(self, other):
  206. if isinstance(other, group):
  207. other = maybe_unroll_group(other)
  208. if not isinstance(self, chain) and isinstance(other, chain):
  209. return chain((self, ) + other.tasks, app=self._app)
  210. elif isinstance(other, chain):
  211. return chain(*self.tasks + other.tasks, app=self._app)
  212. elif isinstance(other, Signature):
  213. if isinstance(self, chain):
  214. return chain(*self.tasks + (other, ), app=self._app)
  215. return chain(self, other, app=self._app)
  216. return NotImplemented
  217. def __deepcopy__(self, memo):
  218. memo[id(self)] = self
  219. return dict(self)
  220. def __invert__(self):
  221. return self.apply_async().get()
  222. def __reduce__(self):
  223. # for serialization, the task type is lazily loaded,
  224. # and not stored in the dict itself.
  225. return subtask, (dict(self), )
  226. def reprcall(self, *args, **kwargs):
  227. args, kwargs, _ = self._merge(args, kwargs, {})
  228. return reprcall(self['task'], args, kwargs)
  229. def election(self):
  230. type = self.type
  231. app = type.app
  232. tid = self.options.get('task_id') or uuid()
  233. with app.producer_or_acquire(None) as P:
  234. props = type.backend.on_task_call(P, tid)
  235. app.control.election(tid, 'task', self.clone(task_id=tid, **props),
  236. connection=P.connection)
  237. return type.AsyncResult(tid)
  238. def __repr__(self):
  239. return self.reprcall()
  240. @cached_property
  241. def type(self):
  242. return self._type or self.app.tasks[self['task']]
  243. @cached_property
  244. def app(self):
  245. return self._app or current_app
  246. @cached_property
  247. def AsyncResult(self):
  248. try:
  249. return self.type.AsyncResult
  250. except KeyError: # task not registered
  251. return self.app.AsyncResult
  252. @cached_property
  253. def _apply_async(self):
  254. try:
  255. return self.type.apply_async
  256. except KeyError:
  257. return _partial(self.app.send_task, self['task'])
  258. id = _getitem_property('options.task_id')
  259. task = _getitem_property('task')
  260. args = _getitem_property('args')
  261. kwargs = _getitem_property('kwargs')
  262. options = _getitem_property('options')
  263. subtask_type = _getitem_property('subtask_type')
  264. immutable = _getitem_property('immutable')
  265. @Signature.register_type
  266. class chain(Signature):
  267. def __init__(self, *tasks, **options):
  268. tasks = (regen(tasks[0]) if len(tasks) == 1 and is_list(tasks[0])
  269. else tasks)
  270. Signature.__init__(
  271. self, 'celery.chain', (), {'tasks': tasks}, **options
  272. )
  273. self.tasks = tasks
  274. self.subtask_type = 'chain'
  275. def __call__(self, *args, **kwargs):
  276. if self.tasks:
  277. return self.apply_async(args, kwargs)
  278. @classmethod
  279. def from_dict(self, d, app=None):
  280. tasks = d['kwargs']['tasks']
  281. if d['args'] and tasks:
  282. # partial args passed on to first task in chain (Issue #1057).
  283. tasks[0]['args'] = tasks[0]._merge(d['args'])[0]
  284. return chain(*d['kwargs']['tasks'], app=app, **kwdict(d['options']))
  285. @property
  286. def type(self):
  287. try:
  288. return self._type or self.tasks[0].type.app.tasks['celery.chain']
  289. except KeyError:
  290. return self.app.tasks['celery.chain']
  291. def __repr__(self):
  292. return ' | '.join(repr(t) for t in self.tasks)
  293. class _basemap(Signature):
  294. _task_name = None
  295. _unpack_args = itemgetter('task', 'it')
  296. def __init__(self, task, it, **options):
  297. Signature.__init__(
  298. self, self._task_name, (),
  299. {'task': task, 'it': regen(it)}, immutable=True, **options
  300. )
  301. def apply_async(self, args=(), kwargs={}, **opts):
  302. # need to evaluate generators
  303. task, it = self._unpack_args(self.kwargs)
  304. return self.type.apply_async(
  305. (), {'task': task, 'it': list(it)}, **opts
  306. )
  307. @classmethod
  308. def from_dict(cls, d, app=None):
  309. return cls(*cls._unpack_args(d['kwargs']), app=app, **d['options'])
  310. @Signature.register_type
  311. class xmap(_basemap):
  312. _task_name = 'celery.map'
  313. def __repr__(self):
  314. task, it = self._unpack_args(self.kwargs)
  315. return '[{0}(x) for x in {1}]'.format(task.task,
  316. truncate(repr(it), 100))
  317. @Signature.register_type
  318. class xstarmap(_basemap):
  319. _task_name = 'celery.starmap'
  320. def __repr__(self):
  321. task, it = self._unpack_args(self.kwargs)
  322. return '[{0}(*x) for x in {1}]'.format(task.task,
  323. truncate(repr(it), 100))
  324. @Signature.register_type
  325. class chunks(Signature):
  326. _unpack_args = itemgetter('task', 'it', 'n')
  327. def __init__(self, task, it, n, **options):
  328. Signature.__init__(
  329. self, 'celery.chunks', (),
  330. {'task': task, 'it': regen(it), 'n': n},
  331. immutable=True, **options
  332. )
  333. @classmethod
  334. def from_dict(self, d, app=None):
  335. return chunks(*self._unpack_args(d['kwargs']), app=app, **d['options'])
  336. def apply_async(self, args=(), kwargs={}, **opts):
  337. return self.group().apply_async(args, kwargs, **opts)
  338. def __call__(self, **options):
  339. return self.group()(**options)
  340. def group(self):
  341. # need to evaluate generators
  342. task, it, n = self._unpack_args(self.kwargs)
  343. return group((xstarmap(task, part, app=self._app)
  344. for part in _chunks(iter(it), n)),
  345. app=self._app)
  346. @classmethod
  347. def apply_chunks(cls, task, it, n, app=None):
  348. return cls(task, it, n, app=app)()
  349. def _maybe_group(tasks):
  350. if isinstance(tasks, group):
  351. tasks = list(tasks.tasks)
  352. elif isinstance(tasks, Signature):
  353. tasks = [tasks]
  354. else:
  355. tasks = regen(tasks)
  356. return tasks
  357. def _maybe_clone(tasks, app):
  358. return [s.clone() if isinstance(s, Signature) else signature(s, app=app)
  359. for s in tasks]
  360. @Signature.register_type
  361. class group(Signature):
  362. def __init__(self, *tasks, **options):
  363. if len(tasks) == 1:
  364. tasks = _maybe_group(tasks[0])
  365. Signature.__init__(
  366. self, 'celery.group', (), {'tasks': tasks}, **options
  367. )
  368. self.tasks, self.subtask_type = tasks, 'group'
  369. @classmethod
  370. def from_dict(self, d, app=None):
  371. tasks = d['kwargs']['tasks']
  372. if d['args'] and tasks:
  373. # partial args passed on to all tasks in the group (Issue #1057).
  374. for task in tasks:
  375. task['args'] = task._merge(d['args'])[0]
  376. return group(tasks, app=app, **kwdict(d['options']))
  377. def apply_async(self, args=(), kwargs=None, **options):
  378. tasks = _maybe_clone(self.tasks, app=self._app)
  379. if not tasks:
  380. return self.freeze()
  381. type = self.type
  382. return type(*type.prepare(dict(self.options, **options),
  383. tasks, args))
  384. def set_immutable(self, immutable):
  385. for task in self.tasks:
  386. task.set_immutable(immutable)
  387. def link(self, sig):
  388. # Simply link to first task
  389. sig = sig.clone().set(immutable=True)
  390. return self.tasks[0].link(sig)
  391. def link_error(self, sig):
  392. sig = sig.clone().set(immutable=True)
  393. return self.tasks[0].link_error(sig)
  394. def apply(self, *args, **kwargs):
  395. if not self.tasks:
  396. return self.freeze() # empty group returns GroupResult
  397. return Signature.apply(self, *args, **kwargs)
  398. def __call__(self, *partial_args, **options):
  399. return self.apply_async(partial_args, **options)
  400. def freeze(self, _id=None):
  401. opts = self.options
  402. try:
  403. gid = opts['task_id']
  404. except KeyError:
  405. gid = opts['task_id'] = uuid()
  406. new_tasks, results = [], []
  407. for task in self.tasks:
  408. task = maybe_signature(task, app=self._app).clone()
  409. results.append(task._freeze())
  410. new_tasks.append(task)
  411. self.tasks = self.kwargs['tasks'] = new_tasks
  412. return self.app.GroupResult(gid, results)
  413. _freeze = freeze
  414. def skew(self, start=1.0, stop=None, step=1.0):
  415. it = fxrange(start, stop, step, repeatlast=True)
  416. for task in self.tasks:
  417. task.set(countdown=next(it))
  418. return self
  419. def __iter__(self):
  420. return iter(self.tasks)
  421. def __repr__(self):
  422. return repr(self.tasks)
  423. @property
  424. def type(self):
  425. if self._type:
  426. return self._type
  427. # taking the app from the first task in the list, there may be a
  428. # better solution for this, e.g. to consolidate tasks with the same
  429. # app and apply them in batches.
  430. app = self._app if self._app else self.tasks[0].type.app
  431. return app.tasks[self['task']]
  432. @Signature.register_type
  433. class chord(Signature):
  434. def __init__(self, header, body=None, task='celery.chord',
  435. args=(), kwargs={}, **options):
  436. Signature.__init__(
  437. self, task, args,
  438. dict(kwargs, header=_maybe_group(header),
  439. body=maybe_signature(body, app=self._app)), **options
  440. )
  441. self.subtask_type = 'chord'
  442. @classmethod
  443. def from_dict(self, d, app=None):
  444. args, d['kwargs'] = self._unpack_args(**kwdict(d['kwargs']))
  445. return self(*args, app=app, **kwdict(d))
  446. @staticmethod
  447. def _unpack_args(header=None, body=None, **kwargs):
  448. # Python signatures are better at extracting keys from dicts
  449. # than manually popping things off.
  450. return (header, body), kwargs
  451. @property
  452. def type(self):
  453. if self._type:
  454. return self._type
  455. # we will be able to fix this mess in 3.2 when we no longer
  456. # require an actual task implementation for chord/group
  457. if self._app:
  458. app = self._app
  459. else:
  460. try:
  461. app = self.tasks[0].type.app
  462. except IndexError:
  463. app = self.body.type.app
  464. return app.tasks['celery.chord']
  465. def apply_async(self, args=(), kwargs={}, task_id=None, **options):
  466. body = kwargs.get('body') or self.kwargs['body']
  467. kwargs = dict(self.kwargs, **kwargs)
  468. body = body.clone(**options)
  469. _chord = self.type
  470. if _chord.app.conf.CELERY_ALWAYS_EAGER:
  471. return self.apply((), kwargs, task_id=task_id, **options)
  472. res = body.freeze(task_id)
  473. parent = _chord(self.tasks, body, args, **options)
  474. res.parent = parent
  475. return res
  476. def __call__(self, body=None, **options):
  477. return self.apply_async((), {'body': body} if body else {}, **options)
  478. def clone(self, *args, **kwargs):
  479. s = Signature.clone(self, *args, **kwargs)
  480. # need to make copy of body
  481. try:
  482. s.kwargs['body'] = s.kwargs['body'].clone()
  483. except (AttributeError, KeyError):
  484. pass
  485. return s
  486. def link(self, callback):
  487. self.body.link(callback)
  488. return callback
  489. def link_error(self, errback):
  490. self.body.link_error(errback)
  491. return errback
  492. def set_immutable(self, immutable):
  493. # changes mutability of header only, not callback.
  494. for task in self.tasks:
  495. task.set_immutable(immutable)
  496. def __repr__(self):
  497. if self.body:
  498. return self.body.reprcall(self.tasks)
  499. return '<chord without body: {0.tasks!r}>'.format(self)
  500. tasks = _getitem_property('kwargs.header')
  501. body = _getitem_property('kwargs.body')
  502. def signature(varies, *args, **kwargs):
  503. if not (args or kwargs) and isinstance(varies, dict):
  504. if isinstance(varies, Signature):
  505. return varies.clone()
  506. return Signature.from_dict(varies)
  507. return Signature(varies, *args, **kwargs)
  508. subtask = signature # XXX compat
  509. def maybe_signature(d, app=None):
  510. if d is not None:
  511. if isinstance(d, dict):
  512. if not isinstance(d, Signature):
  513. return signature(d, app=app)
  514. elif isinstance(d, list):
  515. return [maybe_signature(s, app=app) for s in d]
  516. if app is not None:
  517. d._app = app
  518. return d
  519. maybe_subtask = maybe_signature # XXX compat