workers.rst 31 KB

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