canvas.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. """
  2. celery.canvas
  3. ~~~~~~~~~~~~~
  4. Designing task workflows.
  5. :copyright: (c) 2009 - 2012 by Ask Solem.
  6. :license: BSD, see LICENSE for more details.
  7. """
  8. from __future__ import absolute_import
  9. from operator import itemgetter
  10. from itertools import chain as _chain
  11. from kombu.utils import fxrange, kwdict, reprcall
  12. from celery import current_app
  13. from celery.local import Proxy
  14. from celery.utils import cached_property, uuid
  15. from celery.utils.compat import chain_from_iterable
  16. from celery.utils.functional import (
  17. maybe_list, is_list, regen,
  18. chunks as _chunks,
  19. )
  20. from celery.utils.text import truncate
  21. Chord = Proxy(lambda: current_app.tasks["celery.chord"])
  22. class _getitem_property(object):
  23. def __init__(self, key):
  24. self.key = key
  25. def __get__(self, obj, type=None):
  26. if obj is None:
  27. return type
  28. return obj.get(self.key)
  29. def __set__(self, obj, value):
  30. obj[self.key] = value
  31. class Signature(dict):
  32. """Class that wraps the arguments and execution options
  33. for a single task invocation.
  34. Used as the parts in a :class:`group` or to safely
  35. pass tasks around as callbacks.
  36. :param task: Either a task class/instance, or the name of a task.
  37. :keyword args: Positional arguments to apply.
  38. :keyword kwargs: Keyword arguments to apply.
  39. :keyword options: Additional options to :meth:`Task.apply_async`.
  40. Note that if the first argument is a :class:`dict`, the other
  41. arguments will be ignored and the values in the dict will be used
  42. instead.
  43. >>> s = subtask("tasks.add", args=(2, 2))
  44. >>> subtask(s)
  45. {"task": "tasks.add", args=(2, 2), kwargs={}, options={}}
  46. """
  47. TYPES = {}
  48. _type = None
  49. @classmethod
  50. def register_type(cls, subclass, name=None):
  51. cls.TYPES[name or subclass.__name__] = subclass
  52. return subclass
  53. @classmethod
  54. def from_dict(self, d):
  55. typ = d.get("subtask_type")
  56. if typ:
  57. return self.TYPES[typ].from_dict(d)
  58. return Signature(d)
  59. def __init__(self, task=None, args=None, kwargs=None, options=None,
  60. type=None, subtask_type=None, immutable=False, **ex):
  61. init = dict.__init__
  62. if isinstance(task, dict):
  63. return init(self, task) # works like dict(d)
  64. # Also supports using task class/instance instead of string name.
  65. try:
  66. task_name = task.name
  67. except AttributeError:
  68. task_name = task
  69. else:
  70. self._type = task
  71. init(self, task=task_name, args=tuple(args or ()),
  72. kwargs=kwargs or {},
  73. options=dict(options or {}, **ex),
  74. subtask_type=subtask_type,
  75. immutable=immutable)
  76. def __call__(self, *partial_args, **partial_kwargs):
  77. return self.apply_async(partial_args, partial_kwargs)
  78. delay = __call__
  79. def apply(self, args=(), kwargs={}, **options):
  80. """Apply this task locally."""
  81. # For callbacks: extra args are prepended to the stored args.
  82. args, kwargs, options = self._merge(args, kwargs, options)
  83. return self.type.apply(args, kwargs, **options)
  84. def _merge(self, args=(), kwargs={}, options={}):
  85. if self.immutable:
  86. return self.args, self.kwargs, dict(self.options, **options)
  87. return (tuple(args) + tuple(self.args) if args else self.args,
  88. dict(self.kwargs, **kwargs) if kwargs else self.kwargs,
  89. dict(self.options, **options) if options else self.options)
  90. def clone(self, args=(), kwargs={}, **options):
  91. args, kwargs, options = self._merge(args, kwargs, options)
  92. s = Signature.from_dict({"task": self.task, "args": args,
  93. "kwargs": kwargs, "options": options,
  94. "subtask_type": self.subtask_type,
  95. "immutable": self.immutable})
  96. s._type = self._type
  97. return s
  98. partial = clone
  99. def replace(self, args=None, kwargs=None, options=None):
  100. s = self.clone()
  101. if args is not None:
  102. s.args = args
  103. if kwargs is not None:
  104. s.kwargs = kwargs
  105. if options is not None:
  106. s.options = options
  107. return s
  108. def set(self, immutable=None, **options):
  109. if immutable is not None:
  110. self.immutable = immutable
  111. self.options.update(options)
  112. return self
  113. def apply_async(self, args=(), kwargs={}, **options):
  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_async(args, kwargs, **options)
  117. def append_to_list_option(self, key, value):
  118. items = self.options.setdefault(key, [])
  119. if value not in items:
  120. items.append(value)
  121. return value
  122. def link(self, callback):
  123. return self.append_to_list_option("link", callback)
  124. def link_error(self, errback):
  125. return self.append_to_list_option("link_error", errback)
  126. def flatten_links(self):
  127. return list(chain_from_iterable(_chain([[self]],
  128. (link.flatten_links()
  129. for link in maybe_list(self.options.get("link")) or []))))
  130. def __or__(self, other):
  131. if isinstance(other, chain):
  132. return chain(*self.tasks + other.tasks)
  133. elif isinstance(other, Signature):
  134. if isinstance(self, chain):
  135. return chain(*self.tasks + (other, ))
  136. return chain(self, other)
  137. return NotImplemented
  138. def __invert__(self):
  139. return self.apply_async().get()
  140. def __reduce__(self):
  141. # for serialization, the task type is lazily loaded,
  142. # and not stored in the dict itself.
  143. return subtask, (dict(self), )
  144. def reprcall(self, *args, **kwargs):
  145. args, kwargs, _ = self._merge(args, kwargs, {})
  146. return reprcall(self["task"], args, kwargs)
  147. def __repr__(self):
  148. return self.reprcall()
  149. @cached_property
  150. def type(self):
  151. return self._type or current_app.tasks[self["task"]]
  152. task = _getitem_property("task")
  153. args = _getitem_property("args")
  154. kwargs = _getitem_property("kwargs")
  155. options = _getitem_property("options")
  156. subtask_type = _getitem_property("subtask_type")
  157. immutable = _getitem_property("immutable")
  158. class chain(Signature):
  159. def __init__(self, *tasks, **options):
  160. tasks = tasks[0] if len(tasks) == 1 and is_list(tasks[0]) else tasks
  161. Signature.__init__(self, "celery.chain", (), {"tasks": tasks}, options)
  162. self.tasks = tasks
  163. self.subtask_type = "chain"
  164. def __call__(self, *args, **kwargs):
  165. return self.apply_async(*args, **kwargs)
  166. @classmethod
  167. def from_dict(self, d):
  168. return chain(*d["kwargs"]["tasks"], **kwdict(d["options"]))
  169. def __repr__(self):
  170. return " | ".join(map(repr, self.tasks))
  171. Signature.register_type(chain)
  172. class _basemap(Signature):
  173. _task_name = None
  174. _unpack_args = itemgetter("task", "it")
  175. def __init__(self, task, it, **options):
  176. Signature.__init__(self, self._task_name, (),
  177. {"task": task, "it": regen(it)}, **options)
  178. def apply_async(self, args=(), kwargs={}, **opts):
  179. # need to evaluate generators
  180. task, it = self._unpack_args(self.kwargs)
  181. return self.type.apply_async((),
  182. {"task": task, "it": list(it)}, **opts)
  183. @classmethod
  184. def from_dict(self, d):
  185. return chunks(*self._unpack_args(d["kwargs"]), **d["options"])
  186. class xmap(_basemap):
  187. _task_name = "celery.map"
  188. def __repr__(self):
  189. task, it = self._unpack_args(self.kwargs)
  190. return "[%s(x) for x in %s]" % (task.task, truncate(repr(it), 100))
  191. Signature.register_type(xmap)
  192. class xstarmap(_basemap):
  193. _task_name = "celery.starmap"
  194. def __repr__(self):
  195. task, it = self._unpack_args(self.kwargs)
  196. return "[%s(*x) for x in %s]" % (task.task, truncate(repr(it), 100))
  197. Signature.register_type(xstarmap)
  198. class chunks(Signature):
  199. _unpack_args = itemgetter("task", "it", "n")
  200. def __init__(self, task, it, n, **options):
  201. Signature.__init__(self, "celery.chunks", (),
  202. {"task": task, "it": regen(it), "n": n}, **options)
  203. @classmethod
  204. def from_dict(self, d):
  205. return chunks(*self._unpack_args(d["kwargs"]), **d["options"])
  206. def apply_async(self, args=(), kwargs={}, **opts):
  207. # need to evaluate generators
  208. task, it, n = self._unpack_args(self.kwargs)
  209. return self.type.apply_async((),
  210. {"task": task, "it": list(it), "n": n}, **opts)
  211. def __call__(self, **options):
  212. return self.group()(**options)
  213. def group(self):
  214. task, it, n = self._unpack_args(self.kwargs)
  215. return group(xstarmap(task, part) for part in _chunks(iter(it), n))
  216. @classmethod
  217. def apply_chunks(cls, task, it, n):
  218. return cls(task, it, n)()
  219. Signature.register_type(chunks)
  220. class group(Signature):
  221. def __init__(self, *tasks, **options):
  222. tasks = regen(tasks[0] if len(tasks) == 1 and is_list(tasks[0])
  223. else tasks)
  224. Signature.__init__(self, "celery.group", (), {"tasks": tasks}, options)
  225. self.tasks, self.subtask_type = tasks, "group"
  226. @classmethod
  227. def from_dict(self, d):
  228. return group(d["kwargs"]["tasks"], **kwdict(d["options"]))
  229. def __call__(self, **options):
  230. tasks, result, gid = self.type.prepare(options,
  231. map(Signature.clone, self.tasks))
  232. return self.type(tasks, result, gid)
  233. def skew(self, start=1.0, stop=None, step=1.0):
  234. _next_skew = fxrange(start, stop, step, repeatlast=True).next
  235. for task in self.tasks:
  236. task.set(countdown=_next_skew())
  237. return self
  238. def __repr__(self):
  239. return repr(self.tasks)
  240. Signature.register_type(group)
  241. class chord(Signature):
  242. Chord = Chord
  243. def __init__(self, header, body=None, **options):
  244. Signature.__init__(self, "celery.chord", (),
  245. {"header": regen(header),
  246. "body": maybe_subtask(body)}, options)
  247. self.subtask_type = "chord"
  248. @classmethod
  249. def from_dict(self, d):
  250. kwargs = d["kwargs"]
  251. return chord(kwargs["header"], kwargs.get("body"),
  252. **kwdict(d["options"]))
  253. def __call__(self, body=None, **options):
  254. _chord = self.Chord
  255. self.kwargs["body"] = body or self.kwargs["body"]
  256. if _chord.app.conf.CELERY_ALWAYS_EAGER:
  257. return self.apply((), {}, **options)
  258. callback_id = body.options.setdefault("task_id", uuid())
  259. _chord(**self.kwargs)
  260. return _chord.AsyncResult(callback_id)
  261. def clone(self, *args, **kwargs):
  262. s = Signature.clone(self, *args, **kwargs)
  263. # need to make copy of body
  264. try:
  265. s.kwargs["body"] = s.kwargs["body"].clone()
  266. except (AttributeError, KeyError):
  267. pass
  268. return s
  269. def link(self, callback):
  270. self.body.link(callback)
  271. return callback
  272. def link_error(self, errback):
  273. self.body.link_error(errback)
  274. return errback
  275. def __repr__(self):
  276. if self.body:
  277. return self.body.reprcall(self.tasks)
  278. return "<chord without body: %r>" % (self.tasks, )
  279. @property
  280. def tasks(self):
  281. return self.kwargs["header"]
  282. @property
  283. def body(self):
  284. return self.kwargs.get("body")
  285. Signature.register_type(chord)
  286. def subtask(varies, *args, **kwargs):
  287. if not (args or kwargs) and isinstance(varies, dict):
  288. if isinstance(varies, Signature):
  289. return varies.clone()
  290. return Signature.from_dict(varies)
  291. return Signature(varies, *args, **kwargs)
  292. def maybe_subtask(d):
  293. return subtask(d) if d is not None and not isinstance(d, Signature) else d