monitoring.rst 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786
  1. .. _guide-monitoring:
  2. =================================
  3. Monitoring and Management Guide
  4. =================================
  5. .. contents::
  6. :local:
  7. Introduction
  8. ============
  9. There are several tools available to monitor and inspect Celery clusters.
  10. This document describes some of these, as as well as
  11. features related to monitoring, like events and broadcast commands.
  12. .. _monitoring-workers:
  13. Workers
  14. =======
  15. .. _monitoring-control:
  16. Management Command-line Utilities (``inspect``/``control``)
  17. -----------------------------------------------------------
  18. :program:`celery` can also be used to inspect
  19. and manage worker nodes (and to some degree tasks).
  20. To list all the commands available do:
  21. .. code-block:: console
  22. $ celery help
  23. or to get help for a specific command do:
  24. .. code-block:: console
  25. $ celery <command> --help
  26. Commands
  27. ~~~~~~~~
  28. * **shell**: Drop into a Python shell.
  29. The locals will include the ``celery`` variable, which is the current app.
  30. Also all known tasks will be automatically added to locals (unless the
  31. :option:`--without-tasks <celery shell --without-tasks>` flag is set).
  32. Uses :pypi:`Ipython`, :pypi:`bpython`, or regular python in that order if
  33. installed. You can force an implementation using
  34. :option:`--ipython <celery shell --ipython>`,
  35. :option:`--bpython <celery shell --bpython>`, or
  36. :option:`--python <celery shell --python>`.
  37. * **status**: List active nodes in this cluster
  38. .. code-block:: console
  39. $ celery -A proj status
  40. * **result**: Show the result of a task
  41. .. code-block:: console
  42. $ celery -A proj result -t tasks.add 4e196aa4-0141-4601-8138-7aa33db0f577
  43. Note that you can omit the name of the task as long as the
  44. task doesn't use a custom result backend.
  45. * **purge**: Purge messages from all configured task queues.
  46. .. warning::
  47. There is no undo for this operation, and messages will
  48. be permanently deleted!
  49. .. code-block:: console
  50. $ celery -A proj purge
  51. * **inspect active**: List active tasks
  52. .. code-block:: console
  53. $ celery -A proj inspect active
  54. These are all the tasks that are currently being executed.
  55. * **inspect scheduled**: List scheduled ETA tasks
  56. .. code-block:: console
  57. $ celery -A proj inspect scheduled
  58. These are tasks reserved by the worker because they have the
  59. `eta` or `countdown` argument set.
  60. * **inspect reserved**: List reserved tasks
  61. .. code-block:: console
  62. $ celery -A proj inspect reserved
  63. This will list all tasks that have been prefetched by the worker,
  64. and is currently waiting to be executed (does not include tasks
  65. with an eta).
  66. * **inspect revoked**: List history of revoked tasks
  67. .. code-block:: console
  68. $ celery -A proj inspect revoked
  69. * **inspect registered**: List registered tasks
  70. .. code-block:: console
  71. $ celery -A proj inspect registered
  72. * **inspect stats**: Show worker statistics (see :ref:`worker-statistics`)
  73. .. code-block:: console
  74. $ celery -A proj inspect stats
  75. * **control enable_events**: Enable events
  76. .. code-block:: console
  77. $ celery -A proj control enable_events
  78. * **control disable_events**: Disable events
  79. .. code-block:: console
  80. $ celery -A proj control disable_events
  81. * **migrate**: Migrate tasks from one broker to another (**EXPERIMENTAL**).
  82. .. code-block:: console
  83. $ celery -A proj migrate redis://localhost amqp://localhost
  84. This command will migrate all the tasks on one broker to another.
  85. As this command is new and experimental you should be sure to have
  86. a backup of the data before proceeding.
  87. .. note::
  88. All ``inspect`` and ``control`` commands supports a
  89. :option:`--timeout <celery inspect --timeout>` argument,
  90. This is the number of seconds to wait for responses.
  91. You may have to increase this timeout if you're not getting a response
  92. due to latency.
  93. .. _inspect-destination:
  94. Specifying destination nodes
  95. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  96. By default the inspect and control commands operates on all workers.
  97. You can specify a single, or a list of workers by using the
  98. :option:`--destination <celery inspect --destination>` argument:
  99. .. code-block:: console
  100. $ celery -A proj inspect -d w1,w2 reserved
  101. $ celery -A proj control -d w1,w2 enable_events
  102. .. _monitoring-flower:
  103. Flower: Real-time Celery web-monitor
  104. ------------------------------------
  105. Flower is a real-time web based monitor and administration tool for Celery.
  106. It is under active development, but is already an essential tool.
  107. Being the recommended monitor for Celery, it obsoletes the Django-Admin
  108. monitor, ``celerymon`` and the ``ncurses`` based monitor.
  109. Flower is pronounced like "flow", but you can also use the botanical version
  110. if you prefer.
  111. Features
  112. ~~~~~~~~
  113. - Real-time monitoring using Celery Events
  114. - Task progress and history
  115. - Ability to show task details (arguments, start time, run-time, and more)
  116. - Graphs and statistics
  117. - Remote Control
  118. - View worker status and statistics
  119. - Shutdown and restart worker instances
  120. - Control worker pool size and autoscale settings
  121. - View and modify the queues a worker instance consumes from
  122. - View currently running tasks
  123. - View scheduled tasks (ETA/countdown)
  124. - View reserved and revoked tasks
  125. - Apply time and rate limits
  126. - Configuration viewer
  127. - Revoke or terminate tasks
  128. - HTTP API
  129. - List workers
  130. - Shut down a worker
  131. - Restart worker’s pool
  132. - Grow worker’s pool
  133. - Shrink worker’s pool
  134. - Autoscale worker pool
  135. - Start consuming from a queue
  136. - Stop consuming from a queue
  137. - List tasks
  138. - List (seen) task types
  139. - Get a task info
  140. - Execute a task
  141. - Execute a task by name
  142. - Get a task result
  143. - Change soft and hard time limits for a task
  144. - Change rate limit for a task
  145. - Revoke a task
  146. - OpenID authentication
  147. **Screenshots**
  148. .. figure:: ../images/dashboard.png
  149. :width: 700px
  150. .. figure:: ../images/monitor.png
  151. :width: 700px
  152. More screenshots_:
  153. .. _screenshots: https://github.com/mher/flower/tree/master/docs/screenshots
  154. Usage
  155. ~~~~~
  156. You can use pip to install Flower:
  157. .. code-block:: console
  158. $ pip install flower
  159. Running the flower command will start a web-server that you can visit:
  160. .. code-block:: console
  161. $ celery -A proj flower
  162. The default port is http://localhost:5555, but you can change this using the
  163. :option:`--port <flower --port>` argument:
  164. .. code-block:: console
  165. $ celery -A proj flower --port=5555
  166. Broker URL can also be passed through the
  167. :option:`--broker <celery --broker>` argument :
  168. .. code-block:: console
  169. $ celery flower --broker=amqp://guest:guest@localhost:5672//
  170. or
  171. $ celery flower --broker=redis://guest:guest@localhost:6379/0
  172. Then, you can visit flower in your web browser :
  173. .. code-block:: console
  174. $ open http://localhost:5555
  175. Flower has many more features than are detailed here, including
  176. authorization options. Check out the `official documentation`_ for more
  177. information.
  178. .. _official documentation: http://flower.readthedocs.org/en/latest/
  179. .. _monitoring-celeryev:
  180. celery events: Curses Monitor
  181. -----------------------------
  182. .. versionadded:: 2.0
  183. `celery events` is a simple curses monitor displaying
  184. task and worker history. You can inspect the result and traceback of tasks,
  185. and it also supports some management commands like rate limiting and shutting
  186. down workers. This monitor was started as a proof of concept, and you
  187. probably want to use Flower instead.
  188. Starting:
  189. .. code-block:: console
  190. $ celery -A proj events
  191. You should see a screen like:
  192. .. figure:: ../images/celeryevshotsm.jpg
  193. `celery events` is also used to start snapshot cameras (see
  194. :ref:`monitoring-snapshots`:
  195. .. code-block:: console
  196. $ celery -A proj events --camera=<camera-class> --frequency=1.0
  197. and it includes a tool to dump events to :file:`stdout`:
  198. .. code-block:: console
  199. $ celery -A proj events --dump
  200. For a complete list of options use :option:`--help <celery --help>`:
  201. .. code-block:: console
  202. $ celery events --help
  203. .. _`celerymon`: https://github.com/celery/celerymon/
  204. .. _monitoring-rabbitmq:
  205. RabbitMQ
  206. ========
  207. To manage a Celery cluster it is important to know how
  208. RabbitMQ can be monitored.
  209. RabbitMQ ships with the `rabbitmqctl(1)`_ command,
  210. with this you can list queues, exchanges, bindings,
  211. queue lengths, the memory usage of each queue, as well
  212. as manage users, virtual hosts and their permissions.
  213. .. note::
  214. The default virtual host (``"/"``) is used in these
  215. examples, if you use a custom virtual host you have to add
  216. the ``-p`` argument to the command, e.g:
  217. ``rabbitmqctl list_queues -p my_vhost …``
  218. .. _`rabbitmqctl(1)`: http://www.rabbitmq.com/man/rabbitmqctl.1.man.html
  219. .. _monitoring-rmq-queues:
  220. Inspecting queues
  221. -----------------
  222. Finding the number of tasks in a queue:
  223. .. code-block:: console
  224. $ rabbitmqctl list_queues name messages messages_ready \
  225. messages_unacknowledged
  226. Here `messages_ready` is the number of messages ready
  227. for delivery (sent but not received), `messages_unacknowledged`
  228. is the number of messages that has been received by a worker but
  229. not acknowledged yet (meaning it is in progress, or has been reserved).
  230. `messages` is the sum of ready and unacknowledged messages.
  231. Finding the number of workers currently consuming from a queue:
  232. .. code-block:: console
  233. $ rabbitmqctl list_queues name consumers
  234. Finding the amount of memory allocated to a queue:
  235. .. code-block:: console
  236. $ rabbitmqctl list_queues name memory
  237. :Tip: Adding the ``-q`` option to `rabbitmqctl(1)`_ makes the output
  238. easier to parse.
  239. .. _monitoring-redis:
  240. Redis
  241. =====
  242. If you're using Redis as the broker, you can monitor the Celery cluster using
  243. the `redis-cli(1)` command to list lengths of queues.
  244. .. _monitoring-redis-queues:
  245. Inspecting queues
  246. -----------------
  247. Finding the number of tasks in a queue:
  248. .. code-block:: console
  249. $ redis-cli -h HOST -p PORT -n DATABASE_NUMBER llen QUEUE_NAME
  250. The default queue is named `celery`. To get all available queues, invoke:
  251. .. code-block:: console
  252. $ redis-cli -h HOST -p PORT -n DATABASE_NUMBER keys \*
  253. .. note::
  254. Queue keys only exists when there are tasks in them, so if a key
  255. does not exist it simply means there are no messages in that queue.
  256. This is because in Redis a list with no elements in it is automatically
  257. removed, and hence it won't show up in the `keys` command output,
  258. and `llen` for that list returns 0.
  259. Also, if you're using Redis for other purposes, the
  260. output of the `keys` command will include unrelated values stored in
  261. the database. The recommended way around this is to use a
  262. dedicated `DATABASE_NUMBER` for Celery, you can also use
  263. database numbers to separate Celery applications from each other (virtual
  264. hosts), but this will not affect the monitoring events used by e.g. Flower
  265. as Redis pub/sub commands are global rather than database based.
  266. .. _monitoring-munin:
  267. Munin
  268. =====
  269. This is a list of known Munin plug-ins that can be useful when
  270. maintaining a Celery cluster.
  271. * ``rabbitmq-munin``: Munin plug-ins for RabbitMQ.
  272. https://github.com/ask/rabbitmq-munin
  273. * ``celery_tasks``: Monitors the number of times each task type has
  274. been executed (requires `celerymon`).
  275. http://exchange.munin-monitoring.org/plugins/celery_tasks-2/details
  276. * ``celery_task_states``: Monitors the number of tasks in each state
  277. (requires `celerymon`).
  278. http://exchange.munin-monitoring.org/plugins/celery_tasks/details
  279. .. _monitoring-events:
  280. Events
  281. ======
  282. The worker has the ability to send a message whenever some event
  283. happens. These events are then captured by tools like Flower,
  284. and :program:`celery events` to monitor the cluster.
  285. .. _monitoring-snapshots:
  286. Snapshots
  287. ---------
  288. .. versionadded:: 2.1
  289. Even a single worker can produce a huge amount of events, so storing
  290. the history of all events on disk may be very expensive.
  291. A sequence of events describes the cluster state in that time period,
  292. by taking periodic snapshots of this state you can keep all history, but
  293. still only periodically write it to disk.
  294. To take snapshots you need a Camera class, with this you can define
  295. what should happen every time the state is captured; You can
  296. write it to a database, send it by email or something else entirely.
  297. :program:`celery events` is then used to take snapshots with the camera,
  298. for example if you want to capture state every 2 seconds using the
  299. camera ``myapp.Camera`` you run :program:`celery events` with the following
  300. arguments:
  301. .. code-block:: console
  302. $ celery -A proj events -c myapp.Camera --frequency=2.0
  303. .. _monitoring-camera:
  304. Custom Camera
  305. ~~~~~~~~~~~~~
  306. Cameras can be useful if you need to capture events and do something
  307. with those events at an interval. For real-time event processing
  308. you should use :class:`@events.Receiver` directly, like in
  309. :ref:`event-real-time-example`.
  310. Here is an example camera, dumping the snapshot to screen:
  311. .. code-block:: python
  312. from pprint import pformat
  313. from celery.events.snapshot import Polaroid
  314. class DumpCam(Polaroid):
  315. clear_after = True # clear after flush (incl, state.event_count).
  316. def on_shutter(self, state):
  317. if not state.event_count:
  318. # No new events since last snapshot.
  319. return
  320. print('Workers: {0}'.format(pformat(state.workers, indent=4)))
  321. print('Tasks: {0}'.format(pformat(state.tasks, indent=4)))
  322. print('Total: {0.event_count} events, {0.task_count} tasks'.format(
  323. state))
  324. See the API reference for :mod:`celery.events.state` to read more
  325. about state objects.
  326. Now you can use this cam with :program:`celery events` by specifying
  327. it with the :option:`-c <celery events -c>` option:
  328. .. code-block:: console
  329. $ celery -A proj events -c myapp.DumpCam --frequency=2.0
  330. Or you can use it programmatically like this:
  331. .. code-block:: python
  332. from celery import Celery
  333. from myapp import DumpCam
  334. def main(app, freq=1.0):
  335. state = app.events.State()
  336. with app.connection() as connection:
  337. recv = app.events.Receiver(connection, handlers={'*': state.event})
  338. with DumpCam(state, freq=freq):
  339. recv.capture(limit=None, timeout=None)
  340. if __name__ == '__main__':
  341. app = Celery(broker='amqp://guest@localhost//')
  342. main(app)
  343. .. _event-real-time-example:
  344. Real-time processing
  345. --------------------
  346. To process events in real-time you need the following
  347. - An event consumer (this is the ``Receiver``)
  348. - A set of handlers called when events come in.
  349. You can have different handlers for each event type,
  350. or a catch-all handler can be used ('*')
  351. - State (optional)
  352. :class:`@events.State` is a convenient in-memory representation
  353. of tasks and workers in the cluster that is updated as events come in.
  354. It encapsulates solutions for many common things, like checking if a
  355. worker is still alive (by verifying heartbeats), merging event fields
  356. together as events come in, making sure time-stamps are in sync, and so on.
  357. Combining these you can easily process events in real-time:
  358. .. code-block:: python
  359. from celery import Celery
  360. def my_monitor(app):
  361. state = app.events.State()
  362. def announce_failed_tasks(event):
  363. state.event(event)
  364. # task name is sent only with -received event, and state
  365. # will keep track of this for us.
  366. task = state.tasks.get(event['uuid'])
  367. print('TASK FAILED: %s[%s] %s' % (
  368. task.name, task.uuid, task.info(),))
  369. with app.connection() as connection:
  370. recv = app.events.Receiver(connection, handlers={
  371. 'task-failed': announce_failed_tasks,
  372. '*': state.event,
  373. })
  374. recv.capture(limit=None, timeout=None, wakeup=True)
  375. if __name__ == '__main__':
  376. app = Celery(broker='amqp://guest@localhost//')
  377. my_monitor(app)
  378. .. note::
  379. The ``wakeup`` argument to ``capture`` sends a signal to all workers
  380. to force them to send a heartbeat. This way you can immediately see
  381. workers when the monitor starts.
  382. You can listen to specific events by specifying the handlers:
  383. .. code-block:: python
  384. from celery import Celery
  385. def my_monitor(app):
  386. state = app.events.State()
  387. def announce_failed_tasks(event):
  388. state.event(event)
  389. # task name is sent only with -received event, and state
  390. # will keep track of this for us.
  391. task = state.tasks.get(event['uuid'])
  392. print('TASK FAILED: %s[%s] %s' % (
  393. task.name, task.uuid, task.info(),))
  394. with app.connection() as connection:
  395. recv = app.events.Receiver(connection, handlers={
  396. 'task-failed': announce_failed_tasks,
  397. })
  398. recv.capture(limit=None, timeout=None, wakeup=True)
  399. if __name__ == '__main__':
  400. app = Celery(broker='amqp://guest@localhost//')
  401. my_monitor(app)
  402. .. _event-reference:
  403. Event Reference
  404. ===============
  405. This list contains the events sent by the worker, and their arguments.
  406. .. _event-reference-task:
  407. Task Events
  408. -----------
  409. .. event:: task-sent
  410. task-sent
  411. ~~~~~~~~~
  412. :signature: ``task-sent(uuid, name, args, kwargs, retries, eta, expires,
  413. queue, exchange, routing_key, root_id, parent_id)``
  414. Sent when a task message is published and
  415. the :setting:`task_send_sent_event` setting is enabled.
  416. .. event:: task-received
  417. task-received
  418. ~~~~~~~~~~~~~
  419. :signature: ``task-received(uuid, name, args, kwargs, retries, eta, hostname,
  420. timestamp, root_id, parent_id)``
  421. Sent when the worker receives a task.
  422. .. event:: task-started
  423. task-started
  424. ~~~~~~~~~~~~
  425. :signature: ``task-started(uuid, hostname, timestamp, pid)``
  426. Sent just before the worker executes the task.
  427. .. event:: task-succeeded
  428. task-succeeded
  429. ~~~~~~~~~~~~~~
  430. :signature: ``task-succeeded(uuid, result, runtime, hostname, timestamp)``
  431. Sent if the task executed successfully.
  432. Run-time is the time it took to execute the task using the pool.
  433. (Starting from the task is sent to the worker pool, and ending when the
  434. pool result handler callback is called).
  435. .. event:: task-failed
  436. task-failed
  437. ~~~~~~~~~~~
  438. :signature: ``task-failed(uuid, exception, traceback, hostname, timestamp)``
  439. Sent if the execution of the task failed.
  440. .. event:: task-rejected
  441. task-rejected
  442. ~~~~~~~~~~~~~
  443. :signature: ``task-rejected(uuid, requeued)``
  444. The task was rejected by the worker, possibly to be re-queued or moved to a
  445. dead letter queue.
  446. .. event:: task-revoked
  447. task-revoked
  448. ~~~~~~~~~~~~
  449. :signature: ``task-revoked(uuid, terminated, signum, expired)``
  450. Sent if the task has been revoked (Note that this is likely
  451. to be sent by more than one worker).
  452. - ``terminated`` is set to true if the task process was terminated,
  453. and the ``signum`` field set to the signal used.
  454. - ``expired`` is set to true if the task expired.
  455. .. event:: task-retried
  456. task-retried
  457. ~~~~~~~~~~~~
  458. :signature: ``task-retried(uuid, exception, traceback, hostname, timestamp)``
  459. Sent if the task failed, but will be retried in the future.
  460. .. _event-reference-worker:
  461. Worker Events
  462. -------------
  463. .. event:: worker-online
  464. worker-online
  465. ~~~~~~~~~~~~~
  466. :signature: ``worker-online(hostname, timestamp, freq, sw_ident, sw_ver, sw_sys)``
  467. The worker has connected to the broker and is online.
  468. - `hostname`: Nodename of the worker.
  469. - `timestamp`: Event time-stamp.
  470. - `freq`: Heartbeat frequency in seconds (float).
  471. - `sw_ident`: Name of worker software (e.g. ``py-celery``).
  472. - `sw_ver`: Software version (e.g. 2.2.0).
  473. - `sw_sys`: Operating System (e.g. Linux, Windows, Darwin).
  474. .. event:: worker-heartbeat
  475. worker-heartbeat
  476. ~~~~~~~~~~~~~~~~
  477. :signature: ``worker-heartbeat(hostname, timestamp, freq, sw_ident, sw_ver, sw_sys,
  478. active, processed)``
  479. Sent every minute, if the worker has not sent a heartbeat in 2 minutes,
  480. it is considered to be offline.
  481. - `hostname`: Nodename of the worker.
  482. - `timestamp`: Event time-stamp.
  483. - `freq`: Heartbeat frequency in seconds (float).
  484. - `sw_ident`: Name of worker software (e.g. ``py-celery``).
  485. - `sw_ver`: Software version (e.g. 2.2.0).
  486. - `sw_sys`: Operating System (e.g. Linux, Windows, Darwin).
  487. - `active`: Number of currently executing tasks.
  488. - `processed`: Total number of tasks processed by this worker.
  489. .. event:: worker-offline
  490. worker-offline
  491. ~~~~~~~~~~~~~~
  492. :signature: ``worker-offline(hostname, timestamp, freq, sw_ident, sw_ver, sw_sys)``
  493. The worker has disconnected from the broker.