workers.rst 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. ===============
  2. Workers Guide
  3. ===============
  4. Starting the worker
  5. ===================
  6. Starting celeryd in the foreground::
  7. $ celeryd --loglevel=INFO
  8. You probably want to use a daemonization tool to start and stop
  9. ``celeryd`` in the background, see :doc:`../cookbook/daemonizing` for help using
  10. some of the most popular solutions.
  11. For a full list of available command line options see :mod:`~celery.bin.celeryd`.
  12. You can also start multiple celeryd's on the same machine, but if you do so
  13. be sure to give a unique name to each individual worker by specifying the
  14. ``-hostname`` argument::
  15. $ celeryd --loglevel=INFO --concurrency=10 -n worker1.example.com
  16. $ celeryd --loglevel=INFO --concurrency=10 -n worker2.example.com
  17. $ celeryd --loglevel=INFO --concurrency=10 -n worker3.example.com
  18. Stopping the worker
  19. ===================
  20. Shutdown should be accomplished using the ``TERM`` signal (although ``INT``
  21. also works).
  22. When shutdown is initiated the worker will finish any tasks it's currently
  23. executing before it terminates, so if these tasks are important you should
  24. wait for it to finish before doing anything drastic (like sending the ``KILL``
  25. signal).
  26. If the worker won't shutdown after considerate time, you probably have hanging
  27. tasks, in this case it's safe to use the ``KILL`` signal but be aware that
  28. currently executing tasks will be lost (unless the tasks have the
  29. :attr:`~celery.task.base.Task.acks_late` option set).
  30. Also, since the ``KILL`` signal can't be catched by processes the worker will
  31. not be able to reap its children, so make sure you do it manually. This
  32. command usually does the trick::
  33. $ ps auxww | grep celeryd | awk '{print $2}' | xargs kill -KILL
  34. Restarting the worker
  35. =====================
  36. Other than stopping then starting the worker to restart, you can also
  37. restart the worker using the ``HUP`` signal::
  38. $ kill -HUP $pid
  39. The worker will then replace itself using the same arguments as it was
  40. started with.
  41. Concurrency
  42. ===========
  43. Multiprocessing is used to perform concurrent execution of tasks. The number
  44. of worker processes can be changed using the ``--concurrency`` argument, and
  45. defaults to the number of CPUs in the system.
  46. More worker processes are usually better, but there's a cut-off point where
  47. adding more processes affects performance in negative ways.
  48. There is even some evidence to support that having multiple celeryd's running,
  49. may perform better than having a single worker. For example 3 celeryd's with
  50. 10 worker processes each, but you need to experiment to find the values that
  51. works best for you, as this varies based on application, work load, task
  52. runtimes and other factors.
  53. Time limits
  54. ===========
  55. A single task can potentially run forever, if you have lots of tasks
  56. waiting for some event that will never happen you will block the worker
  57. from processing new tasks indefinitely. The best way to defend against
  58. this scenario happening is enabling time limits.
  59. The time limit (``--time-limit``) is the maximum number of seconds a task
  60. may run before the process executing it is terminated and replaced by a
  61. new process. You can also enable a soft time limit (``--soft-time-limit``),
  62. this raises an exception that the task can catch to clean up before the hard
  63. time limit kills it:
  64. .. code-block:: python
  65. from celery.decorators import task
  66. from celery.exceptions import SoftTimeLimitExceeded
  67. @task()
  68. def mytask():
  69. try:
  70. do_work()
  71. except SoftTimeLimitExceeded:
  72. clean_up_in_a_hurry()
  73. Time limits can also be set using the ``CELERYD_TASK_TIME_LIMIT`` /
  74. ``CELERYD_SOFT_TASK_TIME_LIMIT`` settings.
  75. **NOTE** Time limits does not currently work on Windows.
  76. Max tasks per child setting
  77. ===========================
  78. With this option you can configure the maximum number of tasks
  79. a worker can execute before it's replaced by a new process.
  80. This is useful if you have memory leaks you have no control over,
  81. for example closed source C extensions.
  82. The option can be set using the ``--maxtasksperchild`` argument
  83. to ``celeryd`` or using the ``CELERYD_MAX_TASKS_PER_CHILD`` setting.
  84. Remote control
  85. ==============
  86. Workers have the ability to be remote controlled using a broadcast message
  87. queue. The commands can be directed to all, or a specific list of workers.
  88. Commands can also have replies, the client can then wait for and collect
  89. those replies, but since there's no central authority to know how many
  90. workers are available in the cluster, there is also no way to estimate
  91. how many workers may send a reply, therefore the client has a configurable
  92. timeout - the deadline in seconds for replies to arrive in. This timeout
  93. defaults to one second. If the worker didn't reply within the deadline,
  94. it doesn't necessarily mean the worker didn't reply, or worse is dead, but
  95. may just be caused by network latency or the worker being slow at processing
  96. commands, so adjust the timeout accordingly.
  97. In addition to timeouts, the client can specify the maximum number
  98. of replies to wait for. If a destination is specified this limit is set
  99. to the number of destinations.
  100. The :func:`~celery.task.control.broadcast` function.
  101. ----------------------------------------------------
  102. This is the client function used to send commands to the workers.
  103. Some remote control commands also have higher-level interfaces using
  104. :func:`~celery.task.control.broadcast` in the background, like
  105. :func:`~celery.task.control.rate_limit` and :func:`~celery.task.control.ping`.
  106. Sending the ``rate_limit`` command and keyword arguments::
  107. >>> from celery.task.control import broadcast
  108. >>> broadcast("rate_limit", arguments={"task_name": "myapp.mytask",
  109. ... "rate_limit": "200/m"})
  110. This will send the command asynchronously, without waiting for a reply.
  111. To request a reply you have to use the ``reply`` argument::
  112. >>> broadcast("rate_limit", {"task_name": "myapp.mytask",
  113. ... "rate_limit": "200/m"}, reply=True)
  114. [{'worker1.example.com': 'New rate limit set successfully'},
  115. {'worker2.example.com': 'New rate limit set successfully'},
  116. {'worker3.example.com': 'New rate limit set successfully'}]
  117. Using the ``destination`` argument you can specify a list of workers
  118. to receive the command::
  119. >>> broadcast
  120. >>> broadcast("rate_limit", {"task_name": "myapp.mytask",
  121. ... "rate_limit": "200/m"}, reply=True,
  122. ... destination=["worker1.example.com"])
  123. [{'worker1.example.com': 'New rate limit set successfully'}]
  124. Of course, using the higher-level interface to set rate limits is much
  125. more convenient, but there are commands that can only be requested
  126. using :func:`~celery.task.control.broadcast`.
  127. Rate limits
  128. -----------
  129. Example changing the rate limit for the ``myapp.mytask`` task to accept
  130. 200 tasks a minute on all servers:
  131. >>> from celery.task.control import rate_limit
  132. >>> rate_limit("myapp.mytask", "200/m")
  133. Example changing the rate limit on a single host by specifying the
  134. destination hostname::
  135. >>> rate_limit("myapp.mytask", "200/m",
  136. ... destination=["worker1.example.com"])
  137. **NOTE** This won't affect workers with the ``CELERY_DISABLE_RATE_LIMITS``
  138. setting on. To re-enable rate limits you have to restart the worker.
  139. Remote shutdown
  140. ---------------
  141. This command will gracefully shut down the worker from remote.
  142. >>> broadcast("shutdown") # shutdown all workers
  143. >>> broadcast("shutdown, destination="worker1.example.com")
  144. Ping
  145. ----
  146. This command requests a ping from alive workers.
  147. The workers reply with the string 'pong', and that's just about it.
  148. It will use the default one second limit for replies unless you specify
  149. a custom ``timeout``.
  150. >>> from celery.task.control import ping
  151. >>> ping()
  152. [{'worker1.example.com': 'pong'},
  153. {'worker2.example.com': 'pong'},
  154. {'worker3.example.com': 'pong'}]
  155. :func:`~celery.task.control.ping` also supports the ``destination`` argument,
  156. so you can specify which workers to ping::
  157. >>> ping(['worker2.example.com', 'worker3.example.com'])
  158. [{'worker2.example.com': 'pong'},
  159. {'worker3.example.com': 'pong'}]
  160. Enable/disable events
  161. ---------------------
  162. You can enable/disable events by using the ``enable_events``,
  163. ``disable_events`` commands. This is useful to temporarily monitor
  164. a worker using celeryev/celerymon.
  165. >>> broadcast("enable_events")
  166. >>> broadcast("disable_events")
  167. Writing your own remote control commands
  168. ----------------------------------------
  169. Remote control commands are registered in the control panel and
  170. they take a single argument: the current
  171. :class:`~celery.worker.control.ControlDispatch` instance.
  172. From there you have access to the active
  173. :class:`celery.worker.listener.CarrotListener` if needed.
  174. Here's an example control command that restarts the broker connection:
  175. .. code-block:: python
  176. from celery.worker.control import Panel
  177. @Panel.register
  178. def reset_connection(panel):
  179. panel.logger.critical("Connection reset by remote control.")
  180. panel.listener.reset_connection()
  181. return {"ok": "connection reset"}
  182. These can be added to task modules, or you can keep them in their own module
  183. then import them using the ``CELERY_IMPORTS`` setting::
  184. CELERY_IMPORTS = ("myapp.worker.control", )
  185. Debugging
  186. =========
  187. Dump of registered tasks
  188. ------------------------
  189. You can get a list of tasks registered in the worker using the
  190. ``dump_tasks`` remote control command::
  191. >>> broadcast("dump_tasks", reply=True)
  192. [{'worker1.example.com': ['celery.delete_expired_task_meta',
  193. 'celery.execute_remote',
  194. 'celery.map_async',
  195. 'celery.ping',
  196. 'celery.task.http.HttpDispatchTask',
  197. 'tasks.add',
  198. 'tasks.sleeptask']}]
  199. Dump of scheduled (ETA) tasks
  200. -----------------------------
  201. You can get a list of tasks waiting to be scheduled by using
  202. the ``dump_schedule`` remote control command.
  203. >>> broadcast("dump_schedule", reply=True)
  204. [{'worker1.example.com':
  205. ['0. 2010-06-07 09:07:52 pri0 <TaskRequest: {
  206. name:"tasks.sleeptask",
  207. id:"1a7980ea-8b19-413e-91d2-0b74f3844c4d",
  208. args:"[1]", kwargs:"{}"}>',
  209. '1. 2010-06-07 09:07:53 pri0 <TaskRequest: {
  210. name:"tasks.sleeptask",
  211. id:"49661b9a-aa22-4120-94b7-9ee8031d219d",
  212. args:"[2]",
  213. kwargs:"{}"}>',
  214. The outputted fields are (in order): position, eta, priority, request.
  215. Note that these are tasks with an eta/countdown argument, not periodic tasks.
  216. Dump of reserved tasks
  217. ----------------------
  218. Reserved tasks are tasks that has been received by the broker and is waiting
  219. for immediate execution.
  220. You can get a list of these using the ``dump_reserved`` remote control command.
  221. >>> broadcast("dump_reserved", reply=True)
  222. [{'worker1.example.com':
  223. ['<TaskRequest: {name:"tasks.sleeptask",
  224. id:"32666e9b-809c-41fa-8e93-5ae0c80afbbf",
  225. args:"(8,)", kwargs:"{}"}>']}]