workers.rst 33 KB

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