workers.rst 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227
  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:: bash
  17. $ celery --app=app 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:: bash
  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. host name with the :option:`--hostname|-n` argument:
  25. .. code-block:: bash
  26. $ celery worker --loglevel=INFO --concurrency=10 -n worker1.%h
  27. $ celery worker --loglevel=INFO --concurrency=10 -n worker2.%h
  28. $ celery 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. .. _worker-stopping:
  39. Stopping the worker
  40. ===================
  41. Shutdown should be accomplished using the :sig:`TERM` signal.
  42. When shutdown is initiated the worker will finish all currently executing
  43. tasks before it actually terminates, so if these tasks are important you should
  44. wait for it to finish before doing anything drastic (like sending the :sig:`KILL`
  45. signal).
  46. If the worker won't shutdown after considerate time, for example because
  47. of tasks stuck in an infinite-loop, you can use the :sig:`KILL` signal to
  48. force terminate the worker, but be aware that currently executing tasks will
  49. be lost (unless the tasks have the :attr:`~@Task.acks_late`
  50. option set).
  51. Also as processes can't override the :sig:`KILL` signal, the worker will
  52. not be able to reap its children, so make sure to do so manually. This
  53. command usually does the trick:
  54. .. code-block:: bash
  55. $ ps auxww | grep 'celery worker' | awk '{print $2}' | xargs kill -9
  56. .. _worker-restarting:
  57. Restarting the worker
  58. =====================
  59. To restart the worker you should send the `TERM` signal and start a new
  60. instance. The easiest way to manage workers for development
  61. is by using `celery multi`:
  62. .. code-block:: bash
  63. $ celery multi start 1 -A proj -l info -c4 --pidfile=/var/run/celery/%n.pid
  64. $ celery multi restart 1 --pidfile=/var/run/celery/%n.pid
  65. For production deployments you should be using init scripts or other process
  66. supervision systems (see :ref:`daemonizing`).
  67. Other than stopping then starting the worker to restart, you can also
  68. restart the worker using the :sig:`HUP` signal, but note that the worker
  69. will be responsible for restarting itself so this is prone to problems and
  70. is not recommended in production:
  71. .. code-block:: bash
  72. $ kill -HUP $pid
  73. .. note::
  74. Restarting by :sig:`HUP` only works if the worker is running
  75. in the background as a daemon (it does not have a controlling
  76. terminal).
  77. :sig:`HUP` is disabled on OS X because of a limitation on
  78. that platform.
  79. .. _worker-process-signals:
  80. Process Signals
  81. ===============
  82. The worker's main process overrides the following signals:
  83. +--------------+-------------------------------------------------+
  84. | :sig:`TERM` | Warm shutdown, wait for tasks to complete. |
  85. +--------------+-------------------------------------------------+
  86. | :sig:`QUIT` | Cold shutdown, terminate ASAP |
  87. +--------------+-------------------------------------------------+
  88. | :sig:`USR1` | Dump traceback for all active threads. |
  89. +--------------+-------------------------------------------------+
  90. | :sig:`USR2` | Remote debug, see :mod:`celery.contrib.rdb`. |
  91. +--------------+-------------------------------------------------+
  92. .. _worker-files:
  93. Variables in file paths
  94. =======================
  95. The file path arguments for :option:`--logfile`, :option:`--pidfile` and :option:`--statedb`
  96. can contain variables that the worker will expand:
  97. Node name replacements
  98. ----------------------
  99. - ``%h``: Hostname including domain name.
  100. - ``%n``: Hostname only.
  101. - ``%d``: Domain name only.
  102. - ``%i``: Prefork pool process index or 0 if MainProcess.
  103. - ``%I``: Prefork pool process index with separator.
  104. E.g. if the current hostname is ``george.example.com`` then
  105. these will expand to:
  106. - ``--logfile=%h.log`` -> :file:`george.example.com.log`
  107. - ``--logfile=%n.log`` -> :file:`george.log`
  108. - ``--logfile=%d`` -> :file:`example.com.log`
  109. .. _worker-files-process-index:
  110. Prefork pool process index
  111. --------------------------
  112. The prefork pool process index specifiers will expand into a different
  113. filename depending on the process that will eventually need to open the file.
  114. This can be used to specify one log file per child process.
  115. Note that the numbers will stay within the process limit even if processes
  116. exit or if autoscale/maxtasksperchild/time limits are used. I.e. the number
  117. is the *process index* not the process count or pid.
  118. * ``%i`` - Pool process index or 0 if MainProcess.
  119. Where ``-n worker1@example.com -c2 -f %n-%i.log`` will result in
  120. three log files:
  121. - :file:`worker1-0.log` (main process)
  122. - :file:`worker1-1.log` (pool process 1)
  123. - :file:`worker1-2.log` (pool process 2)
  124. * ``%I`` - Pool process index with separator.
  125. Where ``-n worker1@example.com -c2 -f %n%I.log`` will result in
  126. three log files:
  127. - :file:`worker1.log` (main process)
  128. - :file:`worker1-1.log`` (pool process 1)
  129. - :file:`worker1-2.log`` (pool process 2)
  130. .. _worker-concurrency:
  131. Concurrency and Pool choices
  132. ============================
  133. Celery has a number of pools to handle concurrency, each with its own tradeoffs.
  134. Prefork
  135. -------
  136. This is the *default pool*. It relies on billiard (a fork of multiprocessing) to have a set of processes running tasks in
  137. parallel. This is a good choice for:
  138. * CPU-bound tasks
  139. * Tasks that need isolation (example: tasks that could leak memory, crash the Python interpreter)
  140. Specific options:
  141. * :option:`--concurrency`: The number of worker processes, defaults to the number of CPUs available on the machine.
  142. * :option:`--maxtasksperchild` or :setting:`CELERYD_MAX_TASKS_PER_CHILD`: Maximum number of tasks a pool worker process
  143. can execute before it’s replaced with a new one. Default is no limit.
  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. Threads
  153. -------
  154. This requires the ``threadpool`` package. You can install it with the threads extra, eg: ``pip install
  155. "celery[threads]"``. This is a good choice for I/O-bound tasks with moderate concurrency.
  156. Specific options:
  157. * :option:`--concurrency`: The number of threads in the pool.
  158. Eventlet / gevent
  159. -----------------
  160. These pools are good is you have I/O-bound tasks and need very high concurrency.
  161. Specific options:
  162. * :option:`--concurrency`: The maximum number of greenlets to run.
  163. .. admonition::
  164. Never select these pool via the :setting:`CELERYD_POOL` setting.
  165. You must use the `-P` option instead, otherwise the monkey patching
  166. will happen too late and things will break in strange and silent ways.
  167. Solo
  168. ----
  169. This pool runs everything serially. It's provided as an example for custom pool implementations. You should not use this
  170. normally.
  171. Workhorse
  172. ---------
  173. This is a specialized pool implementation that only works on Linux and (*TODO*)BSDs. It relies on the fork, signalfd or
  174. (*TODO*)kqueue system calls - it cannot be used on Windows.
  175. This pool is a good choice where extreme task isolation is required (where you would use low values of
  176. :option:`--maxtasksperchild` or :setting:`CELERYD_MAX_TASKS_PER_CHILD` with the prefork pool). It has better performance
  177. than the prefork pool in those cases due to low overhead: no pipes are being setup for each subprocess, children are
  178. reaped very efficiently (via signalfd).
  179. Specific options:
  180. * :option:`--concurrency`: The maxiumum number of workers.
  181. .. _worker-remote-control:
  182. Remote control
  183. ==============
  184. .. versionadded:: 2.0
  185. .. sidebar:: The ``celery`` command
  186. The :program:`celery` program is used to execute remote control
  187. commands from the command-line. It supports all of the commands
  188. listed below. See :ref:`monitoring-control` for more information.
  189. pool support: *prefork, eventlet, gevent*, blocking:*threads/solo* (see note)
  190. broker support: *amqp, redis*
  191. Workers have the ability to be remote controlled using a high-priority
  192. broadcast message queue. The commands can be directed to all, or a specific
  193. list of workers.
  194. Commands can also have replies. The client can then wait for and collect
  195. those replies. Since there's no central authority to know how many
  196. workers are available in the cluster, there is also no way to estimate
  197. how many workers may send a reply, so the client has a configurable
  198. timeout — the deadline in seconds for replies to arrive in. This timeout
  199. defaults to one second. If the worker doesn't reply within the deadline
  200. it doesn't necessarily mean the worker didn't reply, or worse is dead, but
  201. may simply be caused by network latency or the worker being slow at processing
  202. commands, so adjust the timeout accordingly.
  203. In addition to timeouts, the client can specify the maximum number
  204. of replies to wait for. If a destination is specified, this limit is set
  205. to the number of destination hosts.
  206. .. note::
  207. The solo and threads pool supports remote control commands,
  208. but any task executing will block any waiting control command,
  209. so it is of limited use if the worker is very busy. In that
  210. case you must increase the timeout waiting for replies in the client.
  211. .. _worker-broadcast-fun:
  212. The :meth:`~@control.broadcast` function.
  213. ----------------------------------------------------
  214. This is the client function used to send commands to the workers.
  215. Some remote control commands also have higher-level interfaces using
  216. :meth:`~@control.broadcast` in the background, like
  217. :meth:`~@control.rate_limit` and :meth:`~@control.ping`.
  218. Sending the :control:`rate_limit` command and keyword arguments::
  219. >>> app.control.broadcast('rate_limit',
  220. ... arguments={'task_name': 'myapp.mytask',
  221. ... 'rate_limit': '200/m'})
  222. This will send the command asynchronously, without waiting for a reply.
  223. To request a reply you have to use the `reply` argument::
  224. >>> app.control.broadcast('rate_limit', {
  225. ... 'task_name': 'myapp.mytask', 'rate_limit': '200/m'}, reply=True)
  226. [{'worker1.example.com': 'New rate limit set successfully'},
  227. {'worker2.example.com': 'New rate limit set successfully'},
  228. {'worker3.example.com': 'New rate limit set successfully'}]
  229. Using the `destination` argument you can specify a list of workers
  230. to receive the command::
  231. >>> app.control.broadcast('rate_limit', {
  232. ... 'task_name': 'myapp.mytask',
  233. ... 'rate_limit': '200/m'}, reply=True,
  234. ... destination=['worker1@example.com'])
  235. [{'worker1.example.com': 'New rate limit set successfully'}]
  236. Of course, using the higher-level interface to set rate limits is much
  237. more convenient, but there are commands that can only be requested
  238. using :meth:`~@control.broadcast`.
  239. .. control:: revoke
  240. Revoking tasks
  241. ==============
  242. pool support: all
  243. broker support: *amqp, redis*
  244. All worker nodes keeps a memory of revoked task ids, either in-memory or
  245. persistent on disk (see :ref:`worker-persistent-revokes`).
  246. When a worker receives a revoke request it will skip executing
  247. the task, but it won't terminate an already executing task unless
  248. the `terminate` option is set.
  249. .. note::
  250. The terminate option is a last resort for administrators when
  251. a task is stuck. It's not for terminating the task,
  252. it's for terminating the process that is executing the task, and that
  253. process may have already started processing another task at the point
  254. when the signal is sent, so for this rason you must never call this
  255. programatically.
  256. If `terminate` is set the worker child process processing the task
  257. will be terminated. The default signal sent is `TERM`, but you can
  258. specify this using the `signal` argument. Signal can be the uppercase name
  259. of any signal defined in the :mod:`signal` module in the Python Standard
  260. Library.
  261. Terminating a task also revokes it.
  262. **Example**
  263. ::
  264. >>> result.revoke()
  265. >>> AsyncResult(id).revoke()
  266. >>> app.control.revoke('d9078da5-9915-40a0-bfa1-392c7bde42ed')
  267. >>> app.control.revoke('d9078da5-9915-40a0-bfa1-392c7bde42ed',
  268. ... terminate=True)
  269. >>> app.control.revoke('d9078da5-9915-40a0-bfa1-392c7bde42ed',
  270. ... terminate=True, signal='SIGKILL')
  271. Revoking multiple tasks
  272. -----------------------
  273. .. versionadded:: 3.1
  274. The revoke method also accepts a list argument, where it will revoke
  275. several tasks at once.
  276. **Example**
  277. ::
  278. >>> app.control.revoke([
  279. ... '7993b0aa-1f0b-4780-9af0-c47c0858b3f2',
  280. ... 'f565793e-b041-4b2b-9ca4-dca22762a55d',
  281. ... 'd9d35e03-2997-42d0-a13e-64a66b88a618',
  282. ])
  283. The ``GroupResult.revoke`` method takes advantage of this since
  284. version 3.1.
  285. .. _worker-persistent-revokes:
  286. Persistent revokes
  287. ------------------
  288. Revoking tasks works by sending a broadcast message to all the workers,
  289. the workers then keep a list of revoked tasks in memory. When a worker starts
  290. up it will synchronize revoked tasks with other workers in the cluster.
  291. The list of revoked tasks is in-memory so if all workers restart the list
  292. of revoked ids will also vanish. If you want to preserve this list between
  293. restarts you need to specify a file for these to be stored in by using the `--statedb`
  294. argument to :program:`celery worker`:
  295. .. code-block:: bash
  296. celery -A proj worker -l info --statedb=/var/run/celery/worker.state
  297. or if you use :program:`celery multi` you will want to create one file per
  298. worker instance so then you can use the `%n` format to expand the current node
  299. name:
  300. .. code-block:: bash
  301. celery multi start 2 -l info --statedb=/var/run/celery/%n.state
  302. See also :ref:`worker-files`
  303. Note that remote control commands must be working for revokes to work.
  304. Remote control commands are only supported by the RabbitMQ (amqp) and Redis
  305. at this point.
  306. .. _worker-time-limits:
  307. Time Limits
  308. ===========
  309. .. versionadded:: 2.0
  310. pool support: *prefork/gevent*
  311. .. sidebar:: Soft, or hard?
  312. The time limit is set in two values, `soft` and `hard`.
  313. The soft time limit allows the task to catch an exception
  314. to clean up before it is killed: the hard timeout is not catchable
  315. and force terminates the task.
  316. A single task can potentially run forever, if you have lots of tasks
  317. waiting for some event that will never happen you will block the worker
  318. from processing new tasks indefinitely. The best way to defend against
  319. this scenario happening is enabling time limits.
  320. The time limit (`--time-limit`) is the maximum number of seconds a task
  321. may run before the process executing it is terminated and replaced by a
  322. new process. You can also enable a soft time limit (`--soft-time-limit`),
  323. this raises an exception the task can catch to clean up before the hard
  324. time limit kills it:
  325. .. code-block:: python
  326. from myapp import app
  327. from celery.exceptions import SoftTimeLimitExceeded
  328. @app.task
  329. def mytask():
  330. try:
  331. do_work()
  332. except SoftTimeLimitExceeded:
  333. clean_up_in_a_hurry()
  334. Time limits can also be set using the :setting:`CELERYD_TASK_TIME_LIMIT` /
  335. :setting:`CELERYD_TASK_SOFT_TIME_LIMIT` settings.
  336. .. note::
  337. Time limits do not currently work on Windows and other
  338. platforms that do not support the ``SIGUSR1`` signal.
  339. Changing time limits at runtime
  340. -------------------------------
  341. .. versionadded:: 2.3
  342. broker support: *amqp, redis*
  343. There is a remote control command that enables you to change both soft
  344. and hard time limits for a task — named ``time_limit``.
  345. Example changing the time limit for the ``tasks.crawl_the_web`` task
  346. to have a soft time limit of one minute, and a hard time limit of
  347. two minutes::
  348. >>> app.control.time_limit('tasks.crawl_the_web',
  349. soft=60, hard=120, reply=True)
  350. [{'worker1.example.com': {'ok': 'time limits set successfully'}}]
  351. Only tasks that starts executing after the time limit change will be affected.
  352. .. _worker-rate-limits:
  353. Rate Limits
  354. ===========
  355. .. control:: rate_limit
  356. Changing rate-limits at runtime
  357. -------------------------------
  358. Example changing the rate limit for the `myapp.mytask` task to execute
  359. at most 200 tasks of that type every minute:
  360. .. code-block:: python
  361. >>> app.control.rate_limit('myapp.mytask', '200/m')
  362. The above does not specify a destination, so the change request will affect
  363. all worker instances in the cluster. If you only want to affect a specific
  364. list of workers you can include the ``destination`` argument:
  365. .. code-block:: python
  366. >>> app.control.rate_limit('myapp.mytask', '200/m',
  367. ... destination=['celery@worker1.example.com'])
  368. .. warning::
  369. This won't affect workers with the
  370. :setting:`CELERY_DISABLE_RATE_LIMITS` setting enabled.
  371. .. _worker-maxtasksperchild:
  372. Max tasks per child setting
  373. ===========================
  374. .. versionadded:: 2.0
  375. pool support: *prefork*
  376. With this option you can configure the maximum number of tasks
  377. a worker can execute before it's replaced by a new process.
  378. This is useful if you have memory leaks you have no control over
  379. for example from closed source C extensions.
  380. The option can be set using the workers `--maxtasksperchild` argument
  381. or using the :setting:`CELERYD_MAX_TASKS_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` option, which needs two
  392. numbers: the maximum and minimum number of pool processes::
  393. --autoscale=AUTOSCALE
  394. Enable autoscaling by providing
  395. max_concurrency,min_concurrency. Example:
  396. --autoscale=10,3 (always keep 3 processes, but grow to
  397. 10 if necessary).
  398. You can also define your own rules for the autoscaler by subclassing
  399. :class:`~celery.worker.autoscaler.Autoscaler`.
  400. Some ideas for metrics include load average or the amount of memory available.
  401. You can specify a custom autoscaler with the :setting:`CELERYD_AUTOSCALER` setting.
  402. .. _worker-queues:
  403. Queues
  404. ======
  405. A worker instance can consume from any number of queues.
  406. By default it will consume from all queues defined in the
  407. :setting:`CELERY_QUEUES` setting (which if not specified defaults to the
  408. queue named ``celery``).
  409. You can specify what queues to consume from at startup,
  410. by giving a comma separated list of queues to the :option:`-Q` option:
  411. .. code-block:: bash
  412. $ celery worker -l info -Q foo,bar,baz
  413. If the queue name is defined in :setting:`CELERY_QUEUES` it will use that
  414. configuration, but if it's not defined in the list of queues Celery will
  415. automatically generate a new queue for you (depending on the
  416. :setting:`CELERY_CREATE_MISSING_QUEUES` option).
  417. You can also tell the worker to start and stop consuming from a queue at
  418. runtime using the remote control commands :control:`add_consumer` and
  419. :control:`cancel_consumer`.
  420. .. control:: add_consumer
  421. Queues: Adding consumers
  422. ------------------------
  423. The :control:`add_consumer` control command will tell one or more workers
  424. to start consuming from a queue. This operation is idempotent.
  425. To tell all workers in the cluster to start consuming from a queue
  426. named "``foo``" you can use the :program:`celery control` program:
  427. .. code-block:: bash
  428. $ celery control add_consumer foo
  429. -> worker1.local: OK
  430. started consuming from u'foo'
  431. If you want to specify a specific worker you can use the
  432. :option:`--destination`` argument:
  433. .. code-block:: bash
  434. $ celery control add_consumer foo -d worker1.local
  435. The same can be accomplished dynamically using the :meth:`@control.add_consumer` method::
  436. >>> app.control.add_consumer('foo', reply=True)
  437. [{u'worker1.local': {u'ok': u"already consuming from u'foo'"}}]
  438. >>> app.control.add_consumer('foo', reply=True,
  439. ... destination=['worker1@example.com'])
  440. [{u'worker1.local': {u'ok': u"already consuming from u'foo'"}}]
  441. By now I have only shown examples using automatic queues,
  442. If you need more control you can also specify the exchange, routing_key and
  443. even other options::
  444. >>> app.control.add_consumer(
  445. ... queue='baz',
  446. ... exchange='ex',
  447. ... exchange_type='topic',
  448. ... routing_key='media.*',
  449. ... options={
  450. ... 'queue_durable': False,
  451. ... 'exchange_durable': False,
  452. ... },
  453. ... reply=True,
  454. ... destination=['w1@example.com', 'w2@example.com'])
  455. .. control:: cancel_consumer
  456. Queues: Cancelling consumers
  457. ----------------------------
  458. You can cancel a consumer by queue name using the :control:`cancel_consumer`
  459. control command.
  460. To force all workers in the cluster to cancel consuming from a queue
  461. you can use the :program:`celery control` program:
  462. .. code-block:: bash
  463. $ celery control cancel_consumer foo
  464. The :option:`--destination` argument can be used to specify a worker, or a
  465. list of workers, to act on the command:
  466. .. code-block:: bash
  467. $ celery control cancel_consumer foo -d worker1.local
  468. You can also cancel consumers programmatically using the
  469. :meth:`@control.cancel_consumer` method:
  470. .. code-block:: bash
  471. >>> app.control.cancel_consumer('foo', reply=True)
  472. [{u'worker1.local': {u'ok': u"no longer consuming from u'foo'"}}]
  473. .. control:: active_queues
  474. Queues: List of active queues
  475. -----------------------------
  476. You can get a list of queues that a worker consumes from by using
  477. the :control:`active_queues` control command:
  478. .. code-block:: bash
  479. $ celery inspect active_queues
  480. [...]
  481. Like all other remote control commands this also supports the
  482. :option:`--destination` argument used to specify which workers should
  483. reply to the request:
  484. .. code-block:: bash
  485. $ celery inspect active_queues -d worker1.local
  486. [...]
  487. This can also be done programmatically by using the
  488. :meth:`@control.inspect.active_queues` method::
  489. >>> app.control.inspect().active_queues()
  490. [...]
  491. >>> app.control.inspect(['worker1.local']).active_queues()
  492. [...]
  493. .. _worker-autoreloading:
  494. Autoreloading
  495. =============
  496. .. versionadded:: 2.5
  497. pool support: *prefork, eventlet, gevent, threads, solo*
  498. Starting :program:`celery worker` with the :option:`--autoreload` option will
  499. enable the worker to watch for file system changes to all imported task
  500. modules imported (and also any non-task modules added to the
  501. :setting:`CELERY_IMPORTS` setting or the :option:`-I|--include` option).
  502. This is an experimental feature intended for use in development only,
  503. using auto-reload in production is discouraged as the behavior of reloading
  504. a module in Python is undefined, and may cause hard to diagnose bugs and
  505. crashes. Celery uses the same approach as the auto-reloader found in e.g.
  506. the Django ``runserver`` command.
  507. When auto-reload is enabled the worker starts an additional thread
  508. that watches for changes in the file system. New modules are imported,
  509. and already imported modules are reloaded whenever a change is detected,
  510. and if the prefork pool is used the child processes will finish the work
  511. they are doing and exit, so that they can be replaced by fresh processes
  512. effectively reloading the code.
  513. File system notification backends are pluggable, and it comes with three
  514. implementations:
  515. * inotify (Linux)
  516. Used if the :mod:`pyinotify` library is installed.
  517. If you are running on Linux this is the recommended implementation,
  518. to install the :mod:`pyinotify` library you have to run the following
  519. command:
  520. .. code-block:: bash
  521. $ pip install pyinotify
  522. * kqueue (OS X/BSD)
  523. * stat
  524. The fallback implementation simply polls the files using ``stat`` and is very
  525. expensive.
  526. You can force an implementation by setting the :envvar:`CELERYD_FSNOTIFY`
  527. environment variable:
  528. .. code-block:: bash
  529. $ env CELERYD_FSNOTIFY=stat celery worker -l info --autoreload
  530. .. _worker-autoreload:
  531. .. control:: pool_restart
  532. Pool Restart Command
  533. --------------------
  534. .. versionadded:: 2.5
  535. Requires the :setting:`CELERYD_POOL_RESTARTS` setting to be enabled.
  536. The remote control command :control:`pool_restart` sends restart requests to
  537. the workers child processes. It is particularly useful for forcing
  538. the worker to import new modules, or for reloading already imported
  539. modules. This command does not interrupt executing tasks.
  540. Example
  541. ~~~~~~~
  542. Running the following command will result in the `foo` and `bar` modules
  543. being imported by the worker processes:
  544. .. code-block:: python
  545. >>> app.control.broadcast('pool_restart',
  546. ... arguments={'modules': ['foo', 'bar']})
  547. Use the ``reload`` argument to reload modules it has already imported:
  548. .. code-block:: python
  549. >>> app.control.broadcast('pool_restart',
  550. ... arguments={'modules': ['foo'],
  551. ... 'reload': True})
  552. If you don't specify any modules then all known tasks modules will
  553. be imported/reloaded:
  554. .. code-block:: python
  555. >>> app.control.broadcast('pool_restart', arguments={'reload': True})
  556. The ``modules`` argument is a list of modules to modify. ``reload``
  557. specifies whether to reload modules if they have previously been imported.
  558. By default ``reload`` is disabled. The `pool_restart` command uses the
  559. Python :func:`reload` function to reload modules, or you can provide
  560. your own custom reloader by passing the ``reloader`` argument.
  561. .. note::
  562. Module reloading comes with caveats that are documented in :func:`reload`.
  563. Please read this documentation and make sure your modules are suitable
  564. for reloading.
  565. .. seealso::
  566. - http://pyunit.sourceforge.net/notes/reloading.html
  567. - http://www.indelible.org/ink/python-reloading/
  568. - http://docs.python.org/library/functions.html#reload
  569. .. _worker-inspect:
  570. Inspecting workers
  571. ==================
  572. :class:`@control.inspect` lets you inspect running workers. It
  573. uses remote control commands under the hood.
  574. You can also use the ``celery`` command to inspect workers,
  575. and it supports the same commands as the :class:`@Celery.control` interface.
  576. .. code-block:: python
  577. # Inspect all nodes.
  578. >>> i = app.control.inspect()
  579. # Specify multiple nodes to inspect.
  580. >>> i = app.control.inspect(['worker1.example.com',
  581. 'worker2.example.com'])
  582. # Specify a single node to inspect.
  583. >>> i = app.control.inspect('worker1.example.com')
  584. .. _worker-inspect-registered-tasks:
  585. Dump of registered tasks
  586. ------------------------
  587. You can get a list of tasks registered in the worker using the
  588. :meth:`~@control.inspect.registered`::
  589. >>> i.registered()
  590. [{'worker1.example.com': ['tasks.add',
  591. 'tasks.sleeptask']}]
  592. .. _worker-inspect-active-tasks:
  593. Dump of currently executing tasks
  594. ---------------------------------
  595. You can get a list of active tasks using
  596. :meth:`~@control.inspect.active`::
  597. >>> i.active()
  598. [{'worker1.example.com':
  599. [{'name': 'tasks.sleeptask',
  600. 'id': '32666e9b-809c-41fa-8e93-5ae0c80afbbf',
  601. 'args': '(8,)',
  602. 'kwargs': '{}'}]}]
  603. .. _worker-inspect-eta-schedule:
  604. Dump of scheduled (ETA) tasks
  605. -----------------------------
  606. You can get a list of tasks waiting to be scheduled by using
  607. :meth:`~@control.inspect.scheduled`::
  608. >>> i.scheduled()
  609. [{'worker1.example.com':
  610. [{'eta': '2010-06-07 09:07:52', 'priority': 0,
  611. 'request': {
  612. 'name': 'tasks.sleeptask',
  613. 'id': '1a7980ea-8b19-413e-91d2-0b74f3844c4d',
  614. 'args': '[1]',
  615. 'kwargs': '{}'}},
  616. {'eta': '2010-06-07 09:07:53', 'priority': 0,
  617. 'request': {
  618. 'name': 'tasks.sleeptask',
  619. 'id': '49661b9a-aa22-4120-94b7-9ee8031d219d',
  620. 'args': '[2]',
  621. 'kwargs': '{}'}}]}]
  622. .. note::
  623. These are tasks with an eta/countdown argument, not periodic tasks.
  624. .. _worker-inspect-reserved:
  625. Dump of reserved tasks
  626. ----------------------
  627. Reserved tasks are tasks that has been received, but is still waiting to be
  628. executed.
  629. You can get a list of these using
  630. :meth:`~@control.inspect.reserved`::
  631. >>> i.reserved()
  632. [{'worker1.example.com':
  633. [{'name': 'tasks.sleeptask',
  634. 'id': '32666e9b-809c-41fa-8e93-5ae0c80afbbf',
  635. 'args': '(8,)',
  636. 'kwargs': '{}'}]}]
  637. .. _worker-statistics:
  638. Statistics
  639. ----------
  640. The remote control command ``inspect stats`` (or
  641. :meth:`~@control.inspect.stats`) will give you a long list of useful (or not
  642. so useful) statistics about the worker:
  643. .. code-block:: bash
  644. $ celery -A proj inspect stats
  645. The output will include the following fields:
  646. - ``broker``
  647. Section for broker information.
  648. * ``connect_timeout``
  649. Timeout in seconds (int/float) for establishing a new connection.
  650. * ``heartbeat``
  651. Current heartbeat value (set by client).
  652. * ``hostname``
  653. Hostname of the remote broker.
  654. * ``insist``
  655. No longer used.
  656. * ``login_method``
  657. Login method used to connect to the broker.
  658. * ``port``
  659. Port of the remote broker.
  660. * ``ssl``
  661. SSL enabled/disabled.
  662. * ``transport``
  663. Name of transport used (e.g. ``amqp`` or ``redis``)
  664. * ``transport_options``
  665. Options passed to transport.
  666. * ``uri_prefix``
  667. Some transports expects the host name to be an URL, this applies to
  668. for example SQLAlchemy where the host name part is the connection URI:
  669. redis+socket:///tmp/redis.sock
  670. In this example the uri prefix will be ``redis``.
  671. * ``userid``
  672. User id used to connect to the broker with.
  673. * ``virtual_host``
  674. Virtual host used.
  675. - ``clock``
  676. Value of the workers logical clock. This is a positive integer and should
  677. be increasing every time you receive statistics.
  678. - ``pid``
  679. Process id of the worker instance (Main process).
  680. - ``pool``
  681. Pool-specific section.
  682. * ``max-concurrency``
  683. Max number of processes/threads/green threads.
  684. * ``max-tasks-per-child``
  685. Max number of tasks a thread may execute before being recycled.
  686. * ``processes``
  687. List of pids (or thread-id's).
  688. * ``put-guarded-by-semaphore``
  689. Internal
  690. * ``timeouts``
  691. Default values for time limits.
  692. * ``writes``
  693. Specific to the prefork pool, this shows the distribution of writes
  694. to each process in the pool when using async I/O.
  695. - ``prefetch_count``
  696. Current prefetch count value for the task consumer.
  697. - ``rusage``
  698. System usage statistics. The fields available may be different
  699. on your platform.
  700. From :manpage:`getrusage(2)`:
  701. * ``stime``
  702. Time spent in operating system code on behalf of this process.
  703. * ``utime``
  704. Time spent executing user instructions.
  705. * ``maxrss``
  706. The maximum resident size used by this process (in kilobytes).
  707. * ``idrss``
  708. Amount of unshared memory used for data (in kilobytes times ticks of
  709. execution)
  710. * ``isrss``
  711. Amount of unshared memory used for stack space (in kilobytes times
  712. ticks of execution)
  713. * ``ixrss``
  714. Amount of memory shared with other processes (in kilobytes times
  715. ticks of execution).
  716. * ``inblock``
  717. Number of times the file system had to read from the disk on behalf of
  718. this process.
  719. * ``oublock``
  720. Number of times the file system has to write to disk on behalf of
  721. this process.
  722. * ``majflt``
  723. Number of page faults which were serviced by doing I/O.
  724. * ``minflt``
  725. Number of page faults which were serviced without doing I/O.
  726. * ``msgrcv``
  727. Number of IPC messages received.
  728. * ``msgsnd``
  729. Number of IPC messages sent.
  730. * ``nvcsw``
  731. Number of times this process voluntarily invoked a context switch.
  732. * ``nivcsw``
  733. Number of times an involuntary context switch took place.
  734. * ``nsignals``
  735. Number of signals received.
  736. * ``nswap``
  737. The number of times this process was swapped entirely out of memory.
  738. - ``total``
  739. List of task names and a total number of times that task have been
  740. executed since worker start.
  741. Additional Commands
  742. ===================
  743. .. control:: shutdown
  744. Remote shutdown
  745. ---------------
  746. This command will gracefully shut down the worker remotely:
  747. .. code-block:: python
  748. >>> app.control.broadcast('shutdown') # shutdown all workers
  749. >>> app.control.broadcast('shutdown, destination="worker1@example.com")
  750. .. control:: ping
  751. Ping
  752. ----
  753. This command requests a ping from alive workers.
  754. The workers reply with the string 'pong', and that's just about it.
  755. It will use the default one second timeout for replies unless you specify
  756. a custom timeout:
  757. .. code-block:: python
  758. >>> app.control.ping(timeout=0.5)
  759. [{'worker1.example.com': 'pong'},
  760. {'worker2.example.com': 'pong'},
  761. {'worker3.example.com': 'pong'}]
  762. :meth:`~@control.ping` also supports the `destination` argument,
  763. so you can specify which workers to ping::
  764. >>> ping(['worker2.example.com', 'worker3.example.com'])
  765. [{'worker2.example.com': 'pong'},
  766. {'worker3.example.com': 'pong'}]
  767. .. _worker-enable-events:
  768. .. control:: enable_events
  769. .. control:: disable_events
  770. Enable/disable events
  771. ---------------------
  772. You can enable/disable events by using the `enable_events`,
  773. `disable_events` commands. This is useful to temporarily monitor
  774. a worker using :program:`celery events`/:program:`celerymon`.
  775. .. code-block:: python
  776. >>> app.control.enable_events()
  777. >>> app.control.disable_events()
  778. .. _worker-custom-control-commands:
  779. Writing your own remote control commands
  780. ========================================
  781. Remote control commands are registered in the control panel and
  782. they take a single argument: the current
  783. :class:`~celery.worker.control.ControlDispatch` instance.
  784. From there you have access to the active
  785. :class:`~celery.worker.consumer.Consumer` if needed.
  786. Here's an example control command that increments the task prefetch count:
  787. .. code-block:: python
  788. from celery.worker.control import Panel
  789. @Panel.register
  790. def increase_prefetch_count(state, n=1):
  791. state.consumer.qos.increment_eventually(n)
  792. return {'ok': 'prefetch count incremented'}