workers.rst 34 KB

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