canvas.py 17 KB

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