canvas.py 16 KB

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