workers.rst 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170
  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 autoscale/``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-max-tasks-per-child:
  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:`--max-tasks-per-child <celery worker --max-tasks-per-child>` argument
  369. or using the :setting:`worker_max_tasks_per_child` setting.
  370. .. _worker-max-memory-per-child:
  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:`--max-memory-per-child <celery worker --max-memory-per-child>` argument
  381. or using the :setting:`worker_max_memory_per_child` setting.
  382. .. _worker-autoscaling:
  383. Autoscaling
  384. ===========
  385. .. versionadded:: 2.2
  386. :pool support: *prefork*, *gevent*
  387. The *autoscaler* component is used to dynamically resize the pool
  388. based on load:
  389. - The autoscaler adds more pool processes when there is work to do,
  390. - and starts removing processes when the workload is low.
  391. It's enabled by the :option:`--autoscale <celery worker --autoscale>` option,
  392. which needs two numbers: the maximum and minimum number of pool processes:
  393. .. code-block:: text
  394. --autoscale=AUTOSCALE
  395. Enable autoscaling by providing
  396. max_concurrency,min_concurrency. Example:
  397. --autoscale=10,3 (always keep 3 processes, but grow to
  398. 10 if necessary).
  399. You can also define your own rules for the autoscaler by subclassing
  400. :class:`~celery.worker.autoscaler.Autoscaler`.
  401. Some ideas for metrics include load average or the amount of memory available.
  402. You can specify a custom autoscaler with the :setting:`worker_autoscaler` setting.
  403. .. _worker-queues:
  404. Queues
  405. ======
  406. A worker instance can consume from any number of queues.
  407. By default it will consume from all queues defined in the
  408. :setting:`task_queues` setting (that if not specified falls back to the
  409. default queue named ``celery``).
  410. You can specify what queues to consume from at start-up, by giving a comma
  411. separated list of queues to the :option:`-Q <celery worker -Q>` option:
  412. .. code-block:: console
  413. $ celery -A proj worker -l info -Q foo,bar,baz
  414. If the queue name is defined in :setting:`task_queues` it will use that
  415. configuration, but if it's not defined in the list of queues Celery will
  416. automatically generate a new queue for you (depending on the
  417. :setting:`task_create_missing_queues` option).
  418. You can also tell the worker to start and stop consuming from a queue at
  419. run-time using the remote control commands :control:`add_consumer` and
  420. :control:`cancel_consumer`.
  421. .. control:: add_consumer
  422. Queues: Adding consumers
  423. ------------------------
  424. The :control:`add_consumer` control command will tell one or more workers
  425. to start consuming from a queue. This operation is idempotent.
  426. To tell all workers in the cluster to start consuming from a queue
  427. named "``foo``" you can use the :program:`celery control` program:
  428. .. code-block:: console
  429. $ celery -A proj control add_consumer foo
  430. -> worker1.local: OK
  431. started consuming from u'foo'
  432. If you want to specify a specific worker you can use the
  433. :option:`--destination <celery control --destination>` argument:
  434. .. code-block:: console
  435. $ celery -A proj control add_consumer foo -d celery@worker1.local
  436. The same can be accomplished dynamically using the :meth:`@control.add_consumer` method:
  437. .. code-block:: pycon
  438. >>> app.control.add_consumer('foo', reply=True)
  439. [{u'worker1.local': {u'ok': u"already consuming from u'foo'"}}]
  440. >>> app.control.add_consumer('foo', reply=True,
  441. ... destination=['worker1@example.com'])
  442. [{u'worker1.local': {u'ok': u"already consuming from u'foo'"}}]
  443. By now we've only shown examples using automatic queues,
  444. If you need more control you can also specify the exchange, routing_key and
  445. even other options:
  446. .. code-block:: pycon
  447. >>> app.control.add_consumer(
  448. ... queue='baz',
  449. ... exchange='ex',
  450. ... exchange_type='topic',
  451. ... routing_key='media.*',
  452. ... options={
  453. ... 'queue_durable': False,
  454. ... 'exchange_durable': False,
  455. ... },
  456. ... reply=True,
  457. ... destination=['w1@example.com', 'w2@example.com'])
  458. .. control:: cancel_consumer
  459. Queues: Canceling consumers
  460. ---------------------------
  461. You can cancel a consumer by queue name using the :control:`cancel_consumer`
  462. control command.
  463. To force all workers in the cluster to cancel consuming from a queue
  464. you can use the :program:`celery control` program:
  465. .. code-block:: console
  466. $ celery -A proj control cancel_consumer foo
  467. The :option:`--destination <celery control --destination>` argument can be
  468. used to specify a worker, or a list of workers, to act on the command:
  469. .. code-block:: console
  470. $ celery -A proj control cancel_consumer foo -d celery@worker1.local
  471. You can also cancel consumers programmatically using the
  472. :meth:`@control.cancel_consumer` method:
  473. .. code-block:: console
  474. >>> app.control.cancel_consumer('foo', reply=True)
  475. [{u'worker1.local': {u'ok': u"no longer consuming from u'foo'"}}]
  476. .. control:: active_queues
  477. Queues: List of active queues
  478. -----------------------------
  479. You can get a list of queues that a worker consumes from by using
  480. the :control:`active_queues` control command:
  481. .. code-block:: console
  482. $ celery -A proj inspect active_queues
  483. [...]
  484. Like all other remote control commands this also supports the
  485. :option:`--destination <celery inspect --destination>` argument used
  486. to specify the workers that should reply to the request:
  487. .. code-block:: console
  488. $ celery -A proj inspect active_queues -d celery@worker1.local
  489. [...]
  490. This can also be done programmatically by using the
  491. :meth:`@control.inspect.active_queues` method:
  492. .. code-block:: pycon
  493. >>> app.control.inspect().active_queues()
  494. [...]
  495. >>> app.control.inspect(['worker1.local']).active_queues()
  496. [...]
  497. .. _worker-inspect:
  498. Inspecting workers
  499. ==================
  500. :class:`@control.inspect` lets you inspect running workers. It
  501. uses remote control commands under the hood.
  502. You can also use the ``celery`` command to inspect workers,
  503. and it supports the same commands as the :class:`@control` interface.
  504. .. code-block:: pycon
  505. >>> # Inspect all nodes.
  506. >>> i = app.control.inspect()
  507. >>> # Specify multiple nodes to inspect.
  508. >>> i = app.control.inspect(['worker1.example.com',
  509. 'worker2.example.com'])
  510. >>> # Specify a single node to inspect.
  511. >>> i = app.control.inspect('worker1.example.com')
  512. .. _worker-inspect-registered-tasks:
  513. Dump of registered tasks
  514. ------------------------
  515. You can get a list of tasks registered in the worker using the
  516. :meth:`~@control.inspect.registered`:
  517. .. code-block:: pycon
  518. >>> i.registered()
  519. [{'worker1.example.com': ['tasks.add',
  520. 'tasks.sleeptask']}]
  521. .. _worker-inspect-active-tasks:
  522. Dump of currently executing tasks
  523. ---------------------------------
  524. You can get a list of active tasks using
  525. :meth:`~@control.inspect.active`:
  526. .. code-block:: pycon
  527. >>> i.active()
  528. [{'worker1.example.com':
  529. [{'name': 'tasks.sleeptask',
  530. 'id': '32666e9b-809c-41fa-8e93-5ae0c80afbbf',
  531. 'args': '(8,)',
  532. 'kwargs': '{}'}]}]
  533. .. _worker-inspect-eta-schedule:
  534. Dump of scheduled (ETA) tasks
  535. -----------------------------
  536. You can get a list of tasks waiting to be scheduled by using
  537. :meth:`~@control.inspect.scheduled`:
  538. .. code-block:: pycon
  539. >>> i.scheduled()
  540. [{'worker1.example.com':
  541. [{'eta': '2010-06-07 09:07:52', 'priority': 0,
  542. 'request': {
  543. 'name': 'tasks.sleeptask',
  544. 'id': '1a7980ea-8b19-413e-91d2-0b74f3844c4d',
  545. 'args': '[1]',
  546. 'kwargs': '{}'}},
  547. {'eta': '2010-06-07 09:07:53', 'priority': 0,
  548. 'request': {
  549. 'name': 'tasks.sleeptask',
  550. 'id': '49661b9a-aa22-4120-94b7-9ee8031d219d',
  551. 'args': '[2]',
  552. 'kwargs': '{}'}}]}]
  553. .. note::
  554. These are tasks with an ETA/countdown argument, not periodic tasks.
  555. .. _worker-inspect-reserved:
  556. Dump of reserved tasks
  557. ----------------------
  558. Reserved tasks are tasks that have been received, but are still waiting to be
  559. executed.
  560. You can get a list of these using
  561. :meth:`~@control.inspect.reserved`:
  562. .. code-block:: pycon
  563. >>> i.reserved()
  564. [{'worker1.example.com':
  565. [{'name': 'tasks.sleeptask',
  566. 'id': '32666e9b-809c-41fa-8e93-5ae0c80afbbf',
  567. 'args': '(8,)',
  568. 'kwargs': '{}'}]}]
  569. .. _worker-statistics:
  570. Statistics
  571. ----------
  572. The remote control command ``inspect stats`` (or
  573. :meth:`~@control.inspect.stats`) will give you a long list of useful (or not
  574. so useful) statistics about the worker:
  575. .. code-block:: console
  576. $ celery -A proj inspect stats
  577. The output will include the following fields:
  578. - ``broker``
  579. Section for broker information.
  580. * ``connect_timeout``
  581. Timeout in seconds (int/float) for establishing a new connection.
  582. * ``heartbeat``
  583. Current heartbeat value (set by client).
  584. * ``hostname``
  585. Node name of the remote broker.
  586. * ``insist``
  587. No longer used.
  588. * ``login_method``
  589. Login method used to connect to the broker.
  590. * ``port``
  591. Port of the remote broker.
  592. * ``ssl``
  593. SSL enabled/disabled.
  594. * ``transport``
  595. Name of transport used (e.g., ``amqp`` or ``redis``)
  596. * ``transport_options``
  597. Options passed to transport.
  598. * ``uri_prefix``
  599. Some transports expects the host name to be a URL.
  600. .. code-block:: text
  601. redis+socket:///tmp/redis.sock
  602. In this example the URI-prefix will be ``redis``.
  603. * ``userid``
  604. User id used to connect to the broker with.
  605. * ``virtual_host``
  606. Virtual host used.
  607. - ``clock``
  608. Value of the workers logical clock. This is a positive integer and should
  609. be increasing every time you receive statistics.
  610. - ``pid``
  611. Process id of the worker instance (Main process).
  612. - ``pool``
  613. Pool-specific section.
  614. * ``max-concurrency``
  615. Max number of processes/threads/green threads.
  616. * ``max-tasks-per-child``
  617. Max number of tasks a thread may execute before being recycled.
  618. * ``processes``
  619. List of PIDs (or thread-id's).
  620. * ``put-guarded-by-semaphore``
  621. Internal
  622. * ``timeouts``
  623. Default values for time limits.
  624. * ``writes``
  625. Specific to the prefork pool, this shows the distribution of writes
  626. to each process in the pool when using async I/O.
  627. - ``prefetch_count``
  628. Current prefetch count value for the task consumer.
  629. - ``rusage``
  630. System usage statistics. The fields available may be different
  631. on your platform.
  632. From :manpage:`getrusage(2)`:
  633. * ``stime``
  634. Time spent in operating system code on behalf of this process.
  635. * ``utime``
  636. Time spent executing user instructions.
  637. * ``maxrss``
  638. The maximum resident size used by this process (in kilobytes).
  639. * ``idrss``
  640. Amount of non-shared memory used for data (in kilobytes times ticks of
  641. execution)
  642. * ``isrss``
  643. Amount of non-shared memory used for stack space (in kilobytes times
  644. ticks of execution)
  645. * ``ixrss``
  646. Amount of memory shared with other processes (in kilobytes times
  647. ticks of execution).
  648. * ``inblock``
  649. Number of times the file system had to read from the disk on behalf of
  650. this process.
  651. * ``oublock``
  652. Number of times the file system has to write to disk on behalf of
  653. this process.
  654. * ``majflt``
  655. Number of page faults that were serviced by doing I/O.
  656. * ``minflt``
  657. Number of page faults that were serviced without doing I/O.
  658. * ``msgrcv``
  659. Number of IPC messages received.
  660. * ``msgsnd``
  661. Number of IPC messages sent.
  662. * ``nvcsw``
  663. Number of times this process voluntarily invoked a context switch.
  664. * ``nivcsw``
  665. Number of times an involuntary context switch took place.
  666. * ``nsignals``
  667. Number of signals received.
  668. * ``nswap``
  669. The number of times this process was swapped entirely out of memory.
  670. - ``total``
  671. Map of task names and the total number of tasks with that type
  672. the worker has accepted since start-up.
  673. Additional Commands
  674. ===================
  675. .. control:: shutdown
  676. Remote shutdown
  677. ---------------
  678. This command will gracefully shut down the worker remotely:
  679. .. code-block:: pycon
  680. >>> app.control.broadcast('shutdown') # shutdown all workers
  681. >>> app.control.broadcast('shutdown', destination='worker1@example.com')
  682. .. control:: ping
  683. Ping
  684. ----
  685. This command requests a ping from alive workers.
  686. The workers reply with the string 'pong', and that's just about it.
  687. It will use the default one second timeout for replies unless you specify
  688. a custom timeout:
  689. .. code-block:: pycon
  690. >>> app.control.ping(timeout=0.5)
  691. [{'worker1.example.com': 'pong'},
  692. {'worker2.example.com': 'pong'},
  693. {'worker3.example.com': 'pong'}]
  694. :meth:`~@control.ping` also supports the `destination` argument,
  695. so you can specify the workers to ping:
  696. .. code-block:: pycon
  697. >>> ping(['worker2.example.com', 'worker3.example.com'])
  698. [{'worker2.example.com': 'pong'},
  699. {'worker3.example.com': 'pong'}]
  700. .. _worker-enable-events:
  701. .. control:: enable_events
  702. .. control:: disable_events
  703. Enable/disable events
  704. ---------------------
  705. You can enable/disable events by using the `enable_events`,
  706. `disable_events` commands. This is useful to temporarily monitor
  707. a worker using :program:`celery events`/:program:`celerymon`.
  708. .. code-block:: pycon
  709. >>> app.control.enable_events()
  710. >>> app.control.disable_events()
  711. .. _worker-custom-control-commands:
  712. Writing your own remote control commands
  713. ========================================
  714. There are two types of remote control commands:
  715. - Inspect command
  716. Does not have side effects, will usually just return some value
  717. found in the worker, like the list of currently registered tasks,
  718. the list of active tasks, etc.
  719. - Control command
  720. Performs side effects, like adding a new queue to consume from.
  721. Remote control commands are registered in the control panel and
  722. they take a single argument: the current
  723. :class:`~celery.worker.control.ControlDispatch` instance.
  724. From there you have access to the active
  725. :class:`~celery.worker.consumer.Consumer` if needed.
  726. Here's an example control command that increments the task prefetch count:
  727. .. code-block:: python
  728. from celery.worker.control import control_command
  729. @control_command(
  730. args=[('n', int)],
  731. signature='[N=1]', # <- used for help on the command-line.
  732. )
  733. def increase_prefetch_count(state, n=1):
  734. state.consumer.qos.increment_eventually(n)
  735. return {'ok': 'prefetch count incremented'}
  736. Make sure you add this code to a module that is imported by the worker:
  737. this could be the same module as where your Celery app is defined, or you
  738. can add the module to the :setting:`imports` setting.
  739. Restart the worker so that the control command is registered, and now you
  740. can call your command using the :program:`celery control` utility:
  741. .. code-block:: console
  742. $ celery -A proj control increase_prefetch_count 3
  743. You can also add actions to the :program:`celery inspect` program,
  744. for example one that reads the current prefetch count:
  745. .. code-block:: python
  746. from celery.worker.control import inspect_command
  747. @inspect_command
  748. def current_prefetch_count(state):
  749. return {'prefetch_count': state.consumer.qos.value}
  750. After restarting the worker you can now query this value using the
  751. :program:`celery inspect` program:
  752. .. code-block:: console
  753. $ celery -A proj inspect current_prefetch_count