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= или pg_probackup с параметрами ИМЯ_СЛОТА, --wal-method=stream, --checkpoint=fast--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=#хостУказывает хост узла для входящих соединений.
-Iid_узла--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=#хостУказывает хост узла для входящих соединений.
-Iid_узла--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(по умолчанию)requireverify-ca
За подробной информацией о режимах обратитесь к sslmode.
--postgres-ssl-mode=#режим_sslОпределяет политику аутентификации по SSL для суперпользователя. Поддерживаются следующие режимы:
verify-full(по умолчанию)requireverify-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
Выводит текущую версию отказоустойчивого кластера.
См. также
initdb, pg_basebackup, pg_probackupbihactl
bihactl — create a BiHA cluster in Postgres Pro
Synopsis
bihactl add --biha-node-id= node_id--host= [hostoptions]
bihactl init --biha-node-id= node_id--nquorum= quorum_value--host= [hostoptions]
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
PGDATAdirectory. Thebihactlutility may create thebiha_init.logandbiha_add.logfiles in the directory where it is executed. However, the targetPGDATAdirectory 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 thertcprefix 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= parameters and pg_probackup with the SLOT_NAME, --wal-method=stream, --checkpoint=fast--stream --slot= parameters that prevents deletion of WAL on the leader during backup. SLOT_NAME
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.
-Ddatadir--pgdata=#datadirSpecifies the directory where the database cluster should be stored. If not specified, bihactl uses the
PGDATAvalue.-fmagic_file--magic-file=#magic_fileSpecifies 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 addcommand.-hhost--host=#hostSpecifies the node host for incoming connections.
-Inode_id--biha-node-id=#node_idSpecifies the unique ID of the node.
-lconn_info--use-leader=#conn_infoSpecifies parameters to connect to the leader node in the following format:
host=
leader_hostport=leader_portbiha-port=leader_biha_port-mbackup_method--backup-method=#backup_methodSpecifies the backup utility. The allowed values are
pg_basebackupandpg_probackup. The default value ispg_basebackup. If you do not specify the--backup-methodoption, the default backup method is used. Thepg_basebackuputility is the only value that can be used when adding the referee node.-Obackup_options--backup-options=#backup_optionsSpecifies additional options of pg_basebackup or pg_probackup depending on the backup utility specified in the
--backup-methodoption.-pport--port=#portSpecifies the node port for incoming connections.
If not specified:
When converting the existing cluster using --convert-standby, bihactl uses the
PGPORTvalue.When creating a BiHA cluster from scratch, bihactl uses the default 5432 value.
-Pbiha_port--biha-port=#biha_portSpecifies the port used to exchange service information between nodes. If not specified, the value is set to
.port+ 1-rnode_mode--mode=#node_modeSpecifies 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 therefereemode and receives the entire WAL from the leader node.
By default, the
postgresdatabase is not copied to a node inrefereeorreferee_with_walmodes. To copy thepostgresdatabase to the referee, use the --referee-with-postgres-db option.-R--referee-with-postgres-db#Copies the
postgresdatabase with all the objects to the referee node. You can only use this option when adding a node inrefereeorreferee_with_walmodes.-smagic_string--magic-string=#magic_stringSpecifies 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.
-Ddatadir--pgdata=#datadirSpecifies the directory where the database cluster should be stored. If not specified, bihactl uses the
PGDATAvalue.-fmagic_file--magic-file=#magic_fileSpecifies the path for a file to be created. This file contains encoded data to connect to the leader node (magic string).
-hhost--host=#hostSpecifies the node host for incoming connections.
-Inode_id--biha-node-id=#node_idSpecifies the unique ID of the node.
-Mmin_node_num--minnodes=#min_node_numSpecifies the minimum number of operational nodes for the leader node to be open for write transactions. If not specified, the value equals the
nquorumvalue.-Nquorum_value--nquorum=#quorum_valueSpecifies 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, thenquorumvalue must be 2.-oinitdb_options--options=#initdb_optionsSpecifies additional options of initdb.
-pport--port=#portSpecifies the node port for incoming connections.
If not specified:
When converting the existing cluster using --convert, bihactl uses the
PGPORTvalue.When creating a BiHA cluster from scratch, bihactl uses the default 5432 value.
-Pbiha_port--biha-port=#biha_portSpecifies 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.
-Ysync_standbys_num--sync-standbys=#sync_standbys_numEnables quorum-based synchronous replication by setting the synchronous_standby_names parameter and specifying the number of synchronous standbys (quorum) with the
ANYmethod. It is recommended that thesync_standbys_numvalue be less than the value of the--minnodesoption.-ysync_standbys_min_num--sync-standbys-min=#sync_standbys_min_numEnables relaxed quorum-based synchronous replication by specifying the
MINfield 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. Thesync_standbys_min_numvalue 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_modeDetermines the SSL authentication policy for the
biha_replication_userrole. The following modes are supported:verify-full(default)requireverify-ca
For more information about modes, see sslmode.
--postgres-ssl-mode=#ssl_modeDetermines the SSL authentication policy for the superuser. The following modes are supported:
verify-full(default)requireverify-ca
For more information about modes, see sslmode.
--root-cert=#/path/to/ca.crtSpecifies the path to the trusted CA certificate in the PEM format.
--server-cert=#/path/to/server.crtSpecifies the path to the SSL certificate for the BiHA node in the PEM format.
--server-key=#/path/to/server.keySpecifies the path to the private key for the --server-cert certificate in the PEM format.
--user-biha-cert=#/path/to/client.crtSpecifies the path to the SSL certificate for the
biha_replication_userrole authentication in the PEM format.--user-biha-key=#/path/to/client.keySpecifies the path to the private key for the --user-biha-cert certificate in the PEM format.
--user-postgres-cert=#/path/to/client.crtSpecifies the path to the SSL certificate for the superuser authentication in the PEM format.
--user-postgres-key=#/path/to/client.keySpecifies 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:
-fmagic_file--magic-file=magic_fileSpecifies the path to the magic file that contains encoded data to connect to the leader node.
-hhost--host=hostSpecifies the node host for incoming connections.
-pport--port=portSpecifies the node port for incoming connections. If not specified, bihactl uses the
PGPORTvalue. The default value is 5432.-smagic_string--magic-string=magic_stringSpecifies 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.