canvas.py 19 KB

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