Rabbitmq не работает админка

Содержание
  1. Невозможно получить доступ к веб-интерфейсу управления RabbitMQ после новой установки
  2. ОТВЕТЫ
  3. Ответ 1
  4. Ответ 2
  5. Ответ 3
  6. Не удается включить плагин rabbitmq-management в Windows
  7. 7 ответов
  8. Can’t access RabbitMQ web management interface after fresh install
  9. 5 Answers 5
  10. Установка RabbitMQ на windows 10
  11. Установка Erlang
  12. Установка RabbitMQ
  13. Установка плагина управления RabbitMQ с WEB-интерфейса
  14. Протестируем работу сервиса
  15. Резюме
  16. Subscribe to Блог php программиста: статьи по PHP, JavaScript, MySql
  17. Management Plugin
  18. Overview
  19. Management UI and External Monitoring Systems
  20. Getting Started
  21. Usage
  22. Management UI Access
  23. Notable Features
  24. Management UI Access in Clusters
  25. Access and Permissions
  26. Command Line Examples
  27. Authenticating with OAuth 2
  28. HTTP API
  29. API Endpoints
  30. HTTP API and Monitoring
  31. HTTP API Clients and Tooling
  32. Configuration
  33. HTTPS
  34. Using HTTP and HTTPS Together
  35. Advanced HTTP Options
  36. Response Compression
  37. Client Inactivity Timeouts
  38. HTTP Request Logging
  39. Statistics Interval
  40. Message Rates
  41. Sample (Data Point) Retention
  42. Disable statistics and metrics collection
  43. Content Security Policy (CSP)
  44. Strict Transport Security (HSTS)
  45. Cross-origin Resource Sharing (CORS)
  46. Login Session Timeout
  47. Path Prefix
  48. Example
  49. Loading Definitions (Schema) at Startup
  50. Metrics Collection and HTTP API in Clusters
  51. Client Requests
  52. Running Management Plugin on a Subset of Nodes
  53. Aggregation Queries in Clusters
  54. (Reverse HTTP) Proxy Setup
  55. Restarting Statistics Database
  56. Memory Usage Analysis and Memory Management
  57. Publishing and Consuming over HTTP API
  58. Getting Help and Providing Feedback
  59. Help Us Improve the Docs <3

Невозможно получить доступ к веб-интерфейсу управления RabbitMQ после новой установки

Я установил последний сервер RabbitMQ (rabbitmq-server-3.3.0-1.noarch.rpm) на новую версию Centos 5.10 VM в соответствии с инструкциями на официальном сайте.

Я делал это много раз раньше во время разработки и никогда не испытывал никаких проблем. Однако на этот раз я не могу войти в веб-интерфейс управления, используя гостевой/гостевой пользователь по умолчанию.

В журналах я вижу следующее:

Что может быть причиной этого?

ОТВЕТЫ

Ответ 1

Если вы хотите, чтобы гостевой пользователь читал this или этот RabbitMQ 3.3.1 не может войти с гостями/гостями

Если вы хотите создать нового пользователя с грантами администратора:

Теперь вы можете получить доступ, используя тестовый тест.

Ответ 2

Для тех, кто когда-либо попадал в эту ветку, но все еще не может получить доступ к консоли управления после новой установки, моя проблема заключалась в том, что консоль управления не была включена, я решил ее выполнить по этой команде:

    перейти в командную строку rabbitMq

Ответ 3

Что-то, что только что случилось со мной и вызвало у меня головные боли:

Я установил новый Linux RabbitMQ-сервер и использовал оболочку script для настройки моих собственных пользователей (не гостей!).

script имел несколько таких блоков кода:

Очень похож на тот, что был в Gabriele answer, поэтому я беру его код и не нуждаюсь в исправлении паролей.

Тем не менее я не смог войти в консоль управления. Затем я заметил, что я создал настройку script в Windows (завершение строки CR + LF) и преобразовал файл в Linux (только для LF), а затем запустил установку script на моем Linux-сервере.

. и до сих пор не удалось войти в систему, потому что потребовалось еще 15 минут, пока я не понял, что вызов add_user снова и снова не будет исправлять сломанные пароли (которые, вероятно, закончились символом CR). Мне пришлось вызвать change_password для каждого пользователя, чтобы исправить мою предыдущую ошибку:

(Еще одно решение — удалить всех пользователей, а затем снова вызвать script)

Источник

Не удается включить плагин rabbitmq-management в Windows

Итак, вот что я сделал:

  1. установлен Erlang на моей Windows x64 бит-машине
  2. Установлен RabbitMQ
  3. запущен сервис RabbitMQ

на данном этапе у меня нет ошибок. Когда, Однако, я пытаюсь enabe rabbitmq-management, я получаю некоторые сообщения об ошибках в консоли. Способ, которым я пытаюсь включить его, таков:

применение конфигурации плагина кролик@Якоби. не удалось

добавить к этому, я знаю, о этой нить, но я не уверен, что эта команда означает SET HOMEDRIVE=C: . Тем не менее, я попробовал так:

но я все еще получил то же сообщение об ошибке. Спасибо!

редактировать

похоже, что RabbitMQ стало RubbishMQ . Загвоздка в том, что я следовал очень стандартным и очень основным шагам чтобы установить RabbitMQ теперь на машине Ubuntu и получил ужасный список сообщений об ошибках еще раз. Вот шаги, которым я следовал:—8—>

когда я выполнить последнюю команду я получаю тонны сообщений об ошибках. Среди них я вижу такие ,как » error_logger . Ошибка при чтении ./.Эрланг.cookie: eaccess». Итак, я думаю, что есть некоторые секретные недостающие шаги или какое-то заклинание вуду, которое может заставить его работать. Но я не знаю всего этого и надеюсь услышать некоторые советы. Это то, что я ожидаю увидеть-1) шаг Пошаговая установка RabbitMQ на Windows и пошаговый тест, что все работает 2) то же самое для Ubuntu. Готовься, Спокойно, Вперед!

7 ответов

Я столкнулся с той же проблемой, и мои исследования привели меня к https://stackoverflow.com/a/34538688 что помогло мне решить эту проблему. После выполнения шагов в этом ответе запустите службу, и проблема должна быть решена.

в основном, проблема вызвана тем, что установщик RabbitMQ не регистрирует службу правильно.

проверьте, если этот файл C:\Windows\.erlang.cookie и этот файл C:\Users\youruser\.erlang.cookie равны.

если нет, то скопировать C:\Windows\.erlang.cookie до C:\Users\youruser\.erlang.cookie

youruser является пользователем windows, который используется для включения консоли управления. например в моем случае: C:\Users\gabriele\.erlang.cookie

Try: rabbitmq-запуск сервера. Работал на меня

каким-то образом это решило мою проблему из командной строки от имени администратора.

C:\. \rabbitmq-server-3.5.6\sbin> SET HOMEDRIVE=C: C:\. \rabbitmq-server-3.5.6\sbin> rabbitmq-service remove C:\. \rabbitmq-server-3.5.6\sbin> rabbitmq-service install C:\. \rabbitmq-server-3.5.6\sbin> rabbitmq-plugins.bat enable rabbitmq_management

я столкнулся с той же проблемой, но ни одно из представленных решений мне не помогло. Может быть, кто-то найдет мое решение полезно.

команда я обнаружил, что служба RabbitMQ в диспетчере служб windows была добавлена, но не запущена. Я включил его вручную, а затем

команда работает отлично.

после этого http://localhost:15672 успешно работать

Как только я установил RabbitMQ, я не смог открыть localhost: 15672, потому что я не включил плагины, чтобы включить это открытие»Командная строка RabbitMQ (sbin dir)» и выполните следующую команду

он включит все плагины, связанные с RabbitMQ. Теперь откройте браузер и введите http://localhost:15672 он откроет вход в консоль RabbitMQ с «гость Как имя пользователя» и » гость Как пароль.»

вот шаги, которые я сделал, чтобы исправить проблему.

  1. удалить RabbitMQ и Erlang
  2. удалить записи реестра в разделе HKLM / SOFTWARE/Ericsson/Erlang / ErlSrv.
  3. удалить все .Эрланг.cookie (возможно, в %HOMEDRIVE%%HOMEPATH% и %SYSTEMROOT%)
  4. установите Erlang затем RabbitMQ с пользователем администратора.
  5. убедитесь, что в системной среде, ERLANG_HOME с C:\Program файлы\erlваш номер версии. Если нет, создавать.
  6. Run rabbitmq-Плагины включить rabbitmq_management из папки RabbitMQ sbin

Источник

Can’t access RabbitMQ web management interface after fresh install

I’ve installed the latest RabbitMQ server (rabbitmq-server-3.3.0-1.noarch.rpm) on a fresh Centos 5.10 VM according to the instructions on the official site.

I’ve done this many times before during development and never had any issues. However, this time I cannot log into the management web interface using the default guest/guest user.

In the logs, I see the following:

What could be causing this?

5 Answers 5

If you want enable the guest user read this or this RabbitMQ 3.3.1 can not login with guest/guest

If you want create a new user with admin grants:

Now you can access using test test.

If you still can’t access the management console after a fresh install, check if the management console was enabled. To enable it:

Go to the RabbitMQ command prompt.

Something that just happened to me and caused me some headaches:

I have set up a new Linux RabbitMQ server and used a shell script to set up my own custom users (not guest!).

The script had several of those «code» blocks:

Very similar to the one in Gabriele’s answer, so I take his code and don’t need to redact passwords.

Still I was not able to log in in the management console. Then I noticed that I had created the setup script in Windows (CR+LF line ending) and converted the file to Linux (LF only), then reran the setup script on my Linux server.

. and was still not able to log in, because it took another 15 minutes until I realized that calling add_user over and over again would not fix the broken passwords (which probably ended with a CR character). I had to call change_password for every user to fix my earlier mistake:

(Another solution would have been to delete all users and then call the script again)

Источник

Установка RabbitMQ на windows 10

RabbitMQ — это прекрасный инструмент по работе с очередями, работающий на всех популярных платформах. Если вы планируете использовать систему очередей в своём проекте, вам нужна асинхронная обработка процессов, и работа с задачами в фоне, то RabbitMQ является очень удачным выбором.

RabbitMQ — это отличный инструмент, который выполняет свои задачи превосходно. Отличным преимуществом является качественная документация и широкий спектр функциональных возможностей.

RabbitMQ считается одной из самых продвинутых систем по работе с очередями. Это всё благодаря тому, что RabbitMQ имеет много возможностей. Если хорошо разобраться в этой системе, то, в дальнейшем, работа с другими системами очередей не вызовет у вас конфуза.

Но, прежде, чем писать RabbitMQ tutorial, как обычно, начнём с установки и запуска. В этой статье я шаг за шагом продемонстрирую процесс установки. Если вы ещё не знакомы, с системами очередей, и слабо понимаете механизм их работы, то советую прочитать ранее опубликованную статью об основам очередей.

Читайте также:  Как настроить роутер ростелеком fast 1744

Установка Erlang

RabbitMQ запускается в виртуальной среде Erlang. Не спрашивайте зачем, просто установите Erlang, без которого RabbitMQ не сможет работать. Последнюю версию для windows можно скачать по ссылке.

На странице скачивания установочного файла нужно выбрать версию, в зависимости от вашей системы (в моём случае, это версия для 64-разрядного процессора):

Установка RabbitMQ

После установки Erlang следующим шагом будет установка самого RabbitMQ (ну наконец-то). Скачать последнюю версию RabbitMQ можно по ссылке.
С установкой всё просто — запускаем скачанный файл, и со всем соглашаемся.

Установка плагина управления RabbitMQ с WEB-интерфейса

После установки, RabbitMQ сразу же будет запущен, потому, можно сразу же начинать с ним работать.

Обычным для программиста является работа из консоли. Но, иногда, одной консоли бывает недостаточно. Потому, в этом шаге будет установлен плагин RabbitMQ Web для работы с очередями из WEB-интерфейса. Этот интерфейс предоставляет удобный вывод статистики, информацию о работающих процессах, логах, и т.д.

Для того, чтобы установить плагин, нужно из консоли перейти в папку sbin , которая находится по пути установки RabbitMQ (в моём случае C:\Program Files\RabbitMQ Server\rabbitmq_server-3.7.7\sbin ). При этом, запускать нужно от имени администратора.

Или же, проще нажать кнопку winsows, и начать печатать rabbit, и, из найденных результатов интересует в данном случае только RabbitMQ Command Prompt.

Запустив который мы окажемся в консоли, в нужной для работы директории.

В открывшейся консоли нужно выполнить команду
rabbitmq-plugins.bat enable rabbitmq_management ,
которая, как раз и включит этот плагин. Получиться должно что-то вроде этого:

Заключительным шагом от нас требуется перезапустить сервис, поочерёдно выполнив команды:

Теперь, удостоверимся, что все шаги были проделаны правильно, открыв ссылку в адресной строке http://localhost:15672 .

Ожидаемо должны увидеть страницу входа в WEB-интерфейс:

По умолчанию, данные для входа в панель управления:
Логин: guest
Пароль: guest

Вот, что вы должны увидеть в итоге:

На этом установка полностью завершена, и сервис RabbitMQ готов к работе. Теперь можно свободно работать, и использовать все функции этого мощного и полезного инструмента. В следующей статье по RabbitMQ будет рассмотрен практический пример по работе с системой очередей: добавление, удаление, обработка, и т.д.

Протестируем работу сервиса

Если вы всё ещё не верите мне, что RabbitMQ работает, то, для теста можете открыть ссылку http://localhost:15672/api/vhosts , пройдя базовую аутентификацию (данные для входа те же — guest:guest), и должны получить JSON-ответ с информацией о состоянии работы сервиса.

Резюме

В этой статье я показал, как установить RabbitMQ на windows 10, как протестировать его работу, и установить плагин RabbitMQ WEB (для работы в WEB-интерфейсе). Это очень крутой инструмент, который рекомендовано освоить каждому программисту.

По поводу «рекомендовано» — это мягко говоря. Сейчас RabbitMQ используется почти во всех high-load проектах. И, зачастую, во всех вакансиях (на PHP программиста) требуют именно знание системы очередей RabbitMQ. Потому, хорошее понимание этого инструмента, и опыт работы с ним повышает шансы найти работу в хорошей компании.

Subscribe to Блог php программиста: статьи по PHP, JavaScript, MySql

Get the latest posts delivered right to your inbox

Источник

Management Plugin

Overview

The RabbitMQ management plugin provides an HTTP-based API for management and monitoring of RabbitMQ nodes and clusters, along with a browser-based UI and a command line tool, rabbitmqadmin.

It periodically collects and aggregates data about many aspects of the system. Those metrics are exposed to both operators in the UI and monitoring systems for long term storage, alerting, visualisation, chart analysis and so on.

The plugin can be configured to use HTTPS, OAuth 2, a non-standard port, path prefix, HTTP server options, custom strict transport security settings, cross-origin resource sharing, and more.

Some settings directly affect CPU resource usage of the metric collection system and this plugin:

The plugin also provides tools for analysing memory usage of the node, and other features related to monitoring, metrics, user, permission, and topology management. Previously it also provided definition export and import functionality. Those are now core RabbitMQ features and do not require or rely on this plugin.

In a multi-node cluster, management plugin is most commonly enabled on every node.

The plugin also provides extension points that other plugins, such as rabbitmq-top or rabbitmq-shovel-management, use to extend the UI.

While a monitoring option, management UI lacks certain features that external monitoring solutions such as Prometheus and Grafana provide.

Management UI and External Monitoring Systems

The management UI and its HTTP API is a built-in monitoring option for RabbitMQ. This is a convenient option for development and in environments where external monitoring is difficult or impossible to introduce.

However, the management UI has a number of limitations:

  • The monitoring system is intertwined with the system being monitored
  • A certain amount of overhead
  • It only stores recent data (think hours, not days or months)
  • It has a basic user interface
  • Its design emphasizes ease of use over best possible availability.
  • Management UI access is controlled via the RabbitMQ permission tags system (or a convention on JWT token scopes)

Long term metric storage and visualisation services such as Prometheus and Grafana or the ELK stack are more suitable options for production systems. They offer:

  • Decoupling of the monitoring system from the system being monitored
  • Lower overhead
  • Long term metric storage
  • Access to additional related metrics such as those of the Erlang runtime ones
  • More powerful and customizable user interface
  • Ease of metric data sharing: both metric state and dashboards
  • Metric access permissions are not specific to RabbitMQ
  • Collection and aggregation of node-specific metrics which is more resilient to individual node failures

RabbitMQ provides first class support for Prometheus and Grafana as of 3.8. It is recommended for production environments.

Getting Started

The management plugin is included in the RabbitMQ distribution. Like any other plugin, it must be enabled before it can be used. That’s done using rabbitmq-plugins:

Node restart is not required after plugin activation.

During automated deployments, the plugin can be enabled via enabled plugin file.

Usage

Management UI Access

The management UI can be accessed using a Web browser at http:// :15672/ .

For example, for a node running on a machine with the hostname of warp10.local , it can be accessed by users with sufficient privileges at either http://warp10.local:15672/ or http://localhost:15672/ (provided that localhost resolves correctly).

Note that the UI and HTTP API port — typically 15672 — does not support AMQP 0-9-1, AMQP 1.0, STOMP or MQTT connections. Separate ports should be used by those clients.

Users must be granted permissions for management UI access.

Notable Features

The management UI is implemented as a single page application which relies on the HTTP API. Some of the features include:

  • Declare, list and delete exchanges, queues, bindings, users, virtual hosts and user permissions.
  • Monitor queue length, message rates (globally and per queue, exchange or channel), resource usage of queue, node GC activity, data rates of client connections, and more.
  • Monitor node resource use: sockets and file descriptors, memory usage breakdown, available disk space and bandwidth usage on inter-node communication links.
  • Manage users (provided administrative permissions of the current user).
  • Manage policies and runtime parameters (provided sufficient permissions of the current user).
  • Export schema (vhosts, users, permissions, queues, exchanges, bindings, parameters, policies) and import it on node start. This can be used for recovery purposes or setup automation of new nodes and clusters.
  • Force close client connections, purge queues.
  • Send and receive messages (useful in development environments and for troubleshooting).

The UI application supports recent versions of Google Chrome, Safari, Firefox, and Microsoft Edge browsers.

Management UI Access in Clusters

Any cluster node with rabbitmq-management plugin enabled can be used for management UI access or data collection by monitoring tools. It will reach out to other nodes and collect their stats, then aggregate and return a response to the client.

To access management UI the user has to authenticate and have certain permissions (be authorised). This is covered in the following section.

Access and Permissions

The management UI requires authentication and authorisation, much like RabbitMQ requires it from connecting clients. In addition to successful authentication, management UI access is controlled by user tags. The tags are managed using rabbitmqctl. Newly created users do not have any tags set on them by default.

See Production Checklist for general recommendations on user and credential management.

Tag Capabilities
(None) No access to the management plugin
management Anything the user could do via messaging protocols plus:
  • List virtual hosts to which they can log in via AMQP
  • View all queues, exchanges and bindings in «their» virtual hosts
  • View and close their own channels and connections
  • View «global» statistics covering all their virtual hosts, including activity by other users within them
policymaker Everything «management» can plus:
  • View, create and delete policies and parameters for virtual hosts to which they can log in via AMQP
monitoring Everything «management» can plus:
  • List all virtual hosts, including ones they could not access using messaging protocols
  • View other users’s connections and channels
  • View node-level data such as memory use and clustering
  • View truly global statistics for all virtual hosts
administrator Everything «policymaker» and «monitoring» can plus:
  • Create and delete virtual hosts
  • View, create and delete users
  • View, create and delete permissions
  • Close other users’s connections
Читайте также:  Почему может не работать насос отопления

Note that since «administrator» does everything «monitoring» does, and «monitoring» does everything «management» does, each user often needs a maximum of one tag.

Normal RabbitMQ permissions to resources still apply to monitors and administrators; just because a user is a monitor or administrator does not grant them full access to exchanges, queues and bindings through the management plugin or other means.

All users can only list objects within the virtual hosts they have any permissions for.

If access to management UI is impossible to due the lack of users with sufficient permissions or forgotten/incorrect permissions, CLI tools must be used to manage the users and their credentials. rabbitmqctl add_user should be used to create a user, rabbitmqctl set_permissions to grant the user the desired permissions and finally, rabbitmqctl set_user_tags should be used to give the user management UI access permissions.

Command Line Examples

The following example creates a user with complete access to the management UI/HTTP API (as in, all virtual hosts and management features):

Authenticating with OAuth 2

RabbitMQ can be configured to use JWT-encoded OAuth 2.0 access tokens to authenticate client applications and management UI users. When doing so, the management UI does not automatically redirect users to authenticate against the OAuth 2 server, this must be configured separately. Currently, only UAA is supported authorization server.

To redirect users to the UAA server to authenticate, use the following configuration:

When using management.enable_uaa = true , it is still possible to authenticate with HTTP basic authentication against the HTTP API. This means both of the following examples will work:

To switch to authenticate using OAuth 2 exclusively for management UI access, set the management.disable_basic_auth configuration key to true :

When setting management.disable_basic_auth to true , only the Bearer (token-based) authorization method will work, for example:

This is true for all endpoints except GET /definitions and POST /definitions . Those endpoints require the token to be passed in the token query string parameter.

HTTP API

API Endpoints

When activated, the management plugin provides an HTTP API at http://server-name:15672/api/ by default. Browse to that location for more information on the API. For convenience the same API reference is available on GitHub.

HTTP API and Monitoring

The API is intended to be used for monitoring and alerting purposes. It provides access to detailed information about the state of nodes, connections, channels, queues, consumers, and so on.

Any cluster node with rabbitmq-management plugin enabled can be used for management UI access or data collection by monitoring tools. It will reach out to other nodes and collect their stats, then aggregate and return a response to the client.

When monitoring a cluster of nodes, there is no need to contact each node via HTTP API individually. Instead, contact a random node or a load balancer that sits in front of the cluster.

HTTP API Clients and Tooling

rabbitmqadmin is a Python command line tool that interacts with the HTTP API. It can be downloaded from any RabbitMQ node that has the management plugin enabled at http:// :15672/cli/ .

For HTTP API clients in several languages, see Developer Tools.

Some API endpoints return a lot of information. The volume can be reduced by filtering what columns are returned by HTTP GET requests. See latest HTTP API documentation for details.

Configuration

There are several configuration options which affect the management plugin. These are managed through the main RabbitMQ configuration file.

It is possible to configure HTTP API and management UI to use a different port or network interface, enable HTTPS and so on.

While rarely needed, it is possible to configure multiple listeners (ports), e.g. to both enable HTTPS and retain support for clients that can only use HTTP (without TLS).

The port is configured using the management.tcp.port key:

It is possible to configure what interface the API endpoint will use, similarly to messaging protocol listeners, using the management.tcp.ip key:

To check what interface and port is used by a running node, use rabbitmq-diagnostics :

HTTPS

The management plugin can be configured to use HTTPS. See the guide on TLS to learn more about certificate authorities, certificates and private key files.

More TLS options can be configured for the HTTPS listener.

The above example in the classic config format:

Using HTTP and HTTPS Together

It is possible to use both HTTP and HTTPS on different ports:

The same configuration keys can be used to configure a single listener (just HTTP or HTTPS) and match those used by the Web STOMP and Web MQTT.

Advanced HTTP Options

Cowboy, the embedded Web server used by the management plugin, provides a number of options that can be used to customize the behavior of the server. Most of the options were introduced in RabbitMQ 3.7.9.

Response Compression

Response compression is enabled by default. To enable it explicitly, use management.tcp.compress :

Client Inactivity Timeouts

Some HTTP API endpoints respond quickly, others may need to return or stream a sizeable data set to the client (e.g. many thousands of connections) or perform an operation that takes time proportionally to the input (e.g. import a large definitions file). In those cases the amount of time it takes to process the request can exceed certain timeouts in the Web server as well as HTTP client.

It is possible to bump Cowboy timeouts using the management.tcp.idle_timeout , management.tcp.inactivity_timeout , management.tcp.request_timeout options.

  • management.tcp.inactivity_timeout controls HTTP(S) client’s TCP connection inactivity timeout. When it is reached, the connection will be closed by the HTTP server.
  • management.tcp.request_timeout controls the window of time in which the client has to send an HTTP request.
  • management.tcp.idle_timeout controls the window of time in which the client has to send more data (if any) within the context of an HTTP request.

If a load balancer or proxy is used between HTTP clients and the management HTTP server, the inactivity_timeout and idle_timeout values should be at least as large, and often greater than, the timeout and inactivity values used by the load balancer.

Here are some example configuration snippets that modify the timeouts:

All values are in milliseconds. Their defaults vary:

  • management.tcp.inactivity_timeout has the default of 300 seconds
  • management.tcp.request_timeout has the default of 60 seconds
  • management.tcp.idle_timeout has the default of 5 seconds

It is recommended that if the inactivity or idle timeout need changing, management.tcp.inactivity_timeout value should match or be greater than that of management.tcp.idle_timeout .

management.tcp.request_timeout typically does not need increasing as clients send a request shortly after establishing a TCP connection.

HTTP Request Logging

To create simple access logs of requests to the HTTP API, set the value of the management.http_log_dir key to the path of a directory in which logs can be created:

For the change to have an effect, restart the plugin or the node.

Statistics Interval

By default the server will emit statistics events every 5 seconds ( 5000 ms). The message rate values shown in the management plugin are calculated over this period.

Increasing this value will reduce CPU resource consumption of stats collection in environments with a large number of stats emitting entities such as connections, channels, queues.

In order to do so, set the value of the collect_statistics_interval configuration key to the desired interval in milliseconds and restart the node:

Message Rates

The management plugin by default shows message rates globally, and for each queue, channel, exchange, and vhost. These are known as the basic message rates.

It can also show message rates for all the combinations of channel to exchange, exchange to queue, and queue to channel. These are known as detailed message rates. Detailed message rates are disabled by default as they can have a large memory footprint when there are a large number of combinations of channels, queues and exchanges.

Alternatively, the message rates can be disabled altogether. This can help get reduce CPU resource consumption of the plugin.

The message rate mode is controlled by the management.rates_mode configuration key:

Supported values are basic (the default), detailed , and none .

Sample (Data Point) Retention

The management plugin will retain samples of some data such as message rates and queue lengths. Depending on how long the data is retained, some time range options on UI charts may be incomplete or unavailable.

There are three policies:

  • global : how long to retain data for the overview and virtual host pages
  • basic : how long to retain data for individual connections, channels, exchanges and queues
  • detailed : how long to retain data for message rates between pairs of connections, channels, exchanges and queues (as shown under «Message rates breakdown»)

Below is a configuration example:

The configuration in the example above retains global data at a 5 second resolution (sampling happens every 5 seconds) for a minute, then at a 1 minute (60 second) resolution for 1 hour, then at a 20 minute resolution for one day. It retains basic data at a 5 second resolution for 1 minute, at a 1 minute (60 second) resolution for 1 hour, and detailed data only for 10 seconds.

Читайте также:  Как настроить колонку jbl через блютуз

All three policies are mandatory, and must contain at least one retention setting (period).

Disable statistics and metrics collection

It is possible to disable the statistics in the UI and HTTP API in order for these to be used only for operations. This can be a useful feature if external monitoring solutions such as Prometheus and Grafana are being used. If statistics are disabled in any of the following ways, all charts and detailed statistics will be hidden in the UI.

In order to completely disable the internal metrics collection, the disable_metrics_collector flag must be set in the rabbitmq_management_agent plugin. The Prometheus plugin will still work even if collection is disabled.

Disabling the metrics collection is the preferred option if it is being used with an external monitoring system, as this reduced the overhead that statistics collection and aggregation causes in the broker. If the statistics are only temporary disabled, or are not required in some HTTP API queries, the aggregation of the stats can be disabled in the rabbitmq_management plugin. The disable flag can be also passed as part of the query string in the URI.

As at the moment the Prometheus plugin cannot report individual queue totals, there is a configuration option that allows to list messages , messages_ready and messages_unacknowledged in the queues endpoint.

Below is a configuration example that disables the statistics but returns individual queue totals in the queues page:

Content Security Policy (CSP)

It is possible to configure what CSP header value is used by HTTP API responses. The default value is script-src ‘self’ ‘unsafe-eval’ ‘unsafe-inline’; object-src ‘self’ :

The value can be any valid CSP header string:

Wildcards are also allowed:

A CSP policy frame-ancestors directive can be used to prevent frame embedding of the management UI, mitigating certain types of cross-frame scripting attacks:

Strict Transport Security (HSTS)

It is possible to configure what Strict Transport Security header value is used by HTTP API responses:

Cross-origin Resource Sharing (CORS)

The management UI application will by default refuse access to websites hosted on origins different from its own using the Cross-Origin Resource Sharing mechanism, also known as CORS. It is possible to white list origins:

It is possible to allow any origin to use the API using a wildcard. This is highly discouraged for deployments where the UI application may be exposed to the public.

The CORS pre-flight requests are cached by the browser. The management plugin defines a timeout of 30 minutes by default. The value can be changed. It is configured in seconds:

Login Session Timeout

After the user logs in, her web UI login session will expire after 8 hours by default. It is possible to configure a different timeout using the login_session_timeout setting.

The value should be an integer: it controls the length of login session in minutes. When the time is up, the user will be signed out.

The following example sets the session timeout to 1 hour:

Path Prefix

Some environments require the use of a custom prefix for all HTTP requests to the management plugin. The management.path_prefix setting allows an arbitrary prefix to be set for all HTTP request handlers in the management plugin.

Setting management.path_prefix to /my-prefix specifies all API requests to use the URI host:port/my-prefix/api/[. ]

The management UI login page will have the URI host:port/my-prefix/ — note that the trailing slash is required in this case.

Example

An example configuration file for RabbitMQ that switches on request logging, increases the statistics interval to 10 seconds and explicitly sets some other relevant parameters to their default values, would look like this:

Loading Definitions (Schema) at Startup

Nodes and clusters store information that can be thought of schema, metadata or topology. Users, vhosts, queues, exchanges, bindings, runtime parameters all fall into this category.

Definitions can be exported and imported via the rabbitmqctl or the HTTP API provided by this plugin, including rabbitmqadmin .

Metrics Collection and HTTP API in Clusters

Client Requests

The management plugin is aware of clusters. It can be enabled on one or more nodes in a cluster, and see information pertaining to the entire cluster no matter which node you connect to.

Running Management Plugin on a Subset of Nodes

It is possible to deploy management plugin only on a subset of cluster nodes. In that case only the nodes running the plugin would be able to serve client HTTP API requests. For every cluster node to have its metrics collected, it is still required that the rabbitmq-management-agent plugin is enabled on each node, otherwise the metrics from the node won’t be available.

Aggregation Queries in Clusters

In cluster, HTTP API performs cluster-wide queries when handling client requests, which means it can be affected by network partitions and slow downs. Timeouts for inter-node aggregation queries are controlled via the net tick mechanism.

(Reverse HTTP) Proxy Setup

It is possible to make the web UI available via any proxy that conforms with RFC 1738. The following sample Apache configuration illustrates the minimum necessary directives to coax Apache into conformance. It assumes a management web UI on the default port of 15672:

Restarting Statistics Database

Statistics database is stored entirely in memory. All of its contents is transient and should be treated as such.

Prior to version 3.6.7 stats database is stored on a single node.

Starting from version 3.6.7, each node has its own statistics database containing a fraction of stats recorded on this node.

It is possible to restart the stats database.

The statistics database is stored in the memory of the stats process previously to RabbitMQ 3.6.2, and stored in ETS tables from RabbitMQ 3.6.2. To restart the database with versions earlier than 3.6.2, use

Starting with RabbitMQ 3.6.7, the database can be reset per node using

To reset the entire management database on all nodes

There are also HTTP API endpoints to reset a database. For the entire database

For a single node

Memory Usage Analysis and Memory Management

Management UI can be used to inspect node’s memory use, including displaying a per-category breakdown. See the Memory Use Analysis guide for details.

Management database builds around periodically emitted stats, regulated by the statistics interval described above, or when certain components are created/declared (e.g. a new connection or channel is opened, or a queue declared) or closed/deleted. Message rates do not directly affect management database memory usage.

Total amount of memory consumed by the stats database depends on the topology size (e.g. the number of queues), number of concurrent connections and channels, event emission interval, effective rates mode and retention policies.

Entities that emit stats (connections, channels, queues, nodes) do so periodically. The interval can be configured using the collect_statistics_interval key:

Increasing the interval value to 30-60s will reduce CPU footprint and peak memory consumption for systems with large amounts of connections, channels and queues. This comes with a downside: metrics of said entities will refresh every 30-60 seconds. This can be perfectly reasonable in an externally monitored production system but will make management UI less convenient to use for operators.

The memory usage of the channel and stats collector processes can be limited by setting the maximum backlog queue size using the parameter stats_event_max_backlog . If the backlog queue is full, new channel and queue stats will be dropped until the previous ones have been processed.

The statistics interval can also be changed at runtime. Doing so will have no effect on existing connections, channels or queues. Only new stats emitting entities are affected.

The statistics database can be restarted (see above) and thus forced to release all memory. Management UI’s Overview page contains buttons that reset stats database for individual nodes as well as all nodes in the cluster.

Publishing and Consuming over HTTP API

It is possible to publish and consume messages using the HTTP API. This way of messaging is discouraged: prefer one of the binary messaging protocols supported by RabbitMQ. Publishing and consuming that way will be significantly more efficient and will provide access to various messaging protocol features such as confirmations.

Publishing over HTTP API can be useful in environments where long lived messaging protocol connections is not an option.

Getting Help and Providing Feedback

If you have questions about the contents of this guide or any other topic related to RabbitMQ, don’t hesitate to ask them on the RabbitMQ mailing list.

Help Us Improve the Docs <3

If you’d like to contribute an improvement to the site, its source is available on GitHub. Simply fork the repository and submit a pull request. Thank you!

Источник

Оцените статью