Установка Агента и добавление экземпляра через CLI
В этом разделе описан механизм и приведены примеры установки Агента и добавления экземпляра через командную строку.
Важно
Перед установкой Агента через CLI выполните следующие действия:
проверьте, установлен ли пакет «postgresql-contrib». В противном случае установите его;
проверьте, создано ли расширение «pg_stat_statements». Если нет, то установите его.
Регистрация Агента в Платформе
Данный алгоритм установки позволяет добавить Агента, существующего и без списка экземпляров, за которыми ему нужно осуществлять мониторинг.
Важно
Рекомендуется использовать средства автоматизации (Ansible/Chief/Puppet etc) в вашей организации для подготовки СУБД к установке Агента.
Скачайте и установите Агент.
Для deb дистрибутивов (Astra Linux/Alt Linux/Debian/Ubuntu):
если есть доступ в интернет:
mkdir -p /etc/apt/sources.list.d && sh -c 'echo "deb [arch=amd64] https://nexus.tantorlabs.ru/repository/apt-packages tantorlabs main" > /etc/apt/sources.list.d/tantorlabs.list' wget --quiet -O - https://public.tantorlabs.ru/tantorlabs.ru.asc | apt-key add - apt-get update apt-get install -y pmaagent=5.0.0
если нет доступа в интернет:
curl "https://your-domain-name:8443/packages/pmaagent.deb" -o /tmp/pmaagent.deb -k apt-get install -y /tmp/pmaagent.deb
Вместо <your-domain-name> пропишите доменное имя, указанное при установке Платформы.
Для rpm дистрибутивов (Centos/RedOS/Rocky/RedHat/Amazon Linux/):
если есть доступ в интернет:
mkdir -p /etc/yum.repos.d && cat >/etc/yum.repos.d/tantorlabs.repo <<EOL [tantorlabs] name=tantorlabs baseurl=https://nexus.tantorlabs.ru/repository/yum-packages/ enabled=1 gpgcheck=1 gpgkey=https://public.tantorlabs.ru/tantorlabs.ru.asc repo_gpgcheck=0 priority=1 deltarpm=0 EOL yum install -y pmaagent-5.0.0
если нет доступа в интернет:
curl "https://your-domain-name:8443/packages/pmaagent.rpm" -o /tmp/pmaagent.rpm -k yum install -y /tmp/pmaagent.rpm
Вместо <your-domain-name> пропишите доменное имя, указанное при установке Платформы.
Получите токен в интерфейсе Платформы на странице «Tokens». Чтобы открыть эту страницу, нажмите на значок профиля в верхнем правом углу → «Настройки». Подробнее о том, как получать токены, можно прочитать в инструкции.
С помощью полученного токена зарегистрируйте Агента в Платформе, введя команды на сервере СУБД. Пример команды регистрации:
# pmaagent register --access-token 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJwbWEiLCJleHAiOjE3MTI5NTU1OTksImlhdCI6MTcwMzc1MTA0NSwic2NvcGUiOiJJTlNUQUxMIn0.Om6EK8vn4mSJeVyFQ7WqCBj9YtwWRQDJAHTgBDi8958' --host '10.128.0.121' --workspace-name '10.128.0.121' --endpoint 'tantor.domain.asdfa:4222' Agent successfully registered
После этого в списке Агентов в интерфейсе Платформы (вкладка «Agents» при переходе в рабочее пространство) появится новый Агент.
Добавление экземпляра в Платформу
Доступно добавление экземпляров двух типов:
SERVER — инсталляция СУБД, запущенная непосредственно на сервере.
CONTAINER — инсталляция СУБД, запущенная в контейнере типа docker.
Зарегистрируйте экземпляр в Платформе.
Пример добавления экземпляра standalone (не Patroni) типа SERVER:
Добавьте следующие параметры в конфигурацию СУБД. Пример:
echo "listen_addresses='*'" >/var/lib/postgresql/tantor-se-15/data/postgresql.auto.conf
Добавьте экземпляр следующей командой:
Примечание
В db-user и db-pass указывается имя и пароль пользователя БД, под которым агент будет в дальнейшем подключаться к БД экземпляра.
При создании этого пользователя будет использовано подключение к БД с использованием пароля и логина, указанного в ключах db-admin-user и db-admin-pass.
В конфигурационный файл агента сохраняются только данные, указанные в ключах db-user и db-pass. И только они будут использоваться агентом.
pmaagent instances add --name '10.128.0.121' --environment 'SERVER' --type 'TantorDB' --db-host '10.128.0.121' --db-port '5432' --db-user 'pma_user' --db-pass 'password' --confirm --db-admin-user test_conn --db-admin-pass passwd ########################################################################################## # PMA Agent. Version: 5.0.0. # # Add on-premise PostgreSQL instance # # Local date/time: Tuesday, 10-Sep-24 18:18:30 MSK # ########################################################################################## - Testing database connection using provided host [10.128.0.121]... [OK] - Checking if the PostgreSQL instance is in recovery mode... [OK] - Checking if the [postgresql-contrib] packaged is installed...... [OK] - Checking if the [pg_stat_statements] extension is installed...... [OK] - Checking if the [pg_store_plans] extension is installed...... [WARN] - Could not detect availability of the extension [pg_store_plans]. Need to create the extension. - Creating the [pma_user] database user... [OK] - Checking the pg_hba configuration... [OK] - Updating the [/var/lib/postgresql/tantor-se-16/data/pg_hba.conf] file... [OK] - Reloading the PostgreSQL configuration... [OK] - Testing connection to database with provided parameters... [OK] Instance [6ee6317e-a103-4907-a697-b51c045d72c8] has been added successfully
Перезапустите Агента Платформы командой:
# systemctl restart pmaagent
Пример добавления экземпляра standalone (не Patroni) типа CONTAINER:
pmaagent instances add --name 'demo-patroni1' --type 'PostgreSQL' --environment CONTAINER --container-target-id 64698910af9c --db-host '10.128.0.121' --db-port '5432' --db-user 'postgres' --db-pass 'postgres' --confirm ########################################################################################## # PMA Agent. Version: 5.0.0. # # Add PostgreSQL instance running in container # # Local date/time: Thursday, 21-Dec-23 16:54:14 MSK # ########################################################################################## - Parameters: + Type of instance : on-premise PostgreSQL + PostgreSQL default host : 10.128.0.121 + listener port : 5432 + Database name : postgres + PostgreSQL user (i.e. super user) : postgres + password : (* * * * * *) + PostgreSQL agent's user name : postgres (this database user will be created. Agent connects to the monitored PostgreSQL instance using this user name) + password : (will be prompted to input) - WARNING: During the process, the PostgreSQL instance will be reconfigured and reloaded. - Please make sure the instance of PostgreSQL that is listening the port [5432] - is properly configured, and its client authentication (pg_hba) is consistent. - Testing database connection using provided host [10.128.0.121]... [OK] - Checking if the PostgreSQL instance is in recovery mode... [OK] - Checking if the [postgresql-contrib] packaged is installed...... [OK] - Checking if the [pg_stat_statements] extension is installed...... [OK] - Checking if the [pg_store_plans] extension is installed...... [OK] - Creating the [postgres] database user... [OK] - Testing connection to database with provided parameters... [OK] - Testing container connection using default parameters... [OK] Instance [48631c53-7d14-4d69-984f-3d87612650b9] has been added successfully
Пример добавления экземпляра Patroni типа SERVER:
pmaagent instances add --name '192.168.112.134' --environment 'SERVER' --type 'TantorDB' --db-host '192.168.112.134' --db-port '5432' --db-user 'pma_user' --db-pass 'Dota1234@' --db-admin-user 'superus' --db-admin-pass 'Dota1234@' --patroni-cluster-hosts '192.168.112.132,192.168.112.134,192.168.112.135' --patroni-user 'test_user' --patroni-password 'test_pass' --patroni-port '8008' --confirm ########################################################################################## # PMA Agent. Version: 5.0.0. # # Add PostgreSQL and Patroni instances # # Local date/time: Friday, 13-Sep-24 10:58:12 MSK # ########################################################################################## - Parameters: + Type of instance : on-premise PostgreSQL + PostgreSQL default host(empty: "unix socket") : 192.168.112.134 + listener port : 5432 + Database name : postgres + PostgreSQL user (i.e. super user) : superus + password : (* * * * * *) + PostgreSQL agent's user name : pma_user (this database user will be created. Agent connects to the monitored PostgreSQL instance using this user name) + password : (* * * * * *) + Path to client key : + Path to client certificate : + Path to root CA certificate : + Client key passphrase : (not provided) - WARNING: During the process, the PostgreSQL instance will be reconfigured and reloaded. - Please make sure the instance of PostgreSQL that is listening the port [5432] - is properly configured, and its client authentication (pg_hba) is consistent. - Testing database connection using provided host [192.168.112.134]... [OK] - Checking if the PostgreSQL instance is in recovery mode... [OK] - Checking if the [postgresql-contrib] packaged is installed...... [OK] - Checking if the [pg_stat_statements] extension is installed...... [WARN] - Could not detect availability of the extension [pg_stat_statements]. Need to create the extension. - Checking if the [pg_store_plans] extension is installed...... [WARN] - Could not detect availability of the extension [pg_store_plans]. Need to create the extension. - Creating the [pma_user] database user... [OK] - Testing connection to database with provided parameters... [OK] - Testing Patroni connection using provided port [8008]... [OK] Instance [d32e74cc-f285-4f9a-8642-1d7e2d551995] has been added successfully
Зайдите в интерфейс Платформы и проверьте, что в списке экземпляров появились новые экземпляры. Метрики появятся в течение двух минут.
Также список экземпляров можно посмотреть в CLI. Пример просмотра:
pmaagent instances list Environment Key Name DB Host DB Port DB Name SERVER 78cdbd4b-029b-40ea-972e-535f42b26855 10.128.0.121 10.128.0.121 5432 postgres
Удаление экземпляра из Платформы
Пример удаления экземпляра:
pmaagent instances remove --key 78cdbd4b-029b-40ea-972e-535f42b26855 --confirm
Важно
При удалении последнего экземпляра, если это экземпляр типа SERVER, мы разрегистрируем Агента в Платформе и конфигурация удалится.
pmaagent instances list
Failed to load the configuration file. Сonfiguration file [/var/lib/pma/agent/agent.yml] not found.
Для просмотра справочной информации вы можете использовать следующие команды:
«pmaagent register --help» — справочная информация о регистрации Агента. Пример использования:
pmaagent register --help Registering the pmaagent Usage: pmaagent register [flags] Flags: --access-token string Access token. Used for authentication and authorization purposes --endpoint string Bus endpoint --help help about any command --host string IP address of host environment used to register the Agent --workspace-name string Destination name of platform workspace. Value is case sensitive Global Flags: -c, --config-file string Path to the configuration file (default "/var/lib/pma/agent/agent.yml") -s, --stdout Send logging information to stdout. By default it is the file destination specified in the configuration file
«pmaagent instances add --help» — справочная информация о добавлении экземпляра. Пример использования:
pmaagent instances add --help Add instance Usage: pmaagent instances add [flags] Flags: --aws-access-key-id string AWS Access Key ID (https://docs.aws.amazon.com/general/latest/gr/aws-sec-cred-types.html). AWS RDS instance only. --aws-secret-access-key string AWS Secret Access Key. AWS RDS instance only. -y, --confirm Auto confirm all dialogs and command line interactions --container-host string Published container host (https://docs.docker.com/engine/reference/commandline/port) --container-port uint16 Published container port --container-target-id string Target managed/monitored container identifier (minimum 12 symbols) --db-host string PostgreSQL instance server host -d, --db-name string Monitored database name (default "postgres") -W, --db-pass string PostgreSQL database user password -p, --db-port uint16 PostgreSQL instance server port (default 5432) -U, --db-user string Connect to the monitored PostgreSQL instance as specified database user. It should have privileged access credentials (default "postgres") -e, --environment string Environment type. Possible values: ["CONTAINER" "XDATABOX" "SERVER" "RDS"] (default "SERVER") -h, --help help for add --name string Instance name --patroni-host string Patroni instance host name or IP address --patroni-password string Patroni instance user password -P, --patroni-port uint16 Patroni instance port --patroni-ssl Use SSL to connect to the Patroni instance (default false) --patroni-user string Patroni instance user name --type string Instance type: ["PostgreSQL" "TantorDB" "RDS"] (default "PostgreSQL") Global Flags: -c, --config-file string Path to the configuration file (default "/var/lib/pma/agent/agent.yml") -s, --stdout Send logging information to stdout. By default it is the file destination specified in the configuration
«pmaagent instances remove --help» — справочная информация об удалении экземпляра. Пример использования:
pmaagent instances remove --help Remove instance Usage: pmaagent instances remove [flags] Flags: -y, --confirm Auto confirm all dialogs and command line interactions -h, --help help for remove --key string Key of the instance to remove --name string Name of the instance to remove Global Flags: -c, --config-file string Path to the configuration file (default "/var/lib/pma/agent/agent.yml") -s, --stdout Send logging information to stdout. By default it is the file destination specified in the configuration file