bihactl

bihactl — создать BiHA-кластер в Postgres Pro

Синтаксис

bihactl add --biha-node-id=id_узла --host=хост [параметры]

bihactl init --biha-node-id=id_узла --nquorum=значение_кворума --host=хост [параметры]

bihactl status [параметры]

bihactl -V | --version

bihactl -? | --help

Описание

bihactl — это утилита командной строки, которая позволяет создать BiHA-кластер, изменять его состав, а также отслеживать статус и версию кластера. За подробной информацией о решении BiHA обратитесь к главе Встроенная отказоустойчивость (BiHA).

В этом разделе содержится информация о командах утилиты bihactl:

Узел-последователь можно добавить с использованием «‎‎магической» строки, сохранённой после выполнения команды bihactl init, передав в команде bihactl add параметр -s.

Важно

  • Не рекомендуется выполнять команды bihactl в каталоге PGDATA. Утилита bihactl может создавать файлы biha_init.log и biha_add.log в том каталоге, откуда запускается. Однако для корректного выполнения команд bihactl целевой каталог PGDATA должен быть пустым.

  • На серверах с архитектурой процессоров Эльбрус команды bihactl необходимо выполнять с помощью двоичного компилятора rtc 4.3. Например, чтобы выполнить bihactl init, добавьте префикс rtc с необходимыми параметрами:

    rtc --path_prefix / -- bihactl init -D node --port=5432 --biha-port=15432

Справка по командной строке #

add #

Синтаксис:

bihactl add --biha-node-id=id_узла
            --host=хост
            {--use-leader=параметры_подключения | --magic-string=магическая_строка | --magic-file=файл_с_магической_строкой}
            [--convert-standby]
            [--pgdata=каталог_данных]
            [--port=порт]
            [--biha-port=порт_biha]
            [--backup-method=метод_резервирования]
            [--backup-options=параметры_резервирования]
            [--mode=режим_узла] [--referee-with-postgres-db]]

Добавляет последователя в инициализированный кластер. При выполнении этой команды создаётся резервная копия лидера с помощью pg_basebackup или pg_probackup. При добавлении узла утилита bihactl удерживает слот репликации, вызывая pg_basebackup с параметрами --slot=ИМЯ_СЛОТА, --wal-method=stream, --checkpoint=fast или pg_probackup с параметрами --stream --slot=ИМЯ_СЛОТА, что предотвращает удаление WAL на лидере во время создания резервной копии.

Примечание

Узлы необходимо добавлять по очереди. Не добавляйте новый узел, если создание ранее добавленного узла ещё не завершено и узел находится в состоянии CSTATE_FORMING. В противном случае может возникнуть следующая ошибка:

            WARNING:  aborting backup due to backend exiting before pg_backup_stop was
            called
        

Для выбора утилиты резервного копирования используется параметр -m, а параметры выбранной утилиты можно задать при помощи параметра -O.

Эта команда может принимать следующие параметры:

-c
--convert-standby #

Преобразовывает существующий узел в узел-последователь отказоустойчивого кластера. Узел должен быть репликой узла-лидера до преобразования.

-D каталог_данных
--pgdata=каталог_данных #

Указывает каталог, где будет храниться кластер баз данных. Если параметр не задан, bihactl будет использовать значение PGDATA.

-f файл_с_магической_строкой
--magic-file=файл_с_магической_строкой #

Указывает путь к «магическому» файлу, который содержит закодированные данные для подключения к лидеру. Файл должен существовать в момент выполнения команды bihactl add.

-h хост
--host=хост #

Указывает хост узла для входящих соединений.

-I id_узла
--biha-node-id=id_узла #

Указывает уникальный идентификатор узла.

-l параметры_подключения
--use-leader=параметры_подключения #

Указывает параметры подключения к узлу-лидеру в следующем формате:

host=хост_узла_лидера port=порт_лидера biha-port=порт_biha_лидера
-m метод_резервирования
--backup-method=метод_резервирования #

Указывает утилиту резервного копирования. Допускаются значения pg_basebackup и pg_probackup. Значение по умолчанию — pg_basebackup. Если не указывать параметр --backup-method, будет использован метод резервного копирования по умолчанию. Утилита pg_basebackup — единственное допустимое значение при добавлении узла-рефери.

-O параметры_резервирования
--backup-options=параметры_резервирования #

Дополнительно указывает параметры pg_basebackup или pg_probackup в зависимости от утилиты резервного копирования, заданной в параметре --backup-method.

-p порт
--port=порт #

Указывает порт узла для входящих соединений.

Если не указан:

  • При преобразовании существующего кластера с помощью --convert-standby bihactl использует значение переменной окружения PGPORT.

  • При создании BiHA-кластера с нуля bihactl использует значение по умолчанию — 5432.

-P порт_biha
--biha-port=порт_biha #

Указывает порт для обмена служебной информацией между узлами. Если порт не указан, устанавливается значение port + 1.

-r режим_работы_узла
--mode=режим_работы_узла #

Указывает режим работы узла. Допустимы следующие значения:

  • regular — узел может быть как лидером, так и последователем. Это значение по умолчанию.

  • referee — узел только участвует в выборах лидера и не содержит пользовательских баз данных.

  • referee_with_wal — узел участвует в выборах лидера так же, как в режиме referee, и получает все файлы WAL от узла-лидера.

По умолчанию база данных postgres не копируется на узел в режиме referee или referee_with_wal. Чтобы скопировать базу данных postgres на рефери, воспользуйтесь параметром --referee-with-postgres-db.

-R
--referee-with-postgres-db #

Копирует базу данных postgres со всеми объектами на узел-рефери. Этот параметр можно использовать только при добавлении узла в режиме referee или referee_with_wal.

-s магическая_строка
--magic-string=магическая_строка #

Указывает «‎‎магическую» строку, содержащую закодированные данные для подключения к лидеру.

init #

Синтаксис:

bihactl init --biha-node-id=id_узла
             --nquorum=значение_кворума
             --host=хост
             [--convert [--root-cert=/путь/к/сертификату_цс --server-cert=/путь/к/сертификату_сервера \
             --server-key=/путь/к/ключу_сервера --user-postgres-cert=/путь/к/сертификату_клиента \
             --user-postgres-key=/путь/к/ключу_клиента [--postgres-ssl-mode=режим_ssl]]]
             [--pgdata=каталог_данных]
             [--port=порт]
             [--biha-port=порт_biha]
             [--use-ssl]
             [--minnodes=минимальное_число_узлов]
             [--magic-file=файл_с_магической_строкой]
             [--options=параметры_initdb]
             [--sync-standbys=число_синхронных_ведомых_узлов [--sync-standbys-min=минимальное_число_синхронных_ведомых_узлов]]
             [--root-cert=/путь/к/сертификату_цс --user-biha-cert=/путь/к/сертификату_клиента \
             --user-biha-key=/путь/к/ключу_клиента [--biha-ssl-mode=режим_ssl]]

Инициализирует кластер и задаёт узел-лидер. При выполнении этой команды bihactl запускает утилиту initdb. На этом этапе также можно указать необходимые параметры этой утилиты при помощи флага -o.

Эта команда может принимать следующие параметры:

-C
--convert #

Преобразовывает существующий узел в узел-лидер отказоустойчивого кластера.

-D каталог_данных
--pgdata=каталог_данных #

Указывает каталог, где будет храниться кластер баз данных. Если параметр не задан, bihactl будет использовать значение PGDATA.

-f файл_с_магической_строкой
--magic-file=файл_с_магической_строкой #

Указывает путь к файлу, который будет создан. Файл содержит данные для подключения к лидеру («магическую» строку).

-h хост
--host=хост #

Указывает хост узла для входящих соединений.

-I id_узла
--biha-node-id=id_узла #

Указывает уникальный идентификатор узла.

-M мин_число_узлов
--minnodes=мин_число_узлов #

Указывает минимальное число работающих узлов, при котором узел-лидер будет доступен для пишущих транзакций. Если параметр не задан, его значение будет равно значению параметра nquorum.

-N значение_кворума
--nquorum=значение_кворума #

Указывает минимальное число узлов, которые должны проголосовать за нового лидера при отказе текущего лидера.

Устанавливая это значение, принимайте во внимание возможный риск разделения кластера. Рекомендуется использовать следующую формулу: (общее_число_узлов + 1)/2. Например, если в кластере 3 узла, значение nquorum должно быть 2.

-o параметры_initdb
--options=параметры_initdb #

Дополнительно указывает параметры утилиты initdb.

-p порт
--port=порт #

Указывает порт узла для входящих соединений.

Если не указан:

  • При преобразовании существующего кластера с помощью --convert bihactl использует значение переменной окружения PGPORT.

  • При создании BiHA-кластера с нуля bihactl использует значение по умолчанию — 5432.

-P порт_biha
--biha-port=порт_biha #

Указывает порт для обмена служебной информацией между узлами. Если порт не указан, устанавливается значение port + 1.

-S
--use-ssl #

Включает защищённый режим передачи служебной информации между узлами кластера по протоколу SSL/TLS управляющего канала biha.

-Y число_синхронных_ведомых_узлов
--sync-standbys=число_синхронных_ведомых_узлов #

Включает кворумную синхронную репликацию, устанавливая параметр synchronous_standby_names и указывая число синхронных резервных узлов (кворум) с методом ANY. Рекомендуется указывать значение число_синхронных_ведомых_узлов меньше, чем значение параметра --minnodes.

-y мин_число_синхронных_ведомых_узлов
--sync-standbys-min=мин_число_синхронных_ведомых_узлов #

Включает нестрогую кворумную синхронную репликацию, указывая значение поля MIN параметра synchronous_standby_names, что задаёт минимальное число синхронных резервных узлов, которые должны быть доступны, чтобы лидер продолжал работать. Значение минимальное_число_синхронных_резервных_узлов должно быть меньше, чем --sync-standbys, и не может быть отрицательным. Если параметр не задан, BiHA-кластер будет работать в соответствии с ограничениями синхронной репликации по умолчанию, т.е. лидер будет недоступен для пишущих транзакций, пока все последователи не нагонят его текущее состояние.

--biha-ssl-mode=режим_ssl #

Определяет политику аутентификации по SSL для роли biha_replication_user. Поддерживаются следующие режимы:

  • verify-full (по умолчанию)

  • require

  • verify-ca

За подробной информацией о режимах обратитесь к sslmode.

--postgres-ssl-mode=режим_ssl #

Определяет политику аутентификации по SSL для суперпользователя. Поддерживаются следующие режимы:

  • verify-full (по умолчанию)

  • require

  • verify-ca

За подробной информацией о режимах обратитесь к sslmode.

--root-cert=/путь/к/сертификату_цс #

Указывает путь к сертификату доверенного ЦС в формате PEM.

--server-cert=/путь/к/сертификату_сервера #

Указывает путь к SSL-сертификату для узла BiHA в формате PEM.

--server-key=/путь/к/ключу_сервера #

Указывает путь к закрытому ключу сертификата --server-cert в формате PEM.

--user-biha-cert=/путь/к/сертификату_клиента #

Указывает путь к SSL-сертификату для аутентификации роли biha_replication_user в формате PEM.

--user-biha-key=/путь/к/ключу_клиента #

Указывает путь к закрытому ключу для сертификата --user-biha-cert в формате PEM.

--user-postgres-cert=/путь/к/сертификату_клиента #

Указывает путь к SSL-сертификату для аутентификации суперпользователя в формате PEM.

--user-postgres-key=/путь/к/ключу_клиента #

Указывает путь к закрытому ключу сертификата --user-postgres-cert в формате PEM.

status #

Синтаксис:

bihactl status {--host=хост [--port=порт] | --magic-string=магическая_строка | --magic-file=файл_с_магической_строкой}

Проверяет статус узла и отображает его в представлении biha.status_v. Эта команда может принимать следующие параметры:

-f файл_с_магической_строкой
--magic-file=файл_с_магической_строкой

Указывает путь к файлу с «‎‎магической» строкой, содержащей закодированные данные для подключения к узлу-лидеру.

-h хост
--host=хост

Указывает хост узла для входящих соединений.

-p порт
--port=порт

Указывает порт узла для входящих соединений. Если параметр не задан, bihactl будет использовать значение PGPORT. Значение по умолчанию — 5432.

-s магическая_строка
--magic-string=магическая_строка

Указывает «‎‎магическую» строку, содержащую закодированные данные для подключения к лидеру.

-V | --version #

Синтаксис:

bihactl -V
bihactl --version

Выводит текущую версию отказоустойчивого кластера.

-? | --help #

Синтаксис:

bihactl -?
bihactl --help

Выводит справку по параметрам командной строки.

bihactl

bihactl — create a BiHA cluster in Postgres Pro

Synopsis

bihactl add --biha-node-id=node_id --host=host [options]

bihactl init --biha-node-id=node_id --nquorum=quorum_value --host=host [options]

bihactl status [options]

bihactl -V | --version

bihactl -? | --help

Description

bihactl is a command line utility that allows creating a BiHA cluster, changing its composition, as well as monitoring the cluster status and version. For more information about the BiHA solution, see Built-in High Availability (BiHA).

This section contains information about the bihactl utility commands:

The follower node can be added using a magic string saved after the bihactl init command by adding the -s option to the bihactl add command.

Important

  • It is not recommended to execute the bihactl commands in the PGDATA directory. The bihactl utility may create the biha_init.log and biha_add.log files in the directory where it is executed. However, the target PGDATA directory must be empty for proper execution of the bihactl commands.

  • For servers with the Elbrus CPU architecture, execute bihactl commands using the rtc 4.3 binary compiler. For example, to execute bihactl init, add the rtc prefix with its options:

    rtc --path_prefix / -- bihactl init -D node --port=5432 --biha-port=15432
    

Command-Line Reference #

add #

Syntax:

bihactl add --biha-node-id=node_id
            --host=host
            {--use-leader=conn_info | --magic-string=magic_string | --magic-file=magic_file}
            [--convert-standby]
            [--pgdata=datadir]
            [--port=port]
            [--biha-port=biha_port]
            [--backup-method=backup_method]
            [--backup-options=backup_options]
            [--mode=node_mode] [--referee-with-postgres-db]]

Adds a follower node to the initialized cluster. When this command is executed, a backup of the leader node is created by means of pg_basebackup or pg_probackup. When you add a node, bihactl keeps the replication slot by calling pg_basebackup with the --slot=SLOT_NAME, --wal-method=stream, --checkpoint=fast parameters and pg_probackup with the --stream --slot=SLOT_NAME parameters that prevents deletion of WAL on the leader during backup.

Note

You must add nodes one by one. Do not add a new node if creation of a previously added node has not been completed yet and the node is in the CSTATE_FORMING state. Otherwise, you may encounter the following error:

            WARNING:  aborting backup due to backend exiting before pg_backup_stop was
            called
        

The backup utility can be set with the -m option, while the parameters of the selected backup are specified with the -O option.

This command can take the following options:

-c
--convert-standby #

Converts an existing node to make it a follower node in the high-availability cluster. The node should be a leader node replica prior to the conversion.

-D datadir
--pgdata=datadir #

Specifies the directory where the database cluster should be stored. If not specified, bihactl uses the PGDATA value.

-f magic_file
--magic-file=magic_file #

Specifies the path to the magic file that contains encoded data to connect to the leader node. The file must exist when you execute the bihactl add command.

-h host
--host=host #

Specifies the node host for incoming connections.

-I node_id
--biha-node-id=node_id #

Specifies the unique ID of the node.

-l conn_info
--use-leader=conn_info #

Specifies parameters to connect to the leader node in the following format:

host=leader_host port=leader_port biha-port=leader_biha_port

-m backup_method
--backup-method=backup_method #

Specifies the backup utility. The allowed values are pg_basebackup and pg_probackup. The default value is pg_basebackup. If you do not specify the --backup-method option, the default backup method is used. The pg_basebackup utility is the only value that can be used when adding the referee node.

-O backup_options
--backup-options=backup_options #

Specifies additional options of pg_basebackup or pg_probackup depending on the backup utility specified in the --backup-method option.

-p port
--port=port #

Specifies the node port for incoming connections.

If not specified:

  • When converting the existing cluster using --convert-standby, bihactl uses the PGPORT value.

  • When creating a BiHA cluster from scratch, bihactl uses the default 5432 value.

-P biha_port
--biha-port=biha_port #

Specifies the port used to exchange service information between nodes. If not specified, the value is set to port + 1.

-r node_mode
--mode=node_mode #

Specifies the operation mode of the node. The allowed values are as follows:

  • regular — the node can operate as the leader or as the follower. This is the default value.

  • referee — the node only participates in the leader elections and does not contain any user databases.

  • referee_with_wal — the node participates both in the leader elections in the same way as in the referee mode and receives the entire WAL from the leader node.

By default, the postgres database is not copied to a node in referee or referee_with_wal modes. To copy the postgres database to the referee, use the --referee-with-postgres-db option.

-R
--referee-with-postgres-db #

Copies the postgres database with all the objects to the referee node. You can only use this option when adding a node in referee or referee_with_wal modes.

-s magic_string
--magic-string=magic_string #

Specifies the magic string that contains encoded data to connect to the leader node.

init #

Syntax:

bihactl init --biha-node-id=node_id
             --nquorum=quorum_value
             --host=host
             [--convert [--root-cert=/path/to/ca.crt --server-cert=/path/to/server.crt \
             --server-key=/path/to/server.key --user-postgres-cert=/path/to/client.crt \
             --user-postgres-key=/path/to/client.key [--postgres-ssl-mode=ssl_mode]]]
             [--pgdata=datadir]
             [--port=port]
             [--biha-port=biha_port]
             [--use-ssl]
             [--minnodes=min_node_num]
             [--magic-file=magic_file]
             [--options=initdb_options]
             [--sync-standbys=sync_standbys_num [--sync-standbys-min=sync_standbys_min_num]
             [--root-cert=/path/to/ca.crt --user-biha-cert=/path/to/client.crt \
             --user-biha-key=/path/to/client.key [--biha-ssl-mode=ssl_mode]]

Initializes a cluster and sets the leader node. When this command is executed, bihactl accesses the initdb utility, at this stage you can also specify its parameters with the -o option.

This command can take the following options:

-C
--convert #

Converts an existing node to make it the leader node in the high-availability cluster.

-D datadir
--pgdata=datadir #

Specifies the directory where the database cluster should be stored. If not specified, bihactl uses the PGDATA value.

-f magic_file
--magic-file=magic_file #

Specifies the path for a file to be created. This file contains encoded data to connect to the leader node (magic string).

-h host
--host=host #

Specifies the node host for incoming connections.

-I node_id
--biha-node-id=node_id #

Specifies the unique ID of the node.

-M min_node_num
--minnodes=min_node_num #

Specifies the minimum number of operational nodes for the leader node to be open for write transactions. If not specified, the value equals the nquorum value.

-N quorum_value
--nquorum=quorum_value #

Specifies the minimum number of nodes, which must vote for the new leader node if the current leader is down. This parameter can be set with the biha.set_nquorum function.

When setting up this value, consider the split-brain risk. It is recommended to use the following formula: (total number of nodes + 1)/2. For example, if your cluster has 3 nodes, the nquorum value must be 2.

-o initdb_options
--options=initdb_options #

Specifies additional options of initdb.

-p port
--port=port #

Specifies the node port for incoming connections.

If not specified:

  • When converting the existing cluster using --convert, bihactl uses the PGPORT value.

  • When creating a BiHA cluster from scratch, bihactl uses the default 5432 value.

-P biha_port
--biha-port=biha_port #

Specifies the port used to exchange service information between nodes. If not specified, the value is set to port + 1.

-S
--use-ssl #

Enables the protected mode of the service information exchange between cluster nodes with SSL/TLS over the biha control channel.

-Y sync_standbys_num
--sync-standbys=sync_standbys_num #

Enables quorum-based synchronous replication by setting the synchronous_standby_names parameter and specifying the number of synchronous standbys (quorum) with the ANY method. It is recommended that the sync_standbys_num value be less than the value of the --minnodes option.

-y sync_standbys_min_num
--sync-standbys-min=sync_standbys_min_num #

Enables relaxed quorum-based synchronous replication by specifying the MIN field value of the synchronous_standby_names parameter, which is the minimum number of synchronous standbys that must be available for the leader node to continue operation. The sync_standbys_min_num value must be lower than --sync-standbys and cannot be negative. If the option is not specified, the BiHA cluster operates according to the default synchronous replication restrictions, i.e. the leader node is not available for write transactions until all followers catch up with its current state.

--biha-ssl-mode=ssl_mode #

Determines the SSL authentication policy for the biha_replication_user role. The following modes are supported:

  • verify-full (default)

  • require

  • verify-ca

For more information about modes, see sslmode.

--postgres-ssl-mode=ssl_mode #

Determines the SSL authentication policy for the superuser. The following modes are supported:

  • verify-full (default)

  • require

  • verify-ca

For more information about modes, see sslmode.

--root-cert=/path/to/ca.crt #

Specifies the path to the trusted CA certificate in the PEM format.

--server-cert=/path/to/server.crt #

Specifies the path to the SSL certificate for the BiHA node in the PEM format.

--server-key=/path/to/server.key #

Specifies the path to the private key for the --server-cert certificate in the PEM format.

--user-biha-cert=/path/to/client.crt #

Specifies the path to the SSL certificate for the biha_replication_user role authentication in the PEM format.

--user-biha-key=/path/to/client.key #

Specifies the path to the private key for the --user-biha-cert certificate in the PEM format.

--user-postgres-cert=/path/to/client.crt #

Specifies the path to the SSL certificate for the superuser authentication in the PEM format.

--user-postgres-key=/path/to/client.key #

Specifies the path to the private key for the --user-postgres-cert certificate in the PEM format.

status #

Syntax:

bihactl status {--host=host [--port=port] | --magic-string=magic_string | --magic-file=magic_file}

Checks the node status and displays it in the biha.status_v view. This command can take the following options:

-f magic_file
--magic-file=magic_file

Specifies the path to the magic file that contains encoded data to connect to the leader node.

-h host
--host=host

Specifies the node host for incoming connections.

-p port
--port=port

Specifies the node port for incoming connections. If not specified, bihactl uses the PGPORT value. The default value is 5432.

-s magic_string
--magic-string=magic_string

Specifies the magic string that contains encoded data to connect to the leader node.

-V | --version #

Syntax:

bihactl -V
bihactl --version

Displays the current version of the high-availability cluster.

-? | --help #

Syntax:

bihactl -?
bihactl --help

Displays command-line help.

FAQ