workers.rst 31 KB

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