monitoring.rst 18 KB

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