workers.rst 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  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 do::
  17. $ celeryd --help
  18. You can also start multiple workers on the same machine. If you do so
  19. be sure to give a unique name to each individual worker by specifying a
  20. host name with the :option:`--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 all currently executing
  29. tasks before it actually 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 as processes can't override the :sig:`KILL` signal, the worker will
  38. not be able to reap its children, so make sure to do so 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. By default multiprocessing is used to perform concurrent execution of tasks,
  53. but you can also use :ref:`Eventlet <concurrency-eventlet>`. The number
  54. of worker processes/threads can be changed using the :option:`--concurrency`
  55. argument and defaults to the number of CPUs available on the machine.
  56. .. admonition:: Number of processes (multiprocessing)
  57. More worker processes are usually better, but there's a cut-off point where
  58. adding more processes affects performance in negative ways.
  59. There is even some evidence to support that having multiple celeryd's running,
  60. may perform better than having a single worker. For example 3 celeryd's with
  61. 10 worker processes each. You need to experiment to find the numbers that
  62. works best for you, as this varies based on application, work load, task
  63. run times and other factors.
  64. .. _worker-persistent-revokes:
  65. Persistent revokes
  66. ==================
  67. Revoking tasks works by sending a broadcast message to all the workers,
  68. the workers then keep a list of revoked tasks in memory.
  69. If you want tasks to remain revoked after worker restart you need to
  70. specify a file for these to be stored in, either by using the `--statedb`
  71. argument to :mod:`~celery.bin.celeryd` or the :setting:`CELERYD_STATE_DB`
  72. setting. See :setting:`CELERYD_STATE_DB` for more information.
  73. .. _worker-time-limits:
  74. Time limits
  75. ===========
  76. .. versionadded:: 2.0
  77. A single task can potentially run forever, if you have lots of tasks
  78. waiting for some event that will never happen you will block the worker
  79. from processing new tasks indefinitely. The best way to defend against
  80. this scenario happening is enabling time limits.
  81. The time limit (`--time-limit`) is the maximum number of seconds a task
  82. may run before the process executing it is terminated and replaced by a
  83. new process. You can also enable a soft time limit (`--soft-time-limit`),
  84. this raises an exception the task can catch to clean up before the hard
  85. time limit kills it:
  86. .. code-block:: python
  87. from celery.task import task
  88. from celery.exceptions import SoftTimeLimitExceeded
  89. @task()
  90. def mytask():
  91. try:
  92. do_work()
  93. except SoftTimeLimitExceeded:
  94. clean_up_in_a_hurry()
  95. Time limits can also be set using the :setting:`CELERYD_TASK_TIME_LIMIT` /
  96. :setting:`CELERYD_SOFT_TASK_TIME_LIMIT` settings.
  97. .. note::
  98. Time limits do not currently work on Windows.
  99. .. _worker-maxtasksperchild:
  100. Max tasks per child setting
  101. ===========================
  102. .. versionadded: 2.0
  103. With this option you can configure the maximum number of tasks
  104. a worker can execute before it's replaced by a new process.
  105. This is useful if you have memory leaks you have no control over
  106. for example from closed source C extensions.
  107. The option can be set using the `--maxtasksperchild` argument
  108. to `celeryd` or using the :setting:`CELERYD_MAX_TASKS_PER_CHILD` setting.
  109. .. _worker-remote-control:
  110. Remote control
  111. ==============
  112. .. versionadded:: 2.0
  113. Workers have the ability to be remote controlled using a high-priority
  114. broadcast message queue. The commands can be directed to all, or a specific
  115. list of workers.
  116. Commands can also have replies. The client can then wait for and collect
  117. those replies. Since there's no central authority to know how many
  118. workers are available in the cluster, there is also no way to estimate
  119. how many workers may send a reply, so the client has a configurable
  120. timeout — the deadline in seconds for replies to arrive in. This timeout
  121. defaults to one second. If the worker doesn't reply within the deadline
  122. it doesn't necessarily mean the worker didn't reply, or worse is dead, but
  123. may simply be caused by network latency or the worker being slow at processing
  124. commands, so adjust the timeout accordingly.
  125. In addition to timeouts, the client can specify the maximum number
  126. of replies to wait for. If a destination is specified, this limit is set
  127. to the number of destination hosts.
  128. .. seealso::
  129. The :program:`celeryctl` program is used to execute remote control
  130. commands from the command line. It supports all of the commands
  131. listed below. See :ref:`monitoring-celeryctl` for more information.
  132. .. _worker-broadcast-fun:
  133. The :func:`~celery.task.control.broadcast` function.
  134. ----------------------------------------------------
  135. This is the client function used to send commands to the workers.
  136. Some remote control commands also have higher-level interfaces using
  137. :func:`~celery.task.control.broadcast` in the background, like
  138. :func:`~celery.task.control.rate_limit` and :func:`~celery.task.control.ping`.
  139. Sending the :control:`rate_limit` command and keyword arguments::
  140. >>> from celery.task.control import broadcast
  141. >>> broadcast("rate_limit", arguments={"task_name": "myapp.mytask",
  142. ... "rate_limit": "200/m"})
  143. This will send the command asynchronously, without waiting for a reply.
  144. To request a reply you have to use the `reply` argument::
  145. >>> broadcast("rate_limit", {"task_name": "myapp.mytask",
  146. ... "rate_limit": "200/m"}, reply=True)
  147. [{'worker1.example.com': 'New rate limit set successfully'},
  148. {'worker2.example.com': 'New rate limit set successfully'},
  149. {'worker3.example.com': 'New rate limit set successfully'}]
  150. Using the `destination` argument you can specify a list of workers
  151. to receive the command::
  152. >>> broadcast
  153. >>> broadcast("rate_limit", {"task_name": "myapp.mytask",
  154. ... "rate_limit": "200/m"}, reply=True,
  155. ... destination=["worker1.example.com"])
  156. [{'worker1.example.com': 'New rate limit set successfully'}]
  157. Of course, using the higher-level interface to set rate limits is much
  158. more convenient, but there are commands that can only be requested
  159. using :func:`~celery.task.control.broadcast`.
  160. .. _worker-rate-limits:
  161. .. control:: rate_limit
  162. Rate limits
  163. -----------
  164. Example changing the rate limit for the `myapp.mytask` task to accept
  165. 200 tasks a minute on all servers::
  166. >>> from celery.task.control import rate_limit
  167. >>> rate_limit("myapp.mytask", "200/m")
  168. Example changing the rate limit on a single host by specifying the
  169. destination hostname::
  170. >>> rate_limit("myapp.mytask", "200/m",
  171. ... destination=["worker1.example.com"])
  172. .. warning::
  173. This won't affect workers with the
  174. :setting:`CELERY_DISABLE_RATE_LIMITS` setting on. To re-enable rate limits
  175. then you have to restart the worker.
  176. .. control:: revoke
  177. Revoking tasks
  178. --------------
  179. All worker nodes keeps a memory of revoked task ids, either in-memory or
  180. persistent on disk (see :ref:`worker-persistent-revokes`).
  181. When a worker receives a revoke request it will skip executing
  182. the task, but it won't terminate an already executing task unless
  183. the `terminate` option is set.
  184. If `terminate` is set the worker child process processing the task
  185. will be terminated. The default signal sent is `TERM`, but you can
  186. specify this using the `signal` argument. Signal can be the uppercase name
  187. of any signal defined in the :mod:`signal` module in the Python Standard
  188. Library.
  189. Terminating a task also revokes it.
  190. **Example**
  191. ::
  192. >>> from celery.task.control import revoke
  193. >>> revoke("d9078da5-9915-40a0-bfa1-392c7bde42ed")
  194. >>> revoke("d9078da5-9915-40a0-bfa1-392c7bde42ed",
  195. ... terminate=True)
  196. >>> revoke("d9078da5-9915-40a0-bfa1-392c7bde42ed",
  197. ... terminate=True, signal="SIGKILL")
  198. .. control:: shutdown
  199. Remote shutdown
  200. ---------------
  201. This command will gracefully shut down the worker remotely::
  202. >>> broadcast("shutdown") # shutdown all workers
  203. >>> broadcast("shutdown, destination="worker1.example.com")
  204. .. control:: ping
  205. Ping
  206. ----
  207. This command requests a ping from alive workers.
  208. The workers reply with the string 'pong', and that's just about it.
  209. It will use the default one second timeout for replies unless you specify
  210. a custom timeout::
  211. >>> from celery.task.control import ping
  212. >>> ping(timeout=0.5)
  213. [{'worker1.example.com': 'pong'},
  214. {'worker2.example.com': 'pong'},
  215. {'worker3.example.com': 'pong'}]
  216. :func:`~celery.task.control.ping` also supports the `destination` argument,
  217. so you can specify which workers to ping::
  218. >>> ping(['worker2.example.com', 'worker3.example.com'])
  219. [{'worker2.example.com': 'pong'},
  220. {'worker3.example.com': 'pong'}]
  221. .. _worker-enable-events:
  222. .. control:: enable_events
  223. .. control:: disable_events
  224. Enable/disable events
  225. ---------------------
  226. You can enable/disable events by using the `enable_events`,
  227. `disable_events` commands. This is useful to temporarily monitor
  228. a worker using :program:`celeryev`/:program:`celerymon`.
  229. .. code-block:: python
  230. >>> broadcast("enable_events")
  231. >>> broadcast("disable_events")
  232. .. _worker-custom-control-commands:
  233. Writing your own remote control commands
  234. ----------------------------------------
  235. Remote control commands are registered in the control panel and
  236. they take a single argument: the current
  237. :class:`~celery.worker.control.ControlDispatch` instance.
  238. From there you have access to the active
  239. :class:`~celery.worker.consumer.Consumer` if needed.
  240. Here's an example control command that restarts the broker connection:
  241. .. code-block:: python
  242. from celery.worker.control import Panel
  243. @Panel.register
  244. def reset_connection(panel):
  245. panel.logger.critical("Connection reset by remote control.")
  246. panel.consumer.reset_connection()
  247. return {"ok": "connection reset"}
  248. These can be added to task modules, or you can keep them in their own module
  249. then import them using the :setting:`CELERY_IMPORTS` setting::
  250. CELERY_IMPORTS = ("myapp.worker.control", )
  251. .. _worker-inspect:
  252. Inspecting workers
  253. ==================
  254. :class:`celery.task.control.inspect` lets you inspect running workers. It
  255. uses remote control commands under the hood.
  256. .. code-block:: python
  257. >>> from celery.task.control import inspect
  258. # Inspect all nodes.
  259. >>> i = inspect()
  260. # Specify multiple nodes to inspect.
  261. >>> i = inspect(["worker1.example.com", "worker2.example.com"])
  262. # Specify a single node to inspect.
  263. >>> i = inspect("worker1.example.com")
  264. .. _worker-inspect-registered-tasks:
  265. Dump of registered tasks
  266. ------------------------
  267. You can get a list of tasks registered in the worker using the
  268. :meth:`~celery.task.control.inspect.registered_tasks`::
  269. >>> i.registered_tasks()
  270. [{'worker1.example.com': ['celery.delete_expired_task_meta',
  271. 'celery.execute_remote',
  272. 'celery.map_async',
  273. 'celery.ping',
  274. 'celery.task.http.HttpDispatchTask',
  275. 'tasks.add',
  276. 'tasks.sleeptask']}]
  277. .. _worker-inspect-active-tasks:
  278. Dump of currently executing tasks
  279. ---------------------------------
  280. You can get a list of active tasks using
  281. :meth:`~celery.task.control.inspect.active`::
  282. >>> i.active()
  283. [{'worker1.example.com':
  284. [{"name": "tasks.sleeptask",
  285. "id": "32666e9b-809c-41fa-8e93-5ae0c80afbbf",
  286. "args": "(8,)",
  287. "kwargs": "{}"}]}]
  288. .. _worker-inspect-eta-schedule:
  289. Dump of scheduled (ETA) tasks
  290. -----------------------------
  291. You can get a list of tasks waiting to be scheduled by using
  292. :meth:`~celery.task.control.inspect.scheduled`::
  293. >>> i.scheduled()
  294. [{'worker1.example.com':
  295. [{"eta": "2010-06-07 09:07:52", "priority": 0,
  296. "request": {
  297. "name": "tasks.sleeptask",
  298. "id": "1a7980ea-8b19-413e-91d2-0b74f3844c4d",
  299. "args": "[1]",
  300. "kwargs": "{}"}},
  301. {"eta": "2010-06-07 09:07:53", "priority": 0,
  302. "request": {
  303. "name": "tasks.sleeptask",
  304. "id": "49661b9a-aa22-4120-94b7-9ee8031d219d",
  305. "args": "[2]",
  306. "kwargs": "{}"}}]}]
  307. Note that these are tasks with an eta/countdown argument, not periodic tasks.
  308. .. _worker-inspect-reserved:
  309. Dump of reserved tasks
  310. ----------------------
  311. Reserved tasks are tasks that has been received, but is still waiting to be
  312. executed.
  313. You can get a list of these using
  314. :meth:`~celery.task.control.inspect.reserved`::
  315. >>> i.reserved()
  316. [{'worker1.example.com':
  317. [{"name": "tasks.sleeptask",
  318. "id": "32666e9b-809c-41fa-8e93-5ae0c80afbbf",
  319. "args": "(8,)",
  320. "kwargs": "{}"}]}]