workers.rst 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072
  1. .. _guide-workers:
  2. ===============
  3. Workers Guide
  4. ===============
  5. .. contents::
  6. :local:
  7. :depth: 1
  8. .. _worker-starting:
  9. Starting the worker
  10. ===================
  11. .. sidebar:: Daemonizing
  12. You probably want to use a daemonization tool to start
  13. in the background. See :ref:`daemonizing` for help
  14. detaching the worker using popular daemonization tools.
  15. You can start the worker in the foreground by executing the command:
  16. .. code-block:: console
  17. $ celery -A proj worker -l info
  18. For a full list of available command-line options see
  19. :mod:`~celery.bin.worker`, or simply do:
  20. .. code-block:: console
  21. $ celery worker --help
  22. You can also start multiple workers on the same machine. If you do so
  23. be sure to give a unique name to each individual worker by specifying a
  24. node name with the :option:`--hostname <celery worker --hostname>` argument:
  25. .. code-block:: console
  26. $ celery -A proj worker --loglevel=INFO --concurrency=10 -n worker1.%h
  27. $ celery -A proj worker --loglevel=INFO --concurrency=10 -n worker2.%h
  28. $ celery -A proj worker --loglevel=INFO --concurrency=10 -n worker3.%h
  29. The ``hostname`` argument can expand the following variables:
  30. - ``%h``: Hostname including domain name.
  31. - ``%n``: Hostname only.
  32. - ``%d``: Domain name only.
  33. E.g. if the current hostname is ``george.example.com`` then
  34. these will expand to:
  35. - ``worker1.%h`` -> ``worker1.george.example.com``
  36. - ``worker1.%n`` -> ``worker1.george``
  37. - ``worker1.%d`` -> ``worker1.example.com``
  38. .. admonition:: Note for :pypi:`supervisor` users.
  39. The ``%`` sign must be escaped by adding a second one: `%%h`.
  40. .. _worker-stopping:
  41. Stopping the worker
  42. ===================
  43. Shutdown should be accomplished using the :sig:`TERM` signal.
  44. When shutdown is initiated the worker will finish all currently executing
  45. tasks before it actually terminates, so if these tasks are important you should
  46. wait for it to finish before doing anything drastic (like sending the :sig:`KILL`
  47. signal).
  48. If the worker won't shutdown after considerate time, for example because
  49. of tasks stuck in an infinite-loop, you can use the :sig:`KILL` signal to
  50. force terminate the worker, but be aware that currently executing tasks will
  51. be lost (unless the tasks have the :attr:`~@Task.acks_late`
  52. option set).
  53. Also as processes can't override the :sig:`KILL` signal, the worker will
  54. not be able to reap its children, so make sure to do so manually. This
  55. command usually does the trick:
  56. .. code-block:: console
  57. $ ps auxww | grep 'celery worker' | awk '{print $2}' | xargs kill -9
  58. .. _worker-restarting:
  59. Restarting the worker
  60. =====================
  61. To restart the worker you should send the `TERM` signal and start a new
  62. instance. The easiest way to manage workers for development
  63. is by using `celery multi`:
  64. .. code-block:: console
  65. $ celery multi start 1 -A proj -l info -c4 --pidfile=/var/run/celery/%n.pid
  66. $ celery multi restart 1 --pidfile=/var/run/celery/%n.pid
  67. For production deployments you should be using init-scripts or other process
  68. supervision systems (see :ref:`daemonizing`).
  69. Other than stopping then starting the worker to restart, you can also
  70. restart the worker using the :sig:`HUP` signal, but note that the worker
  71. will be responsible for restarting itself so this is prone to problems and
  72. is not recommended in production:
  73. .. code-block:: console
  74. $ kill -HUP $pid
  75. .. note::
  76. Restarting by :sig:`HUP` only works if the worker is running
  77. in the background as a daemon (it does not have a controlling
  78. terminal).
  79. :sig:`HUP` is disabled on macOS because of a limitation on
  80. that platform.
  81. .. _worker-process-signals:
  82. Process Signals
  83. ===============
  84. The worker's main process overrides the following signals:
  85. +--------------+-------------------------------------------------+
  86. | :sig:`TERM` | Warm shutdown, wait for tasks to complete. |
  87. +--------------+-------------------------------------------------+
  88. | :sig:`QUIT` | Cold shutdown, terminate ASAP |
  89. +--------------+-------------------------------------------------+
  90. | :sig:`USR1` | Dump traceback for all active threads. |
  91. +--------------+-------------------------------------------------+
  92. | :sig:`USR2` | Remote debug, see :mod:`celery.contrib.rdb`. |
  93. +--------------+-------------------------------------------------+
  94. .. _worker-files:
  95. Variables in file paths
  96. =======================
  97. The file path arguments for :option:`--logfile <celery worker --logfile>`,
  98. :option:`--pidfile <celery worker --pidfile>` and
  99. :option:`--statedb <celery worker --statedb>` can contain variables that the
  100. worker will expand:
  101. Node name replacements
  102. ----------------------
  103. - ``%p``: Full node name.
  104. - ``%h``: Hostname including domain name.
  105. - ``%n``: Hostname only.
  106. - ``%d``: Domain name only.
  107. - ``%i``: Prefork pool process index or 0 if MainProcess.
  108. - ``%I``: Prefork pool process index with separator.
  109. E.g. if the current hostname is ``george@foo.example.com`` then
  110. these will expand to:
  111. - ``--logfile-%p.log`` -> :file:`george@foo.example.com.log`
  112. - ``--logfile=%h.log`` -> :file:`foo.example.com.log`
  113. - ``--logfile=%n.log`` -> :file:`george.log`
  114. - ``--logfile=%d`` -> :file:`example.com.log`
  115. .. _worker-files-process-index:
  116. Prefork pool process index
  117. --------------------------
  118. The prefork pool process index specifiers will expand into a different
  119. filename depending on the process that will eventually need to open the file.
  120. This can be used to specify one log file per child process.
  121. Note that the numbers will stay within the process limit even if processes
  122. exit or if ``maxtasksperchild``/time limits are used. I.e. the number
  123. is the *process index* not the process count or pid.
  124. * ``%i`` - Pool process index or 0 if MainProcess.
  125. Where ``-n worker1@example.com -c2 -f %n-%i.log`` will result in
  126. three log files:
  127. - :file:`worker1-0.log` (main process)
  128. - :file:`worker1-1.log` (pool process 1)
  129. - :file:`worker1-2.log` (pool process 2)
  130. * ``%I`` - Pool process index with separator.
  131. Where ``-n worker1@example.com -c2 -f %n%I.log`` will result in
  132. three log files:
  133. - :file:`worker1.log` (main process)
  134. - :file:`worker1-1.log` (pool process 1)
  135. - :file:`worker1-2.log` (pool process 2)
  136. .. _worker-concurrency:
  137. Concurrency
  138. ===========
  139. By default multiprocessing is used to perform concurrent execution of tasks,
  140. but you can also use :ref:`Eventlet <concurrency-eventlet>`. The number
  141. of worker processes/threads can be changed using the
  142. :option:`--concurrency <celery worker --concurrency>` argument and defaults
  143. to the number of CPUs available on the machine.
  144. .. admonition:: Number of processes (multiprocessing/prefork pool)
  145. More pool processes are usually better, but there's a cut-off point where
  146. adding more pool processes affects performance in negative ways.
  147. There is even some evidence to support that having multiple worker
  148. instances running, may perform better than having a single worker.
  149. For example 3 workers with 10 pool processes each. You need to experiment
  150. to find the numbers that works best for you, as this varies based on
  151. application, work load, task run times and other factors.
  152. .. _worker-remote-control:
  153. Remote control
  154. ==============
  155. .. versionadded:: 2.0
  156. .. sidebar:: The ``celery`` command
  157. The :program:`celery` program is used to execute remote control
  158. commands from the command-line. It supports all of the commands
  159. listed below. See :ref:`monitoring-control` for more information.
  160. :pool support: *prefork, eventlet, gevent*, blocking:*solo* (see note)
  161. :broker support: *amqp*
  162. Workers have the ability to be remote controlled using a high-priority
  163. broadcast message queue. The commands can be directed to all, or a specific
  164. list of workers.
  165. Commands can also have replies. The client can then wait for and collect
  166. those replies. Since there's no central authority to know how many
  167. workers are available in the cluster, there is also no way to estimate
  168. how many workers may send a reply, so the client has a configurable
  169. timeout — the deadline in seconds for replies to arrive in. This timeout
  170. defaults to one second. If the worker doesn't reply within the deadline
  171. it doesn't necessarily mean the worker didn't reply, or worse is dead, but
  172. may simply be caused by network latency or the worker being slow at processing
  173. commands, so adjust the timeout accordingly.
  174. In addition to timeouts, the client can specify the maximum number
  175. of replies to wait for. If a destination is specified, this limit is set
  176. to the number of destination hosts.
  177. .. note::
  178. The ``solo`` pool supports remote control commands,
  179. but any task executing will block any waiting control command,
  180. so it is of limited use if the worker is very busy. In that
  181. case you must increase the timeout waiting for replies in the client.
  182. .. _worker-broadcast-fun:
  183. The :meth:`~@control.broadcast` function.
  184. ----------------------------------------------------
  185. This is the client function used to send commands to the workers.
  186. Some remote control commands also have higher-level interfaces using
  187. :meth:`~@control.broadcast` in the background, like
  188. :meth:`~@control.rate_limit` and :meth:`~@control.ping`.
  189. Sending the :control:`rate_limit` command and keyword arguments:
  190. .. code-block:: pycon
  191. >>> app.control.broadcast('rate_limit',
  192. ... arguments={'task_name': 'myapp.mytask',
  193. ... 'rate_limit': '200/m'})
  194. This will send the command asynchronously, without waiting for a reply.
  195. To request a reply you have to use the `reply` argument:
  196. .. code-block:: pycon
  197. >>> app.control.broadcast('rate_limit', {
  198. ... 'task_name': 'myapp.mytask', 'rate_limit': '200/m'}, reply=True)
  199. [{'worker1.example.com': 'New rate limit set successfully'},
  200. {'worker2.example.com': 'New rate limit set successfully'},
  201. {'worker3.example.com': 'New rate limit set successfully'}]
  202. Using the `destination` argument you can specify a list of workers
  203. to receive the command:
  204. .. code-block:: pycon
  205. >>> app.control.broadcast('rate_limit', {
  206. ... 'task_name': 'myapp.mytask',
  207. ... 'rate_limit': '200/m'}, reply=True,
  208. ... destination=['worker1@example.com'])
  209. [{'worker1.example.com': 'New rate limit set successfully'}]
  210. Of course, using the higher-level interface to set rate limits is much
  211. more convenient, but there are commands that can only be requested
  212. using :meth:`~@control.broadcast`.
  213. Commands
  214. ========
  215. .. control:: revoke
  216. ``revoke``: Revoking tasks
  217. --------------------------
  218. :pool support: all, terminate only supported by prefork
  219. :broker support: *amqp*
  220. :command: :program:`celery -A proj control revoke <task_id>`
  221. All worker nodes keeps a memory of revoked task ids, either in-memory or
  222. persistent on disk (see :ref:`worker-persistent-revokes`).
  223. When a worker receives a revoke request it will skip executing
  224. the task, but it won't terminate an already executing task unless
  225. the `terminate` option is set.
  226. .. note::
  227. The terminate option is a last resort for administrators when
  228. a task is stuck. It's not for terminating the task,
  229. it's for terminating the process that is executing the task, and that
  230. process may have already started processing another task at the point
  231. when the signal is sent, so for this reason you must never call this
  232. programmatically.
  233. If `terminate` is set the worker child process processing the task
  234. will be terminated. The default signal sent is `TERM`, but you can
  235. specify this using the `signal` argument. Signal can be the uppercase name
  236. of any signal defined in the :mod:`signal` module in the Python Standard
  237. Library.
  238. Terminating a task also revokes it.
  239. **Example**
  240. .. code-block:: pycon
  241. >>> result.revoke()
  242. >>> AsyncResult(id).revoke()
  243. >>> app.control.revoke('d9078da5-9915-40a0-bfa1-392c7bde42ed')
  244. >>> app.control.revoke('d9078da5-9915-40a0-bfa1-392c7bde42ed',
  245. ... terminate=True)
  246. >>> app.control.revoke('d9078da5-9915-40a0-bfa1-392c7bde42ed',
  247. ... terminate=True, signal='SIGKILL')
  248. Revoking multiple tasks
  249. -----------------------
  250. .. versionadded:: 3.1
  251. The revoke method also accepts a list argument, where it will revoke
  252. several tasks at once.
  253. **Example**
  254. .. code-block:: pycon
  255. >>> app.control.revoke([
  256. ... '7993b0aa-1f0b-4780-9af0-c47c0858b3f2',
  257. ... 'f565793e-b041-4b2b-9ca4-dca22762a55d',
  258. ... 'd9d35e03-2997-42d0-a13e-64a66b88a618',
  259. ])
  260. The ``GroupResult.revoke`` method takes advantage of this since
  261. version 3.1.
  262. .. _worker-persistent-revokes:
  263. Persistent revokes
  264. ------------------
  265. Revoking tasks works by sending a broadcast message to all the workers,
  266. the workers then keep a list of revoked tasks in memory. When a worker starts
  267. up it will synchronize revoked tasks with other workers in the cluster.
  268. The list of revoked tasks is in-memory so if all workers restart the list
  269. of revoked ids will also vanish. If you want to preserve this list between
  270. restarts you need to specify a file for these to be stored in by using the `--statedb`
  271. argument to :program:`celery worker`:
  272. .. code-block:: console
  273. $ celery -A proj worker -l info --statedb=/var/run/celery/worker.state
  274. or if you use :program:`celery multi` you will want to create one file per
  275. worker instance so then you can use the `%n` format to expand the current node
  276. name:
  277. .. code-block:: console
  278. celery multi start 2 -l info --statedb=/var/run/celery/%n.state
  279. See also :ref:`worker-files`
  280. Note that remote control commands must be working for revokes to work.
  281. Remote control commands are only supported by the RabbitMQ (amqp) at this
  282. point.
  283. .. _worker-time-limits:
  284. Time Limits
  285. ===========
  286. .. versionadded:: 2.0
  287. :pool support: *prefork/gevent*
  288. .. sidebar:: Soft, or hard?
  289. The time limit is set in two values, `soft` and `hard`.
  290. The soft time limit allows the task to catch an exception
  291. to clean up before it is killed: the hard timeout is not catch-able
  292. and force terminates the task.
  293. A single task can potentially run forever, if you have lots of tasks
  294. waiting for some event that will never happen you will block the worker
  295. from processing new tasks indefinitely. The best way to defend against
  296. this scenario happening is enabling time limits.
  297. The time limit (`--time-limit`) is the maximum number of seconds a task
  298. may run before the process executing it is terminated and replaced by a
  299. new process. You can also enable a soft time limit (`--soft-time-limit`),
  300. this raises an exception the task can catch to clean up before the hard
  301. time limit kills it:
  302. .. code-block:: python
  303. from myapp import app
  304. from celery.exceptions import SoftTimeLimitExceeded
  305. @app.task
  306. def mytask():
  307. try:
  308. do_work()
  309. except SoftTimeLimitExceeded:
  310. clean_up_in_a_hurry()
  311. Time limits can also be set using the :setting:`task_time_limit` /
  312. :setting:`task_soft_time_limit` settings.
  313. .. note::
  314. Time limits do not currently work on platforms that do not support
  315. the :sig:`SIGUSR1` signal.
  316. Changing time limits at run-time
  317. --------------------------------
  318. .. versionadded:: 2.3
  319. :broker support: *amqp*
  320. There is a remote control command that enables you to change both soft
  321. and hard time limits for a task — named ``time_limit``.
  322. Example changing the time limit for the ``tasks.crawl_the_web`` task
  323. to have a soft time limit of one minute, and a hard time limit of
  324. two minutes:
  325. .. code-block:: pycon
  326. >>> app.control.time_limit('tasks.crawl_the_web',
  327. soft=60, hard=120, reply=True)
  328. [{'worker1.example.com': {'ok': 'time limits set successfully'}}]
  329. Only tasks that starts executing after the time limit change will be affected.
  330. .. _worker-rate-limits:
  331. Rate Limits
  332. ===========
  333. .. control:: rate_limit
  334. Changing rate-limits at run-time
  335. --------------------------------
  336. Example changing the rate limit for the `myapp.mytask` task to execute
  337. at most 200 tasks of that type every minute:
  338. .. code-block:: pycon
  339. >>> app.control.rate_limit('myapp.mytask', '200/m')
  340. The above does not specify a destination, so the change request will affect
  341. all worker instances in the cluster. If you only want to affect a specific
  342. list of workers you can include the ``destination`` argument:
  343. .. code-block:: pycon
  344. >>> app.control.rate_limit('myapp.mytask', '200/m',
  345. ... destination=['celery@worker1.example.com'])
  346. .. warning::
  347. This won't affect workers with the
  348. :setting:`worker_disable_rate_limits` setting enabled.
  349. .. _worker-maxtasksperchild:
  350. Max tasks per child setting
  351. ===========================
  352. .. versionadded:: 2.0
  353. :pool support: *prefork*
  354. With this option you can configure the maximum number of tasks
  355. a worker can execute before it's replaced by a new process.
  356. This is useful if you have memory leaks you have no control over
  357. for example from closed source C extensions.
  358. The option can be set using the workers
  359. :option:`--maxtasksperchild <celery worker --maxtasksperchild>` argument
  360. or using the :setting:`worker_max_tasks_per_child` setting.
  361. .. _worker-maxmemperchild:
  362. Max memory per child setting
  363. ============================
  364. .. versionadded:: 4.0
  365. :pool support: *prefork*
  366. With this option you can configure the maximum amount of resident
  367. memory a worker can execute before it's replaced by a new process.
  368. This is useful if you have memory leaks you have no control over
  369. for example from closed source C extensions.
  370. The option can be set using the workers
  371. :option:`--maxmemperchild <celery worker --maxmemperchild>` argument
  372. or using the :setting:`worker_max_memory_per_child` setting.
  373. .. _worker-queues:
  374. Queues
  375. ======
  376. A worker instance can consume from any number of queues.
  377. By default it will consume from all queues defined in the
  378. :setting:`task_queues` setting (which if not specified defaults to the
  379. queue named ``celery``).
  380. You can specify what queues to consume from at start-up, by giving a comma
  381. separated list of queues to the :option:`-Q <celery worker -Q>` option:
  382. .. code-block:: console
  383. $ celery -A proj worker -l info -Q foo,bar,baz
  384. If the queue name is defined in :setting:`task_queues` it will use that
  385. configuration, but if it's not defined in the list of queues Celery will
  386. automatically generate a new queue for you (depending on the
  387. :setting:`task_create_missing_queues` option).
  388. You can also tell the worker to start and stop consuming from a queue at
  389. run-time using the remote control commands :control:`add_consumer` and
  390. :control:`cancel_consumer`.
  391. .. control:: add_consumer
  392. Queues: Adding consumers
  393. ------------------------
  394. The :control:`add_consumer` control command will tell one or more workers
  395. to start consuming from a queue. This operation is idempotent.
  396. To tell all workers in the cluster to start consuming from a queue
  397. named "``foo``" you can use the :program:`celery control` program:
  398. .. code-block:: console
  399. $ celery -A proj control add_consumer foo
  400. -> worker1.local: OK
  401. started consuming from u'foo'
  402. If you want to specify a specific worker you can use the
  403. :option:`--destination <celery control --destination>` argument:
  404. .. code-block:: console
  405. $ celery -A proj control add_consumer foo -d celery@worker1.local
  406. The same can be accomplished dynamically using the :meth:`@control.add_consumer` method:
  407. .. code-block:: pycon
  408. >>> app.control.add_consumer('foo', reply=True)
  409. [{u'worker1.local': {u'ok': u"already consuming from u'foo'"}}]
  410. >>> app.control.add_consumer('foo', reply=True,
  411. ... destination=['worker1@example.com'])
  412. [{u'worker1.local': {u'ok': u"already consuming from u'foo'"}}]
  413. By now I have only shown examples using automatic queues,
  414. If you need more control you can also specify the exchange, routing_key and
  415. even other options:
  416. .. code-block:: pycon
  417. >>> app.control.add_consumer(
  418. ... queue='baz',
  419. ... exchange='ex',
  420. ... exchange_type='topic',
  421. ... routing_key='media.*',
  422. ... options={
  423. ... 'queue_durable': False,
  424. ... 'exchange_durable': False,
  425. ... },
  426. ... reply=True,
  427. ... destination=['w1@example.com', 'w2@example.com'])
  428. .. control:: cancel_consumer
  429. Queues: Canceling consumers
  430. ---------------------------
  431. You can cancel a consumer by queue name using the :control:`cancel_consumer`
  432. control command.
  433. To force all workers in the cluster to cancel consuming from a queue
  434. you can use the :program:`celery control` program:
  435. .. code-block:: console
  436. $ celery -A proj control cancel_consumer foo
  437. The :option:`--destination <celery control --destination>` argument can be
  438. used to specify a worker, or a list of workers, to act on the command:
  439. .. code-block:: console
  440. $ celery -A proj control cancel_consumer foo -d celery@worker1.local
  441. You can also cancel consumers programmatically using the
  442. :meth:`@control.cancel_consumer` method:
  443. .. code-block:: console
  444. >>> app.control.cancel_consumer('foo', reply=True)
  445. [{u'worker1.local': {u'ok': u"no longer consuming from u'foo'"}}]
  446. .. control:: active_queues
  447. Queues: List of active queues
  448. -----------------------------
  449. You can get a list of queues that a worker consumes from by using
  450. the :control:`active_queues` control command:
  451. .. code-block:: console
  452. $ celery -A proj inspect active_queues
  453. [...]
  454. Like all other remote control commands this also supports the
  455. :option:`--destination <celery inspect --destination>` argument used
  456. to specify which workers should reply to the request:
  457. .. code-block:: console
  458. $ celery -A proj inspect active_queues -d celery@worker1.local
  459. [...]
  460. This can also be done programmatically by using the
  461. :meth:`@control.inspect.active_queues` method:
  462. .. code-block:: pycon
  463. >>> app.control.inspect().active_queues()
  464. [...]
  465. >>> app.control.inspect(['worker1.local']).active_queues()
  466. [...]
  467. .. _worker-inspect:
  468. Inspecting workers
  469. ==================
  470. :class:`@control.inspect` lets you inspect running workers. It
  471. uses remote control commands under the hood.
  472. You can also use the ``celery`` command to inspect workers,
  473. and it supports the same commands as the :class:`@control` interface.
  474. .. code-block:: pycon
  475. >>> # Inspect all nodes.
  476. >>> i = app.control.inspect()
  477. >>> # Specify multiple nodes to inspect.
  478. >>> i = app.control.inspect(['worker1.example.com',
  479. 'worker2.example.com'])
  480. >>> # Specify a single node to inspect.
  481. >>> i = app.control.inspect('worker1.example.com')
  482. .. _worker-inspect-registered-tasks:
  483. Dump of registered tasks
  484. ------------------------
  485. You can get a list of tasks registered in the worker using the
  486. :meth:`~@control.inspect.registered`:
  487. .. code-block:: pycon
  488. >>> i.registered()
  489. [{'worker1.example.com': ['tasks.add',
  490. 'tasks.sleeptask']}]
  491. .. _worker-inspect-active-tasks:
  492. Dump of currently executing tasks
  493. ---------------------------------
  494. You can get a list of active tasks using
  495. :meth:`~@control.inspect.active`:
  496. .. code-block:: pycon
  497. >>> i.active()
  498. [{'worker1.example.com':
  499. [{'name': 'tasks.sleeptask',
  500. 'id': '32666e9b-809c-41fa-8e93-5ae0c80afbbf',
  501. 'args': '(8,)',
  502. 'kwargs': '{}'}]}]
  503. .. _worker-inspect-eta-schedule:
  504. Dump of scheduled (ETA) tasks
  505. -----------------------------
  506. You can get a list of tasks waiting to be scheduled by using
  507. :meth:`~@control.inspect.scheduled`:
  508. .. code-block:: pycon
  509. >>> i.scheduled()
  510. [{'worker1.example.com':
  511. [{'eta': '2010-06-07 09:07:52', 'priority': 0,
  512. 'request': {
  513. 'name': 'tasks.sleeptask',
  514. 'id': '1a7980ea-8b19-413e-91d2-0b74f3844c4d',
  515. 'args': '[1]',
  516. 'kwargs': '{}'}},
  517. {'eta': '2010-06-07 09:07:53', 'priority': 0,
  518. 'request': {
  519. 'name': 'tasks.sleeptask',
  520. 'id': '49661b9a-aa22-4120-94b7-9ee8031d219d',
  521. 'args': '[2]',
  522. 'kwargs': '{}'}}]}]
  523. .. note::
  524. These are tasks with an eta/countdown argument, not periodic tasks.
  525. .. _worker-inspect-reserved:
  526. Dump of reserved tasks
  527. ----------------------
  528. Reserved tasks are tasks that have been received, but are still waiting to be
  529. executed.
  530. You can get a list of these using
  531. :meth:`~@control.inspect.reserved`:
  532. .. code-block:: pycon
  533. >>> i.reserved()
  534. [{'worker1.example.com':
  535. [{'name': 'tasks.sleeptask',
  536. 'id': '32666e9b-809c-41fa-8e93-5ae0c80afbbf',
  537. 'args': '(8,)',
  538. 'kwargs': '{}'}]}]
  539. .. _worker-statistics:
  540. Statistics
  541. ----------
  542. The remote control command ``inspect stats`` (or
  543. :meth:`~@control.inspect.stats`) will give you a long list of useful (or not
  544. so useful) statistics about the worker:
  545. .. code-block:: console
  546. $ celery -A proj inspect stats
  547. The output will include the following fields:
  548. - ``broker``
  549. Section for broker information.
  550. * ``connect_timeout``
  551. Timeout in seconds (int/float) for establishing a new connection.
  552. * ``heartbeat``
  553. Current heartbeat value (set by client).
  554. * ``hostname``
  555. Node name of the remote broker.
  556. * ``insist``
  557. No longer used.
  558. * ``login_method``
  559. Login method used to connect to the broker.
  560. * ``port``
  561. Port of the remote broker.
  562. * ``ssl``
  563. SSL enabled/disabled.
  564. * ``transport``
  565. Name of transport used (e.g. ``amqp``)
  566. * ``transport_options``
  567. Options passed to transport.
  568. * ``userid``
  569. User id used to connect to the broker with.
  570. * ``virtual_host``
  571. Virtual host used.
  572. - ``clock``
  573. Value of the workers logical clock. This is a positive integer and should
  574. be increasing every time you receive statistics.
  575. - ``pid``
  576. Process id of the worker instance (Main process).
  577. - ``pool``
  578. Pool-specific section.
  579. * ``max-concurrency``
  580. Max number of processes/threads/green threads.
  581. * ``max-tasks-per-child``
  582. Max number of tasks a thread may execute before being recycled.
  583. * ``processes``
  584. List of PIDs (or thread-id's).
  585. * ``put-guarded-by-semaphore``
  586. Internal
  587. * ``timeouts``
  588. Default values for time limits.
  589. * ``writes``
  590. Specific to the prefork pool, this shows the distribution of writes
  591. to each process in the pool when using async I/O.
  592. - ``prefetch_count``
  593. Current prefetch count value for the task consumer.
  594. - ``rusage``
  595. System usage statistics. The fields available may be different
  596. on your platform.
  597. From :manpage:`getrusage(2)`:
  598. * ``stime``
  599. Time spent in operating system code on behalf of this process.
  600. * ``utime``
  601. Time spent executing user instructions.
  602. * ``maxrss``
  603. The maximum resident size used by this process (in kilobytes).
  604. * ``idrss``
  605. Amount of non-shared memory used for data (in kilobytes times ticks of
  606. execution)
  607. * ``isrss``
  608. Amount of non-shared memory used for stack space (in kilobytes times
  609. ticks of execution)
  610. * ``ixrss``
  611. Amount of memory shared with other processes (in kilobytes times
  612. ticks of execution).
  613. * ``inblock``
  614. Number of times the file system had to read from the disk on behalf of
  615. this process.
  616. * ``oublock``
  617. Number of times the file system has to write to disk on behalf of
  618. this process.
  619. * ``majflt``
  620. Number of page faults which were serviced by doing I/O.
  621. * ``minflt``
  622. Number of page faults which were serviced without doing I/O.
  623. * ``msgrcv``
  624. Number of IPC messages received.
  625. * ``msgsnd``
  626. Number of IPC messages sent.
  627. * ``nvcsw``
  628. Number of times this process voluntarily invoked a context switch.
  629. * ``nivcsw``
  630. Number of times an involuntary context switch took place.
  631. * ``nsignals``
  632. Number of signals received.
  633. * ``nswap``
  634. The number of times this process was swapped entirely out of memory.
  635. - ``total``
  636. Map of task names and the total number of tasks with that type
  637. the worker has accepted since start-up.
  638. Additional Commands
  639. ===================
  640. .. control:: shutdown
  641. Remote shutdown
  642. ---------------
  643. This command will gracefully shut down the worker remotely:
  644. .. code-block:: pycon
  645. >>> app.control.broadcast('shutdown') # shutdown all workers
  646. >>> app.control.broadcast('shutdown, destination='worker1@example.com')
  647. .. control:: ping
  648. Ping
  649. ----
  650. This command requests a ping from alive workers.
  651. The workers reply with the string 'pong', and that's just about it.
  652. It will use the default one second timeout for replies unless you specify
  653. a custom timeout:
  654. .. code-block:: pycon
  655. >>> app.control.ping(timeout=0.5)
  656. [{'worker1.example.com': 'pong'},
  657. {'worker2.example.com': 'pong'},
  658. {'worker3.example.com': 'pong'}]
  659. :meth:`~@control.ping` also supports the `destination` argument,
  660. so you can specify which workers to ping:
  661. .. code-block:: pycon
  662. >>> ping(['worker2.example.com', 'worker3.example.com'])
  663. [{'worker2.example.com': 'pong'},
  664. {'worker3.example.com': 'pong'}]
  665. .. _worker-enable-events:
  666. .. control:: enable_events
  667. .. control:: disable_events
  668. Enable/disable events
  669. ---------------------
  670. You can enable/disable events by using the `enable_events`,
  671. `disable_events` commands. This is useful to temporarily monitor
  672. a worker using :program:`celery events`/:program:`celerymon`.
  673. .. code-block:: pycon
  674. >>> app.control.enable_events()
  675. >>> app.control.disable_events()
  676. .. _worker-custom-control-commands:
  677. Writing your own remote control commands
  678. ========================================
  679. Remote control commands are registered in the control panel and
  680. they take a single argument: the current
  681. :class:`~celery.worker.control.ControlDispatch` instance.
  682. From there you have access to the active
  683. :class:`~celery.worker.consumer.Consumer` if needed.
  684. Here's an example control command that increments the task prefetch count:
  685. .. code-block:: python
  686. from celery.worker.control import Panel
  687. @Panel.register
  688. def increase_prefetch_count(state, n=1):
  689. state.consumer.qos.increment_eventually(n)
  690. return {'ok': 'prefetch count incremented'}