workers.rst 11 KB

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