29.4. Настройка агентов #

На всех серверах:

  1. Установите агенты:

    # apt install ppem-agent
  2. Создайте пользователя СУБД, от имени которого агент будет подключаться к базам данных сервера СУБД:

    # sudo -u postgres createuser --pwprompt ppem_agent

    При выполнении этой команды укажите пароль пользователя СУБД.

  3. Предоставьте пользователю СУБД права на чтение системного каталога и запуск функций.

    Рекомендуется назначить следующие права:

    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.

  4. Убедитесь, что пользователь СУБД может подключиться к следующим базам данных:

    • К базе данных репозитория на сервере, где установлен менеджер.

      Например, чтобы проверить возможность доступа к базе данных 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
  5. Получите API-ключ для настройки агента:

    1. Войдите в веб-приложение.

    2. Перейдите на главную страницу.

    3. Если на странице отображается инструкция по настройке агента, скопируйте ключ из инструкции.

    4. Если инструкции нет, выполните следующие действия:

      1. Перейдите на навигационную вкладку Инфраструктура → Агенты.

      2. В столбце Ключ аутентификации для любого агента нажмите либо , чтобы скопировать ключ, либо , чтобы посмотреть ключ.

  6. В файле конфигурации агента /etc/ppem-agent.yml укажите значения для следующих параметров:

    • agent.name

      Укажите уникальное имя агента.

    • agent.manager.url

      Укажите следующие значение и замените необходимые данные:

      http://адрес_менеджера_ppem:8080
    • agent.manager.api_key

      Укажите значение API-ключа, которое было получено ранее.

    • jwt.secret

      В целях безопасности задайте значение, отличное от значения по умолчанию.

    • agent.instance.connection_defaults

      Укажите параметры, которые используются агентом для подключения к экземплярам СУБД на хосте с установленным агентом.

  7. Создайте основной и дополнительный каталоги агентов и назначьте пользователя операционной системы их владельцем:

      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.

  8. Создайте каталог для настройки systemd:

      sudo mkdir /etc/systemd/system.conf.d
  9. Создайте файл конфигурации systemd:

      sudo nano /etc/systemd/system.conf.d/custom_path.conf
  10. В файле конфигурации systemd укажите:

      [Manager]
      ManagerEnvironment="SYSTEMD_UNIT_PATH=/var/lib/ppem/systemd:"
  11. Добавьте пользователя операционной системы в группу для работы с экземплярами:

      sudo usermod -aG postgres ppem
  12. В файле конфигурации 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.

  13. В файле конфигурации агента ppem-agent.yml укажите:

      system:
        postgresql_configs_path: "/var/lib/ppem/postgresql"
        systemd_units_path: "/var/lib/ppem/systemd"
  14. Настройте запуск службы агента от имени пользователя операционной системы:

    1. Начните редактирование модуля systemd:

      # systemctl edit ppem-agent
    2. В разделе [Service] укажите пользователя операционной системы:

      [Service]
      User=ppem
    3. Убедитесь, что пользователь операционной системы имеет право чтения файла конфигурации агента ppem-agent.yml.

      Если право отсутствует, выполните запрос:

      # chown ppem:ppem /etc/ppem-agent.yml
      # chmod 400 /etc/ppem-agent.yml
    4. Сохраните параметры модуля systemd, затем перезагрузите его:

      # systemctl daemon-reload
  15. Запустите службу агента и добавьте её в автозагрузку сервера:

    # systemctl start ppem-agent
    # systemctl enable ppem-agent

29.4. Configuring Agents #

On all servers:

  1. Install agents:

    # apt install ppem-agent
    
  2. 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.

  3. 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.

  4. 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 ppem database:

      # 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.conf configuration file.

      Example pg_hba.conf entries:

      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 db1 database:

      # 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.conf configuration file.

      Example pg_hba.conf entries:

      host    all  ppem_agent  ::1/128       trust
      host    all  ppem_agent  127.0.0.1/32  trust
      

  5. Get an API key to configure the agent:

    1. Log in to the web application.

    2. Go to the summary page.

    3. If the agent configuration instruction is displayed on the page, then copy the key from the instruction.

    4. If no instruction is displayed, then complete the following steps:

      1. Go to the Infrastructure navigation tab → Agents.

      2. In the Authentication key column for any agent, click either to copy the key or to view the key.

  6. In the /etc/ppem-agent.yml agent configuration file, specify values for the following parameters:

    • agent.name

      Specify the unique agent name.

    • agent.manager.url

      Specify the following value and substitute the necessary data:

      http://ppem_manager_address:8080
      
    • agent.manager.api_key

      Specify the value of the API key that was obtained earlier.

    • jwt.secret

      For security reasons, specify a value different from the default one.

    • agent.instance.connection_defaults

      Specify the parameters which are used by the agent when connecting to the DBMS instances on the host where the agent is installed.

  7. 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/ppem
    

    The main agent catalog is used for storing instances and their parameters, instance management units, and local storages. You must specify the /var/lib/ppem/instances catalog when creating instances and the /var/lib/ppem/backups catalog when creating local storages.

  8. Create a catalog for configuring systemd:

      sudo mkdir /etc/systemd/system.conf.d
    
  9. Create the systemd configuration file:

      sudo nano /etc/systemd/system.conf.d/custom_path.conf
    
  10. In the systemd configuration file, specify:

      [Manager]
      ManagerEnvironment="SYSTEMD_UNIT_PATH=/var/lib/ppem/systemd:"
    
  11. Add the operating system user to the group for working with instances:

      sudo usermod -aG postgres ppem
    
  12. 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_V and PG_CTL_V command aliases. The ppem ALL = (root) and ppem ALL = (postgres) lines allow the ppem operating system user to run the commands of the PG_SYS_V alias on behalf of the superuser and the commands of the PG_CTL_V alias on behalf of the postgres operating system user. The NOPASSWD tag disables the password prompt and the SETENV tag 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*.service

    Checking 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*.service

    Adding 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-reload

    Reloading 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/ppem directory.

    Used to create subdirectories in /var/lib/ppem for 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 with ppem.

    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/ppem agent 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/ppem agent 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 /tmp and then deleted. For example, the agent changes the owner of the temporary password file created during instance initialization.

    /usr/bin/echo

    Writing 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.procs file of the instance control group.

    /usr/bin/test

    Checking 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/mv

    Moving 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/ppem directory.

    Used, for example, to delete the instance data directory.

    /usr/lib/postgresql/[0-9][0-9]/bin/pg_ctl

    Managing instances.

    Used to run pg_ctl on behalf of the postgres user. 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/initdb

    Initializing instances.

    Used to run initdb on behalf of the postgres user 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/initdb

    Initializing instances.

    Used for Postgres Pro Enterprise installations.

    /opt/pgpro/ent-[0-9][0-9]/bin/pg_ctl

    Managing instances.

    Used for Postgres Pro Enterprise installations.

    /opt/pgpro/ent-[0-9][0-9]/bin/pg_probackup

    Working 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 the PG_CTL_V alias commands.

  13. In the ppem-agent.yml agent configuration file, specify:

      system:
        postgresql_configs_path: "/var/lib/ppem/postgresql"
        systemd_units_path: "/var/lib/ppem/systemd"
    
  14. Configure the agent service to start on behalf of the operating system user:

    1. Start editing the systemd unit:

      # systemctl edit ppem-agent
      
    2. In the [Service] section, specify the operating system user:

      [Service]
      User=ppem
      
    3. Ensure that the operating system user is granted the privilege to read the ppem-agent.yml agent configuration file.

      If the privilege is not granted, execute:

      # chown ppem:ppem /etc/ppem-agent.yml
      # chmod 400 /etc/ppem-agent.yml
      
    4. Save systemd unit parameters, then reload it:

      # systemctl daemon-reload
      
  15. Start the agent service and add it to the server startup:

    # systemctl start ppem-agent
    # systemctl enable ppem-agent
    
FAQ