29.4. Настройка агентов #
На всех серверах:
Установите агенты:
# apt install ppem-agent
Создайте пользователя СУБД, от имени которого агент будет подключаться к базам данных сервера СУБД:
# sudo -u postgres createuser --pwprompt ppem_agent
При выполнении этой команды укажите пароль пользователя СУБД.
Предоставьте пользователю СУБД права на чтение системного каталога и запуск функций.
Рекомендуется назначить следующие права:
GRANT pg_monitor, pg_maintain, pg_signal_backend, pg_read_all_settings TO ppem_agent;
Предоставьте пользователю СУБД следующие права на каждую базу данных в экземпляре:
GRANT EXECUTE ON FUNCTION pg_catalog.pg_stat_file(TEXT) TO ppem_agent; GRANT EXECUTE ON FUNCTION pg_catalog.pg_stat_file(TEXT, BOOLEAN) TO ppem_agent; GRANT SELECT ON pg_catalog.pg_statistic TO ppem_agent; GRANT SELECT ON pg_catalog.pg_config TO ppem_agent; GRANT EXECUTE ON FUNCTION pg_catalog.pg_config() TO ppem_agent; GRANT SELECT ON pg_catalog.pg_file_settings TO ppem_agent; GRANT EXECUTE ON FUNCTION pg_catalog.pg_show_all_file_settings() TO ppem_agent; GRANT SELECT ON pg_catalog.pg_authid TO ppem_agent;
Предоставьте пользователю СУБД следующие права на управление резервными копиями:
ALTER ROLE ppem_agent WITH REPLICATION; GRANT USAGE ON SCHEMA pg_catalog TO ppem_agent; GRANT EXECUTE ON FUNCTION pg_catalog.current_setting(text) TO ppem_agent; GRANT EXECUTE ON FUNCTION pg_catalog.set_config(text, text, boolean) TO ppem_agent; GRANT EXECUTE ON FUNCTION pg_catalog.pg_is_in_recovery() TO ppem_agent; GRANT EXECUTE ON FUNCTION pg_catalog.pg_backup_start(text, boolean) TO ppem_agent; GRANT EXECUTE ON FUNCTION pg_catalog.pg_backup_stop(boolean) TO ppem_agent; GRANT EXECUTE ON FUNCTION pg_catalog.pg_create_restore_point(text) TO ppem_agent; GRANT EXECUTE ON FUNCTION pg_catalog.pg_switch_wal() TO ppem_agent; GRANT EXECUTE ON FUNCTION pg_catalog.pg_last_wal_replay_lsn() TO ppem_agent; GRANT EXECUTE ON FUNCTION pg_catalog.txid_current() TO ppem_agent; GRANT EXECUTE ON FUNCTION pg_catalog.txid_current_snapshot() TO ppem_agent; GRANT EXECUTE ON FUNCTION pg_catalog.txid_snapshot_xmax(txid_snapshot) TO ppem_agent; GRANT EXECUTE ON FUNCTION pg_catalog.pg_control_checkpoint() TO ppem_agent;
Права достаточно назначить для базы данных, которая будет использоваться при подключении пользователя к экземпляру.
За подробной информацией о правах обратитесь к официальной документации Postgres Pro по pg_probackup.
Убедитесь, что пользователь СУБД может подключиться к следующим базам данных:
К базе данных репозитория на сервере, где установлен менеджер.
Например, чтобы проверить возможность доступа к базе данных
ppem:# psql -h localhost -U ppem_agent -d ppem
При проблемах с подключением убедитесь, что в файле конфигурации
pg_hba.confуказаны метод авторизации и правило HBA, разрешающие пользователю СУБД подключаться к базе данных.Пример записей в
pg_hba.conf:host ppem ppem_agent ::1/128 trust host ppem ppem_agent 127.0.0.1/32 trust
Ко всем базам данных на сервере, где установлены СУБД, которыми нужно управлять.
Например, чтобы проверить возможность доступа к базе данных
db1:# psql -h localhost -U ppem_agent -d db1
При проблемах с подключением убедитесь, что в файле конфигурации
pg_hba.confуказаны метод авторизации и правило HBA, разрешающие пользователю СУБД подключаться к базе данных.Пример записей в
pg_hba.conf:host all ppem_agent ::1/128 trust host all ppem_agent 127.0.0.1/32 trust
Получите API-ключ для настройки агента:
Перейдите на главную страницу.
Если на странице отображается инструкция по настройке агента, скопируйте ключ из инструкции.
Если инструкции нет, выполните следующие действия:
Перейдите на навигационную вкладку Инфраструктура → Агенты.
В столбце Ключ аутентификации для любого агента нажмите либо , чтобы скопировать ключ, либо , чтобы посмотреть ключ.
В файле конфигурации агента
/etc/ppem-agent.ymlукажите значения для следующих параметров:Укажите уникальное имя агента.
Укажите следующие значение и замените необходимые данные:
http://
адрес_менеджера_ppem:8080Укажите значение API-ключа, которое было получено ранее.
В целях безопасности задайте значение, отличное от значения по умолчанию.
agent.instance.connection_defaultsУкажите параметры, которые используются агентом для подключения к экземплярам СУБД на хосте с установленным агентом.
Создайте основной и дополнительный каталоги агентов и назначьте пользователя операционной системы их владельцем:
sudo mkdir --parents /var/lib/ppem/{instances,postgresql,systemd,backups} sudo chown --recursive ppem:ppem /var/lib/ppemОсновной каталог агентов используется для хранения экземпляров и их параметров, единиц измерения экземпляров, а также локальных хранилищ. При создании экземпляров необходимо указывать каталог
/var/lib/ppem/instances, а при создании локальных хранилищ — каталог/var/lib/ppem/backups.Создайте каталог для настройки systemd:
sudo mkdir /etc/systemd/system.conf.d
Создайте файл конфигурации systemd:
sudo nano /etc/systemd/system.conf.d/custom_path.conf
В файле конфигурации systemd укажите:
[Manager] ManagerEnvironment="SYSTEMD_UNIT_PATH=/var/lib/ppem/systemd:"
Добавьте пользователя операционной системы в группу для работы с экземплярами:
sudo usermod -aG postgres ppem
В файле конфигурации sudoers разрешите пользователю операционной системы выполнять команды от имени суперпользователя, указав:
Cmnd_Alias PG_SYS_V = /usr/bin/systemctl status *postgres*.service, \ /usr/bin/systemctl start *postgres*.service, \ /usr/bin/systemctl stop *postgres*.service, \ /usr/bin/systemctl restart *postgres*.service, \ /usr/bin/systemctl reload *postgres*.service, \ /usr/bin/systemctl enable *postgres*.service, \ /usr/bin/systemctl disable *postgres*.service, \ /usr/bin/systemctl daemon-reload, \ /usr/bin/mkdir --parents /var/lib/ppem/*, \ /usr/bin/mkdir /var/lib/ppem/*, \ /usr/bin/mkdir --parents /sys/fs/cgroup/ppem*, \ /usr/bin/mkdir /sys/fs/cgroup/ppem*, \ /usr/bin/chmod --recursive 0[5-7][0-7][0-7] /var/lib/ppem/*, \ /usr/bin/chmod 0[5-7][0-7][0-7] /var/lib/ppem/*, \ /usr/bin/chown --recursive [a-z]*\:[a-z]* /var/lib/ppem/*, \ /usr/bin/chown [a-z]*\:[a-z]* /var/lib/ppem/*, \ /usr/bin/chown [a-z]*\:[a-z]* /tmp/*, \ /usr/bin/chown --recursive [a-z]*\:[a-z]* /tmp/*, \ /usr/bin/echo, \ /usr/bin/test, \ /usr/bin/sh -c /usr/bin/echo, \ /usr/bin/mv, \ /usr/bin/rm /var/lib/ppem/*, \ /usr/bin/rm /tmp/*, \ /usr/bin/rm --recursive --force /var/lib/ppem/* Cmnd_Alias PG_CTL_V = /usr/lib/postgresql/[0-9][0-9]/bin/pg_ctl, \ /usr/lib/postgresql/[0-9][0-9]/bin/initdb, \ /usr/bin/pg_probackup-[0-9][0-9], \ /opt/pgpro/ent-[0-9][0-9]/bin/initdb, \ /opt/pgpro/ent-[0-9][0-9]/bin/pg_ctl, \ /opt/pgpro/ent-[0-9][0-9]/bin/pg_probackup ppem ALL = (root) NOPASSWD:SETENV: PG_SYS_V ppem ALL = (postgres) NOPASSWD:SETENV: PG_CTL_V
Агент работает от имени обычного пользователя операционной системы, поэтому ему предоставляется право выполнять только команды, необходимые для управления экземплярами. Эти команды сгруппированы в псевдонимы команд
PG_SYS_VиPG_CTL_V. Строкиppem ALL = (root)иppem ALL = (postgres)позволяют пользователю операционной системыppemвыполнять команды псевдонимаPG_SYS_Vот имени суперпользователя, а команды псевдонимаPG_CTL_V— от имени пользователя операционной системыpostgres. ТегNOPASSWDотключает запрос пароля, а тегSETENVразрешает агенту передавать переменные окружения выполняемым командам. Ниже приводится описание этих команд.Команда
Назначение
Использование
/usr/bin/systemctl status|start|stop|restart|reload *postgres*.serviceПроверка состояния экземпляра, запуск, остановка, перезапуск и перезагрузка с помощью systemd.
Используется для управления состоянием экземпляра через systemd. Это основной сценарий работы агента.
/usr/bin/systemctl enable|disable *postgres*.serviceДобавление модулей systemd экземпляров в автозагрузку сервера и удаление из неё.
Используется при инициализации экземпляра и при его удалении.
/usr/bin/systemctl daemon-reloadПерезагрузка конфигурации менеджера systemd.
Используется после добавления или удаления модуля systemd экземпляра, чтобы systemd принял изменения.
/usr/bin/mkdir --parents /var/lib/ppem/*,/usr/bin/mkdir /var/lib/ppem/*Создание подкаталогов в каталоге
/var/lib/ppem.Используется для создания подкаталогов в
/var/lib/ppemдля экземпляров, резервных копий и других данных. Необходимо для корректной работы агента без прав суперпользователя./usr/bin/mkdir --parents /sys/fs/cgroup/ppem*,/usr/bin/mkdir /sys/fs/cgroup/ppem*Создание подкаталогов в каталоге
/sys/fs/cgroup/с именами, начинающимися сppem.Используется только для экземпляров, управление которыми осуществляется через
pg_ctl. Необходимо для создания контрольных групп операционной системы./usr/bin/chmod --recursive 0[5-7][0-7][0-7] /var/lib/ppem/*,/usr/bin/chmod 0[5-7][0-7][0-7] /var/lib/ppem/*Изменение прав доступа к подкаталогам в каталоге агента
/var/lib/ppem.Используется с шаблоном
0[5-7][0-7][0-7]и шаблоном пути/var/lib/ppem/*, ограничивающими допустимые значения и расположение./usr/bin/chown --recursive [a-z]*\:[a-z]* /var/lib/ppem/*,/usr/bin/chown [a-z]*\:[a-z]* /var/lib/ppem/*Изменение владельца подкаталогов в каталоге агента
/var/lib/ppem, например изменение владельца будущего каталога данных экземпляра.Используется с шаблоном
[a-z]*:[a-z]*и шаблоном пути/var/lib/ppem/*, ограничивающими допустимые значения и расположение./usr/bin/chown [a-z]*\:[a-z]* /tmp/*,/usr/bin/chown --recursive [a-z]*\:[a-z]* /tmp/*Изменение владельца вспомогательных файлов в
/tmp.Используется для смены владельца временных файлов, которые создаются в
/tmpдля инициализации экземпляра и репликации и затем удаляются. Например, агент меняет владельца временного файла пароля, создаваемого при инициализации экземпляра./usr/bin/echoЗапись данных в файлы.
Используется, когда агент PPEM, работающий от имени непривилегированного пользователя, не может самостоятельно записывать данные в системные файлы, например, чтобы добавить идентификатор процесса экземпляра в файл
cgroup.procsконтрольной группы экземпляра./usr/bin/testПроверка существования файлов и каталогов.
Используется перед созданием файла или каталога для проверки того, что он ещё не существует. В противном случае объект нельзя создать.
/usr/bin/mvПеремещение файлов.
Используется для перемещения файлов, например файлов конфигурации при инициализации экземпляра.
/usr/bin/rm /var/lib/ppem/*,/usr/bin/rm /tmp/*Удаление файлов.
Используется для удаления файлов экземпляров и временных файлов. Шаблоны путей
/var/lib/ppem/*и/tmp/*ограничивают допустимое расположение./usr/bin/rm --recursive --force /var/lib/ppem/*Удаление подкаталогов в каталоге
/var/lib/ppem.Используется, например, для удаления каталога данных экземпляра.
/usr/lib/postgresql/[0-9][0-9]/bin/pg_ctlУправление экземплярами.
Используется для запуска pg_ctl от имени пользователя
postgres. Шаблон[0-9][0-9]покрывает разные версии утилиты. Указанный путь типичен для систем на основе Debian. Настройте его в соответствии с установкой на целевом сервере./usr/lib/postgresql/[0-9][0-9]/bin/initdbИнициализация экземпляров.
Используется для запуска
initdbот имени пользователяpostgresв установках PostgreSQL./usr/bin/pg_probackup-[0-9][0-9]Работа с резервными копиями с помощью pg_probackup.
Используется в инсталляциях PostgreSQL.
/opt/pgpro/ent-[0-9][0-9]/bin/initdbИнициализация экземпляров.
Используется в инсталляциях Postgres Pro Enterprise.
/opt/pgpro/ent-[0-9][0-9]/bin/pg_ctlУправление экземплярами.
Используется в инсталляциях Postgres Pro Enterprise.
/opt/pgpro/ent-[0-9][0-9]/bin/pg_probackupРабота с резервными копиями с помощью pg_probackup.
Используется в инсталляциях Postgres Pro Enterprise.
Для Postgres Pro Standard замените
/opt/pgpro/ent-[0-9][0-9]на/opt/pgpro/std-[0-9][0-9]в командах псевдонимаPG_CTL_V.В файле конфигурации агента
ppem-agent.ymlукажите:system: postgresql_configs_path: "/var/lib/ppem/postgresql" systemd_units_path: "/var/lib/ppem/systemd"Настройте запуск службы агента от имени пользователя операционной системы:
Начните редактирование модуля systemd:
# systemctl edit ppem-agent
В разделе
[Service]укажите пользователя операционной системы:[Service] User=ppem
Убедитесь, что пользователь операционной системы имеет право чтения файла конфигурации агента
ppem-agent.yml.Если право отсутствует, выполните запрос:
# chown ppem:ppem /etc/ppem-agent.yml # chmod 400 /etc/ppem-agent.yml
Сохраните параметры модуля systemd, затем перезагрузите его:
# systemctl daemon-reload
Запустите службу агента и добавьте её в автозагрузку сервера:
# systemctl start ppem-agent # systemctl enable ppem-agent
29.4. Configuring Agents #
On all servers:
Install agents:
# apt install ppem-agent
Create the DBMS user on behalf of which the agent will connect to the DBMS server databases:
# sudo -u postgres createuser --pwprompt ppem_agent
When executing this command, specify the DBMS user password.
Grant the DBMS user the privilege to read the system catalog and run functions.
It is recommended to grant the following privileges:
GRANT pg_monitor, pg_maintain, pg_signal_backend, pg_read_all_settings TO ppem_agent;
Grant the DBMS user the following privileges on every database in the instance:
GRANT EXECUTE ON FUNCTION pg_catalog.pg_stat_file(TEXT) TO ppem_agent; GRANT EXECUTE ON FUNCTION pg_catalog.pg_stat_file(TEXT, BOOLEAN) TO ppem_agent; GRANT SELECT ON pg_catalog.pg_statistic TO ppem_agent; GRANT SELECT ON pg_catalog.pg_config TO ppem_agent; GRANT EXECUTE ON FUNCTION pg_catalog.pg_config() TO ppem_agent; GRANT SELECT ON pg_catalog.pg_file_settings TO ppem_agent; GRANT EXECUTE ON FUNCTION pg_catalog.pg_show_all_file_settings() TO ppem_agent; GRANT SELECT ON pg_catalog.pg_authid TO ppem_agent;
Grant the DBMS user the following privileges to manage backups:
ALTER ROLE ppem_agent WITH REPLICATION; GRANT USAGE ON SCHEMA pg_catalog TO ppem_agent; GRANT EXECUTE ON FUNCTION pg_catalog.current_setting(text) TO ppem_agent; GRANT EXECUTE ON FUNCTION pg_catalog.set_config(text, text, boolean) TO ppem_agent; GRANT EXECUTE ON FUNCTION pg_catalog.pg_is_in_recovery() TO ppem_agent; GRANT EXECUTE ON FUNCTION pg_catalog.pg_backup_start(text, boolean) TO ppem_agent; GRANT EXECUTE ON FUNCTION pg_catalog.pg_backup_stop(boolean) TO ppem_agent; GRANT EXECUTE ON FUNCTION pg_catalog.pg_create_restore_point(text) TO ppem_agent; GRANT EXECUTE ON FUNCTION pg_catalog.pg_switch_wal() TO ppem_agent; GRANT EXECUTE ON FUNCTION pg_catalog.pg_last_wal_replay_lsn() TO ppem_agent; GRANT EXECUTE ON FUNCTION pg_catalog.txid_current() TO ppem_agent; GRANT EXECUTE ON FUNCTION pg_catalog.txid_current_snapshot() TO ppem_agent; GRANT EXECUTE ON FUNCTION pg_catalog.txid_snapshot_xmax(txid_snapshot) TO ppem_agent; GRANT EXECUTE ON FUNCTION pg_catalog.pg_control_checkpoint() TO ppem_agent;
You can grant privileges only for the database that will be used for connecting the user to the instance.
For more information about privileges, refer to the official Postgres Pro documentation on pg_probackup.
Ensure that the DBMS user can connect to the following databases:
On the server where the manager is installed, to the repository database.
For example, to check access to the
ppemdatabase:# psql -h localhost -U ppem_agent -d ppem
In case of connection issues, ensure that the authorization method and the HBA rule allowing the DBMS user to connect to the database are specified in the
pg_hba.confconfiguration file.Example
pg_hba.confentries:host ppem ppem_agent ::1/128 trust host ppem ppem_agent 127.0.0.1/32 trust
On the server where the DBMS to be managed are installed, to all databases.
For example, to check access to the
db1database:# psql -h localhost -U ppem_agent -d db1
In case of connection issues, ensure that the authorization method and the HBA rule allowing the DBMS user to connect to the database are specified in the
pg_hba.confconfiguration file.Example
pg_hba.confentries:host all ppem_agent ::1/128 trust host all ppem_agent 127.0.0.1/32 trust
Get an API key to configure the agent:
Go to the summary page.
If the agent configuration instruction is displayed on the page, then copy the key from the instruction.
If no instruction is displayed, then complete the following steps:
Go to the Infrastructure navigation tab → Agents.
In the Authentication key column for any agent, click either to copy the key or to view the key.
In the
/etc/ppem-agent.ymlagent configuration file, specify values for the following parameters:Specify the unique agent name.
Specify the following value and substitute the necessary data:
http://
ppem_manager_address:8080Specify the value of the API key that was obtained earlier.
For security reasons, specify a value different from the default one.
agent.instance.connection_defaultsSpecify the parameters which are used by the agent when connecting to the DBMS instances on the host where the agent is installed.
Create the main and additional agent catalogs and make the operating system user their owner:
sudo mkdir --parents /var/lib/ppem/{instances,postgresql,systemd,backups} sudo chown --recursive ppem:ppem /var/lib/ppemThe main agent catalog is used for storing instances and their parameters, instance management units, and local storages. You must specify the
/var/lib/ppem/instancescatalog when creating instances and the/var/lib/ppem/backupscatalog when creating local storages.Create a catalog for configuring systemd:
sudo mkdir /etc/systemd/system.conf.d
Create the systemd configuration file:
sudo nano /etc/systemd/system.conf.d/custom_path.conf
In the systemd configuration file, specify:
[Manager] ManagerEnvironment="SYSTEMD_UNIT_PATH=/var/lib/ppem/systemd:"
Add the operating system user to the group for working with instances:
sudo usermod -aG postgres ppem
In the sudoers configuration file, enable the operating system user to execute commands under the superuser by specifying:
Cmnd_Alias PG_SYS_V = /usr/bin/systemctl status *postgres*.service, \ /usr/bin/systemctl start *postgres*.service, \ /usr/bin/systemctl stop *postgres*.service, \ /usr/bin/systemctl restart *postgres*.service, \ /usr/bin/systemctl reload *postgres*.service, \ /usr/bin/systemctl enable *postgres*.service, \ /usr/bin/systemctl disable *postgres*.service, \ /usr/bin/systemctl daemon-reload, \ /usr/bin/mkdir --parents /var/lib/ppem/*, \ /usr/bin/mkdir /var/lib/ppem/*, \ /usr/bin/mkdir --parents /sys/fs/cgroup/ppem*, \ /usr/bin/mkdir /sys/fs/cgroup/ppem*, \ /usr/bin/chmod --recursive 0[5-7][0-7][0-7] /var/lib/ppem/*, \ /usr/bin/chmod 0[5-7][0-7][0-7] /var/lib/ppem/*, \ /usr/bin/chown --recursive [a-z]*\:[a-z]* /var/lib/ppem/*, \ /usr/bin/chown [a-z]*\:[a-z]* /var/lib/ppem/*, \ /usr/bin/chown [a-z]*\:[a-z]* /tmp/*, \ /usr/bin/chown --recursive [a-z]*\:[a-z]* /tmp/*, \ /usr/bin/echo, \ /usr/bin/test, \ /usr/bin/sh -c /usr/bin/echo, \ /usr/bin/mv, \ /usr/bin/rm /var/lib/ppem/*, \ /usr/bin/rm /tmp/*, \ /usr/bin/rm --recursive --force /var/lib/ppem/* Cmnd_Alias PG_CTL_V = /usr/lib/postgresql/[0-9][0-9]/bin/pg_ctl, \ /usr/lib/postgresql/[0-9][0-9]/bin/initdb, \ /usr/bin/pg_probackup-[0-9][0-9], \ /opt/pgpro/ent-[0-9][0-9]/bin/initdb, \ /opt/pgpro/ent-[0-9][0-9]/bin/pg_ctl, \ /opt/pgpro/ent-[0-9][0-9]/bin/pg_probackup ppem ALL = (root) NOPASSWD:SETENV: PG_SYS_V ppem ALL = (postgres) NOPASSWD:SETENV: PG_CTL_V
The agent runs as the non-superuser of the operating system, so it is granted the privilege to execute only the commands required for managing instances. The commands are grouped into the
PG_SYS_VandPG_CTL_Vcommand aliases. Theppem ALL = (root)andppem ALL = (postgres)lines allow theppemoperating system user to run the commands of thePG_SYS_Valias on behalf of the superuser and the commands of thePG_CTL_Valias on behalf of thepostgresoperating system user. TheNOPASSWDtag disables the password prompt and theSETENVtag allows the agent to pass environment variables to the executed commands. The commands are described below.Command
Purpose
Usage
/usr/bin/systemctl status|start|stop|restart|reload *postgres*.serviceChecking the state of an instance, starting, stopping, restarting, and reloading it using systemd.
Used to manage the instance state through systemd. It is the main scenario of agent operation.
/usr/bin/systemctl enable|disable *postgres*.serviceAdding the systemd units of instances to the server startup and removing them from it.
Used when an instance is initialized and when it is deleted.
/usr/bin/systemctl daemon-reloadReloading the systemd manager configuration.
Used after adding or removing the systemd unit of an instance for systemd to pick up the changes.
/usr/bin/mkdir --parents /var/lib/ppem/*,/usr/bin/mkdir /var/lib/ppem/*Creating subdirectories in the
/var/lib/ppemdirectory.Used to create subdirectories in
/var/lib/ppemfor instances, backups, and other data. Required for the agent to work properly without superuser privileges./usr/bin/mkdir --parents /sys/fs/cgroup/ppem*,/usr/bin/mkdir /sys/fs/cgroup/ppem*Creating subdirectories in the
/sys/fs/cgroup/directory with names starting withppem.Used only for instances managed through
pg_ctl. Required for creating operating system control groups./usr/bin/chmod --recursive 0[5-7][0-7][0-7] /var/lib/ppem/*,/usr/bin/chmod 0[5-7][0-7][0-7] /var/lib/ppem/*Changing access privileges for subdirectories in the
/var/lib/ppemagent directory.Used with the
0[5-7][0-7][0-7]pattern and the/var/lib/ppem/*path pattern, which restrict the allowed values and locations./usr/bin/chown --recursive [a-z]*\:[a-z]* /var/lib/ppem/*,/usr/bin/chown [a-z]*\:[a-z]* /var/lib/ppem/*Changing the owner of subdirectories in the
/var/lib/ppemagent directory, for example, changing the owner of the future instance data directory.Used with the
[a-z]*:[a-z]*pattern and the/var/lib/ppem/*path pattern, which restrict the allowed values and locations./usr/bin/chown [a-z]*\:[a-z]* /tmp/*,/usr/bin/chown --recursive [a-z]*\:[a-z]* /tmp/*Changing the owner of auxiliary files in
/tmp.Used to change the owner of temporary files for instance initialization and replication that are created in
/tmpand then deleted. For example, the agent changes the owner of the temporary password file created during instance initialization./usr/bin/echoWriting data to files.
Used when the PPEM agent running under a non-superuser cannot write to system files by its own means, for example, to add the instance process identifier to the
cgroup.procsfile of the instance control group./usr/bin/testChecking file and directory existence.
Used to check that a file or directory does not already exist before creating it. Otherwise, the object cannot be created.
/usr/bin/mvMoving files.
Used to move files, for example, configuration files during instance initialization.
/usr/bin/rm /var/lib/ppem/*,/usr/bin/rm /tmp/*Deleting files.
Used to delete instance files and temporary files. The
/var/lib/ppem/*and/tmp/*path patterns restrict the allowed locations./usr/bin/rm --recursive --force /var/lib/ppem/*Deleting subdirectories in the
/var/lib/ppemdirectory.Used, for example, to delete the instance data directory.
/usr/lib/postgresql/[0-9][0-9]/bin/pg_ctlManaging instances.
Used to run pg_ctl on behalf of the
postgresuser. The[0-9][0-9]pattern covers different versions of the utility. The given path is typical for Debian-based systems; adjust it to the installation used on the target server./usr/lib/postgresql/[0-9][0-9]/bin/initdbInitializing instances.
Used to run
initdbon behalf of thepostgresuser in PostgreSQL installations./usr/bin/pg_probackup-[0-9][0-9]Working with backups using pg_probackup.
Used for PostgreSQL installations.
/opt/pgpro/ent-[0-9][0-9]/bin/initdbInitializing instances.
Used for Postgres Pro Enterprise installations.
/opt/pgpro/ent-[0-9][0-9]/bin/pg_ctlManaging instances.
Used for Postgres Pro Enterprise installations.
/opt/pgpro/ent-[0-9][0-9]/bin/pg_probackupWorking with backups using pg_probackup.
Used for Postgres Pro Enterprise installations.
For Postgres Pro Standard, replace
/opt/pgpro/ent-[0-9][0-9]with/opt/pgpro/std-[0-9][0-9]in thePG_CTL_Valias commands.In the
ppem-agent.ymlagent configuration file, specify:system: postgresql_configs_path: "/var/lib/ppem/postgresql" systemd_units_path: "/var/lib/ppem/systemd"Configure the agent service to start on behalf of the operating system user:
Start editing the systemd unit:
# systemctl edit ppem-agent
In the
[Service]section, specify the operating system user:[Service] User=ppem
Ensure that the operating system user is granted the privilege to read the
ppem-agent.ymlagent configuration file.If the privilege is not granted, execute:
# chown ppem:ppem /etc/ppem-agent.yml # chmod 400 /etc/ppem-agent.yml
Save systemd unit parameters, then reload it:
# systemctl daemon-reload
Start the agent service and add it to the server startup:
# systemctl start ppem-agent # systemctl enable ppem-agent