canvas.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  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 not 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.exceptions import NotRegistered
  17. from celery.result import AsyncResult, GroupResult
  18. from celery.utils.functional import (
  19. maybe_list, is_list, regen,
  20. chunks as _chunks,
  21. )
  22. from celery.utils.text import truncate
  23. __all__ = ['Signature', 'chain', 'xmap', 'xstarmap', 'chunks',
  24. 'group', 'chord', 'subtask', 'maybe_subtask']
  25. class _getitem_property(object):
  26. """Attribute -> dict key descriptor.
  27. The target object must support ``__getitem__``,
  28. and optionally ``__setitem__``.
  29. Example:
  30. class Me(dict):
  31. deep = defaultdict(dict)
  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. class Signature(dict):
  61. """Class that wraps the arguments and execution options
  62. for a single task invocation.
  63. Used as the parts in a :class:`group` and other constructs,
  64. or to pass tasks around as callbacks while being compatible
  65. with serializers with a strict type subset.
  66. :param task: Either a task class/instance, or the name of a task.
  67. :keyword args: Positional arguments to apply.
  68. :keyword kwargs: Keyword arguments to apply.
  69. :keyword options: Additional options to :meth:`Task.apply_async`.
  70. Note that if the first argument is a :class:`dict`, the other
  71. arguments will be ignored and the values in the dict will be used
  72. instead.
  73. >>> s = subtask('tasks.add', args=(2, 2))
  74. >>> subtask(s)
  75. {'task': 'tasks.add', args=(2, 2), kwargs={}, options={}}
  76. """
  77. TYPES = {}
  78. _app = _type = None
  79. @classmethod
  80. def register_type(cls, subclass, name=None):
  81. cls.TYPES[name or subclass.__name__] = subclass
  82. return subclass
  83. @classmethod
  84. def from_dict(self, d, app=None):
  85. typ = d.get('subtask_type')
  86. if typ:
  87. return self.TYPES[typ].from_dict(kwdict(d), app=app)
  88. return Signature(d, app=app)
  89. def __init__(self, task=None, args=None, kwargs=None, options=None,
  90. type=None, subtask_type=None, immutable=False,
  91. app=None, **ex):
  92. self._app = app
  93. init = dict.__init__
  94. if isinstance(task, dict):
  95. return init(self, task) # works like dict(d)
  96. # Also supports using task class/instance instead of string name.
  97. try:
  98. task_name = task.name
  99. except AttributeError:
  100. task_name = task
  101. else:
  102. self._type = task
  103. init(self,
  104. task=task_name, args=tuple(args or ()),
  105. kwargs=kwargs or {},
  106. options=dict(options or {}, **ex),
  107. subtask_type=subtask_type,
  108. immutable=immutable)
  109. def __call__(self, *partial_args, **partial_kwargs):
  110. args, kwargs, _ = self._merge(partial_args, partial_kwargs, None)
  111. return self.type(*args, **kwargs)
  112. def delay(self, *partial_args, **partial_kwargs):
  113. return self.apply_async(partial_args, partial_kwargs)
  114. def apply(self, args=(), kwargs={}, **options):
  115. """Apply this task locally."""
  116. # For callbacks: extra args are prepended to the stored args.
  117. args, kwargs, options = self._merge(args, kwargs, options)
  118. return self.type.apply(args, kwargs, **options)
  119. def _merge(self, args=(), kwargs={}, options={}):
  120. if self.immutable:
  121. return (self.args, self.kwargs,
  122. dict(self.options, **options) if options else self.options)
  123. return (tuple(args) + tuple(self.args) if args else self.args,
  124. dict(self.kwargs, **kwargs) if kwargs else self.kwargs,
  125. dict(self.options, **options) if options else self.options)
  126. def clone(self, args=(), kwargs={}, **opts):
  127. # need to deepcopy options so origins links etc. is not modified.
  128. if args or kwargs or opts:
  129. args, kwargs, opts = self._merge(args, kwargs, opts)
  130. else:
  131. args, kwargs, opts = self.args, self.kwargs, self.options
  132. s = Signature.from_dict({'task': self.task, 'args': tuple(args),
  133. 'kwargs': kwargs, 'options': deepcopy(opts),
  134. 'subtask_type': self.subtask_type,
  135. 'immutable': self.immutable}, app=self._app)
  136. s._type = self._type
  137. return s
  138. partial = clone
  139. def freeze(self, _id=None):
  140. opts = self.options
  141. try:
  142. tid = opts['task_id']
  143. except KeyError:
  144. tid = opts['task_id'] = _id or uuid()
  145. if 'reply_to' not in opts:
  146. opts['reply_to'] = self.type.app.oid
  147. return self.AsyncResult(tid)
  148. _freeze = freeze
  149. def replace(self, args=None, kwargs=None, options=None):
  150. s = self.clone()
  151. if args is not None:
  152. s.args = args
  153. if kwargs is not None:
  154. s.kwargs = kwargs
  155. if options is not None:
  156. s.options = options
  157. return s
  158. def set(self, immutable=None, **options):
  159. if immutable is not None:
  160. self.immutable = immutable
  161. self.options.update(options)
  162. return self
  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 or current_app).tasks[self['task']]
  221. @cached_property
  222. def AsyncResult(self):
  223. try:
  224. return self.type.AsyncResult
  225. except KeyError: # task not registered
  226. return AsyncResult
  227. @cached_property
  228. def _apply_async(self):
  229. try:
  230. return self.type.apply_async
  231. except KeyError:
  232. return _partial((self._app or current_app).send_task, self['task'])
  233. id = _getitem_property('options.task_id')
  234. task = _getitem_property('task')
  235. args = _getitem_property('args')
  236. kwargs = _getitem_property('kwargs')
  237. options = _getitem_property('options')
  238. subtask_type = _getitem_property('subtask_type')
  239. immutable = _getitem_property('immutable')
  240. @Signature.register_type
  241. class chain(Signature):
  242. def __init__(self, *tasks, **options):
  243. tasks = (regen(tasks[0]) if len(tasks) == 1 and is_list(tasks[0])
  244. else tasks)
  245. Signature.__init__(
  246. self, 'celery.chain', (), {'tasks': tasks}, **options
  247. )
  248. self.tasks = tasks
  249. self.subtask_type = 'chain'
  250. def __call__(self, *args, **kwargs):
  251. if self.tasks:
  252. return self.apply_async(args, kwargs)
  253. @classmethod
  254. def from_dict(self, d, app=None):
  255. tasks = d['kwargs']['tasks']
  256. if d['args'] and tasks:
  257. # partial args passed on to first task in chain (Issue #1057).
  258. tasks[0]['args'] = tasks[0]._merge(d['args'])[0]
  259. return chain(*d['kwargs']['tasks'], app=app, **kwdict(d['options']))
  260. @property
  261. def type(self):
  262. try:
  263. return self._type or self.tasks[0].type.app.tasks['celery.chain']
  264. except NotRegistered:
  265. return (self._app or current_app).tasks['celery.chain']
  266. def __repr__(self):
  267. return ' | '.join(repr(t) for t in self.tasks)
  268. class _basemap(Signature):
  269. _task_name = None
  270. _unpack_args = itemgetter('task', 'it')
  271. def __init__(self, task, it, **options):
  272. Signature.__init__(
  273. self, self._task_name, (),
  274. {'task': task, 'it': regen(it)}, immutable=True, **options
  275. )
  276. def apply_async(self, args=(), kwargs={}, **opts):
  277. # need to evaluate generators
  278. task, it = self._unpack_args(self.kwargs)
  279. return self.type.apply_async(
  280. (), {'task': task, 'it': list(it)}, **opts
  281. )
  282. @classmethod
  283. def from_dict(cls, d, app=None):
  284. return cls(*cls._unpack_args(d['kwargs']), app=app, **d['options'])
  285. @Signature.register_type
  286. class xmap(_basemap):
  287. _task_name = 'celery.map'
  288. def __repr__(self):
  289. task, it = self._unpack_args(self.kwargs)
  290. return '[{0}(x) for x in {1}]'.format(task.task,
  291. truncate(repr(it), 100))
  292. @Signature.register_type
  293. class xstarmap(_basemap):
  294. _task_name = 'celery.starmap'
  295. def __repr__(self):
  296. task, it = self._unpack_args(self.kwargs)
  297. return '[{0}(*x) for x in {1}]'.format(task.task,
  298. truncate(repr(it), 100))
  299. @Signature.register_type
  300. class chunks(Signature):
  301. _unpack_args = itemgetter('task', 'it', 'n')
  302. def __init__(self, task, it, n, **options):
  303. Signature.__init__(
  304. self, 'celery.chunks', (),
  305. {'task': task, 'it': regen(it), 'n': n},
  306. immutable=True, **options
  307. )
  308. @classmethod
  309. def from_dict(self, d, app=None):
  310. return chunks(*self._unpack_args(d['kwargs']), app=app, **d['options'])
  311. def apply_async(self, args=(), kwargs={}, **opts):
  312. return self.group().apply_async(args, kwargs, **opts)
  313. def __call__(self, **options):
  314. return self.group()(**options)
  315. def group(self):
  316. # need to evaluate generators
  317. task, it, n = self._unpack_args(self.kwargs)
  318. return group((xstarmap(task, part, app=self._app)
  319. for part in _chunks(iter(it), n)),
  320. app=self._app)
  321. @classmethod
  322. def apply_chunks(cls, task, it, n, app=None):
  323. return cls(task, it, n, app=app)()
  324. def _maybe_group(tasks):
  325. if isinstance(tasks, group):
  326. tasks = list(tasks.tasks)
  327. elif isinstance(tasks, Signature):
  328. tasks = [tasks]
  329. else:
  330. tasks = regen(tasks)
  331. return tasks
  332. @Signature.register_type
  333. class group(Signature):
  334. def __init__(self, *tasks, **options):
  335. if len(tasks) == 1:
  336. tasks = _maybe_group(tasks[0])
  337. Signature.__init__(
  338. self, 'celery.group', (), {'tasks': tasks}, **options
  339. )
  340. self.tasks, self.subtask_type = tasks, 'group'
  341. @classmethod
  342. def from_dict(self, d, app=None):
  343. tasks = d['kwargs']['tasks']
  344. if d['args'] and tasks:
  345. # partial args passed on to all tasks in the group (Issue #1057).
  346. for task in tasks:
  347. task['args'] = task._merge(d['args'])[0]
  348. return group(tasks, app=app, **kwdict(d['options']))
  349. def apply_async(self, *args, **kwargs):
  350. if not self.tasks:
  351. return self.freeze() # empty group returns GroupResult
  352. return Signature.apply_async(self, *args, **kwargs)
  353. def apply(self, *args, **kwargs):
  354. if not self.tasks:
  355. return self.freeze() # empty group returns GroupResult
  356. return Signature.apply(self, *args, **kwargs)
  357. def __call__(self, *partial_args, **opts):
  358. tasks = [task.clone() for task in self.tasks]
  359. if not tasks:
  360. return
  361. # taking the app from the first task in the list,
  362. # there may be a better solution to this, e.g.
  363. # consolidate tasks with the same app and apply them in
  364. # batches.
  365. type = tasks[0].type.app.tasks[self['task']]
  366. return type(*type.prepare(dict(self.options, **opts),
  367. tasks, partial_args))
  368. def freeze(self, _id=None):
  369. opts = self.options
  370. try:
  371. gid = opts['task_id']
  372. except KeyError:
  373. gid = opts['task_id'] = uuid()
  374. new_tasks, results = [], []
  375. for task in self.tasks:
  376. task = maybe_subtask(task).clone()
  377. results.append(task._freeze())
  378. new_tasks.append(task)
  379. self.tasks = self.kwargs['tasks'] = new_tasks
  380. return GroupResult(gid, results)
  381. _freeze = freeze
  382. def skew(self, start=1.0, stop=None, step=1.0):
  383. it = fxrange(start, stop, step, repeatlast=True)
  384. for task in self.tasks:
  385. task.set(countdown=next(it))
  386. return self
  387. def __iter__(self):
  388. return iter(self.tasks)
  389. def __repr__(self):
  390. return repr(self.tasks)
  391. @property
  392. def type(self):
  393. return self._type or self.tasks[0].type.app.tasks[self['task']]
  394. @Signature.register_type
  395. class chord(Signature):
  396. def __init__(self, header, body=None, task='celery.chord',
  397. args=(), kwargs={}, **options):
  398. Signature.__init__(
  399. self, task, args,
  400. dict(kwargs, header=_maybe_group(header),
  401. body=maybe_subtask(body)), **options
  402. )
  403. self.subtask_type = 'chord'
  404. @classmethod
  405. def from_dict(self, d, app=None):
  406. args, d['kwargs'] = self._unpack_args(**kwdict(d['kwargs']))
  407. return self(*args, app=app, **kwdict(d))
  408. @staticmethod
  409. def _unpack_args(header=None, body=None, **kwargs):
  410. # Python signatures are better at extracting keys from dicts
  411. # than manually popping things off.
  412. return (header, body), kwargs
  413. @property
  414. def type(self):
  415. return self._type or self.tasks[0].type.app.tasks['celery.chord']
  416. def __call__(self, body=None, task_id=None, **kwargs):
  417. _chord = self.type
  418. body = (body or self.kwargs['body']).clone()
  419. kwargs = dict(self.kwargs, body=body, **kwargs)
  420. if _chord.app.conf.CELERY_ALWAYS_EAGER:
  421. return self.apply((), kwargs)
  422. res = body.freeze(task_id)
  423. parent = _chord(**kwargs)
  424. res.parent = parent
  425. return res
  426. def clone(self, *args, **kwargs):
  427. s = Signature.clone(self, *args, **kwargs)
  428. # need to make copy of body
  429. try:
  430. s.kwargs['body'] = s.kwargs['body'].clone()
  431. except (AttributeError, KeyError):
  432. pass
  433. return s
  434. def link(self, callback):
  435. self.body.link(callback)
  436. return callback
  437. def link_error(self, errback):
  438. self.body.link_error(errback)
  439. return errback
  440. def __repr__(self):
  441. if self.body:
  442. return self.body.reprcall(self.tasks)
  443. return '<chord without body: {0.tasks!r}>'.format(self)
  444. tasks = _getitem_property('kwargs.header')
  445. body = _getitem_property('kwargs.body')
  446. def subtask(varies, *args, **kwargs):
  447. if not (args or kwargs) and isinstance(varies, dict):
  448. if isinstance(varies, Signature):
  449. return varies.clone()
  450. return Signature.from_dict(varies)
  451. return Signature(varies, *args, **kwargs)
  452. def maybe_subtask(d):
  453. if d is not None and isinstance(d, dict) and not isinstance(d, Signature):
  454. return subtask(d)
  455. return d