PostgreSQL это современная, динамично развивающаяся СУБД с очень большим набором возможностей которые позволяют решать самый широкий спектр задач. Использование PostgreSQL как правило относится к очень критичному сегменту ИТ инфраструктуры который связан с обработкой и хранением данных. Учитывая особое место СУБД в инфраструктуре и степень критичности возложенных на нее задач, возникает вопрос мониторинга и надлежащего контроля за работой СУБД. В этом плане PostgreSQL обладает широкими внутренними средствами сбора и хранения статистики. Собираемая статистика позволяет получить довольно подробную картину о том что происходит под капотом в процессе функционирования СУБД. Эта статистика хранится в специальных системных таблицах-представлениях и постоянно обновляется. Выполняя обычные SQL запросы в эти таблицы можно получать разнообразные данные о базах, таблицах, индексах и других подсистемах СУБД.
Ниже я описываю способ и средства для мониторинга PostgreSQL в системе мониторинга Zabbix. Мне нравится эта система мониторинга поскольку предоставляет широкие возможности для реализации самого кастомного мониторинга самых разных систем и процессов.
Мониторинг будет строиться на основе SQL запросов к таблицам статистики. Сами запросы оформлены в виде дополнительного конфигурационного файла к zabbix агенту, в котором SQL запросы обернуты в т.н. UserParameters — пользовательские параметры мониторинга. Пользовательский параметр в Zabbix это отличный способ который позволяет настраивать мониторинг для нестандартных вещей, такими вещами в нашем случае будут параметры работы PostgreSQL. Каждый пользовательский параметр состоит из двух элементов: Название ключа и Команда. Название ключа представляет собой уникальное имя которое не пересекается с другими именами ключей. Команда — это собственно команда-действие которое должен выполнить агент zabbix. В расширенном варианте этой команде могут быть переданы различные параметры. В конфигурации заббикса, это выглядит так:
UserParameter=custom.simple.key,/usr/local/bin/simple-script
UserParameter=custom.ext.key[*],/usr/local/bin/ext-script $1 $2
Таким образом, все запросы к статистике PostgreSQL представляют собой запросы клиента psql обернутые в пользовательские параметры.
Сильные стороны:
- минимальные требования к конфигурированию наблюдаемого узла — в самом простом случае добавляем конфиг и перезапускаем zabbix агент (сложный случай предполагает донастройку прав доступа к PostgreSQL);
- настройка параметров подключения к PostgreSQL, как и пороговые значения для триггеров выполняются через переменные-макросы в веб-интерфейсе — таким образом не нужно залазить в триггеры и плодить шаблон на случай разных пороговых значений для разных хостов (макросы можно назначить на хост);
- широкий спектр собираемых данных (соединения, время транзакций, статистика по базам и таблицам, потоковая репликация и пр.);
- низкоуровневое обнаружение для баз данных, таблиц и серверов stand-by.
Слабые стороны:
- очень много наблюдаемых параметров, возможно кто-то захочет что-то отключить.
- в зависимости от версии PostgreSQL какие-то вещи не будут работать. В частности, это касается мониторинга репликации, т.к. некоторых функций попросту нет в старых версиях. Писалось с оглядкой на версии 9.2 и выше.
- также для некоторых вещей требуется наличие установленных расширений pg_stat_statements и pg_buffercache — если расширения не установлены часть параметров будет недоступна для наблюдения.
Возможности мониторинга:
- информация по объему выделяемых и записываемых буферах, чекпоинтах и времени записи в процессе чекпойинтов — pg_stat_bgwriter
- общая информация по shared buffers — здесь требуется расширение pg_buffercache. Также хочу отметить что запросы к этой статистике являются ресурсозатратными, что отражено в документации к расширению, поэтому в зависимости от потребностей можно либо увеличить интервал опроса, либо выключить параметры совсем.
- общая информация по сервису — аптайм, время ответа, cache hit ratio, среднее время запроса.
- информация по клиентским соединениям и времени выполнения запросов/транзакций — pg_stat_activity.
- размер баз данных и суммарная статистика по всем базам (коммиты/роллбэки, чтение/запись, временные файлы) — pg_stat_database
- потабличная статистика (чтение/запись, кол-во служебных задач такие как vacuum/analyze) — pg_stat_user_tables, pg_statio_user_tables.
- информация по потоковой репликации (статус сервера, количество реплик, лаг с ними) — pg_stat_replication
- прочие штуки (кол-во строк в таблице, существование триггера, параметры конфигурации, WAL журналы)
Дополнительно стоит отметить, что для сбора статистических данных необходимо включить следующие параметры в postgresql.conf:
track_activities — включает трекинг команд (queries/statements) всеми клиентскими процессами;
track_counts — включает сбор статистики по таблицам и индексам;
Установка и настройка.
Все необходимое для настройки находится в Github репозитории.
# git clone https://github.com/lesovsky/zabbix-extensions/
# cp zabbix-extensions/files/postgresql/postgresql.conf /etc/zabbix/zabbix_agentd.d/
Дальше следует отметить что для выполнения запросов со стороны агента, необходимо чтобы в pg_hba конфигурации был определен соответствующий доступ — агент должен иметь возможность устаналивать соединения с postgres сервисом в целевую базу и исполнять запросы. В самом простом случае нужно добавить следующую строку в pg_hba.conf (для разных дистрибутив расположение файла может отличаться) — разрешаем подключения от имени postgres к базе mydb с localhost.
host mydb postgres 127.0.0.1/32 trust
Незабываем, что после изменения pg_hba.conf сервису postgresql нужно сделать reload (pg_ctl reload). Однако это самый простой вариант и не совсем безопасный, поэтому если вы хотите использовать парольную или более сложную схему доступа, то еще раз внимательно ознакомьтесь с pg_hba и .pgpass.
Итак файл конфигурации скопирован, осталось подгрузить его в основную конфигурацию, убедитесь что в основном файле конфигурации агента, есть строка Include c указанным там путем где размещены дополнительные файлы конфигурации. Теперь перезапускаем агента, после чего можем проверить работу выполнением самой простой проверки — используем pgsql.ping и в квадратных скобках указываем опции подключения к postgres, которые будет переданы psql клиенту.
# systemctl restart zabbix-agent.service
# zabbix-get -s 127.0.0.1 -k pgsql.ping['-h 127.0.0.1 -p 5432 -U postgres -d mydb']
Если вы правильно прописали доступ, то вам вернется время ответа сервиса в милисекундах. Если вернулась пустая строка, то тут проблема с доступом в pg_hba. Если вернулась строка ZBX_NOTSUPPORTED — конфигурация не подгрузилась, проверяйте конфиг агента, пути в Include и выставленные на конфиг права.
Когда команда проверки возвращает правильный ответ, остается скачать шаблон и загрузить его в веб интерфейс и назначить на целевой хост. Скачать шаблон можно также из репозитория (postgresql-extended-template.xml). После импорта нужно перейти на вкладку настройки макросов шаблона и настроить их.
Ниже список и краткое описание:
- PG_CONNINFO — это параметры подключения который будут переданы клиенту psql при выполнении запроса. Это самый важный макрос т.к. определяет параметры подключения к postgres сервису. Строка указанная по умолчанию является более-менее универсальной для любых случаев, однако если у вас несколько серверов и у каждого сервера отличные от других настройки, то у хостов в заббиксе можно определить макрос с таким же именем и задать ему индивидуальное значение. При выполнении проверки макрос хоста имеет приоритет перед макросом шаблона.
- PG_CONNINFO_STANDBY — это параметры подключения который будут переданы утилите psql при выполнении запроса на stanby сервера (определение лага репликации).
- PG_CACHE_HIT_RATIO — это пороговое значение для триггера на процент успешного попадания в кэш; сработает триггер если процент попадания будет ниже этой отметки;
- PG_CHECKPOINTS_REQ_THRESHOLD — пороговое значение для чекпойнтов по требованию
- PG_CONFLICTS_THRESHOLD — пороговое значение для конфликтов возникших при выполнении запросов на серверах standby;
- PG_CONN_IDLE_IN_TRANSACTION — пороговое значение для соединений которые открыли транзакцию и ничего при этом не делают (плохие транзакции);
- PG_CONN_TOTAL_PCT — пороговое значение для процента открытых соединений к максимально возможному числу соединений (если 100%, то всё, коннекты кончились);
- PG_CONN_WAITING — пороговое значение для заблокированных запросов которые ждут завершения других запросов;
- PG_DATABASE_SIZE_THRESHOLD — пороговое значение для размера БД;
- PG_DEADLOCKS_THRESHOLD — пороговое значение для дедлоков (к счастью они разрешаются автоматически, но об их наличии желательно быть в курсе, т.к. это прямое свидетельство некачественно написанного кода);
- PG_LONG_QUERY_THRESHOLD — пороговое значение для времени выполнения запросов; сработает триггер если будут запросы чье время выполнения больше этой отметки;
- PG_PING_THRESHOLD_MS — пороговое значение для времени ответа сервиса;
- PG_SR_LAG_BYTE — пороговое значение для лага репликации в байтах;
- PG_SR_LAG_SEC — пороговое значение для лага репликации в секундах;
- PG_UPTIME_THRESHOLD — пороговое значение аптайма, если аптайм ниже отметки значит сервис перезапустили;
Из текста триггеров должно стать понятно для чего нужны эти пороговые значения:
- PostgreSQL active transaction to long — зафиксирована длинная транзакция или запрос;
- PostgreSQL cache hit ratio too low — слишком низкий процент попадания в кэш;
- PostgreSQL deadlock occured — зафиксирован дедлок;
- PostgreSQL idle in transaction connections to high — много коннектов в состоянии idle in transaction;
- PostgreSQL idle transaction to long — зафиксирована длинная транзакция в состоянии idel in transaction;
- PostgreSQL number of waiting connections to high — зафиксированн запрос или транзакция в состоянии ожидания;
- PostgreSQL recovery conflict occured — обнаружен конфликт при восстановлении на реплике;
- PostgreSQL required checkpoints occurs to frequently — чекпоинты случаются слишком часто;
- PostgreSQL response to long — долгое время ответа;
- PostgreSQL service not running — сервис не запущен;
- PostgreSQL service was restarted — сервис перезапустился;
- PostgreSQL total number of connections to high — общее число коннектов слишком большое и приближается к max_connections;
- PostgreSQL waiting transaction to long — зафиксирована слишком длинный запрос или транзакция в состоянии ожидания;
- PostgreSQL database {#DBNAME} to large — размер БД слишком большой;
- PostgreSQL streaming lag between {HOSTNAME} and {#HOTSTANDBY} to high — лаг репликации между серверами слишком большой.
Правила низкоуровневого обнаружения
- PostgreSQL databases discovery — обнаружение имеющихся БД с возможностью фильтрации по регулярным выражениям. При обнаружении добавляется график о размерах;
- PostgreSQL database tables discovery — обнаружение имеющихся таблиц в наблюдаемой базе с возможностью фильтрации по регулярным выражениям. Будьте внимательны с фильтром и добавляйте только те таблицы что вам реально интересны, т.к. это правило порождает 21 параметр на каждую найденную таблицу. При обнаружении добавляются графики о размерах, сканированиях, изменении строк и статистике по чтению.
- PostgreSQL streaming stand-by discovery — обнаружение подключенных реплик. При обнаружении добавляется график с лагом репликации.
Доступные графики, если говорить про графики, то я постарался сгруппировать наблюдаемые параметры, при этом не перегружая графики чрезмерно большим количеством парамтеров. Так информация из pg_stat_user_tables разнесена на 4 графика.
- PostgreSQL bgwriter — общая информация о том что происходит с буфферами (сколько выделено, сколько и каким образом записано).
- PostgreSQL buffers — общая информация по состоянию shared buffers (сколько буфферов, сколько используется, сколько «грязных» буфферов).
- PostgreSQL checkpoints — информация по происходящим чекпоинтам.
- PostgreSQL connections — информация по клиентским соединениям.
- PostgreSQL service responce — время ответа сервиса и среднее время выполнения запросов.
- PostgreSQL summary db stats: block hit/read — чтение из кэша и с диска.
- PostgreSQL summary db stats: events — события в базе (дедлоки, конфликты, коммиты, роллбэки).
- PostgreSQL summary db stats: temp files — информация по временным файлам.
- PostgreSQL summary db stats: tuples — общая информация по изменениям строк.
- PostgreSQL transactions — время выполнения запросов.
- PostgreSQL uptime — аптайм и процент попадания в кэш.
- PostgreSQL write-ahead log — информация по WAL журналу (объем записи и кол-во файлов).
- PostgreSQL: database {#DBNAME} size — информация по изменению размера БД.
- PostgreSQL table {#TABLENAME} maintenance — операции обслуживания таблицы (autovacuum, autoanalyze, vacuum, analyze).
- PostgreSQL table {#TABLENAME} read stats — статистика по чтению из кэша, диска.
- PostgreSQL table {#TABLENAME} rows — изменение в строках.
- PostgreSQL table {#TABLENAME} scans — информация по сканирования (sequential/index scans).
- PostgreSQL table {#TABLENAME} size — информация по размерам таблиц и их индексов.
- PostgreSQL streaming replication lag with {#HOTSTANDBY} — размер лага репликации с серверами-репликами.
В заключении, немного графиков-примеров:
Здесь как мы видим, в базе регулярно создаются временные файлы, следует поискать виновника в логе и пересмотреть work_mem.
Здесь события происходящие в базе — коммиты/роллбэки и конфликты/дедлоки — вцелом все хорошо здесь.
Здесь состояние потоковой репликации с одним из серверов — время отставания в секундах и байтах.
И заключительный график — время отклика службы и среднее время запроса.
Вот и все, всем спасибо за внимание!
Last year, the popular monitoring service Zabbix introduced Agent 2, designed to reduce the number of TCP connections and provide convenient extendability through plugins in Golang. In this article, I will discuss the main features of the Zabbix Agent 2 plugin for monitoring PostgreSQL, give tips on how to configure it, and explain by example how to customize the plugin.
What is the story behind the PostgreSQL monitoring plugin for Zabbix Agent 2?
In 2019 Zabbix announced the release of the new Agent 2. The Zabbix team created it from scratch in Golang. Each application requires a separate monitoring plugin. We at Postgres Professional have been using Zabbix for monitoring PostgreSQL for long years, that is why we decided to invest our experience in developing a PostgreSQL monitoring module for Agent 2.
How does DBMS monitoring work in Zabbix?
Let us start with a short introduction to the Zabbix monitoring strategy for beginners.
The structure we are interested in consists of two components:
- Zabbix Server, which stores, visualizes, and processes the collected data.
- Zabbix Agent, which is deployed on a monitoring target to monitor local resources and applications (hard drives, memory, processor statistics etc.).
Zabbix Server requires a template — an XML file — to monitor each application. It contains the metrics’ keys (unique IDs) and their processing parameters.
Zabbix Agent 2 provides the user with a monitoring tool out of the box. It is quick and easy to customize and possesses a good extendability.
So how does PostgreSQL plugin for Zabbix Agent 2 work?
There is the main function from which the handlers with a unique key for each metric are called. The handler collects data. It is a file in which a SQL query is specified and executed to get one or more metrics. A variable of int, float, or string type stores the results of the query execution. If it contains the values of several metrics, it will be converted to JSON. The metrics received by Zabbix Agent 2 are regularly sent to Zabbix Server.
The plugin and the handlers are located in this folder: /plugins/postgres.
Which features does the PostgreSQL monitoring module for Zabbix Agent 2 have?
- A constant connection to PostgreSQL.
- Monitoring for multiple PostgreSQL instances simultaneously.
- Options to monitor and check metrics in real-time via command line.
- One agent configuration file for configuring all plugin parameters.
- Keeping the state between checks.
- Very simple customization of how the existing metrics are collected.
- Ability to write new plugins according to your requirements.
The plugin has an official template, which is accessible here:
https://www.zabbix.com/integrations/postgresql#tab:official2
It has basic triggers and a complex screen that displays a combination of several charts. The plugin collects more than 95 metrics. The full list of all metrics can also be found on the Zabbix website.
In Zabbix Server web-interface you can easily customize the template and its components. What exactly can you set up?
- Change the time interval for how often the desired metrics are collected.
- Add a trigger for the metric.
- Add a macro or edit an existing one.
How to install and use the PostgreSQL plugin for Zabbix Agent 2?
- Create a PostgreSQL user for monitoring (<password> at your discretion):
CREATE USER 'zbx_monitor' IDENTIFIED BY '<password>';
GRANT EXECUTE ON FUNCTION pg_catalog.pg_ls_dir(text) TO zbx_monitor;
GRANT EXECUTE ON FUNCTION pg_catalog.pg_stat_file(text) TO zbx_monitor;
- Edit pg_hba.conf to allow connections from Zabbix agent:
# TYPE DATABASE USER ADDRESS METHOD
host all zbx_monitor 127.0.0.1 md5
For more information, please read the PostgreSQL documentation here: https://www.postgresql.org/docs/current/auth-pg-hba-conf.html.
Now you need to specify the PostgreSQL connection parameters for Zabbix Agent 2. There are two ways to do this:
- to use macros for connection parameters,
- to create a session.
The first way is a little easier. It can suffice if you need to configure monitoring for one PostgreSQL instance:
- Set in the {$PG.URI} macro the system data source name of the PostgreSQL instance such as <protocol(host:port)> in the template.
- Set the macro with your username and password ({$PG.USER} and {$PG.PASSWORD}) in the template. You can also specify the macro {$PG.DATABASE}. This parameter is optional for most metrics. If it is not specified in the key, then the base name specified in the agent configuration file will be used. An example can be seen in Picture 1.
The official template already has all required macros in the parameters of all keys. Please note that the order of the parameters in the key is fixed.
The second way enables you to set the connection parameters to several PostgreSQL instances:
- Set the connection parameters for the session in the configuration file zabbix_agent2.conf in the section of the Postgres plugin:
Postgres.Sessions.<Session_name>.URI, Postgres.Sessions.<Session_name>.User, Postgres.Sessions.<Session_name>.Password
- Instead of the
<Session_name>
, you should specify a unique name for the new session (as shown in Picture 2). - Create a macro with the session name {$PG.<Session_name>} in the template (as shown in Picture 3).
- Specify the macro as the only parameter for metrics in the template (as shown in Picture 4).
How to add new metrics to existing ones?
Let us explore how to use the plugin to collect more metrics. In our example, we’ll be adding an uptime metric.
To do this, you will need to create a new handler with a query, and then add its key to the main function.
- Let’s create a file to get a new metric:
zabbix/src/go/plugins/postgres/handler_uptime.go
Import the postgres package and specify the key(s) of the metrics:
package postgres
const (
keyPostgresUptime = "pgsql.uptime"
)
- Declare a handler with a query, do the same for the variable to store results:
func (p *Plugin) uptimeHandler(conn *postgresConn, params []string)(interface{}, error)
{
var uptime float64
query := `SELECT date_part('epoch', now() - pg_postmaster_start_time());`
- Execute a query, check if there is an error. If everything is OK, the uptime variable will be returned with some result.
err := conn.postgresPool.QueryRow(context.Background(), query).Scan(&uptime)
if err != nil {
...
}
return uptime, nil
- Finally, register a key for the new metric:
func init() {
plugin.RegisterMetrics(&impl, pluginName,
…
keyPostgresUptime, "Returns uptime.",
)
}
Recompile the agent!
Other Related Resources:
Article by Vadim Ipatov — co-developer of Zabbix Agent 2:
https://blog.zabbix.com/developing-plugins-for-zabbix-agent-2/9682/
Template for our PostgreSQL monitoring plugin:
https://www.zabbix.com/integrations/postgresql#tab:official2
Zabbix Git. It is for those who want to see more real-world examples and have a look at all SQL queries for metrics:
https://git.zabbix.com/projects/ZBX/repos/zabbix/browse/src/go/plugins/postgres
What’s next?
The new version of the above-mentioned plugin for PostgreSQL monitoring will become available soon! It will feature new metric enabling users to collect results of custom queries from separate SQL files. This version will also include minor bug fixes and introduce the module’s architecture update.
Join Postgres Pro & Zabbix for a Meetup!
If you have any questions related to the monitoring plugin for Zabbix Agent 2, you can ask them directly at the upcoming PostgreSQL Monitoring Day with Zabbix & Postgres Pro. I will speak there discussing the enhancements of version 2 of this monitoring plugin. The community event featuring 5 sessions on Postgres monitoring will take place online on December 10, 2020, at 6 PM CET. Hope to see many of you there!
Очередной небольшой чек лист по настройке мониторинга через Zabbix. На этот раз я кратко опишу процесс того, как выполняется Мониторинг PostgreSQL через Zabbix. Опорное руководство по настройке.
Описание окружения
Версия сервера Zabbix – Zabbix Server Zabbix 6.4.9.
Версия операционной системы на хосте с PostgreSQL – Debian Server 11.8.
Версия PostgreSQL – PostgreSQL 13.12.
Агент Zabbix на хосте с PostgreSQL – Zabbix Agent 2.
Предварительная подготовка
1. Поскольку я использую Zabbix Agent 2, то мне нужно убедиться, что плагин агента для PostgreSQL установлен.
sudo apt list zabbix-agent2-plugin-postgresql
Listing... Done
zabbix-agent2-plugin-postgresql/unknown,now 1:6.4.9-1+debian11 amd64 [installed]
Если плагин агента не установлен, то установите его:
sudo apt install zabbix-agent2-plugin-postgresql
2. Теперь подключимся консольным клиентом к PostgreSQL:
sudo -u postgres psql
3. Создадим отдельного пользователя, через которго Zabbix будет подключаться к серверу PostgreSQL. Также назначим необходимый минимум разрешений для пользователя. Только укажите надежный пароль:
CREATE USER zbx_monitor WITH PASSWORD 'Qwerty123' INHERIT;
GRANT pg_monitor TO zbx_monitor;
4. Отключимся от консольного клиента:
\q
5. Отредактируем конфигурационный файл pg_hba.conf, чтобы разрешить нашему клиенту подключаться к серверу PostgreSQL. Обратите внимание, что путь к файлу может отличаться в зависимости от версии PostgreSQL:
sudo nano /etc/postgresql/13/main/pg_hba.conf
6. Добавим следующую строчку в файл pg_hba.conf:
host all zbx_monitor 127.0.0.1/32 md5
7. Перечитаем конфигурационные файлы сервера PostgreSQL:
sudo systemctl reload postgresql
Настройки на стороне сервера PostgreSQL завершены.
Теперь переходим к настройкам на стороне сервера Zabbix. По большому счету все стандарно:
- Нужно добавить необходимый шаблон для хоста.
- Скорректировать параметры макросов для подключения к серверу PostgreSQL.
Добавляем шаблон мониторинга для нужного хоста PostgreSQL.
Корректируем макросы для указания учетных данных для подключения к серверу PostgreSQL.
Проверка
Переходим в раздел с последними данными в веб интерфейсе сервера Zabbix и проверяем доступность метрик:
Только необходимо учитывать тот момент, что данные могут появиться не сразу – нужно будет немного подождать.
Monitor PostgreSQL using Zabbix
Monitor PostgreSQL using Zabbix
Would you like to learn how to monitor a PostgreSQL server using Zabbix? In this tutorial, we are going to show you how to use Zabbix to monitor a PostgreSQL server.
Zabbix Playlist:
On this page, we offer quick access to a list of videos related to Zabbix installation.
Don’t forget to subscribe to our youtube channel named FKIT.
Zabbix Related Tutorial:
On this page, we offer quick access to a list of tutorials related to Zabbix installation.
Configure a PostgreSQL user to Zabbix
• IP – 192.168.15.11
• Operational System – Ubuntu 19.10
• Hostname – POSTGRESQL
Zabbix requires an account to access the PostgreSQL server and perform the database monitoring.
On the PostgreSQL database server, create an account to Zabbix.
Give monitoring privilege over all PostgreSQL databases to the Zabbix user.
Take note of the PostgreSQL username and password created.
Locate and edit the pg_hba.conf configuration file.
Add the following lines at the beginning of this file.
Here is our pg_hba.conf file content:
Restart the PostgreSQL service.
Test if you are able to connect to the local PostgreSQL server using the zbx_monitor account.
The system should not ask for a password.
You have finished the PostgreSQL service configuration.
Install the Zabbix Agent on the PostgreSQL Server
• IP – 192.168.15.11
• Operational System – Ubuntu 19.10
• Hostname – POSTGRESQL
Now, we need to install the Zabbix agent on the computer running the PostgreSQL service.
On the Linux console, use the following commands to install the required packages.
Download the Zabbix installation package.
Extract the Zabbix installation package, compile and install the Zabbix agent.
Find the location of the zabbix_agentd.conf file on your system.
Edit the zabbix_agentd.conf file.
Here is the original file, before our configuration.
Here is the new file with our configuration.
In our example, the Zabbix agent is configured to allow the connection from the Zabbix server 192.168.15.10.
The Zabbix server with the IP address 192.168.15.10 is allowed to request and receive information from this agent.
The Localhost, 127.0.0.1, is allowed to request and receive information from the agent.
Create the following required directories.
Download the Zabbix source code from Github.
Copy the required files to monitor the PostgreSQL server from the Zabbix repository.
The Zabbix installation package comes with a service startup script.
Copy the startup script using the commands below.
You can now use the following commands to start the Zabbix agent service.
In our example, the Zabbix agent will monitor the PostgreSQL service installed on the localhost.
Restart the Zabbix Agent.
You have finished the Zabbix agent installation.
You can now use the Zabbix server dashboard to add this computer to the network monitoring service.
Zabbix Monitor PostgreSQL
Access the Zabbix server dashboard and add the Linux computer running PostgreSQL as a Host.
Open your browser and enter the IP address of your web server plus /zabbix.
In our example, the following URL was entered in the Browser:
• http://192.168.15.10/zabbix
On the login screen, use the default username and default password.
• Default Username: Admin
• Default Password: zabbix
After a successful login, you will be sent to the Zabbix Dashboard.
On the dashboard screen, access the Configuration menu and select the Host option.
On the top right of the screen, click on the Create host button.
Enter the following information:
• Host Name – Enter a Hostname to identify the Linux server running PostgreSQL.
• Visible Hostname – Repeat the hostname.
• Group – Select the name of a group to identify similar devices.
• Agent Interface – Enter the IP address of the Linux server.
Here is the original image, before our configuration.
Here is the new image with our configuration.
Next, we need to associate the host with a specific network monitor template.
By default, Zabbix comes with a large variety of monitoring templates.
Access the Templates tab on the top of the screen.
Click on the Select button and locate the template named: Template DB PostgreSQL
Click on the Add option.
Click on the Add button.
After a few minutes, you will be able to see the initial result on the Zabbix Dashboard.
In order to test your configuration, access the Monitoring menu and click on the Graphs option.
On the top right of the screen, select the group named ALL.
Select your PostgreSQL computer hostname.
Select the graph named: PostgreSQL connections
You should be able to see the graphic named PostgreSQL connections
Congratulations! You have configured the Zabbix server to monitor PostgreSQL.
VirtualCoin CISSP, PMP, CCNP, MCSE, LPIC22019-11-23T00:00:53-03:00
Related Posts
Page load link
Ok
Video Lecture
Description
I show how to set up monitoring for a PostgreSQL database server in Zabbix.
Install PostgreSQL
To set up a new PostgreSQL database server on Ubuntu 22.04 LTS, then use these commands.
sudo apt update
sudo apt install postgresql postgresql-contrib
sudo service postgresql start
Check the status.
sudo service postgresql status
Press CTRL C to exit.
If the status shows active running, then you can continue.
Install and Configure Zabbix Agent
You will also need a Zabbix agent running on the server.
My Zabbix server is Zabbix 6.0 LTS, and my server that will be hosting the agent is an Ubuntu 20.04. So I will use these commands.
sudo wget https://repo.zabbix.com/zabbix/6.0/ubuntu/pool/main/z/zabbix-release/zabbix-release_6.0-4%2Bubuntu22.04_all.deb
sudo dpkg -i zabbix-release_6.0-4+ubuntu22.04_all.deb
sudo apt update
sudo apt install zabbix-agent
Visit https://www.zabbix.com/download to know which commands to run for your combination of Zabbix server version and operating system where you will install the agent.
Open the Zabbix agent configuration file, find and set the parameters appropriately.
sudo nano /etc/zabbix/zabbix_agentd.conf
For my setup, I used,
Server=zabbix.sbcode.net
ServerActive=zabbix.sbcode.net
Hostname=postgresql
The values that you enter for the above keys will be different.
CTRL X and then Y to save changes.
Add PostgreSQL Read-Only User
We now need to enter the PostgreSQL (psql) prompt and add a read-only user named zbx_monitor
.
Add the user.
CREATE USER zbx_monitor WITH PASSWORD '<PASSWORD>' INHERIT;
GRANT pg_monitor TO zbx_monitor;
Confirm user exists
select * from pg_catalog.pg_user;
Exit back to the bash prompt.
Set Up Zabbix PostgreSQL Template Dependencies
Now to download the Zabbix repository from GitHub. This contains the PostgreSQL database queries used by the template that we will import into Zabbix.
git clone https://github.com/zabbix/zabbix.git
It is a very large repository, so it will take a long time to download. Possibly 10 mins.
After download, you should see a new directory named zabbix
.
We now need to copy the ./zabbix/templates/db/postgresql/
folder and contents to the /var/lib/zabbix/
folder.
You may need to first create the folder /var/lib/zabbix
Now run the copy command.
cp -r ./zabbix/templates/db/postgresql/. /var/lib/zabbix/
CD into the /var/lib/zabbix
to check that the folders and contents were copied ok.
We also need to copy just the template_db_postgresql.conf
file to /etc/zabbix/zabbix_agentd.d/
cp /var/lib/zabbix/template_db_postgresql.conf /etc/zabbix/zabbix_agentd.d/
Check it copied ok.
cd /etc/zabbix/zabbix_agentd.d/
ls
Configure PostgreSQL pg_hba.conf
File
Now we need to edit the pg_hba.conf
to allow the zbx_monitor
user to connect.
sudo nano /etc/postgresql/14/main/pg_hba.conf
Add these lines to the end
host all zbx_monitor 127.0.0.1/32 trust
host all zbx_monitor 0.0.0.0/0 md5
host all zbx_monitor ::0/0 md5
CTRL X and then Y to save changes.
Configure Host and Template in Zabbix
Restart Zabbix Agent and check status.
sudo service zabbix-agent restart
sudo service zabbix-agent status
Go into Zabbix and create a new host named ‘postgresql’.
Assign the template PostgeSQL by Zabbix agent
.
Add to any group you desire. Templates/Databases
is a good option.
Add an Agent
interface, and set the IP address of your PostgreSQL server.
Select the Macros
tab and check/set each macro key. (Most keys will be already set to the correct value)
Macro key | Value |
---|---|
{$PG.HOST} | 127.0.0.1 |
{$PG.PORT} | 5432 |
{$PG.USER} | zbx_monitor |
{$PG.PASSWORD} | the same password you used above when creating zbx_monitor the user |
{$PG.DB} | postgres |
Press Update
and after some time, you will see new values populating in Monitoring
→ Latest Data
Trouble Shooting
Special characters "\, ', ", \*, ?, [, ], {, }, ~, $, !, &, ;, (, ), <, >, |, #, @, 0x0a" are not allowed in the parameters.
If you used the password <PASSWORD>
as I did in the video, you will have an error indicating you have special characters in the macro. To fix this, I updated the password I used for my zbx_monitor
user in PostgreSQL using these commands.
ALTER USER zbx_monitor WITH PASSWORD 'new_password';
\q
Next go into the macros tab of your host and update the {$PG.PASSWORD}
macro to match the new password.
Recommendation
The messages relayed between the Zabbix server and Zabbix agent running on the PostgreSQL Database server, are not encrypted. I recommend configuring PSK encryption for agents that communicate with the Zabbix server directly across a public network.
See Enable PSK Encryption for Zabbix Agents