workers.rst 33 KB

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