Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

canvas.py 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698
  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 import these from :mod:`celery` and not this module.
  8. """
  9. from __future__ import absolute_import
  10. from collections import MutableSequence
  11. from copy import deepcopy
  12. from functools import partial as _partial, reduce
  13. from operator import itemgetter
  14. from itertools import chain as _chain
  15. from kombu.utils import cached_property, fxrange, kwdict, reprcall, uuid
  16. from celery._state import current_app
  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. __all__ = ['Signature', 'chain', 'xmap', 'xstarmap', 'chunks',
  23. 'group', 'chord', 'signature', 'maybe_signature']
  24. class _getitem_property(object):
  25. """Attribute -> dict key descriptor.
  26. The target object must support ``__getitem__``,
  27. and optionally ``__setitem__``.
  28. Example:
  29. >>> from collections import defaultdict
  30. >>> class Me(dict):
  31. ... deep = defaultdict(dict)
  32. ...
  33. ... foo = _getitem_property('foo')
  34. ... deep_thing = _getitem_property('deep.thing')
  35. >>> me = Me()
  36. >>> me.foo
  37. None
  38. >>> me.foo = 10
  39. >>> me.foo
  40. 10
  41. >>> me['foo']
  42. 10
  43. >>> me.deep_thing = 42
  44. >>> me.deep_thing
  45. 42
  46. >>> me.deep
  47. defaultdict(<type 'dict'>, {'thing': 42})
  48. """
  49. def __init__(self, keypath):
  50. path, _, self.key = keypath.rpartition('.')
  51. self.path = path.split('.') if path else None
  52. def _path(self, obj):
  53. return (reduce(lambda d, k: d[k], [obj] + self.path) if self.path
  54. else obj)
  55. def __get__(self, obj, type=None):
  56. if obj is None:
  57. return type
  58. return self._path(obj).get(self.key)
  59. def __set__(self, obj, value):
  60. self._path(obj)[self.key] = value
  61. def maybe_unroll_group(g):
  62. """Unroll group with only one member."""
  63. # Issue #1656
  64. try:
  65. size = len(g.tasks)
  66. except TypeError:
  67. try:
  68. size = g.tasks.__length_hint__()
  69. except (AttributeError, TypeError):
  70. pass
  71. else:
  72. return list(g.tasks)[0] if size == 1 else g
  73. else:
  74. return g.tasks[0] if size == 1 else g
  75. def _upgrade(fields, sig):
  76. """Used by custom signatures in .from_dict, to keep common fields."""
  77. sig.update(chord_size=fields.get('chord_size'))
  78. return sig
  79. class Signature(dict):
  80. """Class that wraps the arguments and execution options
  81. for a single task invocation.
  82. Used as the parts in a :class:`group` and other constructs,
  83. or to pass tasks around as callbacks while being compatible
  84. with serializers with a strict type subset.
  85. :param task: Either a task class/instance, or the name of a task.
  86. :keyword args: Positional arguments to apply.
  87. :keyword kwargs: Keyword arguments to apply.
  88. :keyword options: Additional options to :meth:`Task.apply_async`.
  89. Note that if the first argument is a :class:`dict`, the other
  90. arguments will be ignored and the values in the dict will be used
  91. instead.
  92. >>> s = signature('tasks.add', args=(2, 2))
  93. >>> signature(s)
  94. {'task': 'tasks.add', args=(2, 2), kwargs={}, options={}}
  95. """
  96. TYPES = {}
  97. _app = _type = None
  98. @classmethod
  99. def register_type(cls, subclass, name=None):
  100. cls.TYPES[name or subclass.__name__] = subclass
  101. return subclass
  102. @classmethod
  103. def from_dict(self, d, app=None):
  104. typ = d.get('subtask_type')
  105. if typ:
  106. return self.TYPES[typ].from_dict(kwdict(d), app=app)
  107. return Signature(d, app=app)
  108. def __init__(self, task=None, args=None, kwargs=None, options=None,
  109. type=None, subtask_type=None, immutable=False,
  110. app=None, **ex):
  111. self._app = app
  112. init = dict.__init__
  113. if isinstance(task, dict):
  114. return init(self, task) # works like dict(d)
  115. # Also supports using task class/instance instead of string name.
  116. try:
  117. task_name = task.name
  118. except AttributeError:
  119. task_name = task
  120. else:
  121. self._type = task
  122. init(self,
  123. task=task_name, args=tuple(args or ()),
  124. kwargs=kwargs or {},
  125. options=dict(options or {}, **ex),
  126. subtask_type=subtask_type,
  127. immutable=immutable,
  128. chord_size=None)
  129. def __call__(self, *partial_args, **partial_kwargs):
  130. args, kwargs, _ = self._merge(partial_args, partial_kwargs, None)
  131. return self.type(*args, **kwargs)
  132. def delay(self, *partial_args, **partial_kwargs):
  133. return self.apply_async(partial_args, partial_kwargs)
  134. def apply(self, args=(), kwargs={}, **options):
  135. """Apply this task locally."""
  136. # For callbacks: extra args are prepended to the stored args.
  137. args, kwargs, options = self._merge(args, kwargs, options)
  138. return self.type.apply(args, kwargs, **options)
  139. def _merge(self, args=(), kwargs={}, options={}):
  140. if self.immutable:
  141. return (self.args, self.kwargs,
  142. dict(self.options, **options) if options else self.options)
  143. return (tuple(args) + tuple(self.args) if args else self.args,
  144. dict(self.kwargs, **kwargs) if kwargs else self.kwargs,
  145. dict(self.options, **options) if options else self.options)
  146. def clone(self, args=(), kwargs={}, app=None, **opts):
  147. # need to deepcopy options so origins links etc. is not modified.
  148. if args or kwargs or opts:
  149. args, kwargs, opts = self._merge(args, kwargs, opts)
  150. else:
  151. args, kwargs, opts = self.args, self.kwargs, self.options
  152. s = Signature.from_dict({'task': self.task, 'args': tuple(args),
  153. 'kwargs': kwargs, 'options': deepcopy(opts),
  154. 'subtask_type': self.subtask_type,
  155. 'chord_size': self.chord_size,
  156. 'immutable': self.immutable},
  157. app=app or self._app)
  158. s._type = self._type
  159. return s
  160. partial = clone
  161. def freeze(self, _id=None, group_id=None, chord=None):
  162. opts = self.options
  163. try:
  164. tid = opts['task_id']
  165. except KeyError:
  166. tid = opts['task_id'] = _id or uuid()
  167. if 'reply_to' not in opts:
  168. opts['reply_to'] = self.app.oid
  169. if group_id:
  170. opts['group_id'] = group_id
  171. if chord:
  172. opts['chord'] = chord
  173. return self.app.AsyncResult(tid)
  174. _freeze = freeze
  175. def replace(self, args=None, kwargs=None, options=None):
  176. s = self.clone()
  177. if args is not None:
  178. s.args = args
  179. if kwargs is not None:
  180. s.kwargs = kwargs
  181. if options is not None:
  182. s.options = options
  183. return s
  184. def set(self, immutable=None, **options):
  185. if immutable is not None:
  186. self.set_immutable(immutable)
  187. self.options.update(options)
  188. return self
  189. def set_immutable(self, immutable):
  190. self.immutable = immutable
  191. def apply_async(self, args=(), kwargs={}, **options):
  192. try:
  193. _apply = self._apply_async
  194. except IndexError: # no tasks for chain, etc to find type
  195. return
  196. # For callbacks: extra args are prepended to the stored args.
  197. if args or kwargs or options:
  198. args, kwargs, options = self._merge(args, kwargs, options)
  199. else:
  200. args, kwargs, options = self.args, self.kwargs, self.options
  201. return _apply(args, kwargs, **options)
  202. def append_to_list_option(self, key, value):
  203. items = self.options.setdefault(key, [])
  204. if not isinstance(items, MutableSequence):
  205. items = self.options[key] = [items]
  206. if value not in items:
  207. items.append(value)
  208. return value
  209. def link(self, callback):
  210. return self.append_to_list_option('link', callback)
  211. def link_error(self, errback):
  212. return self.append_to_list_option('link_error', errback)
  213. def flatten_links(self):
  214. return list(_chain.from_iterable(_chain(
  215. [[self]],
  216. (link.flatten_links()
  217. for link in maybe_list(self.options.get('link')) or [])
  218. )))
  219. def __or__(self, other):
  220. if isinstance(other, group):
  221. other = maybe_unroll_group(other)
  222. if not isinstance(self, chain) and isinstance(other, chain):
  223. return chain((self, ) + other.tasks, app=self._app)
  224. elif isinstance(other, chain):
  225. return chain(*self.tasks + other.tasks, app=self._app)
  226. elif isinstance(other, Signature):
  227. if isinstance(self, chain):
  228. return chain(*self.tasks + (other, ), app=self._app)
  229. return chain(self, other, app=self._app)
  230. return NotImplemented
  231. def __deepcopy__(self, memo):
  232. memo[id(self)] = self
  233. return dict(self)
  234. def __invert__(self):
  235. return self.apply_async().get()
  236. def __reduce__(self):
  237. # for serialization, the task type is lazily loaded,
  238. # and not stored in the dict itself.
  239. return subtask, (dict(self), )
  240. def reprcall(self, *args, **kwargs):
  241. args, kwargs, _ = self._merge(args, kwargs, {})
  242. return reprcall(self['task'], args, kwargs)
  243. def election(self):
  244. type = self.type
  245. app = type.app
  246. tid = self.options.get('task_id') or uuid()
  247. with app.producer_or_acquire(None) as P:
  248. props = type.backend.on_task_call(P, tid)
  249. app.control.election(tid, 'task', self.clone(task_id=tid, **props),
  250. connection=P.connection)
  251. return type.AsyncResult(tid)
  252. def __repr__(self):
  253. return self.reprcall()
  254. @cached_property
  255. def type(self):
  256. return self._type or self.app.tasks[self['task']]
  257. @cached_property
  258. def app(self):
  259. return self._app or current_app
  260. @cached_property
  261. def AsyncResult(self):
  262. try:
  263. return self.type.AsyncResult
  264. except KeyError: # task not registered
  265. return self.app.AsyncResult
  266. @cached_property
  267. def _apply_async(self):
  268. try:
  269. return self.type.apply_async
  270. except KeyError:
  271. return _partial(self.app.send_task, self['task'])
  272. id = _getitem_property('options.task_id')
  273. task = _getitem_property('task')
  274. args = _getitem_property('args')
  275. kwargs = _getitem_property('kwargs')
  276. options = _getitem_property('options')
  277. subtask_type = _getitem_property('subtask_type')
  278. chord_size = _getitem_property('chord_size')
  279. immutable = _getitem_property('immutable')
  280. @Signature.register_type
  281. class chain(Signature):
  282. def __init__(self, *tasks, **options):
  283. tasks = (regen(tasks[0]) if len(tasks) == 1 and is_list(tasks[0])
  284. else tasks)
  285. Signature.__init__(
  286. self, 'celery.chain', (), {'tasks': tasks}, **options
  287. )
  288. self.tasks = tasks
  289. self.subtask_type = 'chain'
  290. def __call__(self, *args, **kwargs):
  291. if self.tasks:
  292. return self.apply_async(args, kwargs)
  293. @classmethod
  294. def from_dict(self, d, app=None):
  295. tasks = [maybe_signature(t, app=app) for t in d['kwargs']['tasks']]
  296. if d['args'] and tasks:
  297. # partial args passed on to first task in chain (Issue #1057).
  298. tasks[0]['args'] = tasks[0]._merge(d['args'])[0]
  299. return _upgrade(d, chain(*tasks, app=app, **d['options']))
  300. @property
  301. def type(self):
  302. try:
  303. return self._type or self.tasks[0].type.app.tasks['celery.chain']
  304. except KeyError:
  305. return self.app.tasks['celery.chain']
  306. def __repr__(self):
  307. return ' | '.join(repr(t) for t in self.tasks)
  308. class _basemap(Signature):
  309. _task_name = None
  310. _unpack_args = itemgetter('task', 'it')
  311. def __init__(self, task, it, **options):
  312. Signature.__init__(
  313. self, self._task_name, (),
  314. {'task': task, 'it': regen(it)}, immutable=True, **options
  315. )
  316. def apply_async(self, args=(), kwargs={}, **opts):
  317. # need to evaluate generators
  318. task, it = self._unpack_args(self.kwargs)
  319. return self.type.apply_async(
  320. (), {'task': task, 'it': list(it)}, **opts
  321. )
  322. @classmethod
  323. def from_dict(cls, d, app=None):
  324. return _upgrade(
  325. d, cls(*cls._unpack_args(d['kwargs']), app=app, **d['options']),
  326. )
  327. @Signature.register_type
  328. class xmap(_basemap):
  329. _task_name = 'celery.map'
  330. def __repr__(self):
  331. task, it = self._unpack_args(self.kwargs)
  332. return '[{0}(x) for x in {1}]'.format(task.task,
  333. truncate(repr(it), 100))
  334. @Signature.register_type
  335. class xstarmap(_basemap):
  336. _task_name = 'celery.starmap'
  337. def __repr__(self):
  338. task, it = self._unpack_args(self.kwargs)
  339. return '[{0}(*x) for x in {1}]'.format(task.task,
  340. truncate(repr(it), 100))
  341. @Signature.register_type
  342. class chunks(Signature):
  343. _unpack_args = itemgetter('task', 'it', 'n')
  344. def __init__(self, task, it, n, **options):
  345. Signature.__init__(
  346. self, 'celery.chunks', (),
  347. {'task': task, 'it': regen(it), 'n': n},
  348. immutable=True, **options
  349. )
  350. @classmethod
  351. def from_dict(self, d, app=None):
  352. return _upgrade(
  353. d, chunks(*self._unpack_args(
  354. d['kwargs']), app=app, **d['options']),
  355. )
  356. def apply_async(self, args=(), kwargs={}, **opts):
  357. return self.group().apply_async(args, kwargs, **opts)
  358. def __call__(self, **options):
  359. return self.group()(**options)
  360. def group(self):
  361. # need to evaluate generators
  362. task, it, n = self._unpack_args(self.kwargs)
  363. return group((xstarmap(task, part, app=self._app)
  364. for part in _chunks(iter(it), n)),
  365. app=self._app)
  366. @classmethod
  367. def apply_chunks(cls, task, it, n, app=None):
  368. return cls(task, it, n, app=app)()
  369. def _maybe_group(tasks):
  370. if isinstance(tasks, group):
  371. tasks = list(tasks.tasks)
  372. elif isinstance(tasks, Signature):
  373. tasks = [tasks]
  374. else:
  375. tasks = regen(tasks)
  376. return tasks
  377. def _maybe_clone(tasks, app):
  378. return [s.clone() if isinstance(s, Signature) else signature(s, app=app)
  379. for s in tasks]
  380. @Signature.register_type
  381. class group(Signature):
  382. def __init__(self, *tasks, **options):
  383. if len(tasks) == 1:
  384. tasks = _maybe_group(tasks[0])
  385. Signature.__init__(
  386. self, 'celery.group', (), {'tasks': tasks}, **options
  387. )
  388. self.tasks, self.subtask_type = tasks, 'group'
  389. @classmethod
  390. def from_dict(self, d, app=None):
  391. tasks = [maybe_signature(t, app=app) for t in d['kwargs']['tasks']]
  392. if d['args'] and tasks:
  393. # partial args passed on to all tasks in the group (Issue #1057).
  394. for task in tasks:
  395. task['args'] = task._merge(d['args'])[0]
  396. return _upgrade(d, group(tasks, app=app, **kwdict(d['options'])))
  397. def apply_async(self, args=(), kwargs=None, add_to_parent=True, **options):
  398. tasks = _maybe_clone(self.tasks, app=self._app)
  399. if not tasks:
  400. return self.freeze()
  401. type = self.type
  402. return type(*type.prepare(dict(self.options, **options), tasks, args),
  403. add_to_parent=add_to_parent)
  404. def set_immutable(self, immutable):
  405. for task in self.tasks:
  406. task.set_immutable(immutable)
  407. def link(self, sig):
  408. # Simply link to first task
  409. sig = sig.clone().set(immutable=True)
  410. return self.tasks[0].link(sig)
  411. def link_error(self, sig):
  412. sig = sig.clone().set(immutable=True)
  413. return self.tasks[0].link_error(sig)
  414. def apply(self, *args, **kwargs):
  415. if not self.tasks:
  416. return self.freeze() # empty group returns GroupResult
  417. return Signature.apply(self, *args, **kwargs)
  418. def __call__(self, *partial_args, **options):
  419. return self.apply_async(partial_args, **options)
  420. def freeze(self, _id=None, group_id=None, chord=None):
  421. opts = self.options
  422. try:
  423. gid = opts['task_id']
  424. except KeyError:
  425. gid = opts['task_id'] = uuid()
  426. if group_id:
  427. opts['group_id'] = group_id
  428. if chord:
  429. opts['chord'] = group_id
  430. new_tasks, results = [], []
  431. for task in self.tasks:
  432. task = maybe_signature(task, app=self._app).clone()
  433. results.append(task.freeze(group_id=group_id, chord=chord))
  434. new_tasks.append(task)
  435. self.tasks = self.kwargs['tasks'] = new_tasks
  436. return self.app.GroupResult(gid, results)
  437. _freeze = freeze
  438. def skew(self, start=1.0, stop=None, step=1.0):
  439. it = fxrange(start, stop, step, repeatlast=True)
  440. for task in self.tasks:
  441. task.set(countdown=next(it))
  442. return self
  443. def __iter__(self):
  444. return iter(self.tasks)
  445. def __repr__(self):
  446. return repr(self.tasks)
  447. @property
  448. def app(self):
  449. return self._app or (self.tasks[0].app if self.tasks else current_app)
  450. @property
  451. def type(self):
  452. if self._type:
  453. return self._type
  454. # taking the app from the first task in the list, there may be a
  455. # better solution for this, e.g. to consolidate tasks with the same
  456. # app and apply them in batches.
  457. return self.app.tasks[self['task']]
  458. @Signature.register_type
  459. class chord(Signature):
  460. def __init__(self, header, body=None, task='celery.chord',
  461. args=(), kwargs={}, **options):
  462. Signature.__init__(
  463. self, task, args,
  464. dict(kwargs, header=_maybe_group(header),
  465. body=maybe_signature(body, app=self._app)), **options
  466. )
  467. self.subtask_type = 'chord'
  468. def apply(self, args=(), kwargs={}, **options):
  469. # For callbacks: extra args are prepended to the stored args.
  470. args, kwargs, options = self._merge(args, kwargs, options)
  471. return self.type.apply(args, kwargs, **options)
  472. def freeze(self, _id=None, group_id=None, chord=None):
  473. return self.body.freeze(_id, group_id=group_id, chord=chord)
  474. @classmethod
  475. def from_dict(self, d, app=None):
  476. args, d['kwargs'] = self._unpack_args(**kwdict(d['kwargs']))
  477. return _upgrade(d, self(*args, app=app, **kwdict(d)))
  478. @staticmethod
  479. def _unpack_args(header=None, body=None, **kwargs):
  480. # Python signatures are better at extracting keys from dicts
  481. # than manually popping things off.
  482. return (header, body), kwargs
  483. @property
  484. def app(self):
  485. # we will be able to fix this mess in 3.2 when we no longer
  486. # require an actual task implementation for chord/group
  487. if self._app:
  488. return self._app
  489. app = None if self.body is None else self.body.app
  490. if app is None:
  491. try:
  492. app = self.tasks[0].app
  493. except IndexError:
  494. app = None
  495. return app if app is not None else current_app
  496. @property
  497. def type(self):
  498. if self._type:
  499. return self._type
  500. return self.app.tasks['celery.chord']
  501. def delay(self, *partial_args, **partial_kwargs):
  502. # There's no partial_kwargs for chord.
  503. return self.apply_async(partial_args)
  504. def apply_async(self, args=(), kwargs={}, task_id=None,
  505. producer=None, publisher=None, connection=None,
  506. router=None, result_cls=None, **options):
  507. args = (tuple(args) + tuple(self.args)
  508. if args and not self.immutable else self.args)
  509. body = kwargs.get('body') or self.kwargs['body']
  510. kwargs = dict(self.kwargs, **kwargs)
  511. body = body.clone(**options)
  512. _chord = self.type
  513. if _chord.app.conf.CELERY_ALWAYS_EAGER:
  514. return self.apply(args, kwargs, task_id=task_id, **options)
  515. res = body.freeze(task_id)
  516. parent = _chord(self.tasks, body, args, **options)
  517. res.parent = parent
  518. return res
  519. def __call__(self, body=None, **options):
  520. return self.apply_async(
  521. (), {'body': body} if body else {}, **options)
  522. def clone(self, *args, **kwargs):
  523. s = Signature.clone(self, *args, **kwargs)
  524. # need to make copy of body
  525. try:
  526. s.kwargs['body'] = s.kwargs['body'].clone()
  527. except (AttributeError, KeyError):
  528. pass
  529. return s
  530. def link(self, callback):
  531. self.body.link(callback)
  532. return callback
  533. def link_error(self, errback):
  534. self.body.link_error(errback)
  535. return errback
  536. def set_immutable(self, immutable):
  537. # changes mutability of header only, not callback.
  538. for task in self.tasks:
  539. task.set_immutable(immutable)
  540. def __repr__(self):
  541. if self.body:
  542. return self.body.reprcall(self.tasks)
  543. return '<chord without body: {0.tasks!r}>'.format(self)
  544. tasks = _getitem_property('kwargs.header')
  545. body = _getitem_property('kwargs.body')
  546. def signature(varies, args=(), kwargs={}, options={}, app=None, **kw):
  547. if isinstance(varies, dict):
  548. if isinstance(varies, Signature):
  549. return varies.clone(app=app)
  550. return Signature.from_dict(varies, app=app)
  551. return Signature(varies, args, kwargs, options, app=app, **kw)
  552. subtask = signature # XXX compat
  553. def maybe_signature(d, app=None):
  554. if d is not None:
  555. if isinstance(d, dict):
  556. if not isinstance(d, Signature):
  557. return signature(d, app=app)
  558. elif isinstance(d, list):
  559. return [maybe_signature(s, app=app) for s in d]
  560. if app is not None:
  561. d._app = app
  562. return d
  563. maybe_subtask = maybe_signature # XXX compat