monitoring.rst 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642
  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 Utility
  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. $ celery help
  23. or to get help for a specific command do::
  24. $ celery <command> --help
  25. Commands
  26. ~~~~~~~~
  27. * **shell**: Drop into a Python shell.
  28. The locals will include the ``celery`` variable, which is the current app.
  29. Also all known tasks will be automatically added to locals (unless the
  30. ``--without-tasks`` flag is set).
  31. Uses Ipython, bpython, or regular python in that order if installed.
  32. You can force an implementation using ``--force-ipython|-I``,
  33. ``--force-bpython|-B``, or ``--force-python|-P``.
  34. * **status**: List active nodes in this cluster
  35. ::
  36. $ celery status
  37. * **result**: Show the result of a task
  38. ::
  39. $ celery result -t tasks.add 4e196aa4-0141-4601-8138-7aa33db0f577
  40. Note that you can omit the name of the task as long as the
  41. task doesn't use a custom result backend.
  42. * **purge**: Purge messages from all configured task queues.
  43. ::
  44. $ celery purge
  45. .. warning::
  46. There is no undo for this operation, and messages will
  47. be permanently deleted!
  48. * **inspect active**: List active tasks
  49. ::
  50. $ celery inspect active
  51. These are all the tasks that are currently being executed.
  52. * **inspect scheduled**: List scheduled ETA tasks
  53. ::
  54. $ celery inspect scheduled
  55. These are tasks reserved by the worker because they have the
  56. `eta` or `countdown` argument set.
  57. * **inspect reserved**: List reserved tasks
  58. ::
  59. $ celery inspect reserved
  60. This will list all tasks that have been prefetched by the worker,
  61. and is currently waiting to be executed (does not include tasks
  62. with an eta).
  63. * **inspect revoked**: List history of revoked tasks
  64. ::
  65. $ celery inspect revoked
  66. * **inspect registered**: List registered tasks
  67. ::
  68. $ celery inspect registered
  69. * **inspect stats**: Show worker statistics
  70. ::
  71. $ celery inspect stats
  72. * **control enable_events**: Enable events
  73. ::
  74. $ celery control enable_events
  75. * **control disable_events**: Disable events
  76. ::
  77. $ celery inspect disable_events
  78. * **migrate**: Migrate tasks from one broker to another (**EXPERIMENTAL**).
  79. ::
  80. $ celery migrate redis://localhost amqp://localhost
  81. This command will migrate all the tasks on one broker to another.
  82. As this command is new and experimental you should be sure to have
  83. a backup of the data before proceeding.
  84. .. note::
  85. All ``inspect`` commands supports a ``--timeout`` argument,
  86. This is the number of seconds to wait for responses.
  87. You may have to increase this timeout if you're not getting a response
  88. due to latency.
  89. .. _celeryctl-inspect-destination:
  90. Specifying destination nodes
  91. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  92. By default the inspect commands operates on all workers.
  93. You can specify a single, or a list of workers by using the
  94. `--destination` argument::
  95. $ celery inspect -d w1,w2 reserved
  96. .. _monitoring-django-admin:
  97. Celery Flower: Web interface
  98. ----------------------------
  99. Celery Flower is a web based, real-time monitor and administration tool.
  100. Features
  101. ~~~~~~~~
  102. * Workers monitoring and management
  103. * Configuration viewer
  104. * Worker pool control
  105. * Broker options viewer
  106. * Queues management
  107. * Tasks execution statistics
  108. * Task viewer
  109. *Screenshot*
  110. .. figure:: https://github.com/mher/flower/raw/master/docs/screenshots/dashborad.png
  111. More screenshots_:
  112. .. _screenshots: https://github.com/mher/flower/tree/master/docs/screenshots
  113. Usage
  114. ~~~~~
  115. Install Celery Flower: ::
  116. $ pip install flower
  117. Launch Celery Flower and open http://localhost:8008 in browser: ::
  118. $ celery flower
  119. Django Admin Monitor
  120. --------------------
  121. .. versionadded:: 2.1
  122. When you add `django-celery`_ to your Django project you will
  123. automatically get a monitor section as part of the Django admin interface.
  124. This can also be used if you're not using Celery with a Django project.
  125. *Screenshot*
  126. .. figure:: ../images/djangoceleryadmin2.jpg
  127. .. _`django-celery`: http://pypi.python.org/pypi/django-celery
  128. .. _monitoring-django-starting:
  129. Starting the monitor
  130. ~~~~~~~~~~~~~~~~~~~~
  131. The Celery section will already be present in your admin interface,
  132. but you won't see any data appearing until you start the snapshot camera.
  133. The camera takes snapshots of the events your workers sends at regular
  134. intervals, storing them in your database (See :ref:`monitoring-snapshots`).
  135. To start the camera run::
  136. $ python manage.py celerycam
  137. If you haven't already enabled the sending of events you need to do so::
  138. $ python manage.py celery control enable_events
  139. :Tip: You can enable events when the worker starts using the `-E` argument.
  140. Now that the camera has been started, and events have been enabled
  141. you should be able to see your workers and the tasks in the admin interface
  142. (it may take some time for workers to show up).
  143. The admin interface shows tasks, worker nodes, and even
  144. lets you perform some actions, like revoking and rate limiting tasks,
  145. or shutting down worker nodes.
  146. .. _monitoring-django-frequency:
  147. Shutter frequency
  148. ~~~~~~~~~~~~~~~~~
  149. By default the camera takes a snapshot every second, if this is too frequent
  150. or you want to have higher precision, then you can change this using the
  151. ``--frequency`` argument. This is a float describing how often, in seconds,
  152. it should wake up to check if there are any new events::
  153. $ python manage.py celerycam --frequency=3.0
  154. The camera also supports rate limiting using the ``--maxrate`` argument.
  155. While the frequency controls how often the camera thread wakes up,
  156. the rate limit controls how often it will actually take a snapshot.
  157. The rate limits can be specified in seconds, minutes or hours
  158. by appending `/s`, `/m` or `/h` to the value.
  159. Example: ``--maxrate=100/m``, means "hundred writes a minute".
  160. The rate limit is off by default, which means it will take a snapshot
  161. for every ``--frequency`` seconds.
  162. The events also expire after some time, so the database doesn't fill up.
  163. Successful tasks are deleted after 1 day, failed tasks after 3 days,
  164. and tasks in other states after 5 days.
  165. .. _monitoring-nodjango:
  166. Using outside of Django
  167. ~~~~~~~~~~~~~~~~~~~~~~~
  168. `django-celery` also installs the :program:`djcelerymon` program. This
  169. can be used by non-Django users, and runs both a web server and a snapshot
  170. camera in the same process.
  171. **Installing**
  172. Using :program:`pip`::
  173. $ pip install -U django-celery
  174. or using :program:`easy_install`::
  175. $ easy_install -U django-celery
  176. **Running**
  177. :program:`djcelerymon` reads configuration from your Celery configuration
  178. module, and sets up the Django environment using the same settings::
  179. $ djcelerymon
  180. Database tables will be created the first time the monitor is run.
  181. By default an `sqlite3` database file named
  182. :file:`djcelerymon.db` is used, so make sure this file is writeable by the
  183. user running the monitor.
  184. If you want to store the events in a different database, e.g. MySQL,
  185. then you can configure the `DATABASE*` settings directly in your Celery
  186. config module. See http://docs.djangoproject.com/en/dev/ref/settings/#databases
  187. for more information about the database options available.
  188. You will also be asked to create a superuser (and you need to create one
  189. to be able to log into the admin later)::
  190. Creating table auth_permission
  191. Creating table auth_group_permissions
  192. [...]
  193. You just installed Django's auth system, which means you don't
  194. have any superusers defined. Would you like to create
  195. one now? (yes/no): yes
  196. Username (Leave blank to use 'username'): username
  197. Email address: me@example.com
  198. Password: ******
  199. Password (again): ******
  200. Superuser created successfully.
  201. [...]
  202. Django version 1.2.1, using settings 'celeryconfig'
  203. Development server is running at http://127.0.0.1:8000/
  204. Quit the server with CONTROL-C.
  205. Now that the service is started you can visit the monitor
  206. at http://127.0.0.1:8000, and log in using the user you created.
  207. For a list of the command line options supported by :program:`djcelerymon`,
  208. please see ``djcelerymon --help``.
  209. .. _monitoring-celeryev:
  210. celery events: Curses Monitor
  211. -----------------------------
  212. .. versionadded:: 2.0
  213. `celery events` is a simple curses monitor displaying
  214. task and worker history. You can inspect the result and traceback of tasks,
  215. and it also supports some management commands like rate limiting and shutting
  216. down workers.
  217. Starting::
  218. $ celery events
  219. You should see a screen like:
  220. .. figure:: ../images/celeryevshotsm.jpg
  221. `celery events` is also used to start snapshot cameras (see
  222. :ref:`monitoring-snapshots`::
  223. $ celery events --camera=<camera-class> --frequency=1.0
  224. and it includes a tool to dump events to :file:`stdout`::
  225. $ celery events --dump
  226. For a complete list of options use ``--help``::
  227. $ celery events --help
  228. .. _monitoring-celerymon:
  229. celerymon: Web monitor
  230. ----------------------
  231. `celerymon`_ is the ongoing work to create a web monitor.
  232. It's far from complete yet, and does currently only support
  233. a JSON API. Help is desperately needed for this project, so if you,
  234. or someone you know would like to contribute templates, design, code
  235. or help this project in any way, please get in touch!
  236. :Tip: The Django admin monitor can be used even though you're not using
  237. Celery with a Django project. See :ref:`monitoring-nodjango`.
  238. .. _`celerymon`: http://github.com/celery/celerymon/
  239. .. _monitoring-rabbitmq:
  240. RabbitMQ
  241. ========
  242. To manage a Celery cluster it is important to know how
  243. RabbitMQ can be monitored.
  244. RabbitMQ ships with the `rabbitmqctl(1)`_ command,
  245. with this you can list queues, exchanges, bindings,
  246. queue lengths, the memory usage of each queue, as well
  247. as manage users, virtual hosts and their permissions.
  248. .. note::
  249. The default virtual host (``"/"``) is used in these
  250. examples, if you use a custom virtual host you have to add
  251. the ``-p`` argument to the command, e.g:
  252. ``rabbitmqctl list_queues -p my_vhost ....``
  253. .. _`rabbitmqctl(1)`: http://www.rabbitmq.com/man/rabbitmqctl.1.man.html
  254. .. _monitoring-rmq-queues:
  255. Inspecting queues
  256. -----------------
  257. Finding the number of tasks in a queue::
  258. $ rabbitmqctl list_queues name messages messages_ready \
  259. messages_unacknowledged
  260. Here `messages_ready` is the number of messages ready
  261. for delivery (sent but not received), `messages_unacknowledged`
  262. is the number of messages that has been received by a worker but
  263. not acknowledged yet (meaning it is in progress, or has been reserved).
  264. `messages` is the sum of ready and unacknowledged messages.
  265. Finding the number of workers currently consuming from a queue::
  266. $ rabbitmqctl list_queues name consumers
  267. Finding the amount of memory allocated to a queue::
  268. $ rabbitmqctl list_queues name memory
  269. :Tip: Adding the ``-q`` option to `rabbitmqctl(1)`_ makes the output
  270. easier to parse.
  271. .. _monitoring-redis:
  272. Redis
  273. =====
  274. If you're using Redis as the broker, you can monitor the Celery cluster using
  275. the `redis-cli(1)` command to list lengths of queues.
  276. .. _monitoring-redis-queues:
  277. Inspecting queues
  278. -----------------
  279. Finding the number of tasks in a queue::
  280. $ redis-cli -h HOST -p PORT -n DATABASE_NUMBER llen QUEUE_NAME
  281. The default queue is named `celery`. To get all available queues, invoke::
  282. $ redis-cli -h HOST -p PORT -n DATABASE_NUMBER keys \*
  283. .. note::
  284. If a list has no elements in Redis, it doesn't exist. Hence it won't show up
  285. in the `keys` command output. `llen` for that list returns 0 in that case.
  286. On the other hand, if you're also using Redis for other purposes, the output
  287. of the `keys` command will include unrelated values stored in the database.
  288. The recommended way around this is to use a dedicated `DATABASE_NUMBER` for
  289. Celery.
  290. .. _monitoring-munin:
  291. Munin
  292. =====
  293. This is a list of known Munin plug-ins that can be useful when
  294. maintaining a Celery cluster.
  295. * rabbitmq-munin: Munin plug-ins for RabbitMQ.
  296. http://github.com/ask/rabbitmq-munin
  297. * celery_tasks: Monitors the number of times each task type has
  298. been executed (requires `celerymon`).
  299. http://exchange.munin-monitoring.org/plugins/celery_tasks-2/details
  300. * celery_task_states: Monitors the number of tasks in each state
  301. (requires `celerymon`).
  302. http://exchange.munin-monitoring.org/plugins/celery_tasks/details
  303. .. _monitoring-events:
  304. Events
  305. ======
  306. The worker has the ability to send a message whenever some event
  307. happens. These events are then captured by tools like :program:`celerymon`
  308. and :program:`celery events` to monitor the cluster.
  309. .. _monitoring-snapshots:
  310. Snapshots
  311. ---------
  312. .. versionadded:: 2.1
  313. Even a single worker can produce a huge amount of events, so storing
  314. the history of all events on disk may be very expensive.
  315. A sequence of events describes the cluster state in that time period,
  316. by taking periodic snapshots of this state we can keep all history, but
  317. still only periodically write it to disk.
  318. To take snapshots you need a Camera class, with this you can define
  319. what should happen every time the state is captured; You can
  320. write it to a database, send it by email or something else entirely.
  321. :program:`celery events` is then used to take snapshots with the camera,
  322. for example if you want to capture state every 2 seconds using the
  323. camera ``myapp.Camera`` you run :program:`celery events` with the following
  324. arguments::
  325. $ celery events -c myapp.Camera --frequency=2.0
  326. .. _monitoring-camera:
  327. Custom Camera
  328. ~~~~~~~~~~~~~
  329. Here is an example camera, dumping the snapshot to screen:
  330. .. code-block:: python
  331. from pprint import pformat
  332. from celery.events.snapshot import Polaroid
  333. class DumpCam(Polaroid):
  334. def on_shutter(self, state):
  335. if not state.event_count:
  336. # No new events since last snapshot.
  337. return
  338. print('Workers: %s' % (pformat(state.workers, indent=4), ))
  339. print('Tasks: %s' % (pformat(state.tasks, indent=4), ))
  340. print('Total: %s events, %s tasks' % (
  341. state.event_count, state.task_count))
  342. See the API reference for :mod:`celery.events.state` to read more
  343. about state objects.
  344. Now you can use this cam with :program:`celery events` by specifying
  345. it with the `-c` option::
  346. $ celery events -c myapp.DumpCam --frequency=2.0
  347. Or you can use it programmatically like this::
  348. from celery.events import EventReceiver
  349. from celery.messaging import establish_connection
  350. from celery.events.state import State
  351. from myapp import DumpCam
  352. def main():
  353. state = State()
  354. with establish_connection() as connection:
  355. recv = EventReceiver(connection, handlers={'*': state.event})
  356. with DumpCam(state, freq=1.0):
  357. recv.capture(limit=None, timeout=None)
  358. if __name__ == '__main__':
  359. main()
  360. .. _event-reference:
  361. Event Reference
  362. ---------------
  363. This list contains the events sent by the worker, and their arguments.
  364. .. _event-reference-task:
  365. Task Events
  366. ~~~~~~~~~~~
  367. * ``task-sent(uuid, name, args, kwargs, retries, eta, expires,
  368. queue, exchange, routing_key)``
  369. Sent when a task message is published and
  370. the :setting:`CELERY_SEND_TASK_SENT_EVENT` setting is enabled.
  371. * ``task-received(uuid, name, args, kwargs, retries, eta, hostname,
  372. timestamp)``
  373. Sent when the worker receives a task.
  374. * ``task-started(uuid, hostname, timestamp, pid)``
  375. Sent just before the worker executes the task.
  376. * ``task-succeeded(uuid, result, runtime, hostname, timestamp)``
  377. Sent if the task executed successfully.
  378. Runtime is the time it took to execute the task using the pool.
  379. (Starting from the task is sent to the worker pool, and ending when the
  380. pool result handler callback is called).
  381. * ``task-failed(uuid, exception, traceback, hostname, timestamp)``
  382. Sent if the execution of the task failed.
  383. * ``task-revoked(uuid)``
  384. Sent if the task has been revoked (Note that this is likely
  385. to be sent by more than one worker).
  386. * ``task-retried(uuid, exception, traceback, hostname, timestamp)``
  387. Sent if the task failed, but will be retried in the future.
  388. .. _event-reference-worker:
  389. Worker Events
  390. ~~~~~~~~~~~~~
  391. * ``worker-online(hostname, timestamp, freq, sw_ident, sw_ver, sw_sys)``
  392. The worker has connected to the broker and is online.
  393. * `hostname`: Hostname of the worker.
  394. * `timestamp`: Event timestamp.
  395. * `freq`: Heartbeat frequency in seconds (float).
  396. * `sw_ident`: Name of worker software (e.g. ``py-celery``).
  397. * `sw_ver`: Software version (e.g. 2.2.0).
  398. * `sw_sys`: Operating System (e.g. Linux, Windows, Darwin).
  399. * ``worker-heartbeat(hostname, timestamp, freq, sw_ident, sw_ver, sw_sys)``
  400. Sent every minute, if the worker has not sent a heartbeat in 2 minutes,
  401. it is considered to be offline.
  402. * ``worker-offline(hostname, timestamp, freq, sw_ident, sw_ver, sw_sys)``
  403. The worker has disconnected from the broker.