canvas.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  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
  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 import current_app
  16. from celery.local import Proxy
  17. from celery.utils.compat import chain_from_iterable
  18. from celery.result import AsyncResult, GroupResult
  19. from celery.utils.functional import (
  20. maybe_list, is_list, regen,
  21. chunks as _chunks,
  22. )
  23. from celery.utils.text import truncate
  24. Chord = Proxy(lambda: current_app.tasks['celery.chord'])
  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_thinge
  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` or to safely
  64. pass tasks around as callbacks.
  65. :param task: Either a task class/instance, or the name of a task.
  66. :keyword args: Positional arguments to apply.
  67. :keyword kwargs: Keyword arguments to apply.
  68. :keyword options: Additional options to :meth:`Task.apply_async`.
  69. Note that if the first argument is a :class:`dict`, the other
  70. arguments will be ignored and the values in the dict will be used
  71. instead.
  72. >>> s = subtask('tasks.add', args=(2, 2))
  73. >>> subtask(s)
  74. {'task': 'tasks.add', args=(2, 2), kwargs={}, options={}}
  75. """
  76. TYPES = {}
  77. _type = None
  78. @classmethod
  79. def register_type(cls, subclass, name=None):
  80. cls.TYPES[name or subclass.__name__] = subclass
  81. return subclass
  82. @classmethod
  83. def from_dict(self, d):
  84. typ = d.get('subtask_type')
  85. if typ:
  86. return self.TYPES[typ].from_dict(kwdict(d))
  87. return Signature(d)
  88. def __init__(self, task=None, args=None, kwargs=None, options=None,
  89. type=None, subtask_type=None, immutable=False, **ex):
  90. init = dict.__init__
  91. if isinstance(task, dict):
  92. return init(self, task) # works like dict(d)
  93. # Also supports using task class/instance instead of string name.
  94. try:
  95. task_name = task.name
  96. except AttributeError:
  97. task_name = task
  98. else:
  99. self._type = task
  100. init(self,
  101. task=task_name, args=tuple(args or ()),
  102. kwargs=kwargs or {},
  103. options=dict(options or {}, **ex),
  104. subtask_type=subtask_type,
  105. immutable=immutable)
  106. def __call__(self, *partial_args, **partial_kwargs):
  107. return self.apply_async(partial_args, partial_kwargs)
  108. delay = __call__
  109. def apply(self, args=(), kwargs={}, **options):
  110. """Apply this task locally."""
  111. # For callbacks: extra args are prepended to the stored args.
  112. args, kwargs, options = self._merge(args, kwargs, options)
  113. return self.type.apply(args, kwargs, **options)
  114. def _merge(self, args=(), kwargs={}, options={}):
  115. if self.immutable:
  116. return self.args, self.kwargs, dict(self.options, **options)
  117. return (tuple(args) + tuple(self.args) if args else self.args,
  118. dict(self.kwargs, **kwargs) if kwargs else self.kwargs,
  119. dict(self.options, **options) if options else self.options)
  120. def clone(self, args=(), kwargs={}, **opts):
  121. # need to deepcopy options so origins links etc. is not modified.
  122. args, kwargs, opts = self._merge(args, kwargs, opts)
  123. s = Signature.from_dict({'task': self.task, 'args': tuple(args),
  124. 'kwargs': kwargs, 'options': deepcopy(opts),
  125. 'subtask_type': self.subtask_type,
  126. 'immutable': self.immutable})
  127. s._type = self._type
  128. return s
  129. partial = clone
  130. def _freeze(self, _id=None):
  131. opts = self.options
  132. try:
  133. tid = opts['task_id']
  134. except KeyError:
  135. tid = opts['task_id'] = _id or uuid()
  136. return self.AsyncResult(tid)
  137. def replace(self, args=None, kwargs=None, options=None):
  138. s = self.clone()
  139. if args is not None:
  140. s.args = args
  141. if kwargs is not None:
  142. s.kwargs = kwargs
  143. if options is not None:
  144. s.options = options
  145. return s
  146. def set(self, immutable=None, **options):
  147. if immutable is not None:
  148. self.immutable = immutable
  149. self.options.update(options)
  150. return self
  151. def apply_async(self, args=(), kwargs={}, **options):
  152. # For callbacks: extra args are prepended to the stored args.
  153. args, kwargs, options = self._merge(args, kwargs, options)
  154. return self._apply_async(args, kwargs, **options)
  155. def append_to_list_option(self, key, value):
  156. items = self.options.setdefault(key, [])
  157. if value not in items:
  158. items.append(value)
  159. return value
  160. def link(self, callback):
  161. return self.append_to_list_option('link', callback)
  162. def link_error(self, errback):
  163. return self.append_to_list_option('link_error', errback)
  164. def flatten_links(self):
  165. return list(chain_from_iterable(_chain(
  166. [[self]],
  167. (link.flatten_links()
  168. for link in maybe_list(self.options.get('link')) or [])
  169. )))
  170. def __or__(self, other):
  171. if not isinstance(self, chain) and isinstance(other, chain):
  172. return chain((self,) + other.tasks)
  173. elif isinstance(other, chain):
  174. return chain(*self.tasks + other.tasks)
  175. elif isinstance(other, Signature):
  176. if isinstance(self, chain):
  177. return chain(*self.tasks + (other, ))
  178. return chain(self, other)
  179. return NotImplemented
  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 __repr__(self):
  190. return self.reprcall()
  191. @cached_property
  192. def type(self):
  193. return self._type or current_app.tasks[self['task']]
  194. @cached_property
  195. def AsyncResult(self):
  196. try:
  197. return self.type.AsyncResult
  198. except KeyError: # task not registered
  199. return AsyncResult
  200. @cached_property
  201. def _apply_async(self):
  202. try:
  203. return self.type.apply_async
  204. except KeyError:
  205. return _partial(current_app.send_task, self['task'])
  206. id = _getitem_property('options.task_id')
  207. task = _getitem_property('task')
  208. args = _getitem_property('args')
  209. kwargs = _getitem_property('kwargs')
  210. options = _getitem_property('options')
  211. subtask_type = _getitem_property('subtask_type')
  212. immutable = _getitem_property('immutable')
  213. class chain(Signature):
  214. def __init__(self, *tasks, **options):
  215. tasks = tasks[0] if len(tasks) == 1 and is_list(tasks[0]) else tasks
  216. Signature.__init__(
  217. self, 'celery.chain', (), {'tasks': tasks}, **options
  218. )
  219. self.tasks = tasks
  220. self.subtask_type = 'chain'
  221. def __call__(self, *args, **kwargs):
  222. return self.apply_async(args, kwargs)
  223. @classmethod
  224. def from_dict(self, d):
  225. tasks = d['kwargs']['tasks']
  226. if d['args'] and tasks:
  227. # partial args passed on to first task in chain (Issue #1057).
  228. tasks[0]['args'] = d['args'] + tasks[0]['args']
  229. return chain(*d['kwargs']['tasks'], **kwdict(d['options']))
  230. def __repr__(self):
  231. return ' | '.join(map(repr, self.tasks))
  232. Signature.register_type(chain)
  233. class _basemap(Signature):
  234. _task_name = None
  235. _unpack_args = itemgetter('task', 'it')
  236. def __init__(self, task, it, **options):
  237. Signature.__init__(
  238. self, self._task_name, (),
  239. {'task': task, 'it': regen(it)}, immutable=True, **options
  240. )
  241. def apply_async(self, args=(), kwargs={}, **opts):
  242. # need to evaluate generators
  243. task, it = self._unpack_args(self.kwargs)
  244. return self.type.apply_async(
  245. (), {'task': task, 'it': list(it)}, **opts
  246. )
  247. @classmethod
  248. def from_dict(self, d):
  249. return chunks(*self._unpack_args(d['kwargs']), **d['options'])
  250. class xmap(_basemap):
  251. _task_name = 'celery.map'
  252. def __repr__(self):
  253. task, it = self._unpack_args(self.kwargs)
  254. return '[%s(x) for x in %s]' % (task.task, truncate(repr(it), 100))
  255. Signature.register_type(xmap)
  256. class xstarmap(_basemap):
  257. _task_name = 'celery.starmap'
  258. def __repr__(self):
  259. task, it = self._unpack_args(self.kwargs)
  260. return '[%s(*x) for x in %s]' % (task.task, truncate(repr(it), 100))
  261. Signature.register_type(xstarmap)
  262. class chunks(Signature):
  263. _unpack_args = itemgetter('task', 'it', 'n')
  264. def __init__(self, task, it, n, **options):
  265. Signature.__init__(
  266. self, 'celery.chunks', (),
  267. {'task': task, 'it': regen(it), 'n': n},
  268. immutable=True, **options
  269. )
  270. @classmethod
  271. def from_dict(self, d):
  272. return chunks(*self._unpack_args(d['kwargs']), **d['options'])
  273. def apply_async(self, args=(), kwargs={}, **opts):
  274. return self.group().apply_async(args, kwargs, **opts)
  275. def __call__(self, **options):
  276. return self.group()(**options)
  277. def group(self):
  278. # need to evaluate generators
  279. task, it, n = self._unpack_args(self.kwargs)
  280. return group(xstarmap(task, part) for part in _chunks(iter(it), n))
  281. @classmethod
  282. def apply_chunks(cls, task, it, n):
  283. return cls(task, it, n)()
  284. Signature.register_type(chunks)
  285. def _maybe_group(tasks):
  286. if isinstance(tasks, group):
  287. tasks = list(tasks.tasks)
  288. else:
  289. tasks = regen(tasks if is_list(tasks) else tasks)
  290. return tasks
  291. class group(Signature):
  292. def __init__(self, *tasks, **options):
  293. if len(tasks) == 1:
  294. tasks = _maybe_group(tasks[0])
  295. Signature.__init__(
  296. self, 'celery.group', (), {'tasks': tasks}, **options
  297. )
  298. self.tasks, self.subtask_type = tasks, 'group'
  299. @classmethod
  300. def from_dict(self, d):
  301. tasks = d['kwargs']['tasks']
  302. if d['args'] and tasks:
  303. # partial args passed on to all tasks in the group (Issue #1057).
  304. for task in tasks:
  305. task['args'] = d['args'] + task['args']
  306. return group(tasks, **kwdict(d['options']))
  307. def __call__(self, *partial_args, **options):
  308. tasks, result, gid, args = self.type.prepare(
  309. options, map(Signature.clone, self.tasks), partial_args,
  310. )
  311. return self.type(tasks, result, gid, args)
  312. def _freeze(self, _id=None):
  313. opts = self.options
  314. try:
  315. gid = opts['group']
  316. except KeyError:
  317. gid = opts['group'] = uuid()
  318. new_tasks, results = [], []
  319. for task in self.tasks:
  320. task = maybe_subtask(task).clone()
  321. results.append(task._freeze())
  322. new_tasks.append(task)
  323. self.tasks = self.kwargs['tasks'] = new_tasks
  324. return GroupResult(gid, results)
  325. def skew(self, start=1.0, stop=None, step=1.0):
  326. _next_skew = fxrange(start, stop, step, repeatlast=True).next
  327. for task in self.tasks:
  328. task.set(countdown=_next_skew())
  329. return self
  330. def __iter__(self):
  331. return iter(self.tasks)
  332. def __repr__(self):
  333. return repr(self.tasks)
  334. Signature.register_type(group)
  335. class chord(Signature):
  336. Chord = Chord
  337. def __init__(self, header, body=None, task='celery.chord',
  338. args=(), kwargs={}, **options):
  339. Signature.__init__(
  340. self, task, args,
  341. dict(kwargs, header=_maybe_group(header),
  342. body=maybe_subtask(body)), **options
  343. )
  344. self.subtask_type = 'chord'
  345. @classmethod
  346. def from_dict(self, d):
  347. args, d['kwargs'] = self._unpack_args(**kwdict(d['kwargs']))
  348. return self(*args, **kwdict(d))
  349. @staticmethod
  350. def _unpack_args(header=None, body=None, **kwargs):
  351. # Python signatures are better at extracting keys from dicts
  352. # than manually popping things off.
  353. return (header, body), kwargs
  354. def __call__(self, body=None, **kwargs):
  355. _chord = self.Chord
  356. body = (body or self.kwargs['body']).clone()
  357. kwargs = dict(self.kwargs, body=body, **kwargs)
  358. if _chord.app.conf.CELERY_ALWAYS_EAGER:
  359. return self.apply((), kwargs)
  360. callback_id = body.options.setdefault('task_id', uuid())
  361. _chord(**kwargs)
  362. return _chord.AsyncResult(callback_id)
  363. def clone(self, *args, **kwargs):
  364. s = Signature.clone(self, *args, **kwargs)
  365. # need to make copy of body
  366. try:
  367. s.kwargs['body'] = s.kwargs['body'].clone()
  368. except (AttributeError, KeyError):
  369. pass
  370. return s
  371. def link(self, callback):
  372. self.body.link(callback)
  373. return callback
  374. def link_error(self, errback):
  375. self.body.link_error(errback)
  376. return errback
  377. def __repr__(self):
  378. if self.body:
  379. return self.body.reprcall(self.tasks)
  380. return '<chord without body: %r>' % (self.tasks, )
  381. @property
  382. def tasks(self):
  383. return self.kwargs['header']
  384. @property
  385. def body(self):
  386. return self.kwargs.get('body')
  387. Signature.register_type(chord)
  388. def subtask(varies, *args, **kwargs):
  389. if not (args or kwargs) and isinstance(varies, dict):
  390. if isinstance(varies, Signature):
  391. return varies.clone()
  392. return Signature.from_dict(varies)
  393. return Signature(varies, *args, **kwargs)
  394. def maybe_subtask(d):
  395. if d is not None and isinstance(d, dict) and not isinstance(d, Signature):
  396. return subtask(d)
  397. return d