workers.rst 12 KB

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