workers.rst 13 KB

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