canvas.rst 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  1. .. _guide-canvas:
  2. =============================
  3. Canvas: Designing Workflows
  4. =============================
  5. .. contents::
  6. :local:
  7. :depth: 1
  8. .. _canvas-subtasks:
  9. Subtasks
  10. ========
  11. .. versionadded:: 2.0
  12. A :func:`~celery.subtask` wraps the signature of a single task invocation:
  13. arguments, keyword arguments and execution options.
  14. A subtask for the ``add`` task can be created like this::
  15. >>> from celery import subtask
  16. >>> subtask(add.name, args=(4, 4))
  17. or you can create one from the task itself::
  18. >>> from proj.tasks import add
  19. >>> add.subtask(args=(4, 4))
  20. It supports the "Calling API" which means it takes the same arguments
  21. as the :meth:`~@Task.apply_async` method::
  22. >>> add.apply_async(args, kwargs, **options)
  23. >>> add.subtask(args, kwargs, **options)
  24. >>> add.apply_async((2, 2), countdown=1)
  25. >>> add.subtask((2, 2), countdown=1)
  26. And like there is a :meth:`~@Task.delay` shortcut for `apply_async`
  27. there is an :meth:`~@Task.s` shortcut for subtask::
  28. >>> add.s(*args, **kwargs)
  29. >>> add.s(2, 2)
  30. proj.tasks.add(2, 2)
  31. >>> add.s(2, 2) == add.subtask((2, 2))
  32. True
  33. You can't define options with :meth:`~@Task.s`, but a chaining
  34. ``set`` call takes care of that::
  35. >>> add.s(2, 2).set(countdown=1)
  36. proj.tasks.add(2, 2)
  37. Partials
  38. --------
  39. A subtask can be applied too::
  40. >>> add.s(2, 2).delay()
  41. >>> add.s(2, 2).apply_async(countdown=1)
  42. Specifying additional args, kwargs or options to ``apply_async``/``delay``
  43. creates partials:
  44. - Any arguments added will be prepended to the args in the signature::
  45. >>> partial = add.s(2) # incomplete signature
  46. >>> partial.delay(4) # 2 + 4
  47. >>> partial.apply_async((4, )) # same
  48. - Any keyword arguments added will be merged with the kwargs in the signature,
  49. with the new keyword arguments taking precedence::
  50. >>> s = add.s(2, 2)
  51. >>> s.delay(debug=True) # -> add(2, 2, debug=True)
  52. >>> s.apply_async(kwargs={'debug': True}) # same
  53. - Any options added will be merged with the options in the signature,
  54. with the new options taking precedence::
  55. >>> s = add.subtask((2, 2), countdown=10)
  56. >>> s.apply_async(countdown=1) # countdown is now 1
  57. You can also clone subtasks to augment these::
  58. >>> s = add.s(2)
  59. proj.tasks.add(2)
  60. >>> s.clone(args=(4, ), kwargs={'debug': True})
  61. proj.tasks.add(2, 4, debug=True)
  62. Partials are meant to be used with callbacks, any tasks linked or chord
  63. callbacks will be applied with the result of the parent task.
  64. Sometimes you want to specify a callback that does not take
  65. additional arguments, and in that case you can set the subtask
  66. to be immutable::
  67. >>> add.apply_async((2, 2), link=reset_buffers.subtask(immutable=True))
  68. The ``.si()`` shortcut can also be used to create immutable subtasks::
  69. >>> add.apply_async((2, 2), link=reset_buffers.si())
  70. Only the execution options can be set when a subtask is immutable,
  71. and it's not possible to apply the subtask with partial args/kwargs.
  72. .. note::
  73. In this tutorial we use the prefix operator `~` to subtasks.
  74. You probably shouldn't use it in your production code, but it's a handy shortcut
  75. when testing with the Python shell::
  76. >>> ~subtask
  77. >>> # is the same as
  78. >>> subtask.delay().get()
  79. .. _canvas-callbacks:
  80. Callbacks
  81. ---------
  82. Callbacks can be added to any task using the ``link`` argument
  83. to ``apply_async``:
  84. add.apply_async((2, 2), link=other_task.subtask())
  85. The callback will only be applied if the task exited successfully,
  86. and it will be applied with the return value of the parent task as argument.
  87. As we mentioned earlier, any arguments you add to `subtask`,
  88. will be prepended to the arguments specified by the subtask itself!
  89. If you have the subtask::
  90. >>> add.subtask(args=(10, ))
  91. `subtask.delay(result)` becomes::
  92. >>> add.apply_async(args=(result, 10))
  93. ...
  94. Now let's call our ``add`` task with a callback using partial
  95. arguments::
  96. >>> add.apply_async((2, 2), link=add.subtask((8, )))
  97. As expected this will first launch one task calculating :math:`2 + 2`, then
  98. another task calculating :math:`4 + 8`.
  99. .. _canvas-chains:
  100. Chaining
  101. ========
  102. Tasks can be linked together, which in practice means adding
  103. a callback task::
  104. >>> res = add.apply_async((2, 2), link=mul.s(16))
  105. >>> res.get()
  106. 4
  107. The linked task will be applied with the result of its parent
  108. task as the first argument, which in the above case will result
  109. in ``mul(4, 16)`` since the result is 4.
  110. The results will keep track of what subtasks a task applies,
  111. and this can be accessed from the result instance::
  112. >>> res.children
  113. [<AsyncResult: 8c350acf-519d-4553-8a53-4ad3a5c5aeb4>]
  114. >>> res.children[0].get()
  115. 64
  116. The result instance also has a :meth:`~@AsyncResult.collect` method
  117. that treats the result as a graph, enabling you to iterate over
  118. the results::
  119. >>> list(res.collect())
  120. [(<AsyncResult: 7b720856-dc5f-4415-9134-5c89def5664e>, 4),
  121. (<AsyncResult: 8c350acf-519d-4553-8a53-4ad3a5c5aeb4>, 64)]
  122. By default :meth:`~@AsyncResult.collect` will raise an
  123. :exc:`~@IncompleteStream` exception if the graph is not fully
  124. formed (one of the tasks has not completed yet),
  125. but you can get an intermediate representation of the graph
  126. too::
  127. >>> for result, value in res.collect(intermediate=True)):
  128. ....
  129. You can link together as many tasks as you like,
  130. and subtasks can be linked too::
  131. >>> s = add.s(2, 2)
  132. >>> s.link(mul.s(4))
  133. >>> s.link(log_result.s())
  134. You can also add *error callbacks* using the ``link_error`` argument::
  135. >>> add.apply_async((2, 2), link_error=log_error.s())
  136. >>> add.subtask((2, 2), link_error=log_error.s())
  137. Since exceptions can only be serialized when pickle is used
  138. the error callbacks take the id of the parent task as argument instead:
  139. .. code-block:: python
  140. from proj.celery import celery
  141. @celery.task()
  142. def log_error(task_id):
  143. result = celery.AsyncResult(task_id)
  144. result.get(propagate=False) # make sure result written.
  145. with open('/var/errors/%s' % (task_id, )) as fh:
  146. fh.write('--\n\n%s %s %s' % (
  147. task_id, result.result, result.traceback))
  148. To make it even easier to link tasks together there is
  149. a special subtask called :class:`~celery.chain` that lets
  150. you chain tasks together:
  151. .. code-block:: python
  152. >>> from celery import chain
  153. >>> from proj.tasks import add, mul
  154. # (4 + 4) * 8 * 10
  155. >>> res = chain(add.s(4, 4), mul.s(8), mul.s(10))
  156. proj.tasks.add(4, 4) | proj.tasks.mul(8)
  157. Calling the chain will apply the tasks in the current process
  158. and return the result of the last task in the chain::
  159. >>> res = chain(add.s(4, 4), mul.s(8), mul.s(10))
  160. >>> res.get()
  161. 640
  162. And calling ``apply_async`` will create a dedicated
  163. task so that the act of applying the chain happens
  164. in a worker::
  165. >>> res = chain(add.s(4, 4), mul.s(8), mul.s(10))
  166. >>> res.get()
  167. 640
  168. It also sets ``parent`` attributes so that you can
  169. work your way up the chain to get intermediate results::
  170. >>> res.parent.get()
  171. 64
  172. >>> res.parent.parent.get()
  173. 8
  174. >>> res.parent.parent
  175. <AsyncResult: eeaad925-6778-4ad1-88c8-b2a63d017933>
  176. Chains can also be made using the ``|`` (pipe) operator::
  177. >>> (add.s(2, 2) | mul.s(8) | mul.s(10)).apply_async()
  178. Graphs
  179. ------
  180. In addition you can work with the result graph as a
  181. :class:`~celery.datastructures.DependencyGraph`:
  182. .. code-block:: python
  183. >>> res = chain(add.s(4, 4), mul.s(8), mul.s(10))()
  184. >>> res.parent.parent.graph
  185. 285fa253-fcf8-42ef-8b95-0078897e83e6(1)
  186. 463afec2-5ed4-4036-b22d-ba067ec64f52(0)
  187. 872c3995-6fa0-46ca-98c2-5a19155afcf0(2)
  188. 285fa253-fcf8-42ef-8b95-0078897e83e6(1)
  189. 463afec2-5ed4-4036-b22d-ba067ec64f52(0)
  190. You can even convert these graphs to *dot* format::
  191. >>> with open('graph.dot', 'w') as fh:
  192. ... res.parent.parent.graph.to_dot(fh)
  193. and create images::
  194. $ dot -Tpng graph.dot -o graph.png
  195. .. image:: ../images/graph.png
  196. .. _canvas-group:
  197. Groups
  198. ======
  199. A group can be used to execute several tasks in parallel.
  200. The :class:`~celery.group` function takes a list of subtasks::
  201. >>> from celery import group
  202. >>> from proj.tasks import add
  203. >>> group(add.s(2, 2), add.s(4, 4))
  204. (proj.tasks.add(2, 2), proj.tasks.add(4, 4))
  205. If you **call** the group, the tasks will be applied
  206. one after one in the current process, and a :class:`~@TaskSetResult`
  207. instance is returned which can be used to keep track of the results,
  208. or tell how many tasks are ready and so on::
  209. >>> g = group(add.s(2, 2), add.s(4, 4))
  210. >>> res = g()
  211. >>> res.get()
  212. [4, 8]
  213. However, if you call ``apply_async`` on the group it will
  214. send a special grouping task, so that the action of applying
  215. the tasks happens in a worker instead of the current process::
  216. >>> res = g.apply_async()
  217. >>> res.get()
  218. [4, 8]
  219. Group also supports iterators::
  220. >>> group(add.s(i, i) for i in xrange(100))()
  221. A group is a subclass instance, so it can be used in combination
  222. with other subtasks.
  223. Group Results
  224. -------------
  225. The group task returns a special result too,
  226. this result works just like normal task results, except
  227. that it works on the group as a whole::
  228. >>> from celery import group
  229. >>> from tasks import add
  230. >>> job = group([
  231. ... add.subtask((2, 2)),
  232. ... add.subtask((4, 4)),
  233. ... add.subtask((8, 8)),
  234. ... add.subtask((16, 16)),
  235. ... add.subtask((32, 32)),
  236. ... ])
  237. >>> result = job.apply_async()
  238. >>> result.ready() # have all subtasks completed?
  239. True
  240. >>> result.successful() # were all subtasks successful?
  241. True
  242. >>> result.join()
  243. [4, 8, 16, 32, 64]
  244. The :class:`~celery.result.GroupResult` takes a list of
  245. :class:`~celery.result.AsyncResult` instances and operates on them as if it was a
  246. single task.
  247. It supports the following operations:
  248. * :meth:`~celery.result.GroupResult.successful`
  249. Returns :const:`True` if all of the subtasks finished
  250. successfully (e.g. did not raise an exception).
  251. * :meth:`~celery.result.GroupResult.failed`
  252. Returns :const:`True` if any of the subtasks failed.
  253. * :meth:`~celery.result.GroupResult.waiting`
  254. Returns :const:`True` if any of the subtasks
  255. is not ready yet.
  256. * :meth:`~celery.result.GroupResult.ready`
  257. Return :const:`True` if all of the subtasks
  258. are ready.
  259. * :meth:`~celery.result.GroupResult.completed_count`
  260. Returns the number of completed subtasks.
  261. * :meth:`~celery.result.GroupResult.revoke`
  262. Revokes all of the subtasks.
  263. * :meth:`~celery.result.GroupResult.iterate`
  264. Iterates over the return values of the subtasks
  265. as they finish, one by one.
  266. * :meth:`~celery.result.GroupResult.join`
  267. Gather the results for all of the subtasks
  268. and return a list with them ordered by the order of which they
  269. were called.
  270. .. _chords:
  271. Chords
  272. ======
  273. .. versionadded:: 2.3
  274. A chord is a task that only executes after all of the tasks in a taskset has
  275. finished executing.
  276. Let's calculate the sum of the expression
  277. :math:`1 + 1 + 2 + 2 + 3 + 3 ... n + n` up to a hundred digits.
  278. First we need two tasks, :func:`add` and :func:`tsum` (:func:`sum` is
  279. already a standard function):
  280. .. code-block:: python
  281. @celery.task()
  282. def add(x, y):
  283. return x + y
  284. @celery.task()
  285. def tsum(numbers):
  286. return sum(numbers)
  287. Now we can use a chord to calculate each addition step in parallel, and then
  288. get the sum of the resulting numbers::
  289. >>> from celery import chord
  290. >>> from tasks import add, tsum
  291. >>> chord(add.subtask((i, i))
  292. ... for i in xrange(100))(tsum.subtask()).get()
  293. 9900
  294. This is obviously a very contrived example, the overhead of messaging and
  295. synchronization makes this a lot slower than its Python counterpart::
  296. sum(i + i for i in xrange(100))
  297. The synchronization step is costly, so you should avoid using chords as much
  298. as possible. Still, the chord is a powerful primitive to have in your toolbox
  299. as synchronization is a required step for many parallel algorithms.
  300. Let's break the chord expression down::
  301. >>> callback = tsum.subtask()
  302. >>> header = [add.subtask((i, i)) for i in xrange(100)]
  303. >>> result = chord(header)(callback)
  304. >>> result.get()
  305. 9900
  306. Remember, the callback can only be executed after all of the tasks in the
  307. header has returned. Each step in the header is executed as a task, in
  308. parallel, possibly on different nodes. The callback is then applied with
  309. the return value of each task in the header. The task id returned by
  310. :meth:`chord` is the id of the callback, so you can wait for it to complete
  311. and get the final return value (but remember to :ref:`never have a task wait
  312. for other tasks <task-synchronous-subtasks>`)
  313. .. _chord-important-notes:
  314. Important Notes
  315. ---------------
  316. By default the synchronization step is implemented by having a recurring task
  317. poll the completion of the taskset every second, applying the subtask when
  318. ready.
  319. Example implementation:
  320. .. code-block:: python
  321. def unlock_chord(taskset, callback, interval=1, max_retries=None):
  322. if taskset.ready():
  323. return subtask(callback).delay(taskset.join())
  324. raise unlock_chord.retry(countdown=interval, max_retries=max_retries)
  325. This is used by all result backends except Redis and Memcached, which increment a
  326. counter after each task in the header, then applying the callback when the
  327. counter exceeds the number of tasks in the set. *Note:* chords do not properly
  328. work with Redis before version 2.2; you will need to upgrade to at least 2.2 to
  329. use them.
  330. The Redis and Memcached approach is a much better solution, but not easily
  331. implemented in other backends (suggestions welcome!).
  332. .. note::
  333. If you are using chords with the Redis result backend and also overriding
  334. the :meth:`Task.after_return` method, you need to make sure to call the
  335. super method or else the chord callback will not be applied.
  336. .. code-block:: python
  337. def after_return(self, *args, **kwargs):
  338. do_something()
  339. super(MyTask, self).after_return(*args, **kwargs)
  340. Map & Starmap
  341. =============
  342. :class:`~celery.map` and :class:`~celery.starmap` are built-in tasks
  343. that calls the task for every element in a sequence.
  344. They differ from group in that
  345. - only one task message is sent
  346. - the operation is sequential.
  347. For example using ``map``:
  348. .. code-block:: python
  349. >>> from proj.tasks import add
  350. >>> ~xsum.map([range(10), range(100)])
  351. [45, 4950]
  352. is the same as having a task doing:
  353. .. code-block:: python
  354. @celery.task()
  355. def temp():
  356. return [xsum(range(10)), xsum(range(100))]
  357. and using ``starmap``::
  358. >>> ~add.starmap(zip(range(10), range(10)))
  359. [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
  360. is the same as having a task doing:
  361. .. code-block:: python
  362. @celery.task()
  363. def temp():
  364. return [add(i, i) for i in range(10)]
  365. Both ``map`` and ``starmap`` are subtasks, so they can be used as
  366. other subtasks and combined in groups etc., for example
  367. to apply the starmap after 10 seconds::
  368. >>> add.starmap(zip(range(10), range(10))).apply_async(countdown=10)
  369. .. _chunking:
  370. Chunking
  371. ========
  372. -- Chunking lets you divide a iterable of work into pieces,
  373. so that if you have one million objects, you can create
  374. 10 tasks with hundred thousand objects each.
  375. Some may worry that chunking your tasks results in a degradation
  376. of parallelism, but this is rarely true for a busy cluster
  377. and in practice since you are avoiding the overhead of messaging
  378. it may considerably increase performance.
  379. To create a chunks subtask you can use :meth:`@Task.chunks`:
  380. .. code-block:: python
  381. >>> add.chunks(zip(range(100), range(100)), 10)
  382. As with :class:`~celery.group` the act of **calling**
  383. the chunks will apply the tasks in the current process:
  384. .. code-block:: python
  385. >>> from proj.tasks import add
  386. >>> res = add.chunks(zip(range(100), range(100)), 10)()
  387. >>> res.get()
  388. [[0, 2, 4, 6, 8, 10, 12, 14, 16, 18],
  389. [20, 22, 24, 26, 28, 30, 32, 34, 36, 38],
  390. [40, 42, 44, 46, 48, 50, 52, 54, 56, 58],
  391. [60, 62, 64, 66, 68, 70, 72, 74, 76, 78],
  392. [80, 82, 84, 86, 88, 90, 92, 94, 96, 98],
  393. [100, 102, 104, 106, 108, 110, 112, 114, 116, 118],
  394. [120, 122, 124, 126, 128, 130, 132, 134, 136, 138],
  395. [140, 142, 144, 146, 148, 150, 152, 154, 156, 158],
  396. [160, 162, 164, 166, 168, 170, 172, 174, 176, 178],
  397. [180, 182, 184, 186, 188, 190, 192, 194, 196, 198]]
  398. while calling ``.apply_async`` will create a dedicated
  399. task so that the individual tasks are applied in a worker
  400. instead::
  401. >>> add.chunks(zip(range(100), range(100), 10)).apply_async()
  402. You can also convert chunks to a group::
  403. >>> group = add.chunks(zip(range(100), range(100), 10)).group()
  404. and with the group skew the countdown of each task by increments
  405. of one::
  406. >>> group.skew(start=1, stop=10)()
  407. which means that the first task will have a countdown of 1, the second
  408. a countdown of 2 and so on.