mamonsu
mamonsu — агент мониторинга для сбора метрик операционной системы и Postgres Pro
Синтаксис
mamonsu agent [действие_агента]
mamonsu bootstrap -M [пользователь_mamonsu-c | --config] [-x | --create-extensions] [параметры_подключения]
mamonsu export {template | config} имя_файла [параметры_экспорта]
mamonsu report [параметры_отчёта] [параметры_подключения]
mamonsu tune [параметры_оптимизации] [параметры_подключения]
mamonsu upload [параметры_передачи]
mamonsu zabbix dashboard upload имя_шаблона
mamonsu zabbix {template | host | hostgroup} действие_сервера
mamonsu zabbix item {error | lastvalue | lastclock} ид_узла
mamonsu zabbix version
mamonsu [-c | --config] [-d | --daemonize]
mamonsu --version
mamonsu --help
Описание
Приложение mamonsu представляет собой агент мониторинга, собирающий метрики Postgres Pro и системы, которые можно визуализировать на сервере Zabbix. В отличие от стандартного Zabbix Agent, который тоже можно настроить для сбора метрик Postgres Pro, mamonsu использует одно подключение к базе данных, что позволяет минимизировать влияние на целевую систему.
Агент mamonsu включает следующие компоненты:
Руководящий процесс, наблюдающий за активностью системы и базы данных.
Модули, определяющие, какие метрики Postgres Pro и системы будут собираться.
Файлы конфигурации и шаблона, в которых определяется, какие модули будут использоваться и как будут представляться собранные данные.
mamonsu является активным агентом, что означает, что он передаёт серверу Zabbix данные сразу, по мере их сбора. В mamonsu имеется набор готовых метрик для мониторинга Postgres Pro и системы, но вы можете разработать и дополнительные модули для сбора других интересующих вас метрик.
В mamonsu также реализован интерфейс командной строки для управления некоторыми параметрами сервера Zabbix, для получения общего представления о конфигурации целевой системы, а также для оптимизации параметров Postgres Pro и системы «на лету». Список всех команд mamonsu приведён в Разделе «Справка по командной строке».
Установка и подготовка
Важно
Перед началом установки рекомендуется внимательно ознакомиться с Замечаниями о совместимости.
Для использования mamonsu вы должны создать учётную запись Zabbix и настроить сервер Zabbix, как описано в документации Zabbix. Естественно, если вы планируете наблюдать за метриками Postgres Pro, у вас должен работать экземпляр Postgres Pro. Если вам нужны инструкции по установке и настройке кластера Postgres Pro, обратитесь к Главе 17 и Разделу 18.2.
Примечание
Тогда как метрики Postgres Pro mamonsu может собирать с удалённого кластера, метрики системы собираются только локально. Поэтому если вы решите собирать метрики удалённого экземпляра Postgres Pro, во избежание путаницы обязательно отключите системные метрики, иначе оба набора будут представлены в Zabbix как метрики одного узла.
Приложение mamonsu поставляется вместе с Postgres Pro Enterprise в виде отдельного предварительно собранного пакета mamonsu (подробные инструкции по установке приведены в Главе 17). Завершив установку mamonsu, выполните следующие действия, чтобы начать сбор метрик:
По желанию произведите специальную подготовку mamonsu
Если вы опустите этот этап, метрики можно будет собирать только с правами суперпользователя, что не рекомендуется.
На этом этапе команда
bootstrapзадаёт пользователя mamonsu, создаёт схемуmamonsuв базе данных, заданной явно или по умолчанию, а также расширения и объекты, необходимые для мониторинга.Команда
bootstrapне имеет обязательных параметров. При запуске без параметров она берёт необходимые значения из файла конфигурации (по умолчанию —/etc/mamonsu/agent.conf). Ниже приведён простой пример подготовительной процедуры:В разделе
[postgres]файлаagent.confукажите параметры подключения для кластера Postgres Pro, за которым вы собираетесь наблюдать. За дополнительными сведениями обратитесь к разделу Параметры подключения.Выполните следующую команду для подготовки mamonsu:
mamonsu bootstrap
Эта команда создаст пользователя
mamonsuс паролемmamonsu, а также функции мониторинга в базе данных, указанной вagent.conf, и предоставит право выполнять их пользователюmamonsu.
В следующем примере параметры
bootstrapпередаются явно.Создайте непривилегированного пользователя базы данных для mamonsu. Например:
CREATE USER mamonsu_user WITH PASSWORD 'mamonsu_password'; GRANT pg_monitor TO mamonsu_user;
Создайте базу данных, которая будет применяться для установления подключения к Postgres Pro. Например:
CREATE DATABASE mamonsu_database OWNER mamonsu_user;
Выполните следующую команду для подготовки mamonsu:
mamonsu bootstrap -M mamonsu_user -x -c /etc/mamonsu/agent.conf -d mamonsu_database -U postgres --host myhost --port 5432
Для получения подробной информации о параметрах
-M,-xи-cсм.bootstrap. За дополнительными сведениями о других параметрах обратитесь к разделу Параметры подключения. Эта команда создаст функции мониторинга вбазе_mamonsuи предоставит право выполнять ихпользователю_mamonsu. Кроме того, будет создано расширение pg_buffercache, позволяющее собирать метрики общего кеша буферов. При этом задаётся другой путь к файлу конфигурации.
В результате суперпользователь не требуется для дальнейших подключений. Обратите внимание, что в этой базе данных создаётся несколько таблиц в схеме
mamonsu. Не удаляйте эти таблицы, так как они необходимы для работы mamonsu.Настройте mamonsu
Отредактируйте конфигурационный файл
agent.conf, по умолчанию размещённый в каталоге/etc/mamonsu/.Настройте параметры, связанные с Zabbix. Значение
addressдолжно указывать на работающий сервер Zabbix, а в полеclientдолжно задаваться имя узла Zabbix. Узлы, доступные для вашей учётной записи Zabbix, вы можете увидеть в его веб-интерфейсе на странице (Настройка) > (Узлы сети).[zabbix] ; включён по умолчанию enabled =
Trueclient =имя_узла_zabbixaddress =сервер_zabbixПо умолчанию mamonsu будет собирать и метрики Postgres Pro, и системные метрики. При необходимости вы можете запретить сбор метрик первого или второго типа, установив в файле
agent.confдля параметраenabledзначениеFalseв разделе[postgres]или[system], соответственно.[system] ; включён по умолчанию enabled = True
Примечание
Тогда как метрики Postgres Pro mamonsu может собирать с удалённого кластера, метрики системы собираются только локально. Поэтому если вы решите собирать метрики удалённого экземпляра Postgres Pro, во избежание путаницы обязательно отключите системные метрики, иначе оба набора будут представлены в Zabbix как метрики одного узла.
Если вы будете собирать метрики Postgres Pro, необходимо задать параметры подключения к кластеру Postgres Pro, за которым вы намерены наблюдать. Для этого задайте в полях
user,passwordиdatabaseсоответственно имя пользователя (mamonsu_user), пароль (mamonsu_password) и базу данных (mamonsu_database), указанные при подготовке. Если вы пропустили подготовительную процедуру, задайте имя и пароль суперпользователя, а также целевую базу.[postgres] ; включён по умолчанию enabled = True user =
пользователь_mamonsudatabase =база_mamonsupassword =пароль_mamonsuport = 5432
Это базовые параметры, позволяющие начать использование mamonsu. Кроме них можно настроить и другие параметры mamonsu, описанные в Разделе «Параметры конфигурации».
Настройте представление метрик на сервере Zabbix
Создайте шаблон, определяющий, как будут представляться собранные метрики на сервере Zabbix:
mamonsu export template template.xml
mamonsu формирует файл шаблона
template.xmlв текущем каталоге. По умолчанию отображаемым в Zabbix именем шаблона будетPostgresPro-, гдеOSOS— название вашей операционной системы. Чтобы получить шаблон с другим отображаемым именем, в показанную выше команду можно добавить аргумент--template-name.При желании укажите учётные данные в Zabbix в следующих переменных окружения в той системе, где настраивается мониторинг:
Задайте в переменных
ZABBIX_USERиZABBIX_PASSWDимя и пароль вашей учётной записи Zabbix, соответственно.Задайте в переменной
ZABBIX_URLадресhttp://zabbix/
Если этого не сделать, вам нужно будет указывать следующие параметры при каждом вызове любой подкоманды
mamonsu zabbix:--url=http://zabbix/ --user=
имя_пользователя_zabbix--password=пароль_пользователя_zabbixЗагрузите шаблон
template.xmlна сервер Zabbix.mamonsu zabbix template export template.xml
Шаблон также можно загрузить через веб-интерфейс Zabbix: воспользуйтесь своей учётной записью в Zabbix и перейдите на страницу Templates (Шаблоны) > Import (Импорт).
Привяжите полученный шаблон к узлу, за которым будете наблюдать.
Для этого в веб-интерфейсе Zabbix выберите нужный узел, перейдите на страницу Templates (Шаблоны) > Add (Добавить), выберите шаблон и затем щёлкните Update (Обновить).
Подсказка
Если вы хотите связать шаблон с создаваемым узлом в Zabbix, вы можете сделать это в командной строке, используя команды
mamonsu zabbix. Подробнее это описывается в Подразделе «Управление параметрами сервера Zabbix в командной строке».
Завершив настройку, запустите mamonsu. Например, в системах Linux вы можете запустить mamonsu в виде службы так:
service mamonsu start
mamonsu считывает все параметры из файла конфигурации mamonsu и начинает мониторинг системы.
Справка по командной строке
agent
Синтаксис:
mamonsu agent { metric-list | metric-get имя_метрики | version }Предоставлять информацию о собираемых метриках из командной строки. Вы можете задать одно из следующих действий:
metric-listВывести список метрик, которые собирает mamonsu. Вывод этой команды включает ключ метрики, её последнее значение и время получения этого значения.
metric-getимя_метрикиПолучить последнее значение указанной метрики. Список доступных метрик можно получить с помощью команды
metric-list.versionВывести версию mamonsu.
bootstrap
Синтаксис:
mamonsu bootstrap -Mимя пользователя[-c[файл конфигурации] | --config[=файл конфигурации]] [-x | --create-extensions] [параметры подключения]
Подготовить mamonsu к работе. Данная команда может принимать следующие параметры:
-MЗадаёт имя пользователя, который будет владеть всеми процессами mamonsu. Указанный пользователь не должен быть привилегированным.
-cфайл_конфигурации--config=файл_конфигурацииЗадаёт файл
agent.conf, в котором раздел[postgres]содержит имя базы данных, которое будет использоваться, если параметр--dbnameне указан среди.параметров подключенияЗначение по умолчанию:
/etc/mamonsu/agent.conf-x--create-extensionsСоздаёт вспомогательные расширения. Будет создано расширение pg_buffercache, которое больше не создаётся по умолчанию. Для Postgres Pro версии 12 или выше команда
bootstrapсоздаст функции для работы с pgpro_stats и предоставит права на их выполнение пользователю-xmamonsu.параметры_подключенияНеобязательные параметры подключения, задаваемые в командной строке.
export
Синтаксис:
mamonsu export configимя_файла.conf [--add-plugins=каталог_модулей] mamonsu export templateимя_файла.xml [--add-plugins=каталог_модулей] [--template-name=имя_шаблона] [--application=имя_приложения] [--old-zabbix]
Сгенерировать файл конфигурации или файл шаблона для набора метрик. Для настройки набора метрик можно передать дополнительные параметры:
--add-plugins=каталог_модулейСобирать метрики, определённые в дополнительных модулях, расположенных в заданном
каталоге_модулей. Если вы будете использовать какие-либо дополнительные модули, этот параметр нужно передавать при формировании файла конфигурации и шаблона.--template-name=имя_шаблонаЗадаёт название шаблона, которое будет отображаться на сервере Zabbix.
Значение по умолчанию:
PostgresPro-, гдеOSOS— название вашей операционной системы--application=имя_приложенияЗадаёт идентификатор, с которым собранные метрики будут отображаться на сервере Zabbix.
Значение по умолчанию:
App-PostgresPro-, гдеOSOS— название вашей операционной системы--old-zabbixЭкспортировать шаблон для сервера Zabbix версии 4.2 или старее. По умолчанию шаблон генерируется в формате, совместимом с Zabbix 4.4 и новее.
export zabbix-parameters
Синтаксис:
mamonsu export zabbix-parametersимя_файла.conf [--add-plugins=каталог_модулей] [--plugin-type={pg | sys | all}] [--pg-version=версия] [--config=файл_конфигурации]
Экспортировать конфигурацию метрик для использования со стандартным агентом Zabbix. Для настройки сбора метрик можно передать дополнительные параметры:
--add-plugins=каталог_модулейСобирать метрики, определённые в дополнительных модулях, расположенных в заданном
каталоге_модулей. Если вы будете использовать какие-либо дополнительные модули, этот параметр нужно передавать при формировании файла конфигурации и шаблона.--plugin-type={pg | sys | all}Типы метрик, которые должны собираться:
pg— метрики Postgres Pro.sys— системные метрики.all— все метрики.
По умолчанию:
all--pg-version=версияЗадаёт основную версию сервера, для которого будет настраиваться набор метрик. Программа
mamonsuможет собирать метрики во всех поддерживаемых версиях Postgres Pro, а также в PostgreSQL, начиная с версии 9.5.Значение по умолчанию:
10--config=файл_конфигурацииЗадаёт путь к файлу
agent.conf, который будет источником определений метрик.Значение по умолчанию:
/etc/mamonsu/agent.conf
export zabbix-template
Синтаксис:
mamonsu export zabbix-templateимя_файла.conf [--add-plugins=каталог_модулей] [--plugin-type={pg | sys | all}] [--template-name=имя_шаблона] [--application=имя_приложения] [--config=файл_конфигурации] [--old-zabbix]
Экспортировать шаблон для использования со стандартным агентом Zabbix. Для настройки конфигурации можно передать дополнительные параметры:
--add-plugins=каталог_модулейСобирать метрики, определённые в дополнительных модулях, расположенных в заданном
каталоге_модулей. Если вы будете использовать какие-либо дополнительные модули, этот параметр нужно передавать при формировании файла конфигурации и шаблона.--plugin-type={pg | sys | all}Типы метрик, которые должны собираться:
pg— метрики Postgres Pro.sys— системные метрики.all— все метрики.
По умолчанию:
all--template-name=имя_шаблонаЗадаёт название шаблона, которое будет отображаться на сервере Zabbix.
Значение по умолчанию:
PostgresPro-, гдеOSOS— название вашей операционной системы--application=имя_приложенияЗадаёт идентификатор, с которым собранные метрики будут отображаться на сервере Zabbix.
Значение по умолчанию:
App-PostgresPro-, гдеOSOS— название вашей операционной системы--config=файл_конфигурацииЗадаёт путь к файлу
agent.conf, который будет источником определений метрик.Значение по умолчанию:
/etc/mamonsu/agent.conf--old-zabbixЭкспортировать шаблон для сервера Zabbix версии 4.2 или старее. По умолчанию шаблон генерируется в формате, совместимом с Zabbix 4.4 и новее.
report
Синтаксис:
mamonsu report [--run-system=логическое_значение] [--run-postgres=логическое_значение] [--print-report=логическое_значение] [--report-path=файл_отчёта] [--disable-sudo] [параметры_подключения]
Выдать подробный отчёт об оборудовании, операционной системе, использовании памяти и других характеристиках объекта мониторинга, а также конфигурацию Postgres Pro.
Отчёт настраивается с помощью следующих необязательных параметров:
--run-system=логическое_значениеВключить в генерируемый отчёт информацию о системе.
По умолчанию:
True(вкл.)--run-postgres=логическое_значениеВключить в генерируемый отчёт информацию о Postgres Pro.
По умолчанию:
True(вкл.)--print-report=логическое_значениеВывести отчёт в stdout.
По умолчанию:
True(вкл.)--report-path=файл_отчётаВывести отчёт в указанный файл.
Путь по умолчанию:
/tmp/report.txt--disable-sudoСобирать при формировании отчёта только те данные, для получения которых не нужны права суперпользователя. Этот режим поддерживается только в системах Linux.
параметры_подключенияНеобязательные параметры подключения, задаваемые в командной строке.
tune
Синтаксис:
mamonsu tune [--dry-run] [--disable-sudo] [--log-level {INFO|DEBUG|WARN}]
[--dont-tune-pgbadger] [--dont-reload-postgresql]
[параметры_подключения]Оптимизировать конфигурацию Postgres Pro и системы, исходя из собранной статистики. Настроить оптимизацию позволяют следующие параметры:
--dry-runВывести параметры конфигурации системы и Postgres Pro, которые будут настроены, но не изменять их фактически.
--disable-sudoОптимизировать только те параметры, для изменения которых не нужны права суперпользователя. Этот режим поддерживается только в системах Linux.
--dont-tune-pgbadgerНе оптимизировать параметры pgbadger.
--log-level { INFO | DEBUG | WARN}Изменить уровень детализации сообщений.
Значение по умолчанию:
INFO--dont-reload-postgresqlНе допустить выполнения приложением mamonsu функции
pg_reload_conf(). В этом случае изменения некоторых параметров, которые вступают в силу только после перезагрузки конфигурации Postgres Pro, не начнут действовать немедленно.параметры_подключенияНеобязательные параметры подключения, задаваемые в командной строке.
upload
Синтаксис:
mamonsu upload [--zabbix-file=файл_метрик] [--zabbix-address=адрес_zabbix] [--zabbix-port=порт] [--zabbix-client=имя_узла_zabbix] [--zabbix-log-level={INFO|DEBUG|WARN}]
Передать данные метрик, ранее сохранённые в файле, на сервер Zabbix для визуализации. Более подробно получение файла метрик рассматривается в Подразделе «Параметры вывода».
Эта команда может принимать следующие параметры:
--zabbix-address=адрес_zabbixАдрес сервера Zabbix.
Значение по умолчанию:
localhost--zabbix-port=портПорт сервера Zabbix.
Значение по умолчанию: 10051
--zabbix-file=файл_метрикИмя текстового файла с метриками, которые можно визуализировать, например
localhost.log.--zabbix-client=имя_узла_zabbixИмя узла в Zabbix.
Значение по умолчанию:
localhost--zabbix-log-level={INFO|DEBUG|WARN}Изменить уровень детализации сообщений.
Значение по умолчанию:
INFO
zabbix dashboard upload
Синтаксис:
mamonsu dashboard upload имя_шаблонаЗагрузить панель Zabbix с метриками mamonsu в шаблон на сервере Zabbix версии 6.0 или выше.
zabbix item
Синтаксис:
mamonsu zabbix item {error | lastvalue | lastclock } имя_узлаПросмотреть заданное свойство последних метрик, полученных сервером Zabbix для указанного узла.
zabbix version
Синтаксис:
mamonsu zabbix version
Получить версию сервера Zabbix, к которой подключён агент mamonsu.
zabbix host
Синтаксис:
mamonsu zabbix host list mamonsu zabbix host showимя_узлаmamonsu zabbix host idимя_узлаmamonsu zabbix host deleteид_узлаmamonsu zabbix host createимя_узлаид_группы_узловид_шаблонаадрес_mamonsumamonsu zabbix host info {templates | hostgroups | graphs | items}ид_узла
Позволяет управлять узлами Zabbix, выполняя одно из действий, описанных в Подразделе «Управление сервером Zabbix».
zabbix hostgroup
Синтаксис:
mamonsu zabbix hostgroup list mamonsu zabbix hostgroup showимя_группы_узловmamonsu zabbix hostgroup idимя_группы_узловmamonsu zabbix hostgroup deleteид_группы_узловmamonsu zabbix hostgroup createимя_группы_узлов
Позволяет управлять группами узлов Zabbix, выполняя одно из действий, описанных в Подразделе «Управление сервером Zabbix».
zabbix template
Синтаксис:
mamonsu zabbix template list mamonsu zabbix template showимя_шаблонаmamonsu zabbix template idимя_шаблонаmamonsu zabbix template deleteид_шаблонаmamonsu zabbix template exportфайл
Позволяет управлять шаблонами Zabbix, выполняя одно из действий, описанных в Подразделе «Управление сервером Zabbix».
[--config] [--daemonize]
Синтаксис:
mamonsu [-cфайл конфигурации| --config=файл конфигурации] [-d | --daemonize]
Запустить в качестве агента мониторинга на переднем плане или в фоновом режиме, используя параметры, загруженные из файла конфигурации. Если указанный файл конфигурации или стандартный файл конфигурации не существует, завершиться с ошибкой. Полезно для отладки. Принимаются следующие параметры:
-cфайл_конфигурации--config=файл_конфигурацииЗадаёт файл
agent.confдля загрузки параметров конфигурации.Значение по умолчанию:
/etc/mamonsu/agent.conf-d--daemonizeЗапустить в фоновом режиме. Без этого указания mamonsu будет работать на переднем плане.
--version
Синтаксис:
mamonsu --version
Вывести версию mamonsu.
--help
Синтаксис:
mamonsu --help
Вывести справку по параметрам командной строки mamonsu.
Параметры подключения
При вызове вышеуказанных команд параметры_подключения в командной строке задают параметры подключения к целевому кластеру Postgres Pro. параметры_подключения могут содержать аргументы --host, --port, --dbname (-d), --username (-U), и --password (-W). В аргументе --dbname (-d) должна указываться mamonsu_database, созданная для наблюдения. Заметьте, что в аргументе --username (-U) необходимо передать имя суперпользователя в данном кластере.
Если вы не зададите параметры_подключения, mamonsu будет использовать соответствующие параметры из файла конфигурации.
Управление сервером Zabbix
Используя mamonsu, вы можете управлять некоторой функциональностью Zabbix из командной строки. А именно, вы можете создавать или удалять узлы и группы узлов Zabbix, а также генерировать, импортировать и удалять шаблоны Zabbix с помощью описанных ниже команд. В них имя_объекта должно соответствовать типу объекта Zabbix в команде: template (шаблон), host (узел) или hostgroup (группа узлов).
listВывести список доступных шаблонов, узлов или групп узлов.
showимя_объектаВывести информацию об указанном шаблоне, узле или группе узлов.
idимя_объектаПоказать идентификатор заданного объекта, назначаемый автоматически сервером Zabbix.
deleteид_объектаУдалить объект с заданным идентификатором.
createимя_группы_узловcreateимя_узлаид_группы_узловид_шаблонаадрес_mamonsuСоздать новый узел или группу узлов.
exportимя_шаблонаСформировать шаблон Zabbix.
info {templates | hostgroups | graphs | items}ид_узлаВывести подробную информацию о шаблонах, группах узлов, графиках и метриках, связанных с узлом с заданным идентификатором.
Параметры конфигурации
Файл конфигурации agent.conf по умолчанию располагается в каталоге /etc/mamonsu. Он содержит несколько групп параметров, определяющих, какие метрики собирать и как выводить собранные данные:
Все параметры должны задаваться в формате .параметр = значение
Параметры подключения агента
[postgres]
В разделе [postgres] настраивается сбор метрик Postgres Pro и могут содержаться следующие параметры:
enabledВключает/отключает сбор метрик Postgres Pro при значении, равном
TrueилиFalse, соответственно.По умолчанию:
True(вкл.)userПользователь, от имени которого будут запускаться процессы наблюдения за кластером. Это должен быть пользователь mamonsu, заданный при подготовке, либо суперпользователь, если команда
bootstrapне запускалась.Имя по умолчанию:
postgrespasswordПароль указанного пользователя.
databaseБаза данных, через подключение к которой будут собираться метрики.
Имя по умолчанию:
postgreshostАдрес сервера базы данных.
Значение по умолчанию:
localhostportЦелевой порт на сервере.
Значение по умолчанию: 5432
application_nameИмя приложения, идентифицирующее процесс mamonsu, выполняющийся в кластере Postgres Pro.
Значение по умолчанию:
mamonsuquery_timeoutЗначение statement_timeout для сеанса mamonsu, в секундах. Если запрос метрики Postgres Pro не успевает выполниться за указанное время, он прерывается.
Значение по умолчанию: 10
Также вместо параметров конфигурации можно использовать следующие переменные среды: PGUSER, PGPASSWORD, PGHOST, PGDATABASE, PGPORT и PGAPPNAME. За подробным описанием этих переменных обратитесь к Разделу 36.15 для их значения.
[system]
В разделе [system] настраивается сбор системных метрик и могут содержаться следующие параметры:
enabledВключает/отключает сбор системных метрик при значении, равном
TrueилиFalse, соответственно.По умолчанию:
True(вкл.)
[zabbix]
В разделе [zabbix] настраиваются свойства подключения к серверу Zabbix и могут содержаться следующие параметры:
enabledВключает/отключает передачу собранных метрик на сервер Zabbix при значении, равном
TrueилиFalse, соответственно.По умолчанию:
True(вкл.)clientИмя узла в Zabbix.
addressАдрес сервера Zabbix.
Значение по умолчанию: 127.0.0.1
portПорт сервера Zabbix.
Значение по умолчанию: 10051
timeoutМаксимальное время ожидания при подключении к серверу Zabbix (в секундах).
Значение по умолчанию: 15
[agent]
В разделе [agent] задаётся расположение службы mamonsu и включается возможность обращения к метрикам в командной строке:
enabledВключает/отключает сбор метрик в командной строке с помощью команды
agent.По умолчанию:
True(вкл.)hostАдрес системы, в которой работает mamonsu.
Значение по умолчанию: 127.0.0.1
portПорт, через который mamonsu принимает соединения.
Значение по умолчанию: 10052
[sender]
В разделе [sender] определяется размер очереди, в которой накапливаются данные, прежде чем они передаются серверу Zabbix:
queueМаксимальное количество собранных значений метрик, которое может накапливаться локально, прежде чем mamonsu передаст их на сервер Zabbix. После передачи накопленных данных очередь очищается.
Значение по умолчанию: 2048
Параметры вывода
[metric_log]
В разделе [metric_log] настраивается сохранение собранных значений метрик в локальных текстовых файлах. Этот раздел может содержать следующие параметры:
enabledВключает/отключает сохранение собранных значений метрик в текстовом файле. Если этот параметр равен
True, mamonsu создаёт файлlocalhost.logдля сохранения значений метрик.Значение по умолчанию:
FalsedirectoryУказывает каталог, в котором будут сохраняться данные метрик.
Каталог по умолчанию:
/var/log/mamonsumax_size_mbМаксимальный размер файла метрик, в мегабайтах. По достижении заданного размера этот файл переименовывается в
localhost.log.archive, и создаётся новый файлlocalhost.log.Значение по умолчанию: 1024
[log]
В разделе [log] настраивается запись сообщений в журнал mamonsu и могут содержаться следующие параметры:
fileЗадаёт имя файла журнала; может также задавать полный путь.
levelЗадаёт уровень отладки. Этот параметр может принимать значение
DEBUG,ERRORилиINFO.Значение по умолчанию:
INFOformatФормат записываемых сообщений.
Значение по умолчанию:
[%(asctime)s] %(asctime)s - %(name)s - %(message)sЗдесь
levelname— уровень важности сообщения,asctime— текущее время,name— имя модуля, выдавшего это сообщение (либоroot, если сообщение выдано не модулем), иmessage— собственно текст сообщения.
Параметры модулей
[plugins]
В разделе [plugins] описываются дополнительные модули, осуществляющие сбор метрик, и могут содержаться следующие параметры:
enabledВключает/отключает дополнительные модули, осуществляющие сбор метрик, при значении равном
TrueилиFalse, соответственно.Значение по умолчанию:
FalsedirectoryЗадаёт каталог, содержащий дополнительные модули. При значении, равном
None, использование дополнительных модулей отключается.Значение по умолчанию:
/etc/mamonsu/plugins
Если вы хотите настроить модуль, который вы дополнительно добавили в mamonsu после установки, для него нужно добавить раздел параметров в файл agent.conf.
Синтаксис, которому должен соответствовать этот раздел, показан в примере в Подразделе «Разделы отдельных модулей».
Разделы отдельных модулей
Все встроенные модули устанавливаются в составе mamonsu. Чтобы настроить такой модуль, найдите соответствующий ему раздел под заголовком Individual Plugin Sections (Разделы отдельных модулей) и измените значения параметров:
enabledВключает/отключает встроенные модули при значении равном
TrueилиFalseсоответственно. Эти значения чувствительны к регистру.Значение по умолчанию:
FalseintervalУказывает интервал работы модуля в секундах. Параметр задаётся целым числом. Можно установить разные интервалы для разных модулей. Для модулей, собирающих метрики PostgreSQL/Postgres Pro, например autovacuum, checkpoint и т. д., это интервал, в течение которого mamonsu обращается к экземпляру Postgres Pro для сбора метрик. Для системных модулей, например diskstats, memory и т. д., это интервал, в течение которого осуществляется обращение к операционной системе. Для служебных модулей, например agentapi, logsender, zbxsender, это интервал, в течение которого вызываются их функции. Обратите внимание, что параметр
intervalмодуля zbxsender связан с параметромtimeoutраздела[zabbix]. Максимальное время ожидания ответа сервера Zabbix, превышающее интервал работы модуля, может привести к неправильному поведению модуля zbxsender: модуль перезапускается с сообщением об ошибке, если подключение или передача данных занимают больше времени, чем значение, указанное в параметреinterval.Значение по умолчанию: 60
В следующем примере показаны разделы, соответствующие встроенным модулям preparedtransaction и pgprobackup:
[preparedtransaction] max_prepared_transaction_time = 60 interval = 60 [pgprobackup] enabled = false interval = 300 backup_dirs = /backup_dir1,/backup_dir2 pg_probackup_path = /usr/bin/pg_probackup-11
[preparedtransaction]
Этот модуль получает возраст старейшей подготовленной транзакции в секундах, а также число всех транзакций, подготовленных для двухфазной фиксации. За дополнительными сведениями обратитесь к PREPARE TRANSACTION и Разделу 56.17.
Параметр max_prepared_transaction_time задаёт в секундах пороговое значения для возраста подготовленной транзакции.
Данный модуль собирает две метрики: pgsql.prepared.count (число подготовленных транзакций) и pgsql.prepared.oldest (возраст старейшей подготовленной транзакции в секундах).
Если значение pgsql.prepared.oldest превышает порог, заданный параметром max_prepared_transaction_time, срабатывает триггер со следующим сообщением: «PostgreSQL prepared transaction is too old on {host}» (Слишком старая подготовленная транзакция PostgreSQL на {узел}).
[pgprobackup]
Этот модуль обращается к программе pg_probackup для отслеживания состояния её резервных копий, а также вычисляет объём каталогов, в которых хранятся все файлы копий.
Заметьте, что этот модуль подсчитывает общий объём всех файлов в целевом каталоге. Убедитесь в том, что в целевой каталог не попадают посторонние файлы.
Параметр backup_dirs задаёт разделённый запятыми список путей к каталогам, для которых будут собираться метрики.
Параметр pg_probackup_path задаёт путь к программе pg_probackup.
По умолчанию этот модуль отключён. Чтобы включить его, задайте для параметра enabled значение True.
Данный модуль собирает две метрики: pg_probackup.dir.size[#каталог_копий] (объём целевого каталога) и pg_probackup.dir.error[#каталог_копий] (ошибки копий) для каждого указанного каталога_копий.
Если какая-либо копия имеет ошибочное состояние, например ERROR, CORRUPT, ORPHAN, этот модуль вызывает срабатывание триггера.
Использование
Сбор и просмотр метрик
Сразу после запуска mamonsu начинает сбор метрик системы и Postgres Pro. Команда agent позволяет в реальном времени получать текущие значения собираемых метрик в командной строке.
Чтобы просмотреть список имеющихся метрик, воспользуйтесь командой agent metric-list:
mamonsu agent metric-list
Вывод этой команды включает ключ метрики, её последнее значение и время получения этого значения. Например:
system.memory[active] 7921004544 1564570818 system.memory[swap_cache] 868352 1564570818 pgsql.connections[idle] 6.0 1564570818 pgsql.archive_command[failed_trying_to_archive] 0 1564570818
Чтобы просмотреть текущее значение определённой метрики, воспользуйтесь командой agent metric-get:
mamonsu agent metric-get имя_метрики Здесь имя_метрики — ключ интересующей вас метрики, представленный в выводе команды metric-list. Например: pgsql.connections[idle].
Вы можете просмотреть графики собранных метрик в веб-интерфейсе Zabbix в разделе (Графики). Подробнее об использовании Zabbix рассказывается в его официальной документации по адресу https://www.zabbix.com/documentation/current/manual.
Если вы решили сохранять все собираемые метрики в файле как описано в «Параметры вывода», собранные метрики можно передать на сервер Zabbix для визуализации, воспользовавшись командой upload.
Добавление дополнительных модулей
Вы можете расширить функциональность mamonsu, добавив собственные дополнительные модули следующим образом:
Сохраните все нужные вам дополнительные модули в одном каталоге, например, в
/etc/mamonsu/plugins.Убедитесь в том, что этот каталог указан в файле конфигурации в разделе
[plugins]:[plugins] directory = /etc/mamonsu/plugins
Сгенерируйте новый шаблон Zabbix, включающий информацию дополнительных модулей:
mamonsu export template template.xml --add-plugins=/etc/mamonsu/plugins
Загрузите сгенерированный
template.xmlна сервер Zabbix, как описано в Разделе «Установка и подготовка».
Оптимизация конфигурации Postgres Pro и системы
В зависимости от собранных значений метрик, mamonsu может настроить конфигурацию Postgres Pro и системы для оптимальной производительности.
Вы можете получить подробную информацию об оборудовании, операционной системе, использовании памяти и других характеристиках объекта мониторинга, а также конфигурацию Postgres Pro, выполнив команду:
mamonsu report
Чтобы только просмотреть предлагаемые для оптимизации изменения, но не применять их, запустите команду tune с ключом --dry-run:
mamonsu tune --dry-run
Чтобы предлагаемые изменения были применены, запустите команду tune без каких-либо параметров:
mamonsu tune
Вы можете исключить некоторые параметры из отчёта или отключить некоторые методы оптимизации, передав дополнительные аргументы. Полный список аргументов команд report и tune приведён в Разделе «Справка по командной строке».
Управление параметрами сервера Zabbix в командной строке
Приложение mamonsu позволяет работать с сервером Zabbix, используя командную строку. В частности, вы можете загружать файлы шаблонов на сервер Zabbix, создавать и удалять узлы и группы узлов Zabbix, привязывать шаблоны к узлам и получать последние значения метрик.
Чтобы настроить узел мониторинга в Zabbix с самого начала, вы можете выполнить следующие действия:
При желании укажите учётные данные в Zabbix в следующих переменных окружения в той системе, где настраивается мониторинг:
Задайте в переменных
ZABBIX_USERиZABBIX_PASSWDимя и пароль вашей учётной записи Zabbix, соответственно.Задайте в переменной
ZABBIX_URLадресhttp://zabbix/
Если этого не сделать, вам нужно будет указывать следующие параметры при каждом вызове любой подкоманды
mamonsu zabbix:--url=http://zabbix/ --user=
имя_пользователя_zabbix--password=пароль_пользователя_zabbixСгенерируйте новый файл шаблона и загрузите его на сервер Zabbix:
mamonsu export template template.xml mamonsu zabbix template export template.xml
Создайте новую группу узлов:
mamonsu zabbix hostgroup create
имя_группы_узловОпределите идентификаторы созданной группы и загруженного шаблона, назначаемые автоматически сервером Zabbix:
mamonsu zabbix hostgroup id
имя_группы_узловmamonsu zabbix template idимя_шаблонаСоздайте узел, связанный с этой группой, и привяжите к нему загруженный шаблон с помощью одной команды:
mamonsu zabbix host create
имя_узлаид_группы_узловид_шаблонаадрес_mamonsuЗдесь
имя_узла— имя создаваемого узла,ид_группы_узловиид_шаблона— уникальные идентификаторы, полученные на предыдущем шаге, аmamonsu_address— IP-адрес системы, в которой работает mamonsu.
Создав узел в Zabbix, произведите настройку целевой системы, как описано в Разделе «Установка и подготовка».
Экспорт метрик для стандартного агента Zabbix
Используя mamonsu, вы можете преобразовать определения метрик системы и Postgres Pro в формат, который поддерживает стандартный агентом Zabbix.
В настоящее время эта функциональность имеет следующие ограничения:
В Windows экспорт метрик
mamonsuне поддерживается.Определения метрик входящего в Postgres Pro Enterprise расширения
pg_wait_samplingи механизма CFS не преобразуются.
Важно
Для работы с прокси Zabbix необходимо экспортировать все параметры в формат, который поддерживается стандартным агентом Zabbix.
Чтобы использовать агент Zabbix для сбора метрик mamonsu, выполните следующее:
Сгенерируйте файл конфигурации, совместимый со стандартным агентом Zabbix, и поместите его в
/etc/zabbix/zabbix_agent.d/. Вы можете добавить нужный путь перед именем файла:mamonsu export zabbix-parameters /etc/zabbix/zabbix_agent.d/zabbix_agent.conf
Все имеющиеся параметры команды
export zabbix-parametersописаны в Разделе «Справка по командной строке».Сгенерируйте шаблон для стандартного агента Zabbix:
mamonsu export zabbix-template template.xml
Все параметры команды
export zabbix-templateописаны в Разделе «Справка по командной строке».Загрузите сгенерированный шаблон на сервер Zabbix, как описано в Разделе «Установка и подготовка».
Если вы намерены собирать метрики Postgres Pro, после загрузки шаблона измените в веб-интерфейсе следующие макросы:
Вместо
{$PG_CONNINFO}укажите параметры подключения к серверу Postgres Pro, за которым вы намерены наблюдать.Вместо
{$PG_PATH}укажите путь к каталогу, где установлена программа psql.
Замечания о совместимости
Если вы хотите обновить mamonsu до версии, несовместимой с предыдущей, то ваши дальнейшие действия зависят от того, нужно ли вам сохранить собранные данные метрик.
Если вам нужно сохранить собранные данные, выполните следующее:
Установите новую версию mamonsu.
Сгенерируйте новый шаблон для сервера Zabbix.
Если вы выполняли специальную подготовительную процедуру в предыдущей версии mamonsu, запустите команду
bootstrapещё раз.Загрузите новый шаблон на сервер Zabbix.
Переименуйте узел, для которого вы хотите сохранить собранные данные, и оставьте его привязку к старому шаблону.
Создайте новый узел для той же системы и привяжите к нему новый шаблон.
Перезапустите службу mamonsu. Она будет собирать данные для нового узла. Старый узел больше не будет использоваться, но собранные для него данные будут по-прежнему доступны.
Если вам не нужно сохранять собранные данные, выполните следующее:
Установите новую версию mamonsu.
Сгенерируйте новый шаблон для сервера Zabbix.
Если вы выполняли специальную подготовительную процедуру в предыдущей версии mamonsu, запустите команду
bootstrapещё раз.Загрузите новый шаблон на сервер Zabbix.
В параметрах узла Zabbix привяжите к узлу новый шаблон вместо старого.
Перезапустите службу mamonsu, чтобы начался сбор данных. Все данные, собранные ранее, будут потеряны.
mamonsu
mamonsu — a monitoring agent for collecting Postgres Pro and system metrics
Synopsis
mamonsu agent [agent_action]
mamonsu bootstrap -M [mamonsu_user-c | --config] [-x | --create-extensions] [connection_options]
mamonsu export {template | config} filename [export_options]
mamonsu report [report_options] [connection_options]
mamonsu tune [tuning_options] [connection_options]
mamonsu upload [upload_options]
mamonsu zabbix dashboard upload template_name
mamonsu zabbix {template | host | hostgroup} server_action
mamonsu zabbix item {error | lastvalue | lastclock} host_id
mamonsu zabbix version
mamonsu [-c | --config] [-d | --daemonize]
mamonsu --version
mamonsu --help
Description
mamonsu is a monitoring agent for collecting Postgres Pro and system metrics that can be visualized on the Zabbix server. Unlike the native Zabbix Agent configured to collect Postgres Pro metrics, mamonsu uses a single database connection, which allows to minimize performance impact on the monitored system.
The mamonsu agent includes the following components:
A supervisor process that monitors database and system activity.
Plugins that specify which Postgres Pro and system metrics to collect.
Customizable configuration and template files that define which plugins to use and how to visualize the collected data.
mamonsu is an active agent, which means that it sends the data to the Zabbix server once it is collected. Pre-configured to monitor multiple Postgres Pro and system metrics out of the box, mamonsu can be extended with your own custom plugins to track other metrics critical for your system.
mamonsu also provides the command-line interface for updating some Zabbix server settings, as well as getting an overview of the monitored system configuration and tuning Postgres Pro and system settings on the fly. You can find the list of all mamonsu commands in the section called “Command-Line Reference”.
Installation and Setup
Important
Before you start installation, attentively read Compatibility Considerations.
To use mamonsu, you must create a Zabbix account and set up a Zabbix server as explained in Zabbix documentation. Naturally, you must also have a Postgres Pro instance up and running if you are going to monitor Postgres Pro metrics. If you are configuring your Postgres Pro cluster from scratch, see Chapter 17 and Section 18.2 for Postgres Pro installation and setup instructions, respectively.
Note
While mamonsu can collect Postgres Pro metrics from a remote cluster, system metrics are only collected locally. If you choose to collect Postgres Pro metrics remotely, make sure to disable collection of system metrics to avoid confusion, as they will be displayed under the same host in Zabbix.
mamonsu is provided with Postgres Pro Enterprise as a separate pre-built package mamonsu (for the detailed installation instructions, see Chapter 17). Once you have installed mamonsu, complete the following steps to set up metrics collection:
Optionally, bootstrap mamonsu
If you omit this step, metrics can only be collected on behalf of a superuser, which is not recommended.
In this step, the
bootstrapcommand sets the mamonsu user, createsmamonsuschema in the specified or implied database, as well as extensions and objects needed for monitoring.bootstraphas no mandatory options. When run without options, it takes the values needed from the configuration file (/etc/mamonsu/agent.confby default). Below is a simple example of bootstrap:In the
[postgres]section ofagent.conf, specify connection parameters for the Postgres Pro cluster you are going to monitor. For more details, see Connection Parameters.Run the following command to bootstrap mamonsu:
mamonsu bootstrap
This command will create the user
mamonsuwith the passwordmamonsu, create monitoring functions in the database specified inagent.confand grant the right to execute them to themamonsuuser.
In the following example,
bootstrapoptions are passed explicitly.Create a non-privileged database user for mamonsu. For example:
CREATE USER mamonsu_user WITH PASSWORD 'mamonsu_password'; GRANT pg_monitor TO mamonsu_user;
Create a database that will be used for connection to Postgres Pro. For example:
CREATE DATABASE mamonsu_database OWNER mamonsu_user;
Run the following command to bootstrap mamonsu:
mamonsu bootstrap -M mamonsu_user -x -c /etc/mamonsu/agent.conf -d mamonsu_database -U postgres --host myhost --port 5432
For details of the options
-M,-xand-c, seebootstrap. For details of other options, see Connection Options. This command will create monitoring functions in themamonsu_databaseand grant the right to execute them tomamonsu_user. The pg_buffercache extension will also be created to ensure collection of metrics on the shared buffer cache, and the path to the configuration file will be changed.
As a result, a superuser connection is no longer required. Note that mamonsu also creates several tables in the
mamonsuschema in the specified database. Do not delete these tables as they are required for mamonsu to work.Configure mamonsu
Edit the
agent.confconfiguration file, which is located in the/etc/mamonsu/directory by default.Configure Zabbix-related settings. The
addressfield must point to the running Zabbix server, while theclientfield must provide the name of the Zabbix host. You can find the list of hosts available for your account in the Zabbix web interface under > .[zabbix] ; enabled by default enabled =
Trueclient =zabbix_host_nameaddress =zabbix_serverBy default, mamonsu will collect both Postgres Pro and system metrics. If required, you can disable metrics collection of either type by setting the
enabledparameter toFalsein the[postgres]or[system]section of theagent.conffile, respectively.[system] ; enabled by default enabled = True
Note
While mamonsu can collect Postgres Pro metrics from a remote cluster, system metrics are only collected locally. If you choose to collect Postgres Pro metrics remotely, make sure to disable collection of system metrics to avoid confusion, as they will be displayed under the same host in Zabbix.
If you are going to collect Postgres Pro metrics, specify connection parameters for the Postgres Pro cluster you are going to monitor. In the
user,password, anddatabasefields, you must specify themamonsu_user,mamonsu_password, and themamonsu_databaseused for bootstrap, respectively. If you skipped the bootstrap, specify superuser credentials and the database to connect to.[postgres] ; enabled by default enabled = True user =
mamonsu_userdatabase =mamonsu_databasepassword =mamonsu_passwordport = 5432
These are the main mamonsu settings to get started. You can also fine-tune other mamonsu settings as explained in the section called “Configuration Parameters”.
Configure how to display metrics on the Zabbix server
Generate a template that defines how to visualize the collected metrics on the Zabbix server:
mamonsu export template template.xml
mamonsu generates the
template.xmlfile in your current directory. By default, the name of the template that will be displayed in the Zabbix account isPostgresPro-, whereOSOSis the name of your operating system. To get a template with a different display name, you can run the above command with the--template-nameoption.Optionally, specify your Zabbix account settings in the following environment variables on your monitoring system:
Set the
ZABBIX_USERandZABBIX_PASSWDvariables to the login and password of your Zabbix account, respectively.Set the
ZABBIX_URLtohttp://zabbix/
If you skip this step, you will have to add the following options to all
mamonsu zabbixcommands that you run:--url=http://zabbix/ --user=
zabbix_login--password=zabbix_passwordUpload
template.xmlto the Zabbix server.mamonsu zabbix template export template.xml
Alternatively, you can upload the template through the Zabbix web interface: log in to your Zabbix account and select Templates > Import.
Link the generated template to the host to be monitored.
In the Zabbix web interface, select your host, go to Templates > Add, select your template, and click Update.
Tip
If you would like to link a template with a new Zabbix host, you can do it from the command line using
mamonsu zabbixcommands. See the section called “Managing Zabbix Server Settings from the Command Line” for details.
When the setup is complete, start mamonsu. For example, on Linux systems, you can start mamonsu as a service with the following command:
service mamonsu start
mamonsu picks up all the parameters from the mamonsu configuration file and starts monitoring your system.
Command-Line Reference
agent
Syntax:
mamonsu agent { metric-list | metric-get metric_name | version }
Provide information on the collected metrics from the command line. You can specify one of the following parameters:
metric-listShow the list of metrics that mamonsu is collecting. The output of this command provides the item key of each metric, its latest value, and the time when this value was received.
metric-getmetric_nameCheck the latest value for the specified metric. You can get the list of available metrics using the
metric-listoption.versionDisplay mamonsu version.
bootstrap
Syntax:
mamonsu bootstrap -Mmamonsu_user[-c[config_file] | --config[=config_file]] [-x | --create-extensions] [connection_options]
Bootstrap mamonsu. This command can take the following options:
-MSpecify a non-privileged user that will own all mamonsu processes.
-cconfig_file--config=config_fileSpecify the
agent.conffile where the[postgres]section contains the database name to be used if--dbnameis not specified through.connection_optionsDefault:
/etc/mamonsu/agent.conf-x--create-extensionsCreate auxiliary extensions. The pg_buffercache extension will be created, which is no longer created by default. For Postgres Pro 12 or higher, the
bootstrapcommand will also create functions to work with the pgpro_stats extension and grant the right to execute them to the-xmamonsuuser.connection_optionsProvide optional
command-line connection parameters.
export
Syntax:
mamonsu export configfilename.conf [--add-plugins=plugin_directory] mamonsu export templatefilename.xml [--add-plugins=plugin_directory] [--template-name=template_name] [--application=application_name] [--old-zabbix]
Generate a template or configuration file for metrics collection. The optional parameters to customize metrics collection are as follows:
--add-plugins=plugin_directoryCollect metrics that are defined in custom plugins located in the specified
plugin_directory. If you are going to use custom plugins, you must provide this option when generating both the configuration file and the template.--template-name=template_nameSpecify the name of the template that will be displayed on the Zabbix server.
Default:
PostgresPro-, whereOSOSis the name of your operating system--application=application_nameSpecify an identifier under which the collected metrics will be displayed on the Zabbix server.
Default:
App-PostgresPro-, whereOSOSis the name of your operating system--old-zabbixExport a template for Zabbix server version 4.2 or lower. By default, the template is generated in a format compatible with Zabbix 4.4 or higher.
export zabbix-parameters
Syntax:
mamonsu export zabbix-parametersfilename.conf [--add-plugins=plugin_directory] [--plugin-type={pg | sys | all}] [--pg-version=version] [--config=config_file]
Export metrics configuration for use with the native Zabbix agent. The optional parameters to customize metrics collection are as follows:
--add-plugins=plugin_directoryCollect metrics that are defined in custom plugins located in the specified
plugin_directory. If you are going to use custom plugins, you must provide this option when generating both the configuration file and the template.--plugin-type={pg | sys | all}Specify the type of metrics to collect:
pgfor Postgres Pro metrics.sysfor system metrics.allfor both Postgres Pro and system metrics.
Default:
all--pg-version=versionSpecify the major version of the server for which to configure metrics collection.
mamonsucan collect metrics for all supported Postgres Pro versions, as well as PostgreSQL versions starting from 9.5.Default:
10--config=config_fileSpecify the
agent.conffile to be used as the source for metrics definitions.Default:
/etc/mamonsu/agent.conf
export zabbix-template
Syntax:
mamonsu export zabbix-templatefilename.conf [--add-plugins=plugin_directory] [--plugin-type={pg | sys | all}] [--template-name=template_name] [--application=application_name] [--config=config_file] [--old-zabbix]
Export a template for use with the native Zabbix agent. The optional parameters to customize metrics collection are as follows:
--add-plugins=plugin_directoryCollect metrics that are defined in custom plugins located in the specified
plugin_directory. If you are going to use custom plugins, you must provide this option when generating both the configuration file and the template.--plugin-type={pg | sys | all}Specify the type of metrics to collect:
pgconfigures Postgres Pro metrics.sysconfigures system metrics.allconfigures both Postgres Pro and system metrics.
Default:
all--template-name=template_nameSpecify the name of the template that will be displayed on the Zabbix server.
Default:
PostgresPro-, whereOSOSis the name of your operating system--application=application_nameSpecify an identifier under which the collected metrics will be displayed on the Zabbix server.
Default:
App-PostgresPro-, whereOSOSis the name of your operating system--config=config_fileSpecify the
agent.conffile to be used as the source for metrics definitions.Default:
/etc/mamonsu/agent.conf--old-zabbixExport a template for Zabbix server version 4.2 or lower. By default, the template is generated in a format compatible with Zabbix 4.4 or higher.
report
Syntax:
mamonsu report [--run-system=Boolean] [--run-postgres=Boolean] [--print-report=Boolean] [--report-path=report_file] [--disable-sudo] [connection_options]
Generate a detailed report on the hardware, operating system, memory usage and other parameters of the monitored system, as well as Postgres Pro configuration.
The following optional parameters customize the report:
--run-system=BooleanInclude system information into the generated report.
Default:
True--run-postgres=BooleanInclude information on Postgres Pro into the generated report.
Default:
True--print-report=BooleanPrint the report to stdout.
Default:
True--report-path=report_fileSave the report into the specified file.
Default:
/tmp/report.txt--disable-sudoDo not report data that can only be received with superuser rights. This option is only available for Linux systems.
connection_optionsProvide optional
command-line connection parameters.
tune
Syntax:
mamonsu tune [--dry-run] [--disable-sudo] [--log-level {INFO|DEBUG|WARN}]
[--dont-tune-pgbadger] [--dont-reload-postgresql]
[connection_options]
Optimize Postgres Pro and system configuration based on the collected statistics. You can use the following options:
--dry-runDisplay the settings to be tuned without changing the actual system and Postgres Pro configuration.
--disable-sudoDo not tune the settings that can only be changed by a superuser. This option is only available for Linux systems.
--dont-tune-pgbadgerDo not tune pgbadger parameters.
--log-level { INFO | DEBUG | WARN}Change the logging level.
Default:
INFO--dont-reload-postgresqlForbid mamonsu to run the
pg_reload_conf()function. If you specify this option, the modified settings that require reloading Postgres Pro configuration do not take effect immediately.connection_optionsProvide optional
command-line connection parameters.
upload
Syntax:
mamonsu upload [--zabbix-file=metrics_file] [--zabbix-address=zabbix_address] [--zabbix-port=port_number] [--zabbix-client=zabbix_host_name] [--zabbix-log-level={INFO|DEBUG|WARN}]
Upload metrics data previously saved into a file onto a Zabbix server for visualization. For details on how to save metrics into a file, see the section called “Logging Parameters”.
This command can take the following options:
--zabbix-address=zabbix_addressThe address of the Zabbix server.
Default:
localhost--zabbix-port=port_numberThe port of the Zabbix server.
Default: 10051
--zabbix-file=metrics_fileA text file that stores the collected metrics data to be visualized, such as
localhost.log.--zabbix-client=zabbix_host_nameThe name of the Zabbix host.
Default:
localhost--zabbix-log-level={INFO|DEBUG|WARN}Change the logging level.
Default:
INFO
zabbix dashboard upload
Syntax:
mamonsu dashboard upload template_name
Upload a Zabbix dashboard with the mamonsu metrics to a template on the Zabbix server version 6.0 or higher.
zabbix item
Syntax:
mamonsu zabbix item {error | lastvalue | lastclock } host_name
View the specified property of the latest metrics data received by Zabbix for the specified host.
zabbix version
Syntax:
mamonsu zabbix version
Get the version of the Zabbix server that mamonsu is connected to.
zabbix host
Syntax:
mamonsu zabbix host list mamonsu zabbix host showhost_namemamonsu zabbix host idhost_namemamonsu zabbix host deletehost_idmamonsu zabbix host createhost_namehostgroup_idtemplate_idmamonsu_addressmamonsu zabbix host info {templates | hostgroups | graphs | items}host_id
Manage Zabbix hosts using one of the actions described in the section called “Zabbix Server Actions”.
zabbix hostgroup
Syntax:
mamonsu zabbix hostgroup list mamonsu zabbix hostgroup showhostgroup_namemamonsu zabbix hostgroup idhostgroup_namemamonsu zabbix hostgroup deletehostgroup_idmamonsu zabbix hostgroup createhostgroup_name
Manage Zabbix host groups using one of the actions described in the section called “Zabbix Server Actions”.
zabbix template
Syntax:
mamonsu zabbix template list mamonsu zabbix template showtemplate_namemamonsu zabbix template idtemplate_namemamonsu zabbix template deletetemplate_idmamonsu zabbix template exportfile
Manage Zabbix templates using one of the actions described in the section called “Zabbix Server Actions”.
[--config] [--daemonize]
Syntax:
mamonsu [-cconfig_file| --config=config_file] [-d | --daemonize]
Start working as a monitoring agent in the foreground or in the background using configuration parameters loaded from the configuration file. If the specified or default configuration file does not exist, exit with an error. Useful for debugging. You can specify the following options:
-cconfig_file--config=config_fileSpecify the
agent.conffile where to load the configuration parameters from.Default:
/etc/mamonsu/agent.conf-d--daemonizeRun in the background. Without it, mamonsu will run in the foreground.
--version
Syntax:
mamonsu --version
Display mamonsu version.
--help
Syntax:
mamonsu --help
Display mamonsu command-line help.
Connection Options
connection_options provide command-line connection parameters for the target Postgres Pro cluster. connection_options can be --host, --port, --dbname (-d), --username (-U), and --password (-W). The --dbname option should specify the mamonsu_database created for monitoring purposes. Note that the --username (-U) option must specify a superuser that can access the cluster.
If you omit connection_options, mamonsu checks the configuration file for the needed settings.
Zabbix Server Actions
Using mamonsu, you can control some of the Zabbix server functionality from the command line. Specifically, you can create or delete Zabbix hosts and host groups, as well as generate, import, and delete Zabbix templates using one of the following commands. The object_name to use must correspond to the type of the Zabbix object specified in the command: template, host, or hostgroup.
listDisplay the list of available templates, hosts, or host groups.
showobject_nameDisplay the details about the specified template, host, or host group.
idobject_nameShow the ID of the specified object, which is assigned automatically by the Zabbix server.
deleteobject_idDelete the object with the specified ID.
createhostgroup_namecreatehost_namehostgroup_idtemplate_idmamonsu_addressCreate a new host or a host group.
exporttemplate_nameGenerate a Zabbix template.
info {templates | hostgroups | graphs | items}host_idDisplay detailed information about the templates, host groups, graphs, and metrics available on the host with the specified ID.
Configuration Parameters
The agent.conf configuration file is located in the /etc/mamonsu directory by default. It provides several groups of parameters that control which metrics to collect and how to log the collected data:
All parameters must be specified in the format. parameter = value
Connection Parameters
[postgres]
The [postgres] section controls Postgres Pro metrics collection and can contain the following parameters:
enabledEnables/disables Postgres Pro metrics collection if set to
TrueorFalse, respectively.Default:
TrueuserThe user on behalf of which the cluster will be monitored. It must be the mamonsu user set in bootstrap, or a superuser if
bootstrapwas not run.Default:
postgrespasswordThe password for the specified user.
databaseThe database to connect to for metrics collection.
Default:
postgreshostThe server address to connect to.
Default:
localhostportThe port to connect to.
Default: 5432
application_nameApplication name that identifies mamonsu connected to the Postgres Pro cluster.
Default:
mamonsuquery_timeoutstatement_timeout for the mamonsu session, in seconds. If a Postgres Pro metric query does not complete within this time interval, it gets terminated.
Default: 10
Alternatively you can specify environment variables rather than the configuration parameters. The following environment variables can be used: PGUSER, PGPASSWORD, PGHOST, PGDATABASE, PGPORT, and PGAPPNAME. See Section 36.15 for their meaning.
[system]
The [system] section controls system metrics collection and can contain the following parameters:
enabledEnables/disables system metrics collection if set to
TrueorFalse, respectively.Default:
True
[zabbix]
The [zabbix] section provides connection settings for the Zabbix server and can contain the following parameters:
enabledEnables/disables sending the collected metrics data to the Zabbix server if set to
TrueorFalse, respectively.Default:
TrueclientThe name of the Zabbix host.
addressThe address of the Zabbix server.
Default: 127.0.0.1
portThe port of the Zabbix server.
Default: 10051
timeoutMaximum time to wait while connecting to the Zabbix server, in seconds.
Default: 15
[agent]
The [agent] section specifies the location of mamonsu and whether it is allowed to access metrics from the command line:
enabledEnables/disables metrics collection from the command line using the
agentcommand.Default:
TruehostThe address of the system on which mamonsu is running.
Default: 127.0.0.1
portThe port on which mamonsu is running.
Default: 10052
[sender]
The [sender] section controls the queue size of the data to be sent to the Zabbix server:
queueThe maximum number of collected metric values that can be accumulated locally before mamonsu sends them to the Zabbix server. Once the accumulated data is sent, the queue is cleared.
Default: 2048
Logging Parameters
[metric_log]
The [metric_log] section enables storing the collected metrics data in text files locally. This section can contain the following parameters:
enabledEnables/disables storing the collected metrics data in a text file. If this option is set to
True, mamonsu creates thelocalhost.logfile for storing metric values.Default:
FalsedirectorySpecifies the directory where log files with metrics data will be stored.
Default:
/var/log/mamonsumax_size_mbThe maximum size of a log file, in MB. When the specified size is reached, it is renamed to
localhost.log.archive, and an emptylocalhost.logfile is created.Default: 1024
[log]
The [log] section specifies logging settings for mamonsu and can contain the following parameters:
fileSpecifies the log filename, which can be preceded by the full path.
levelSpecifies the debug level. This option can take
DEBUG,ERROR, orINFOvalues.Default:
INFOformatThe format of the logged data.
Default:
[%(levelname)s] %(asctime)s - %(name)s - %(message)swhere
levelnameis the debug level,asctimereturns the current time,namespecifies the plugin that emitted this log entry orroototherwise, andmessageprovides the actual log message.
Plugin Parameters
[plugins]
The [plugins] section specifies custom plugins to be added for metrics collection and can contain the following parameters:
enabledEnables/disables using custom plugins for metrics collection if set to
TrueorFalse, respectively.Default:
FalsedirectorySpecifies the directory that contains custom plugins for metrics collection. Setting this parameter to
Noneforbids using custom plugins.Default:
/etc/mamonsu/plugins
If you need to configure any of the plugins you add to mamonsu after installation, you have to add this plugin section to the agent.conf file.
The syntax of this section should follow the syntax used with the examples shown below in the section called “Individual Plugin Sections”.
Individual Plugin Sections
All built-in plugins are installed along with mamonsu. To configure a built-in plugin you should find a corresponding section below the Individual Plugin Sections heading and edit its parameter values:
enabledEnables/disables using built-in plugins if set to
TrueorFalse, respectively. These values are case-sensitive.Default:
FalseintervalSpecifies the plugin operation interval, in seconds. The parameter is set with an integer specifying the plugin operation interval in seconds. You can set different intervals for different plugins. For plugins that collect PostgreSQL/ Postgres Pro metrics, for example, autovacuum, checkpoint, etc., this is the interval within which mamonsu accesses the Postgres Pro instance for metrics collection. For system plugins, for example, diskstats, memory, etc., this is the interval within which the operating system is accessed. For service plugins, for example, agentapi, logsender, zbxsender, this is the interval within which their functions are called. Note that the
intervalparameter of the zbxsender plugin is associated with thetimeoutparameter of the[zabbix]section. The maximum Zabbix server response timeout greater than the plugin operation interval may cause misbehavior of the zbxsender plugin: the plugin restarts with an error message if the connection or data transfer require longer time than the value specified in theintervalparameter.Default: 60
The example below shows individual plugin sections corresponding to the preparedtransaction and the pgprobackup built-in plugins:
[preparedtransaction] max_prepared_transaction_time = 60 interval = 60 [pgprobackup] enabled = false interval = 300 backup_dirs = /backup_dir1,/backup_dir2 pg_probackup_path = /usr/bin/pg_probackup-11
[preparedtransaction]
This plugin gets age in seconds of the oldest prepared transaction and number of all transactions prepared for a two-phase commit. For additional information refer to PREPARE TRANSACTION and Section 56.17.
The max_prepared_transaction_time parameter specifies the threshold in seconds for the age of the prepared transaction.
The plugin collects two metrics: pgsql.prepared.count (number of prepared transactions) and pgsql.prepared.oldest (oldest prepared transaction age in seconds).
If pgsql.prepared.oldest value exceeds the threshold specified by the max_prepared_transaction_time parameter, a trigger with the following message is fired: "PostgreSQL prepared transaction is too old on {host}".
[pgprobackup]
This plugin uses pg_probackup to track its backups' state and gets size of backup directories which store all backup files.
Please note that this plugin counts the total size of all files in the target directory. Make sure that extraneous files are not stored in this directory.
The backup_dirs parameter specifies a comma-separated list of paths to directories for which metrics should be collected.
The pg_probackup_path parameter specifies the path to pg_probackup.
By default this plugin is disabled. To enable it set the enabled parameter to True.
This plugin collects two metrics: pg_probackup.dir.size[#backup_directory] (the size of the target directory) and pg_probackup.dir.error[#backup_directory] (backup errors) for each specified backup_directory.
If any generated backup has bad status, like ERROR, CORRUPT, ORPHAN, a trigger is fired.
Usage
Collecting and Viewing Metrics Data
Once started, mamonsu begins collecting system and Postgres Pro metrics. The agent command enables you to get an overview of the collected metrics from the command line in real time.
To view the list of available metrics, use the agent metric-list command:
mamonsu agent metric-list
The output of this command provides the item key of each metric, its latest value, and the time when this value was received. For example:
system.memory[active] 7921004544 1564570818 system.memory[swap_cache] 868352 1564570818 pgsql.connections[idle] 6.0 1564570818 pgsql.archive_command[failed_trying_to_archive] 0 1564570818
To view the current value for a specific metric, you can use the agent metric-get command:
mamonsu agent metric-get metric_name
where metric_name is the item key of the metric to monitor, as returned by the metric-list command. For example, pgsql.connections[idle].
You can view graphs for the collected metrics in the Zabbix web interface under the menu. For details on working with Zabbix, see its official documentation at https://www.zabbix.com/documentation/current/manual.
If you have chosen to save all the collected metrics data into a file, as explained in the section called “Logging Parameters”, you can later upload these metrics onto a Zabbix server for visualization using the upload command.
Adding Custom Plugins
You can extend mamonsu with your own custom plugins, as follows:
Save all custom plugins in a single directory, such as
/etc/mamonsu/plugins.Make sure this directory is specified in your configuration file under the
[plugins]section:[plugins] directory = /etc/mamonsu/plugins
Generate a new Zabbix template to include custom plugins:
mamonsu export template template.xml --add-plugins=/etc/mamonsu/plugins
Upload the generated
template.xmlto the Zabbix server as explained in the section called “Installation and Setup”.
Tuning Postgres Pro and System Configuration
Based on the collected metrics data, mamonsu can tune your Postgres Pro and system configuration for optimal performance.
You can get detailed information about the hardware, operating system, memory usage and other parameters of the monitored system, as well as Postgres Pro configuration, as follows:
mamonsu report
To view the suggested optimizations without applying them, run the tune command with the --dry-run option:
mamonsu tune --dry-run
To apply all the suggested changes, run the tune command without any parameters:
mamonsu tune
You can exclude some settings from the report or disable some of the optimizations by passing optional parameters. See the section called “Command-Line Reference” for the full list of parameters available for report and tune commands.
Managing Zabbix Server Settings from the Command Line
mamonsu enables you to work with the Zabbix server from the command line. You can upload template files to Zabbix, create and delete Zabbix hosts and host groups, link templates with hosts and check the latest metric values.
To set up your Zabbix host from scratch, you can follow these steps:
Optionally, specify your Zabbix account settings in the following environment variables on your monitoring system:
Set the
ZABBIX_USERandZABBIX_PASSWDvariables to the login and password of your Zabbix account, respectively.Set the
ZABBIX_URLtohttp://zabbix/
If you skip this step, you will have to add the following options to all
mamonsu zabbixcommands that you run:--url=http://zabbix/ --user=
zabbix_login--password=zabbix_passwordGenerate a new template file and upload it to the Zabbix server:
mamonsu export template template.xml mamonsu zabbix template export template.xml
Create a new host group:
mamonsu zabbix hostgroup create
hostgroup_nameCheck the IDs for this host group and the uploaded template, which are assigned automatically by the Zabbix server:
mamonsu zabbix hostgroup id
hostgroup_namemamonsu zabbix template idtemplate_nameCreate a host associated with this group and link it with the uploaded template using a single command:
mamonsu zabbix host create
host_namehostgroup_idtemplate_idmamonsu_addresswhere
host_nameis the name of the host,hostgroup_idandtemplate_idare the unique IDs returned in the previous step, andmamonsu_addressis the IP address of the system on which mamonsu runs.
Once your Zabbix host is configured, complete the setup of your monitoring system as explained in the section called “Installation and Setup”.
Exporting Metrics for Native Zabbix Agent
Using mamonsu, you can convert system and Postgres Pro metrics definitions to the format supported by the native Zabbix agent.
This feature currently has the following limitations:
You cannot export metrics if you run
mamonsuon Windows systems.Metrics definitions for
pg_wait_samplingand CFS features available in Postgres Pro Enterprise are not converted.
Important
To work with Zabbix proxy, you must export settings to the format supported by the native Zabbix agent.
To collect metrics provided by mamonsu using the native Zabbix agent, do the following:
Generate a configuration file that is compatible with the native Zabbix agent and place it under
/etc/zabbix/zabbix_agent.d/. You can prepend the filename with the required path:mamonsu export zabbix-parameters /etc/zabbix/zabbix_agent.d/zabbix_agent.conf
For all possible options of the
export zabbix-parameterscommand, see the section called “Command-Line Reference”.Generate a template for the native Zabbix agent:
mamonsu export zabbix-template template.xml
For all possible options of the
export zabbix-templatecommand, see the section called “Command-Line Reference”.Upload the generated template to the Zabbix server, as explained in the section called “Installation and Setup”.
If you are going to collect Postgres Pro metrics, change the following macros in the template after the upload:
For
{$PG_CONNINFO}, provide connection parameters for the Postgres Pro server to be monitored.For
{$PG_PATH}, specify psql installation directory.
Compatibility Considerations
If you want to upgrade mamonsu to a version that is not compatible with the previous one, what you must do to continue using the application depends on whether you need to retain the metrics data collected.
If you need to retain the collected data, do the following:
Install the new version of mamonsu.
Generate a new template for the Zabbix server.
If you performed a bootstrap using the previous version of mamonsu, run the
bootstrapcommand again.Upload the new template to the Zabbix server.
Rename the host for which you want to retain the collected data and leave the old template linked to that host.
Create a new host for the same system and link the new template to it.
Restart mamonsu. It will collect data for the new host. The old host will no longer be used, but the data collected will be available.
If you do not need to retain the collected data, do the following:
Install the new version of mamonsu.
Generate a new template for the Zabbix server.
If you performed a bootstrap using the previous version of mamonsu, run the
bootstrapcommand again.Upload the new template to the Zabbix server.
In the settings of the Zabbix host, link the new template to the host instead of the old one.
Restart mamonsu. It will start collecting data. All the data collected earlier will be lost.