canvas.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  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. 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 = subtask('tasks.add', args=(2, 2))
  72. >>> subtask(s)
  73. {'task': 'tasks.add', args=(2, 2), kwargs={}, options={}}
  74. """
  75. TYPES = {}
  76. _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):
  83. typ = d.get('subtask_type')
  84. if typ:
  85. return self.TYPES[typ].from_dict(kwdict(d))
  86. return Signature(d)
  87. def __init__(self, task=None, args=None, kwargs=None, options=None,
  88. type=None, subtask_type=None, immutable=False, **ex):
  89. init = dict.__init__
  90. if isinstance(task, dict):
  91. return init(self, task) # works like dict(d)
  92. # Also supports using task class/instance instead of string name.
  93. try:
  94. task_name = task.name
  95. except AttributeError:
  96. task_name = task
  97. else:
  98. self._type = task
  99. init(self,
  100. task=task_name, args=tuple(args or ()),
  101. kwargs=kwargs or {},
  102. options=dict(options or {}, **ex),
  103. subtask_type=subtask_type,
  104. immutable=immutable)
  105. def __call__(self, *partial_args, **partial_kwargs):
  106. args, kwargs, _ = self._merge(partial_args, partial_kwargs, None)
  107. return self.type(*args, **kwargs)
  108. def delay(self, *partial_args, **partial_kwargs):
  109. return self.apply_async(partial_args, partial_kwargs)
  110. def apply(self, args=(), kwargs={}, **options):
  111. """Apply this task locally."""
  112. # For callbacks: extra args are prepended to the stored args.
  113. args, kwargs, options = self._merge(args, kwargs, options)
  114. return self.type.apply(args, kwargs, **options)
  115. def _merge(self, args=(), kwargs={}, options={}):
  116. if self.immutable:
  117. return (self.args, self.kwargs,
  118. dict(self.options, **options) if options else self.options)
  119. return (tuple(args) + tuple(self.args) if args else self.args,
  120. dict(self.kwargs, **kwargs) if kwargs else self.kwargs,
  121. dict(self.options, **options) if options else self.options)
  122. def clone(self, args=(), kwargs={}, **opts):
  123. # need to deepcopy options so origins links etc. is not modified.
  124. if args or kwargs or opts:
  125. args, kwargs, opts = self._merge(args, kwargs, opts)
  126. else:
  127. args, kwargs, opts = self.args, self.kwargs, self.options
  128. s = Signature.from_dict({'task': self.task, 'args': tuple(args),
  129. 'kwargs': kwargs, 'options': deepcopy(opts),
  130. 'subtask_type': self.subtask_type,
  131. 'immutable': self.immutable})
  132. s._type = self._type
  133. return s
  134. partial = clone
  135. def freeze(self, _id=None):
  136. opts = self.options
  137. try:
  138. tid = opts['task_id']
  139. except KeyError:
  140. tid = opts['task_id'] = _id or uuid()
  141. if 'reply_to' not in opts:
  142. opts['reply_to'] = self.type.app.oid
  143. return self.AsyncResult(tid)
  144. _freeze = freeze
  145. def replace(self, args=None, kwargs=None, options=None):
  146. s = self.clone()
  147. if args is not None:
  148. s.args = args
  149. if kwargs is not None:
  150. s.kwargs = kwargs
  151. if options is not None:
  152. s.options = options
  153. return s
  154. def set(self, immutable=None, **options):
  155. if immutable is not None:
  156. self.immutable = immutable
  157. self.options.update(options)
  158. return self
  159. def apply_async(self, args=(), kwargs={}, **options):
  160. # For callbacks: extra args are prepended to the stored args.
  161. if args or kwargs or options:
  162. args, kwargs, options = self._merge(args, kwargs, options)
  163. else:
  164. args, kwargs, options = self.args, self.kwargs, self.options
  165. return self._apply_async(args, kwargs, **options)
  166. def append_to_list_option(self, key, value):
  167. items = self.options.setdefault(key, [])
  168. if value not in items:
  169. items.append(value)
  170. return value
  171. def link(self, callback):
  172. return self.append_to_list_option('link', callback)
  173. def link_error(self, errback):
  174. return self.append_to_list_option('link_error', errback)
  175. def flatten_links(self):
  176. return list(_chain.from_iterable(_chain(
  177. [[self]],
  178. (link.flatten_links()
  179. for link in maybe_list(self.options.get('link')) or [])
  180. )))
  181. def __or__(self, other):
  182. if not isinstance(self, chain) and isinstance(other, chain):
  183. return chain((self, ) + other.tasks)
  184. elif isinstance(other, chain):
  185. return chain(*self.tasks + other.tasks)
  186. elif isinstance(other, Signature):
  187. if isinstance(self, chain):
  188. return chain(*self.tasks + (other, ))
  189. return chain(self, other)
  190. return NotImplemented
  191. def __deepcopy__(self, memo):
  192. memo[id(self)] = self
  193. return dict(self)
  194. def __invert__(self):
  195. return self.apply_async().get()
  196. def __reduce__(self):
  197. # for serialization, the task type is lazily loaded,
  198. # and not stored in the dict itself.
  199. return subtask, (dict(self), )
  200. def reprcall(self, *args, **kwargs):
  201. args, kwargs, _ = self._merge(args, kwargs, {})
  202. return reprcall(self['task'], args, kwargs)
  203. def election(self):
  204. type = self.type
  205. app = type.app
  206. tid = self.options.get('task_id') or uuid()
  207. with app.producer_or_acquire(None) as P:
  208. props = type.backend.on_task_call(P, tid)
  209. app.control.election(tid, 'task', self.clone(task_id=tid, **props),
  210. connection=P.connection)
  211. return type.AsyncResult(tid)
  212. def __repr__(self):
  213. return self.reprcall()
  214. @cached_property
  215. def type(self):
  216. return self._type or current_app.tasks[self['task']]
  217. @cached_property
  218. def AsyncResult(self):
  219. try:
  220. return self.type.AsyncResult
  221. except KeyError: # task not registered
  222. return AsyncResult
  223. @cached_property
  224. def _apply_async(self):
  225. try:
  226. return self.type.apply_async
  227. except KeyError:
  228. return _partial(current_app.send_task, self['task'])
  229. id = _getitem_property('options.task_id')
  230. task = _getitem_property('task')
  231. args = _getitem_property('args')
  232. kwargs = _getitem_property('kwargs')
  233. options = _getitem_property('options')
  234. subtask_type = _getitem_property('subtask_type')
  235. immutable = _getitem_property('immutable')
  236. @Signature.register_type
  237. class chain(Signature):
  238. def __init__(self, *tasks, **options):
  239. tasks = (regen(tasks[0]) if len(tasks) == 1 and is_list(tasks[0])
  240. else tasks)
  241. Signature.__init__(
  242. self, 'celery.chain', (), {'tasks': tasks}, **options
  243. )
  244. self.tasks = tasks
  245. self.subtask_type = 'chain'
  246. def __call__(self, *args, **kwargs):
  247. if self.tasks:
  248. return self.apply_async(args, kwargs)
  249. @classmethod
  250. def from_dict(self, d):
  251. tasks = d['kwargs']['tasks']
  252. if d['args'] and tasks:
  253. # partial args passed on to first task in chain (Issue #1057).
  254. tasks[0]['args'] = tasks[0]._merge(d['args'])[0]
  255. return chain(*d['kwargs']['tasks'], **kwdict(d['options']))
  256. @property
  257. def type(self):
  258. try:
  259. return self._type or self.tasks[0].type.app.tasks['celery.chain']
  260. except NotRegistered:
  261. return current_app.tasks['celery.chain']
  262. def __repr__(self):
  263. return ' | '.join(repr(t) for t in self.tasks)
  264. class _basemap(Signature):
  265. _task_name = None
  266. _unpack_args = itemgetter('task', 'it')
  267. def __init__(self, task, it, **options):
  268. Signature.__init__(
  269. self, self._task_name, (),
  270. {'task': task, 'it': regen(it)}, immutable=True, **options
  271. )
  272. def apply_async(self, args=(), kwargs={}, **opts):
  273. # need to evaluate generators
  274. task, it = self._unpack_args(self.kwargs)
  275. return self.type.apply_async(
  276. (), {'task': task, 'it': list(it)}, **opts
  277. )
  278. @classmethod
  279. def from_dict(cls, d):
  280. return cls(*cls._unpack_args(d['kwargs']), **d['options'])
  281. @Signature.register_type
  282. class xmap(_basemap):
  283. _task_name = 'celery.map'
  284. def __repr__(self):
  285. task, it = self._unpack_args(self.kwargs)
  286. return '[{0}(x) for x in {1}]'.format(task.task,
  287. truncate(repr(it), 100))
  288. @Signature.register_type
  289. class xstarmap(_basemap):
  290. _task_name = 'celery.starmap'
  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 chunks(Signature):
  297. _unpack_args = itemgetter('task', 'it', 'n')
  298. def __init__(self, task, it, n, **options):
  299. Signature.__init__(
  300. self, 'celery.chunks', (),
  301. {'task': task, 'it': regen(it), 'n': n},
  302. immutable=True, **options
  303. )
  304. @classmethod
  305. def from_dict(self, d):
  306. return chunks(*self._unpack_args(d['kwargs']), **d['options'])
  307. def apply_async(self, args=(), kwargs={}, **opts):
  308. return self.group().apply_async(args, kwargs, **opts)
  309. def __call__(self, **options):
  310. return self.group()(**options)
  311. def group(self):
  312. # need to evaluate generators
  313. task, it, n = self._unpack_args(self.kwargs)
  314. return group(xstarmap(task, part) for part in _chunks(iter(it), n))
  315. @classmethod
  316. def apply_chunks(cls, task, it, n):
  317. return cls(task, it, n)()
  318. def _maybe_group(tasks):
  319. if isinstance(tasks, group):
  320. tasks = list(tasks.tasks)
  321. elif isinstance(tasks, Signature):
  322. tasks = [tasks]
  323. else:
  324. tasks = regen(tasks)
  325. return tasks
  326. @Signature.register_type
  327. class group(Signature):
  328. def __init__(self, *tasks, **options):
  329. if len(tasks) == 1:
  330. tasks = _maybe_group(tasks[0])
  331. Signature.__init__(
  332. self, 'celery.group', (), {'tasks': tasks}, **options
  333. )
  334. self.tasks, self.subtask_type = tasks, 'group'
  335. @classmethod
  336. def from_dict(self, d):
  337. tasks = d['kwargs']['tasks']
  338. if d['args'] and tasks:
  339. # partial args passed on to all tasks in the group (Issue #1057).
  340. for task in tasks:
  341. task['args'] = task._merge(d['args'])[0]
  342. return group(tasks, **kwdict(d['options']))
  343. def __call__(self, *partial_args, **options):
  344. tasks = [task.clone() for task in self.tasks]
  345. if not tasks:
  346. return
  347. # taking the app from the first task in the list,
  348. # there may be a better solution to this, e.g.
  349. # consolidate tasks with the same app and apply them in
  350. # batches.
  351. type = tasks[0].type.app.tasks[self['task']]
  352. return type(*type.prepare(options, tasks, partial_args))
  353. def freeze(self, _id=None):
  354. opts = self.options
  355. try:
  356. gid = opts['group']
  357. except KeyError:
  358. gid = opts['group'] = uuid()
  359. new_tasks, results = [], []
  360. for task in self.tasks:
  361. task = maybe_subtask(task).clone()
  362. results.append(task._freeze())
  363. new_tasks.append(task)
  364. self.tasks = self.kwargs['tasks'] = new_tasks
  365. return GroupResult(gid, results)
  366. _freeze = freeze
  367. def skew(self, start=1.0, stop=None, step=1.0):
  368. it = fxrange(start, stop, step, repeatlast=True)
  369. for task in self.tasks:
  370. task.set(countdown=next(it))
  371. return self
  372. def __iter__(self):
  373. return iter(self.tasks)
  374. def __repr__(self):
  375. return repr(self.tasks)
  376. @Signature.register_type
  377. class chord(Signature):
  378. def __init__(self, header, body=None, task='celery.chord',
  379. args=(), kwargs={}, **options):
  380. Signature.__init__(
  381. self, task, args,
  382. dict(kwargs, header=_maybe_group(header),
  383. body=maybe_subtask(body)), **options
  384. )
  385. self.subtask_type = 'chord'
  386. @classmethod
  387. def from_dict(self, d):
  388. args, d['kwargs'] = self._unpack_args(**kwdict(d['kwargs']))
  389. return self(*args, **kwdict(d))
  390. @staticmethod
  391. def _unpack_args(header=None, body=None, **kwargs):
  392. # Python signatures are better at extracting keys from dicts
  393. # than manually popping things off.
  394. return (header, body), kwargs
  395. @property
  396. def type(self):
  397. return self._type or self.tasks[0].type.app.tasks['celery.chord']
  398. def __call__(self, body=None, task_id=None, **kwargs):
  399. _chord = self.type
  400. body = (body or self.kwargs['body']).clone()
  401. kwargs = dict(self.kwargs, body=body, **kwargs)
  402. if _chord.app.conf.CELERY_ALWAYS_EAGER:
  403. return self.apply((), kwargs)
  404. res = body.freeze(task_id)
  405. parent = _chord(**kwargs)
  406. res.parent = parent
  407. return res
  408. def clone(self, *args, **kwargs):
  409. s = Signature.clone(self, *args, **kwargs)
  410. # need to make copy of body
  411. try:
  412. s.kwargs['body'] = s.kwargs['body'].clone()
  413. except (AttributeError, KeyError):
  414. pass
  415. return s
  416. def link(self, callback):
  417. self.body.link(callback)
  418. return callback
  419. def link_error(self, errback):
  420. self.body.link_error(errback)
  421. return errback
  422. def __repr__(self):
  423. if self.body:
  424. return self.body.reprcall(self.tasks)
  425. return '<chord without body: {0.tasks!r}>'.format(self)
  426. tasks = _getitem_property('kwargs.header')
  427. body = _getitem_property('kwargs.body')
  428. def subtask(varies, *args, **kwargs):
  429. if not (args or kwargs) and isinstance(varies, dict):
  430. if isinstance(varies, Signature):
  431. return varies.clone()
  432. return Signature.from_dict(varies)
  433. return Signature(varies, *args, **kwargs)
  434. def maybe_subtask(d):
  435. if d is not None and isinstance(d, dict) and not isinstance(d, Signature):
  436. return subtask(d)
  437. return d