canvas.rst 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945
  1. .. _guide-canvas:
  2. =============================
  3. Canvas: Designing Workflows
  4. =============================
  5. .. contents::
  6. :local:
  7. :depth: 2
  8. .. _canvas-subtasks:
  9. .. _canvas-signatures:
  10. Signatures
  11. ==========
  12. .. versionadded:: 2.0
  13. You just learned how to call a task using the tasks ``delay`` method
  14. in the :ref:`calling <guide-calling>` guide, and this is often all you need,
  15. but sometimes you may want to pass the signature of a task invocation to
  16. another process or as an argument to another function.
  17. A :func:`~celery.signature` wraps the arguments, keyword arguments, and execution options
  18. of a single task invocation in a way such that it can be passed to functions
  19. or even serialized and sent across the wire.
  20. Signatures are often nicknamed "subtasks" because they describe a task to be called
  21. within a task.
  22. - You can create a signature for the ``add`` task using its name like this::
  23. >>> from celery import signature
  24. >>> signature('tasks.add', args=(2, 2), countdown=10)
  25. tasks.add(2, 2)
  26. This task has a signature of arity 2 (two arguments): ``(2, 2)``,
  27. and sets the countdown execution option to 10.
  28. - or you can create one using the task's ``subtask`` method::
  29. >>> add.subtask((2, 2), countdown=10)
  30. tasks.add(2, 2)
  31. - There is also a shortcut using star arguments::
  32. >>> add.s(2, 2)
  33. tasks.add(2, 2)
  34. - Keyword arguments are also supported::
  35. >>> add.s(2, 2, debug=True)
  36. tasks.add(2, 2, debug=True)
  37. - From any signature instance you can inspect the different fields::
  38. >>> s = add.subtask((2, 2), {'debug': True}, countdown=10)
  39. >>> s.args
  40. (2, 2)
  41. >>> s.kwargs
  42. {'debug': True}
  43. >>> s.options
  44. {'countdown': 10}
  45. - It supports the "Calling API" which means it supports ``delay`` and
  46. ``apply_async`` or being called directly.
  47. Calling the signature will execute the task inline in the current process::
  48. >>> add(2, 2)
  49. 4
  50. >>> add.s(2, 2)()
  51. 4
  52. ``delay`` is our beloved shortcut to ``apply_async`` taking star-arguments::
  53. >>> result = add.delay(2, 2)
  54. >>> result.get()
  55. 4
  56. ``apply_async`` takes the same arguments as the :meth:`Task.apply_async <@Task.apply_async>` method::
  57. >>> add.apply_async(args, kwargs, **options)
  58. >>> add.subtask(args, kwargs, **options).apply_async()
  59. >>> add.apply_async((2, 2), countdown=1)
  60. >>> add.subtask((2, 2), countdown=1).apply_async()
  61. - You can't define options with :meth:`~@Task.s`, but a chaining
  62. ``set`` call takes care of that::
  63. >>> add.s(2, 2).set(countdown=1)
  64. proj.tasks.add(2, 2)
  65. Partials
  66. --------
  67. With a signature, you can execute the task in a worker::
  68. >>> add.s(2, 2).delay()
  69. >>> add.s(2, 2).apply_async(countdown=1)
  70. Or you can call it directly in the current process::
  71. >>> add.s(2, 2)()
  72. 4
  73. Specifying additional args, kwargs or options to ``apply_async``/``delay``
  74. creates partials:
  75. - Any arguments added will be prepended to the args in the signature::
  76. >>> partial = add.s(2) # incomplete signature
  77. >>> partial.delay(4) # 2 + 4
  78. >>> partial.apply_async((4,)) # same
  79. - Any keyword arguments added will be merged with the kwargs in the signature,
  80. with the new keyword arguments taking precedence::
  81. >>> s = add.s(2, 2)
  82. >>> s.delay(debug=True) # -> add(2, 2, debug=True)
  83. >>> s.apply_async(kwargs={'debug': True}) # same
  84. - Any options added will be merged with the options in the signature,
  85. with the new options taking precedence::
  86. >>> s = add.subtask((2, 2), countdown=10)
  87. >>> s.apply_async(countdown=1) # countdown is now 1
  88. You can also clone signatures to create derivates:
  89. >>> s = add.s(2)
  90. proj.tasks.add(2)
  91. >>> s.clone(args=(4,), kwargs={'debug': True})
  92. proj.tasks.add(4, 2, debug=True)
  93. Immutability
  94. ------------
  95. .. versionadded:: 3.0
  96. Partials are meant to be used with callbacks, any tasks linked or chord
  97. callbacks will be applied with the result of the parent task.
  98. Sometimes you want to specify a callback that does not take
  99. additional arguments, and in that case you can set the signature
  100. to be immutable::
  101. >>> add.apply_async((2, 2), link=reset_buffers.subtask(immutable=True))
  102. The ``.si()`` shortcut can also be used to create immutable signatures::
  103. >>> add.apply_async((2, 2), link=reset_buffers.si())
  104. Only the execution options can be set when a signature is immutable,
  105. so it's not possible to call the signature with partial args/kwargs.
  106. .. note::
  107. In this tutorial I sometimes use the prefix operator `~` to signatures.
  108. You probably shouldn't use it in your production code, but it's a handy shortcut
  109. when experimenting in the Python shell::
  110. >>> ~sig
  111. >>> # is the same as
  112. >>> sig.delay().get()
  113. .. _canvas-callbacks:
  114. Callbacks
  115. ---------
  116. .. versionadded:: 3.0
  117. Callbacks can be added to any task using the ``link`` argument
  118. to ``apply_async``::
  119. add.apply_async((2, 2), link=other_task.s())
  120. The callback will only be applied if the task exited successfully,
  121. and it will be applied with the return value of the parent task as argument.
  122. As I mentioned earlier, any arguments you add to a signature,
  123. will be prepended to the arguments specified by the signature itself!
  124. If you have the signature::
  125. >>> sig = add.s(10)
  126. then `sig.delay(result)` becomes::
  127. >>> add.apply_async(args=(result, 10))
  128. ...
  129. Now let's call our ``add`` task with a callback using partial
  130. arguments::
  131. >>> add.apply_async((2, 2), link=add.s(8))
  132. As expected this will first launch one task calculating :math:`2 + 2`, then
  133. another task calculating :math:`4 + 8`.
  134. The Primitives
  135. ==============
  136. .. versionadded:: 3.0
  137. .. topic:: Overview
  138. - ``group``
  139. The group primitive is a signature that takes a list of tasks that should
  140. be applied in parallel.
  141. - ``chain``
  142. The chain primitive lets us link together signatures so that one is called
  143. after the other, essentially forming a *chain* of callbacks.
  144. - ``chord``
  145. A chord is just like a group but with a callback. A chord consists
  146. of a header group and a body, where the body is a task that should execute
  147. after all of the tasks in the header are complete.
  148. - ``map``
  149. The map primitive works like the built-in ``map`` function, but creates
  150. a temporary task where a list of arguments is applied to the task.
  151. E.g. ``task.map([1, 2])`` results in a single task
  152. being called, applying the arguments in order to the task function so
  153. that the result is::
  154. res = [task(1), task(2)]
  155. - ``starmap``
  156. Works exactly like map except the arguments are applied as ``*args``.
  157. For example ``add.starmap([(2, 2), (4, 4)])`` results in a single
  158. task calling::
  159. res = [add(2, 2), add(4, 4)]
  160. - ``chunks``
  161. Chunking splits a long list of arguments into parts, e.g the operation::
  162. >>> items = zip(xrange(1000), xrange(1000)) # 1000 items
  163. >>> add.chunks(items, 10)
  164. will split the list of items into chunks of 10, resulting in 100
  165. tasks (each processing 10 items in sequence).
  166. The primitives are also signature objects themselves, so that they can be combined
  167. in any number of ways to compose complex workflows.
  168. Here's some examples:
  169. - Simple chain
  170. Here's a simple chain, the first task executes passing its return value
  171. to the next task in the chain, and so on.
  172. .. code-block:: python
  173. >>> from celery import chain
  174. # 2 + 2 + 4 + 8
  175. >>> res = chain(add.s(2, 2), add.s(4), add.s(8))()
  176. >>> res.get()
  177. 16
  178. This can also be written using pipes::
  179. >>> (add.s(2, 2) | add.s(4) | add.s(8))().get()
  180. 16
  181. - Immutable signatures
  182. Signatures can be partial so arguments can be
  183. added to the existing arguments, but you may not always want that,
  184. for example if you don't want the result of the previous task in a chain.
  185. In that case you can mark the signature as immutable, so that the arguments
  186. cannot be changed::
  187. >>> add.subtask((2, 2), immutable=True)
  188. There's also an ``.si`` shortcut for this::
  189. >>> add.si(2, 2)
  190. Now you can create a chain of independent tasks instead::
  191. >>> res = (add.si(2, 2) | add.si(4, 4) | add.s(8, 8))()
  192. >>> res.get()
  193. 16
  194. >>> res.parent.get()
  195. 8
  196. >>> res.parent.parent.get()
  197. 4
  198. - Simple group
  199. You can easily create a group of tasks to execute in parallel::
  200. >>> from celery import group
  201. >>> res = group(add.s(i, i) for i in xrange(10))()
  202. >>> res.get(timeout=1)
  203. [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
  204. - Simple chord
  205. The chord primitive enables us to add callback to be called when
  206. all of the tasks in a group have finished executing, which is often
  207. required for algorithms that aren't embarrassingly parallel::
  208. >>> from celery import chord
  209. >>> res = chord((add.s(i, i) for i in xrange(10)), xsum.s())()
  210. >>> res.get()
  211. 90
  212. The above example creates 10 task that all start in parallel,
  213. and when all of them are complete the return values are combined
  214. into a list and sent to the ``xsum`` task.
  215. The body of a chord can also be immutable, so that the return value
  216. of the group is not passed on to the callback::
  217. >>> chord((import_contact.s(c) for c in contacts),
  218. ... notify_complete.si(import_id)).apply_async()
  219. Note the use of ``.si`` above which creates an immutable signature.
  220. - Blow your mind by combining
  221. Chains can be partial too::
  222. >>> c1 = (add.s(4) | mul.s(8))
  223. # (16 + 4) * 8
  224. >>> res = c1(16)
  225. >>> res.get()
  226. 160
  227. Which means that you can combine chains::
  228. # ((4 + 16) * 2 + 4) * 8
  229. >>> c2 = (add.s(4, 16) | mul.s(2) | (add.s(4) | mul.s(8)))
  230. >>> res = c2()
  231. >>> res.get()
  232. 352
  233. Chaining a group together with another task will automatically
  234. upgrade it to be a chord::
  235. >>> c3 = (group(add.s(i, i) for i in xrange(10)) | xsum.s())
  236. >>> res = c3()
  237. >>> res.get()
  238. 90
  239. Groups and chords accepts partial arguments too, so in a chain
  240. the return value of the previous task is forwarded to all tasks in the group::
  241. >>> new_user_workflow = (create_user.s() | group(
  242. ... import_contacts.s(),
  243. ... send_welcome_email.s()))
  244. ... new_user_workflow.delay(username='artv',
  245. ... first='Art',
  246. ... last='Vandelay',
  247. ... email='art@vandelay.com')
  248. If you don't want to forward arguments to the group then
  249. you can make the signatures in the group immutable::
  250. >>> res = (add.s(4, 4) | group(add.si(i, i) for i in xrange(10)))()
  251. >>> res.get()
  252. <GroupResult: de44df8c-821d-4c84-9a6a-44769c738f98 [
  253. bc01831b-9486-4e51-b046-480d7c9b78de,
  254. 2650a1b8-32bf-4771-a645-b0a35dcc791b,
  255. dcbee2a5-e92d-4b03-b6eb-7aec60fd30cf,
  256. 59f92e0a-23ea-41ce-9fad-8645a0e7759c,
  257. 26e1e707-eccf-4bf4-bbd8-1e1729c3cce3,
  258. 2d10a5f4-37f0-41b2-96ac-a973b1df024d,
  259. e13d3bdb-7ae3-4101-81a4-6f17ee21df2d,
  260. 104b2be0-7b75-44eb-ac8e-f9220bdfa140,
  261. c5c551a5-0386-4973-aa37-b65cbeb2624b,
  262. 83f72d71-4b71-428e-b604-6f16599a9f37]>
  263. >>> res.parent.get()
  264. 8
  265. .. _canvas-chain:
  266. Chains
  267. ------
  268. .. versionadded:: 3.0
  269. Tasks can be linked together, which in practice means adding
  270. a callback task::
  271. >>> res = add.apply_async((2, 2), link=mul.s(16))
  272. >>> res.get()
  273. 4
  274. The linked task will be applied with the result of its parent
  275. task as the first argument, which in the above case will result
  276. in ``mul(4, 16)`` since the result is 4.
  277. You can also add *error callbacks* using the ``link_error`` argument::
  278. >>> add.apply_async((2, 2), link_error=log_error.s())
  279. >>> add.subtask((2, 2), link_error=log_error.s())
  280. Since exceptions can only be serialized when pickle is used
  281. the error callbacks take the id of the parent task as argument instead:
  282. .. code-block:: python
  283. from __future__ import print_function
  284. import os
  285. from proj.celery import app
  286. @app.task
  287. def log_error(task_id):
  288. result = app.AsyncResult(task_id)
  289. result.get(propagate=False) # make sure result written.
  290. with open(os.path.join('/var/errors', task_id), 'a') as fh:
  291. print('--\n\n{0} {1} {2}'.format(
  292. task_id, result.result, result.traceback), file=fh)
  293. To make it even easier to link tasks together there is
  294. a special signature called :class:`~celery.chain` that lets
  295. you chain tasks together:
  296. .. code-block:: python
  297. >>> from celery import chain
  298. >>> from proj.tasks import add, mul
  299. # (4 + 4) * 8 * 10
  300. >>> res = chain(add.s(4, 4), mul.s(8), mul.s(10))
  301. proj.tasks.add(4, 4) | proj.tasks.mul(8) | proj.tasks.mul(10)
  302. Calling the chain will call the tasks in the current process
  303. and return the result of the last task in the chain::
  304. >>> res = chain(add.s(4, 4), mul.s(8), mul.s(10))()
  305. >>> res.get()
  306. 640
  307. It also sets ``parent`` attributes so that you can
  308. work your way up the chain to get intermediate results::
  309. >>> res.parent.get()
  310. 64
  311. >>> res.parent.parent.get()
  312. 8
  313. >>> res.parent.parent
  314. <AsyncResult: eeaad925-6778-4ad1-88c8-b2a63d017933>
  315. Chains can also be made using the ``|`` (pipe) operator::
  316. >>> (add.s(2, 2) | mul.s(8) | mul.s(10)).apply_async()
  317. .. note::
  318. It's not possible to synchronize on groups, so a group chained to another
  319. signature is automatically upgraded to a chord:
  320. .. code-block:: python
  321. # will actually be a chord when finally evaluated
  322. res = (group(add.s(i, i) for i in range(10)) | xsum.s()).delay()
  323. Trails
  324. ~~~~~~
  325. Tasks will keep track of what subtasks a task calls in the
  326. result backend (unless disabled using :attr:`Task.trail <~@Task.trail>`)
  327. and this can be accessed from the result instance::
  328. >>> res.children
  329. [<AsyncResult: 8c350acf-519d-4553-8a53-4ad3a5c5aeb4>]
  330. >>> res.children[0].get()
  331. 64
  332. The result instance also has a :meth:`~@AsyncResult.collect` method
  333. that treats the result as a graph, enabling you to iterate over
  334. the results::
  335. >>> list(res.collect())
  336. [(<AsyncResult: 7b720856-dc5f-4415-9134-5c89def5664e>, 4),
  337. (<AsyncResult: 8c350acf-519d-4553-8a53-4ad3a5c5aeb4>, 64)]
  338. By default :meth:`~@AsyncResult.collect` will raise an
  339. :exc:`~@IncompleteStream` exception if the graph is not fully
  340. formed (one of the tasks has not completed yet),
  341. but you can get an intermediate representation of the graph
  342. too::
  343. >>> for result, value in res.collect(intermediate=True)):
  344. ....
  345. Graphs
  346. ~~~~~~
  347. In addition you can work with the result graph as a
  348. :class:`~celery.datastructures.DependencyGraph`:
  349. .. code-block:: python
  350. >>> res = chain(add.s(4, 4), mul.s(8), mul.s(10))()
  351. >>> res.parent.parent.graph
  352. 285fa253-fcf8-42ef-8b95-0078897e83e6(1)
  353. 463afec2-5ed4-4036-b22d-ba067ec64f52(0)
  354. 872c3995-6fa0-46ca-98c2-5a19155afcf0(2)
  355. 285fa253-fcf8-42ef-8b95-0078897e83e6(1)
  356. 463afec2-5ed4-4036-b22d-ba067ec64f52(0)
  357. You can even convert these graphs to *dot* format::
  358. >>> with open('graph.dot', 'w') as fh:
  359. ... res.parent.parent.graph.to_dot(fh)
  360. and create images:
  361. .. code-block:: bash
  362. $ dot -Tpng graph.dot -o graph.png
  363. .. image:: ../images/result_graph.png
  364. .. _canvas-group:
  365. Groups
  366. ------
  367. .. versionadded:: 3.0
  368. A group can be used to execute several tasks in parallel.
  369. The :class:`~celery.group` function takes a list of signatures::
  370. >>> from celery import group
  371. >>> from proj.tasks import add
  372. >>> group(add.s(2, 2), add.s(4, 4))
  373. (proj.tasks.add(2, 2), proj.tasks.add(4, 4))
  374. If you **call** the group, the tasks will be applied
  375. one after one in the current process, and a :class:`~celery.result.GroupResult`
  376. instance is returned which can be used to keep track of the results,
  377. or tell how many tasks are ready and so on::
  378. >>> g = group(add.s(2, 2), add.s(4, 4))
  379. >>> res = g()
  380. >>> res.get()
  381. [4, 8]
  382. Group also supports iterators::
  383. >>> group(add.s(i, i) for i in xrange(100))()
  384. A group is a signature object, so it can be used in combination
  385. with other signatures.
  386. Group Results
  387. ~~~~~~~~~~~~~
  388. The group task returns a special result too,
  389. this result works just like normal task results, except
  390. that it works on the group as a whole::
  391. >>> from celery import group
  392. >>> from tasks import add
  393. >>> job = group([
  394. ... add.s(2, 2),
  395. ... add.s(4, 4),
  396. ... add.s(8, 8),
  397. ... add.s(16, 16),
  398. ... add.s(32, 32),
  399. ... ])
  400. >>> result = job.apply_async()
  401. >>> result.ready() # have all subtasks completed?
  402. True
  403. >>> result.successful() # were all subtasks successful?
  404. True
  405. >>> result.get()
  406. [4, 8, 16, 32, 64]
  407. The :class:`~celery.result.GroupResult` takes a list of
  408. :class:`~celery.result.AsyncResult` instances and operates on them as
  409. if it was a single task.
  410. It supports the following operations:
  411. * :meth:`~celery.result.GroupResult.successful`
  412. Return :const:`True` if all of the subtasks finished
  413. successfully (e.g. did not raise an exception).
  414. * :meth:`~celery.result.GroupResult.failed`
  415. Return :const:`True` if any of the subtasks failed.
  416. * :meth:`~celery.result.GroupResult.waiting`
  417. Return :const:`True` if any of the subtasks
  418. is not ready yet.
  419. * :meth:`~celery.result.GroupResult.ready`
  420. Return :const:`True` if all of the subtasks
  421. are ready.
  422. * :meth:`~celery.result.GroupResult.completed_count`
  423. Return the number of completed subtasks.
  424. * :meth:`~celery.result.GroupResult.revoke`
  425. Revoke all of the subtasks.
  426. * :meth:`~celery.result.GroupResult.join`
  427. Gather the results for all of the subtasks
  428. and return a list with them ordered by the order of which they
  429. were called.
  430. .. _canvas-chord:
  431. Chords
  432. ------
  433. .. versionadded:: 2.3
  434. .. note::
  435. Tasks used within a chord must *not* ignore their results. If the result
  436. backend is disabled for *any* task (header or body) in your chord you
  437. should read ":ref:`chord-important-notes`".
  438. A chord is a task that only executes after all of the tasks in a group have
  439. finished executing.
  440. Let's calculate the sum of the expression
  441. :math:`1 + 1 + 2 + 2 + 3 + 3 ... n + n` up to a hundred digits.
  442. First you need two tasks, :func:`add` and :func:`tsum` (:func:`sum` is
  443. already a standard function):
  444. .. code-block:: python
  445. @app.task
  446. def add(x, y):
  447. return x + y
  448. @app.task
  449. def tsum(numbers):
  450. return sum(numbers)
  451. Now you can use a chord to calculate each addition step in parallel, and then
  452. get the sum of the resulting numbers::
  453. >>> from celery import chord
  454. >>> from tasks import add, tsum
  455. >>> chord(add.s(i, i)
  456. ... for i in xrange(100))(tsum.s()).get()
  457. 9900
  458. This is obviously a very contrived example, the overhead of messaging and
  459. synchronization makes this a lot slower than its Python counterpart::
  460. sum(i + i for i in xrange(100))
  461. The synchronization step is costly, so you should avoid using chords as much
  462. as possible. Still, the chord is a powerful primitive to have in your toolbox
  463. as synchronization is a required step for many parallel algorithms.
  464. Let's break the chord expression down:
  465. .. code-block:: python
  466. >>> callback = tsum.s()
  467. >>> header = [add.s(i, i) for i in range(100)]
  468. >>> result = chord(header)(callback)
  469. >>> result.get()
  470. 9900
  471. Remember, the callback can only be executed after all of the tasks in the
  472. header have returned. Each step in the header is executed as a task, in
  473. parallel, possibly on different nodes. The callback is then applied with
  474. the return value of each task in the header. The task id returned by
  475. :meth:`chord` is the id of the callback, so you can wait for it to complete
  476. and get the final return value (but remember to :ref:`never have a task wait
  477. for other tasks <task-synchronous-subtasks>`)
  478. .. _chord-errors:
  479. Error handling
  480. ~~~~~~~~~~~~~~
  481. So what happens if one of the tasks raises an exception?
  482. This was not documented for some time and before version 3.1
  483. the exception value will be forwarded to the chord callback.
  484. From 3.1 errors will propagate to the callback, so the callback will not be executed
  485. instead the callback changes to failure state, and the error is set
  486. to the :exc:`~@ChordError` exception:
  487. .. code-block:: python
  488. >>> c = chord([add.s(4, 4), raising_task.s(), add.s(8, 8)])
  489. >>> result = c()
  490. >>> result.get()
  491. Traceback (most recent call last):
  492. File "<stdin>", line 1, in <module>
  493. File "*/celery/result.py", line 120, in get
  494. interval=interval)
  495. File "*/celery/backends/amqp.py", line 150, in wait_for
  496. raise meta['result']
  497. celery.exceptions.ChordError: Dependency 97de6f3f-ea67-4517-a21c-d867c61fcb47
  498. raised ValueError('something something',)
  499. If you're running 3.0.14 or later you can enable the new behavior via
  500. the :setting:`CELERY_CHORD_PROPAGATES` setting::
  501. CELERY_CHORD_PROPAGATES = True
  502. While the traceback may be different depending on which result backend is
  503. being used, you can see the error description includes the id of the task that failed
  504. and a string representation of the original exception. You can also
  505. find the original traceback in ``result.traceback``.
  506. Note that the rest of the tasks will still execute, so the third task
  507. (``add.s(8, 8)``) is still executed even though the middle task failed.
  508. Also the :exc:`~@ChordError` only shows the task that failed
  509. first (in time): it does not respect the ordering of the header group.
  510. .. _chord-important-notes:
  511. Important Notes
  512. ~~~~~~~~~~~~~~~
  513. Tasks used within a chord must *not* ignore their results. In practice this
  514. means that you must enable a :const:`CELERY_RESULT_BACKEND` in order to use
  515. chords. Additionally, if :const:`CELERY_IGNORE_RESULT` is set to :const:`True`
  516. in your configuration, be sure that the individual tasks to be used within
  517. the chord are defined with :const:`ignore_result=False`. This applies to both
  518. Task subclasses and decorated tasks.
  519. Example Task subclass:
  520. .. code-block:: python
  521. class MyTask(Task):
  522. abstract = True
  523. ignore_result = False
  524. Example decorated task:
  525. .. code-block:: python
  526. @app.task(ignore_result=False)
  527. def another_task(project):
  528. do_something()
  529. By default the synchronization step is implemented by having a recurring task
  530. poll the completion of the group every second, calling the signature when
  531. ready.
  532. Example implementation:
  533. .. code-block:: python
  534. from celery import maybe_signature
  535. @app.task(bind=True)
  536. def unlock_chord(self, group, callback, interval=1, max_retries=None):
  537. if group.ready():
  538. return maybe_signature(callback).delay(group.join())
  539. raise self.retry(countdown=interval, max_retries=max_retries)
  540. This is used by all result backends except Redis and Memcached, which
  541. increment a counter after each task in the header, then applying the callback
  542. when the counter exceeds the number of tasks in the set. *Note:* chords do not
  543. properly work with Redis before version 2.2; you will need to upgrade to at
  544. least 2.2 to use them.
  545. The Redis and Memcached approach is a much better solution, but not easily
  546. implemented in other backends (suggestions welcome!).
  547. .. note::
  548. If you are using chords with the Redis result backend and also overriding
  549. the :meth:`Task.after_return` method, you need to make sure to call the
  550. super method or else the chord callback will not be applied.
  551. .. code-block:: python
  552. def after_return(self, *args, **kwargs):
  553. do_something()
  554. super(MyTask, self).after_return(*args, **kwargs)
  555. .. _canvas-map:
  556. Map & Starmap
  557. -------------
  558. :class:`~celery.map` and :class:`~celery.starmap` are built-in tasks
  559. that calls the task for every element in a sequence.
  560. They differ from group in that
  561. - only one task message is sent
  562. - the operation is sequential.
  563. For example using ``map``:
  564. .. code-block:: python
  565. >>> from proj.tasks import add
  566. >>> ~xsum.map([range(10), range(100)])
  567. [45, 4950]
  568. is the same as having a task doing:
  569. .. code-block:: python
  570. @app.task
  571. def temp():
  572. return [xsum(range(10)), xsum(range(100))]
  573. and using ``starmap``::
  574. >>> ~add.starmap(zip(range(10), range(10)))
  575. [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
  576. is the same as having a task doing:
  577. .. code-block:: python
  578. @app.task
  579. def temp():
  580. return [add(i, i) for i in range(10)]
  581. Both ``map`` and ``starmap`` are signature objects, so they can be used as
  582. other signatures and combined in groups etc., for example
  583. to call the starmap after 10 seconds::
  584. >>> add.starmap(zip(range(10), range(10))).apply_async(countdown=10)
  585. .. _canvas-chunks:
  586. Chunks
  587. ------
  588. Chunking lets you divide an iterable of work into pieces, so that if
  589. you have one million objects, you can create 10 tasks with hundred
  590. thousand objects each.
  591. Some may worry that chunking your tasks results in a degradation
  592. of parallelism, but this is rarely true for a busy cluster
  593. and in practice since you are avoiding the overhead of messaging
  594. it may considerably increase performance.
  595. To create a chunks signature you can use :meth:`@Task.chunks`:
  596. .. code-block:: python
  597. >>> add.chunks(zip(range(100), range(100)), 10)
  598. As with :class:`~celery.group` the act of sending the messages for
  599. the chunks will happen in the current process when called:
  600. .. code-block:: python
  601. >>> from proj.tasks import add
  602. >>> res = add.chunks(zip(range(100), range(100)), 10)()
  603. >>> res.get()
  604. [[0, 2, 4, 6, 8, 10, 12, 14, 16, 18],
  605. [20, 22, 24, 26, 28, 30, 32, 34, 36, 38],
  606. [40, 42, 44, 46, 48, 50, 52, 54, 56, 58],
  607. [60, 62, 64, 66, 68, 70, 72, 74, 76, 78],
  608. [80, 82, 84, 86, 88, 90, 92, 94, 96, 98],
  609. [100, 102, 104, 106, 108, 110, 112, 114, 116, 118],
  610. [120, 122, 124, 126, 128, 130, 132, 134, 136, 138],
  611. [140, 142, 144, 146, 148, 150, 152, 154, 156, 158],
  612. [160, 162, 164, 166, 168, 170, 172, 174, 176, 178],
  613. [180, 182, 184, 186, 188, 190, 192, 194, 196, 198]]
  614. while calling ``.apply_async`` will create a dedicated
  615. task so that the individual tasks are applied in a worker
  616. instead::
  617. >>> add.chunks(zip(range(100), range(100)), 10).apply_async()
  618. You can also convert chunks to a group::
  619. >>> group = add.chunks(zip(range(100), range(100)), 10).group()
  620. and with the group skew the countdown of each task by increments
  621. of one::
  622. >>> group.skew(start=1, stop=10)()
  623. which means that the first task will have a countdown of 1, the second
  624. a countdown of 2 and so on.