26.4. Справка по расширению biha #
biha — расширение Postgres Pro для управления BiHA-кластером.
В этом разделе содержится информация о параметрах конфигурации, функциях и представлениях расширения biha.
26.4.1. Параметры конфигурации #
Расширение biha поддерживает ряд описанных ниже параметров конфигурации, специфичных для BiHA-кластера:
26.4.1.1. Параметры конфигурации кластера #
Важно
При настройке параметров конфигурации кластера нужно обязательно обеспечить надёжность сети, чтобы изменения затронули все узлы кластера без возникновения ошибок.
Значения этих параметров должны быть одинаковыми на всех узлах кластера.
Не рекомендуется изменять какие-либо параметры конфигурации кластера, пока один из узлов находится в состоянии
NODE_ERROR, так как на этом узле изменения могут не примениться.
service_mode(boolean) #Определяет, включен ли сервисный режим в BiHA-кластере.
Значение можно задать с помощью функции biha.service_mode.
Возможные значения:
f(по умолчанию): сервисный режим отключён.t: сервисный режим включён.
ssl_certificate(text) #Указывает путь к публичному SSL-сертификату, который используется для защиты служебных подключений между узлами инициализированного BiHA-кластера. За подробной информацией обратитесь к Управление SSL для служебных подключений.
Значение можно задать с помощью функции biha.set_ssl_certificate. Чтобы изменения вступили в силу, необходим перезапуск узла.
Значение по умолчанию:
/PGDATA/pg_biha/biha_pub_cert.pemssl_mode(text) #Указывает режим аутентификации для роли
biha_replication_user. За подробной информацией о настройке SSL-аутентификации обратитесь к Настройка SSL для biha_replication_user. За подробной информацией о режимах обратитесь к sslmode.Значение можно задать с помощью функции biha.set_ssl_mode. Чтобы изменения вступили в силу, необходим перезапуск узла.
Возможные значения:
verify-full(по умолчанию)requireverify-ca
ssl_private_key(text) #Указывает путь к закрытому SSL-ключу, который используется для защиты служебных подключений между узлами инициализированного BiHA-кластера. За подробной информацией обратитесь к Управление SSL для служебных подключений.
Значение можно задать с помощью функции biha.set_ssl_private_key. Чтобы изменения вступили в силу, необходим перезапуск узла.
Значение по умолчанию:
/PGDATA/pg_biha/biha_priv_key.pemsynchronous_standby_names.count(integer) #Включает кворумную синхронную репликацию, устанавливая параметр synchronous_standby_names и указывая число синхронных резервных (кворум) с методом
ANY.Значение можно задать с помощью функции biha.set_sync_standbys.
Значение должно быть целым числом больше нуля, больше значения параметра synchronous_standby_names.min, если он задан, а также не должно превышать число последователей, за исключением рефери. Рекомендуется задавать значение
synchronous_standby_names.countменьше, чем значение minnodes.synchronous_standby_names.min(integer) #Включает нестрогую кворумную синхронную репликацию, указывая значение поля
MINпараметра synchronous_standby_names, что является минимальным числом синхронных резервных, которые должны быть доступны, чтобы лидер продолжал подтверждать транзакции. Если значение параметра не указано, BiHA-кластер работает в соответствии с ограничениями синхронной репликации по умолчанию, т.е. лидер не доступен для транзакций на запись, пока все последователи не догонять его текущее состояние.Значение можно задать с помощью функции biha.set_sync_standbys_min.
Значение
synchronous_standby_names.minдолжно быть целым числом равным или больше нуля, а также меньше значения synchronous_standby_names.count. Если задано значение-1, нестрогая кворумная синхронная репликация отключена.synchronous_standby_names.names(integer) #Указывает список синхронных резервных в параметре конфигурации synchronous_standby_names.
Значение можно задать с помощью функции biha.set_ssn, а также изменять список синхронных резервных с помощью функций biha.add_to_ssn или biha.get_ssn.
use_ssl(boolean) #Указывает, будет ли использоваться защищённый режим передачи служебной информации между узлами кластера по протоколу SSL/TLS управляющего канала biha. За подробной информацией обратитесь к Управление SSL для служебных подключений.
Значение можно задать с помощью функции biha.set_use_ssl. Чтобы изменения вступили в силу, необходим перезапуск узла.
Возможные значения:
false(по умолчанию): SSL отключён для служебных подключений BiHA.true: сервисные подключения BiHA защищены SSL.
user_biha_cert(text) #Указывает путь к публичному SSL-сертификату, который используется для аутентификации роли
biha_replication_user. За подробной информацией о настройке SSL-аутентификации обратитесь к Настройка SSL для biha_replication_user.Значение можно задать с помощью функции biha.set_user_cert.
user_biha_key(text) #Указывает путь к закрытому ключу SSL, который используется для аутентификации роли
biha_replication_user. За подробной информацией о настройке SSL-аутентификации обратитесь к Настройка SSL для biha_replication_user.Значение можно задать с помощью функции biha.set_user_key.
26.4.1.2. Параметры конфигурации сегмента #
Следующие параметры конфигурации можно задать индивидуально для каждого логического узла (сегмента). Значения параметров наследуются узлами в рамках сегмента.
heartbeat_max_lost(integer) #Указывает максимальное число сообщений о контроле состояния, которые допустимо не получить по BCP до того, как узел будет считаться недоступным.
Значение можно задать с помощью функции biha.set_heartbeat_max_lost.
Значение по умолчанию:
10Минимальное значение:
3Узлы во всех состояниях используют значение тайм-аута сообщений о контроле состояния, который рассчитывается как
heartbeat_max_lost* heartbeat_send_period, для определения доступности других узлов. Например, если Узел A не получает сообщения о контроле состояния от Узла B в течение вышеупомянутого тайм-аута, состояние Узла B изменится наUNKNOWNв представлении biha.status_v Узла A, что будет означать, что Узел A считает Узел B недоступным. Лидер в состоянииLEADER_RWдополнительно использует тайм-аут, указанный в параметре no_wal_on_follower.heartbeat_send_period(integer) #Указывает частоту отправки сообщений о контроле состояния в миллисекундах.
Значение можно задать с помощью функции biha.set_heartbeat_send_period.
Значение по умолчанию:
1000Минимальное значение:
500Узлы во всех состояниях используют значение тайм-аута сообщений о контроле состояния, который рассчитывается как heartbeat_max_lost *
heartbeat_send_period, для определения доступности других узлов. Например, если Узел A не получает сообщения о контроле состояния от Узла B в течение вышеупомянутого тайм-аута, состояние Узла B изменится наUNKNOWNв представлении biha.status_v Узла A, что будет означать, что Узел A считает Узел B недоступным. Лидер в состоянииLEADER_RWдополнительно использует тайм-аут, указанный в параметре no_wal_on_follower.minnodes(integer) #Указывает минимальное количество рабочих узлов, необходимое, чтобы лидер был открыт для транзакций на запись.
Значение можно задать с помощью функции biha.set_minnodes.
Значение по умолчанию: равно nquorum
Устанавливая это значение, принимайте во внимание возможный риск разделения кластера. Рекомендуется использовать следующую формулу: (
общее_число_узлов+ 1)/2. Например, если в кластере 3 узла, значениеminnodesдолжно быть 2.Если на узле для параметра can_vote установлено значение
false, такой узел игнорируется параметромminnodes.no_wal_on_follower(integer) #Указывает тайм-аут продвижения слота репликации в миллисекундах.
Значение можно задать с помощью функции biha.set_no_wal_on_follower.
Значение по умолчанию:
20000Минимальное значение:
5000BiHA использует этот параметр конфигурации для следующих целей:
Когда вы вручную назначаете узел-последователь в качестве нового лидера с помощью функции biha.set_leader, состояние последователя изменяется на
FOLLOWER_OFFERED.Последователь в состоянии
FOLLOWER_OFFEREDпроверяет, обновилась ли его позиция WAL. Обновление позиции WAL подтверждает, что последователь продолжает получать данные репликации от источника. Если последователь не получает записи WAL дольше, чем задано в параметреno_wal_on_follower, состояние последователя изменяется обратно наFOLLOWER. В этом случае в журнале появляется следующее сообщение: «Timed out waiting for new WAL records from current leader» (Истёк тайм-аут ожидания записей WAL от текущего лидера).Лидер в состоянии
LEADER_RWиспользует параметрno_wal_on_followerв связке со значением тайм-аута сообщений о контроле состояния (который рассчитывается как heartbeat_max_lost * heartbeat_send_period) для определения доступности других узлов.Лидер проверяет позиции слотов репликации других узлов. Если позиция слота репликации узла обновляется, это означает, что узел получает данные репликации от лидера и доступен. Если лидер не получает от узла сообщения о контроле состояния в течение вышеупомянутого тайм-аута, а позиция слота репликации узла не меняется в течение тайм-аута, заданного в
no_wal_on_follower, лидер будет считать узел недоступным, а состояние узла изменится наUNKNOWNв представлении biha.status_v лидера.Если в каскадном BiHA-кластере узел не получает WAL в течение времени, заданного в
no_wal_on_follower, он начинает искать новый источник репликации в соответствии с конфигурацией repl_pref_roles.
nquorum(integer) #Указывает минимальное число узлов, которые должны проголосовать за нового лидера при отказе текущего лидера.
Значение можно задать с помощью функции biha.set_nquorum.
Значение по умолчанию:
2Устанавливая это значение, принимайте во внимание возможный риск разделения кластера. Рекомендуется использовать следующую формулу: (
общее_число_узлов+ 1)/2. Например, если в кластере 3 узла, значениеnquorumдолжно быть 2.Если на узле для параметра can_vote установлено значение
false, такой узел игнорируется параметромnquorum.
26.4.1.3. Параметры конфигурации узла #
Следующие параметры конфигурации можно задать индивидуально для каждого физического узла.
asyncaction_timeout(integer) #Указывает время ожидания выполнения асинхронных операций, таких как добавление сегментов и удаление узлов, в миллисекундах. Если сегмент или узел не добавляются или не удаляются в течение указанного времени, BiHA прерывает SQL-команду.
Значение параметра должно быть одинаковым на всех узлах кластера.
Значение можно задать с помощью функции biha.set_asyncaction_timeout.
Значение по умолчанию:
30000Минимальное значение:
1000biha_hosts(string) #Используется другими узлами для подключения к текущему узлу по внутреннему управляющему каналу (BCP), например, через прокси-сервер или туннель. Если значение
biha_hostsпустое, по умолчанию, используется значение biha_listen_addresses текущего узла.Значение можно задать с помощью функции biha.set_biha_hosts.
Возможные значения: один или несколько разделённых запятыми адресов в формате
hostname:port.port— необязательное значение, если порт не указан или задано значение-1, используется значение biha_port текущего узла.Например:
biha-db-1:5433,biha-proxy:8081,biha-node-1biha_listen_addresses(string) #Определяет, на каких адресах открыты слушающие сокеты для внутреннего управляющего канала BCP.
Значение можно задать с помощью функции bihactl.
Возможные значения: один или несколько разделённых запятыми адресов в формате
hostname:port.port— необязательное значение, если порт не указан или задано значение-1, используется значение biha_port текущего узла.Например:
biha-db-1:5433,biha-proxy:8081,biha-node-1biha_port(integer) #Указывает порт, который используется другими узлами для подключения к текущему узлу по внутреннему управляющему каналу (BCP).
Значение параметра задаётся утилитой bihactl и может быть перезаписано при изменении параметров конфигурации biha_hosts, biha_listen_addresses или replication_hosts.
callbacks_timeout(integer) #Устанавливает время для выполнения всех функций-обработчиков для одного события в миллисекундах.
Значение можно задать с помощью функции biha.set_callbacks_timeout.
Значение по умолчанию:
10000Минимальное значение:
1000config_send_period(integer) #Определяет тайм-аут для рассылки сообщения с конфигурацией кластера.
Значение можно задать с помощью функции biha.set_config_send_period.
Значение по умолчанию:
1000Минимальное значение:
500deny_wal_sources(string) #Указывает перечень узлов, которые не могут быть источниками репликации для текущего узла. Если идентификатор узла внесён в перечень, текущий узел не может реплицировать с этого узла.
Значение можно задать с помощью функции biha.set_deny_wal_sources.
Значение по умолчанию: пустое
Параметр
deny_wal_sourcesимеет более высокий приоритет, чем repl_pref_roles. Например, если идентификатор лидера внесён в переченьdeny_wal_sourcesузла, этот узел не реплицирует с лидера, даже если для его параметраrepl_pref_rolesзадано значениеLF.flw_ro(boolean) #Определяет доступность последователя для операций на чтение.
Значение можно задать с помощью функции biha.set_flw_ro.
Возможные значения:
on(по умолчанию): последователь доступен для операций на чтение.off: чтение с этого последователя разрешено только суперпользователям, а также членам ролейBIHA_CLUSTER_MANAGEMENT_ROLEиpg_monitor.
leader_timeout(integer) #Определяет максимальную длительность переключения после запуска biha.set_leader, в миллисекундах. Если процесс переключения не завершается в указанный период, узел возвращается в состояние
FOLLOWER.Значение можно задать с помощью функции biha.set_leader_timeout.
Значение по умолчанию:
20000Минимальное значение:
0manage_slots_xmin(boolean) #Определяет, отслеживает ли BiHA значение
xminслотов репликации.Значение можно задать с помощью функции biha.set_manage_slots_xmin.
Возможные значения:
true(по умолчанию): отслеживаниеxminвключено.false: отслеживаниеxminотключено.
max_replicas(integer) #Указывает максимальное число подключений biha к узлу для репликации, то есть максимальное число процессов walsender, где
application_name—biha_node_*. За подробной информацией обратитесь к Подразделу 26.1.5.2.Значение можно задать с помощью функции biha.set_max_replicas.
Значение должно быть целым числом больше нуля и не должно превышать значения max_wal_senders.
Другие возможные значения:
INT_MAX(по умолчанию): число подключений неограниченно.0: подключения запрещены.
pg_port(integer) #Указывает порт узла для входящих подключений к Postgres Pro.
Значение параметра задаётся утилитой bihactl и может быть перезаписано при изменении параметров конфигурации biha_hosts, biha_listen_addresses или replication_hosts.
replication_hosts(string) #Используется другими узлами для подключения к текущему узлу по каналу репликации. Если значение
replication_hostsпустое, по умолчанию используется значение biha_listen_addresses текущего узла.Примечание
При изменении значения по умолчанию параметра listen_addresses (
*) убедитесь, чтоreplication_hostsнастроен таким образом, чтобы пакеты, направляемые на указанные адреса, попадали на один из интерфейсов изlisten_addresses. Это необходимо для того, чтобы репликационные подключения могли установить связь со слушающим сокетом.Значение можно задать с помощью функции biha.set_replication_hosts.
Возможные значения: один или несколько разделённых запятыми адресов в формате
hostname:port.port— необязательное значение, если порт не указан или задано значение-1, используется значение biha_port текущего узла.Максимальное значение строки 1024 байта, в противном случае параметр игнорируется.
Например:
biha-db-1:5433,biha-proxy:8081,biha-node-1sql_hosts(string) #Используется другими узлами и bihactl для выполнения SQL-запросов к текущему узлу. Если значение
sql_hostsпустое, по умолчанию используется значение replication_hosts текущего узла.Примечание
При изменении значения по умолчанию параметра listen_addresses (
*) убедитесь, чтоsql_hostsнастроен таким образом, чтобы пакеты, направляемые на указанные адреса, попадали на один из интерфейсов изlisten_addresses. Это необходимо для того, чтобы SQL-подключения могли установить связь со слушающим сокетом.Значение можно задать с помощью функции biha.set_sql_hosts.
Возможные значения: один или несколько разделённых запятыми адресов в формате
hostname:port.port— необязательное значение, если порт не указан или задано значение-1, используется значение biha_port текущего узла.Максимальное значение строки 1024 байта, в противном случае параметр игнорируется.
Например:
biha-db-1:5433,biha-proxy:8081,biha-node-1watchdog_timeout(integer) #Указывает тайм-аут для прекращения принятия запросов узлом, если процесс biha не отвечает, в секундах. За подробной информацией обратитесь к Подразделу 26.3.9.
Значение можно задать с помощью функции biha.set_watchdog_timeout. Чтобы изменения вступили в силу, необходим перезапуск узла.
Значение по умолчанию:
2Минимальное значение:
1
26.4.1.4. Параметры конфигурации, общие для узлов и сегментов #
Следующие параметры конфигурации можно задать индивидуально как для физических, так и для логических узлов (сегментов).
can_be_leader(boolean) #Определяет возможность узла или сегмента стать лидером.
Значение можно задать с помощью функции biha.set_can_be_leader.
Возможные значения:
true(по умолчанию): узел или сегмент может стать кандидатом на выборах нового лидера.false: узел или сегмент не может стать кандидатом на выборах нового лидера.
Самый большой объём WAL может быть на том узле, который не может стать лидером. В этой ситуации при необходимости выборов другие узлы, которые могут предлагать себя в качестве кандидатов в лидеры, попытаются получить недостающие данные с этого узла. В случае успеха один из этих узлов станет лидером. Если данные получить не удалось, на узле, который не может стать лидером, запустится процесс автоматической синхронизации. Если параметр biha.autorewind не включён, состояние этого узла изменится на
NODE_ERROR.can_vote(boolean) #Определяет, может ли узел или сегмент голосовать.
Значение можно задать с помощью функции biha.set_can_vote.
Возможные значения:
true(по умолчанию): узел или сегмент может голосовать.false: узел или сегмент не может голосовать, а также не может быть кандидатом на выборах нового лидера.
mode(text) #Указывает режим работы узла или сегмента. Режим задаётся утилитой bihactl, его нельзя изменить после инициализации кластера.
Возможные значения для узла:
regular(по умолчанию): узел может быть лидером или последователем.referee: узел может только участвовать в выборах лидера и не содержит никаких пользовательских баз данных.referee_with_wal: узел участвует в выборах лидера также, как и в режимеreferee, а также получает полный WAL с лидера.
Возможные значения для сегмента:
regularname(text) #Указывает имя узла или сегмента. Имя задаётся утилитой bihactl, его нельзя изменить после инициализации кластера.
priority(integer) #Задаёт приоритет узла или сегмента в секундах, который влияет как на выборы, так и на репликацию в кластере.
Значение можно задать с помощью функции biha.set_priority.
Значение должно быть целым числом больше или равным нулю. Значение
0означает наивысший приоритет.Значение по умолчанию:
-1, параметр игнорируется.Примечание
После изменения значения по умолчанию его нельзя снова задать, то есть отключение
priorityне поддерживается.BiHA использует этот параметр конфигурации для следующих целей:
Задать тайм-аут начала репликации при выборе источника репликации в BiHA-кластере с каскадной репликацией. Чем выше значение, тем позднее узел начинает репликацию и разрешает подключение менее приоритетных узлов. Параметр необходим для того, чтобы узлы кластера могли наладить схему каскадной репликации автоматически.
Установить приоритет узла в кластере с синхронной репликацией. Значение определяет тайм-аут, по истечении которого узел предложит себя в качестве кандидата на выборах. Нулевое значение означает самый высокий приоритет.
Важно
Чтобы обеспечить корректную работу параметра, установите значение параметра --sync-standbys на единицу меньше общего количества узлов кластера.
repl_pref_roles(text) #Указывает предпочтительную роль узла, выступающего в качестве источника репликации для текущего узла в BiHA-кластере с каскадной репликацией.
Значение можно задать с помощью функции biha.set_pref_roles.
Возможные значения:
L(лидер),F(последователь) илиR(рефери), или их комбинации. Значение должно содержать от одного до трёх символов, которые не должны повторяться. Например:L,F,LFRилиLF.Значение по умолчанию:
L, которое означает, что данные реплицируются с лидера или главного последователя в зависимости от сегмента, в котором расположен узел.
26.4.1.5. Необязательные параметры конфигурации #
Следующие параметры конфигурации являются необязательными и могут быть изменены с помощью команды ALTER SYSTEM SET, например:
ALTER SYSTEM SET biha.autorewind = true;
Значения этих параметров на узлах кластера могут отличаться.
biha.autorewind(boolean) #Управляет политикой автоматической синхронизации для узла, в отношении которого должен быть выполнен
pg_rewind. Например, для старого лидера при его синхронизации с новым лидером. За подробной информацией обратитесь к Автоматическая синхронизация кластера после аварийного переключения.Возможные значения:
false(по умолчанию): автоматическая синхронизация не выполняется.true: автоматическая синхронизация выполняется после ошибки, после которой узел переходит в состояниеNODE_ERROR.
biha.autowaltrim(boolean) #Управляет политикой автоматического выравнивания WAL в рамках одного узла. За подробной информацией обратитесь к Автоматическая синхронизация кластера после аварийного переключения.
Возможные значения:
true(по умолчанию): BiHA автоматически планирует и выполняет процедуру выравнивания WAL, если это возможно.false: процедура выравнивания WAL не выполняется, синхронизация кластера проводится с помощью pg_rewind.
biha.wal_validation(boolean) #Управляет механизмом проверки WAL. Процедура проверки WAL запускается при обновлении истории, а также при состоянии узла
PRESTARTUP, чтобы исключить прерывание процесса восстановления по причине несогласованности WAL.Возможные значения:
true(по умолчанию): валидация WAL включена.false: валидация WAL отключена.
Механизм проверки WAL выполняет следующие действия:
Проверяет линии времени. Если в TLI (идентификаторе линии времени) не хватает полных сегментов WAL до точки переключения или вообще нет сегментов, он считается некорректным.
Скрывает некорректные линии времени от узлов BiHA. Это не позволяет узлу с большей, но некорректной линией времени стать кандидатом на роль лидера.
Перезапускает Postgres Pro в случае несогласованности WAL на повышаемом узле.
Проверяет согласованность WAL при состоянии узла
PRESTARTUPи, при необходимости, пытается исправить WAL автоматически.
26.4.1.6. Уровни протоколирования biha #
26.4.1.6.1. Общие уровни протоколирования #
Общие уровни протоколирования используются для компонентов biha, у которых нет специальных уровней протоколирования.
biha.BihaLog_log_level(enum) #Задаёт уровень протоколирования для предоставления общей информации о работе компонентов biha. Значение по умолчанию —
LOG.biha.BihaWarn_log_level(enum) #Задаёт уровень протоколирования для предупреждения о возможных ошибках в работе компонентов biha. Значение по умолчанию —
WARNING.biha.BihaDetails_log_level(enum) #Задаёт уровень протоколирования для предоставления подробной информации о работе компонентов biha. Значение по умолчанию —
DEBUG1.biha.BihaDebug_log_level(enum) #Задаёт уровень протоколирования для предоставления отладочной информации о работе компонентов biha. Значение по умолчанию —
DEBUG2.biha.BihaDebug2_log_level(enum) #Задаёт уровень протоколирования для предоставления отладочной информации о работе компонентов biha. Значение по умолчанию —
DEBUG3.
26.4.1.6.2. Уровни протоколирования управляющего канала BiHA (BCP) и транспорта #
biha.BcpTransportLog_log_level(enum) #Задаёт уровень протоколирования для предоставления общей информации о работе управляющего канала. Значение по умолчанию —
LOG.biha.BcpTransportWarn_log_level(enum) #Задаёт уровень протоколирования для вывода предупреждений о возможных проблемах в канале управления. Значение по умолчанию —
WARNING.biha.BcpTransportDetails_log_level(enum) #Задаёт уровень протоколирования для предоставления подробной информации о работе управляющего канала. Значение по умолчанию —
DEBUG1.biha.BcpTransportDebug_log_level(enum) #Задаёт уровень протоколирования для предоставления отладочной информации о работе управляющего канала. Значение по умолчанию —
DEBUG2.
26.4.1.6.3. Уровни протоколирования Node Controller #
Следующие уровни протоколирования предоставляют информацию о компоненте Node Controller.
biha.NodeControllerLog_log_level(enum) #Задаёт уровень протоколирования для предоставления общей информации о работе компонента
Node Controller. Значение по умолчанию —LOG.biha.NodeControllerWarn_log_level(enum) #Задаёт уровень протоколирования для вывода предупреждений о возможных проблемах компоненте
Node Controller. Значение по умолчанию —WARNING.biha.NodeControllerDetails_log_level(enum) #Задаёт уровень протоколирования для предоставления подробной информации о работе компонента
Node Controller. Значение по умолчанию —DEBUG1.biha.NodeControllerDebug_log_level(enum) #Задаёт уровень протоколирования для предоставления отладочной информации о работе компонента
Node Controller. Значение по умолчанию —DEBUG2.biha.NodeControllerDebug2_log_level(enum) #Задаёт уровень протоколирования для предоставления отладочной информации о работе компонента
Node Controller. Значение по умолчанию —DEBUG3.
26.4.1.6.4. Уровни протоколирования Postgres Controller #
Следующие уровни протоколирования предоставляют информацию о компоненте Postgres Controller.
biha.PgControllerLog_log_level(enum) #Задаёт уровень протоколирования для предоставления общей информации о работе компонента
Postgres Controller. Значение по умолчанию —LOG.biha.PgControllerWarn_log_level(enum) #Задаёт уровень протоколирования для вывода предупреждений о возможных проблемах в компоненте
Postgres Controller. Значение по умолчанию —WARNING.biha.PgControllerDetails_log_level(enum) #Задаёт уровень протоколирования для предоставления подробной информации о работе компонента
Postgres Controller. Значение по умолчанию —DEBUG1.biha.PgControllerDebug_log_level(enum) #Задаёт уровень протоколирования для предоставления отладочной информации о работе компонента
Postgres Controller. Значение по умолчанию —DEBUG2.biha.PgControllerDebug2_log_level(enum) #Задаёт уровень протоколирования для предоставления отладочной информации о работе компонента
Postgres Controller. Значение по умолчанию —DEBUG3.
26.4.1.6.5. Уровни протоколирования Config Controller #
Следующие уровни протоколирования предоставляют информацию о компоненте Config Controller.
biha.BihaConfigLog_log_level(enum) #Задаёт уровень протоколирования для предоставления общей информации о работе компонента
Config Controller. Значение по умолчанию —LOG.biha.BihaConfigWarn_log_level(enum) #Задаёт уровень протоколирования для вывода предупреждений о возможных проблемах в компоненте
Config Controller. Значение по умолчанию —WARNING.biha.BihaConfigDetails_log_level(enum) #Задаёт уровень протоколирования для предоставления подробной информации о работе компонента
Config Controller. Значение по умолчанию —DEBUG1.biha.BihaConfigDebug_log_level(enum) #Задаёт уровень протоколирования для предоставления отладочной информации о работе компонента
Config Controllercomponent. Значение по умолчанию —DEBUG2.biha.BihaConfigDebug2_log_level(enum) #Задаёт уровень протоколирования для предоставления отладочной информации о работе компонента
Config Controller. Значение по умолчанию —DEBUG3.
26.4.2. Функции #
Все перечисленные ниже функции необходимо вызывать из базы данных biha_db, например:
biha_db=# SELECT biha.add_node(222, 1111);
Если иное не указано в описании функции, функция должна вызываться на лидере.
26.4.2.1. Состав кластера #
biha.add_node (#idinteger,идентификатор_родительского_узлаinteger) →booleanДобавляет сегмент в кластер GDBiHA. Если не указать
идентификатор_родительского_узла, по умолчанию в качестве родительского узла будет назначен узел с идентификатором 1111. За подробной информацией обратитесь к Подразделу 26.3.1.Например, добавьте сегмент с идентификатором
222в кластер с идентификатором1111:biha_db=# SELECT biha.add_node(222, 1111); add_node ------------- t (1 row)
biha.set_leader (#idinteger,режимstring) →booleanУстанавливает лидера, главного последователя или лидер-сегмент вручную. За подробной информацией о процедуре ручного переключения обратитесь к Ручное переключение узлов.
Примечание
Вызывайте эту функцию на узле, который вы хотите сделать новым лидером или главным последователем. Не вызывайте функцию на текущем лидере.
Поддерживаются следующие режимы переключения:
graceful(по умолчанию): повышаемый узел ожидает понижения старого лидера или главного последователя и при необходимости догоняет его по записям WAL.immediate: переключение происходит немедленно, без ожидания. Состояние узла с указанным идентификатором сразу меняется наLEADER_RW/LEADER_ROилиFRONT_FOLLOWER, пропуская состояниеFOLLOWER_OFFERED. В этом режиме функция-обработчикLEADER_CHANGE_STARTEDне вызывается. Если на текущем лидере или главном последователе выполняется команда в режимеimmediate, его состояние сразу меняется наFOLLOWERи собщение о смене лидера передаётся на другие узлы.Важно
Режим
immediateнебезопасен, его использование может привести к потере данных. Перед переключением лидера в этом режиме рекомендуется выполнить следующие действия:Включите автоматическую синхронизацию, задав для параметра biha.autorewind значение
true.Для параметра minnodes задайте значение
1, чтобы лидер мог игнорировать состояние других узлов.
Например, назначьте узел с идентификатором
2новым лидером в режимеimmediate:biha_db=# SELECT biha.set_leader(2, 'immediate'); set_leader ------------- t (1 row)
biha.set_leader_timeout (#idinteger,значение_тайм_аутаinteger) →booleanЗадаёт значение параметра конфигурации leader_timeout.
Например, чтобы установить время ожидания
10000мс для всех узлов в сегменте222, выполните:biha_db=# SELECT * FROM biha.set_leader_timeout(222, 10000); set_leader_timeout ------------- t (1 row)
biha.remove_node (#idinteger) →booleanУдаляет узел или сегмент из кластера. Перед удалением узел необходимо остановить. Если узел является родительским для другого узла, удалить его нельзя. За подробной информацией об изменении состава кластера обратитесь к Подразделу 26.3.1.
Например, удалите узел с идентификатором
4:biha_db=# SELECT biha.remove_node(3); remove_node ------------- t (1 row)
26.4.2.2. Конфигурирование кластера #
biha.config () →#setof recordВозвращает значения параметров конфигурации для каждого узла и сегмента. Наиболее критичные параметры конфигурации можно также посмотреть с помощью представления Подраздел 26.4.3.1.
Отображаются следующие параметры:
id: идентификатор узла (integer).nquorum: текущее значение nquorum (integer).minnodes: текущее значение minnodes (integer).heartbeat_send_period: текущее значение heartbeat_send_period (integer).heartbeat_max_lost: текущее значение heartbeat_max_lost (integer).no_wal_on_follower: текущее значение no_wal_on_follower (integer).sync_standbys_min: текущее значения поляMINпараметра synchronous_standby_names (integer).priority: текущее значение priority (integer).can_be_leader: текущее значение can_be_leader (boolean).can_vote: текущее значение can_vote (boolean).mode: текущее значение mode (text).proxima_enabled: текущий статус proxima, если расширение поддерживается текущей версией Postgres Pro Standard (integer).name: имя узла (text).repl_pref_roles: предпочтительные роли узлов для репликации, заданные в параметре конфигурации repl_pref_roles (text).max_replicas: максимальное число репликационных подключений к узлу, заданное в параметре конфигурации max_replicas (integer).config_version: текущая версия конфигурацииpg_biha/biha_conf_(версия_конфигурации.jsoninteger).parent_id: уникальный идентификатор узла, который является родительским для текущего узла (integer).service_mode: текущее значение service_mode (boolean).unit_type: тип юнита. Возможные значения:NODE,SEGMENT.deny_wal_sources: текущее значение deny_wal_sources (string).biha_hosts: текущее значение biha_hosts (string).replication_hosts: текущее значение replication_hosts (string).sql_hosts: текущее значение sql_hosts (string).leader_timeout: текущее значение leader_timeout (integer).use_ssl: текущее значение use_ssl (boolean).ssl_certificate: текущее значение ssl_certificate (text).ssl_private_key: текущее значение ssl_private_key (text).user_cert: текущее значение user_biha_cert (text).user_key: текущее значение user_biha_key (text).ssl_mode: текущее значение ssl_mode (text).flw_ro: текущее значение flw_ro (boolean).callbacks_timeout: текущее значение callbacks_timeout (integer).watchdog_timeout: текущее значение watchdog_timeout (integer).asyncaction_timeout: текущее значение asyncaction_timeout (integer).manage_slots_xmin: текущее значение manage_slots_xmin (boolean).config_send_period: текущее значение config_send_period (integer).
Например, вызовите функцию
biha.configдля узла с идентификатором1:biha_db=# select * from biha.config() where id = 1 \gx -[ RECORD 1 ]---------+-------------------------- id | 1 nquorum | 3 minnodes | 1 heartbeat_send_period | 1000 heartbeat_max_lost | 10 no_wal_on_follower | 20000 sync_standbys_min | -2 priority | -1 can_be_leader | t can_vote | t mode | regular proxima_enabled | f name | biha_node_1 repl_pref_roles | L max_replicas | 2147483647 config_version | 12 parent_id | 111 service_mode | f unit_type | NODE deny_wal_sources | biha_hosts | biha-db-1:5433,biha-proxy:8081 replication_hosts | biha-db-1:5432,postgres-proxy:8081 sql_hosts | leader_timeout | 20000 use_ssl | f ssl_certificate | pg_biha/biha_pub_cert.pem ssl_private_key | pg_biha/biha_priv_key.pem user_cert | user_key | ssl_mode | flw_ro | t callbacks_timeout | 10000 watchdog_timeout | 2 asyncaction_timeout | 30000 manage_slots_xmin | t config_send_period | 10000
biha.config_json () →#setof recordВозвращает конфигурационный файл в формате JSON. Чтобы увидеть содержимое ветви конфигурационного дерева JSON, используйте функцию biha.get_option.
Например:
biha_db=# select biha.config_json(); config_json ------------------------------------------------------- { + "unit": { + "id": 1111, + "mode": "regular", + "name": "biha_node_1111", + "nquorum": 1, + "can_vote": true, + "children": [ + { + "id": 111, + ... "proxima_enabled": false, + "ssl_certificate": "pg_biha/biha_pub_cert.pem", + "ssl_private_key": "pg_biha/biha_priv_key.pem", + "synchronous_standby_names": { + "min": -2, + "count": -1, + "names": [ + ] + } + } (1 row)biha.get_option (#json_pathtext) →setof recordВозвращает содержимое ветви конфигурационного дерева JSON по указанному JSON-пути. Чтобы увидеть весь конфигурационный файл JSON, используйте функцию biha.config_json.
Например:
biha_db=# select biha.get_option('$.unit.children.[0].children.[1].biha_listen_addresses.[0].address'); get_option ------------ "node-3" (1 row)biha.set_config_send_period (#idinteger,config_send_periodinteger) →booleanЗадаёт значение параметра конфигурации config_send_period.
26.4.2.3. Мониторинг кластера #
biha.error_details () →#setof recordВозвращает описание причины, по которой узел перешёл в состояние
NODE_ERROR. Возвращаемая запись содержит тип ошибки, подробную информацию о ней, место возникновения с указаниемbegin_lsn,end_lsnи идентификаторов текущей и следующей линии времени, а такжеreplay_lsn.Например:
biha_db=# \x biha_db=# SELECT * FROM biha.error_details(); -[ RECORD 1 ]--+------------------------------------------------------------------------------------- │ type | TIMELINE_ERROR │ details | Timeline divergence detected: current timeline ended before replayLSN, rewind needed │ next_tli | 3 │ next_begin_lsn | │ next_end_lsn | │ cur_tli | 2 │ cur_begin_lsn | 0/17F53A0 │ cur_end_lsn | 0/3455FC8 │ replay_lsn | 0/34593B8
biha.monitoring () →#setof recordОтображает таблицу, которая содержит данные мониторинга текущего статуса узлов кластера. Таблица содержит следующие столбцы:
id: уникальный идентификатор узла.time: время получения данных мониторинга.biha_state: текущее состояние узла. За подробной информацией о возможных состояниях обратитесь к biha.status_v.pg_state: текущее состояние Postgres Pro. Возможные значения:Prestartup,Startup,Recovery,Recovery_Pause,Promoting,Promoted.online: показывает, в сети ли узел.startup_progress: показывает прогресс запуска в процентах, когда значениеpg_state—Startup.
Например:
biha_db=# select * from biha.monitoring(); id | time | biha_state | pg_state | online | startup_progress ----+------------------------+----------------+----------+--------+----------------- 3 | 2025-09-02 13:49:57+03 | LEADER_RW | Promoted | t | 1 | 2025-09-02 13:49:57+03 | CSTATE_FORMING | Startup | t | 81 2 | 2025-09-02 13:49:57+03 | FOLLOWER | Recovery | t | (3 rows)
biha.nodes () →#setof recordВыводит состояние транспортного канала BiHA текущего узла по отношению к другим узлам и определяет представление
biha.nodes_v, подробно описанное в biha.nodes_v.Функция выводит таблицу со следующими столбцами:
id: идентификатор узла.host: хост узла.port: порт узла.state: состояние подключения узла. Столбец может содержать одно из следующих значений:ACTIVE: есть активные клиентские подключения к узлу. В этом состоянии выполняются операции на чтение и запись.CONNECTING: попытка установить клиентское соединение с узлом.IDLE: узел находится в состоянии пассивного ожидания.INIT: инициализация клиентского соединения.SSLCONNECT: попытка установить защищённое соединение. Это состояние отображается только при включённом SSL.SSLACCEPT: попытка принять защищённое соединение. Это состояние отображается только при включённом SSL.
conn_start: время начала подключения.conn_count: количество подключений к узлу с момента запуска кластера.
Например:
biha_db=# SELECT * FROM biha.nodes(); id | host | port | state | conn_start | conn_count ----+-----------+-------+--------+------------------------+------------ 1 | localhost | 10001 | ACTIVE | 2023-07-05 17:17:17+07 | 1 2 | localhost | 10002 | | | 5 | localhost | 10005 | ACTIVE | 2023-07-05 17:17:17+07 | 1 3 | localhost | 10003 | ACTIVE | 2023-07-05 17:17:17+07 | 1 4 | localhost | 10004 | ACTIVE | 2023-07-05 17:17:17+07 | 1 (4 rows)
biha.status () →#setof recordОпределяет представление
biha.status_v, подробно описанное в biha.status_v. Использовать эту функцию не рекомендуется, так как она предоставляет необработанные данные для представления.
26.4.2.4. Репликация #
Следующие функции используются для настройки репликации и управления ею.
biha.add_to_ssn (#idinteger) →booleanПримечание
Эту функцию можно вызвать, только если включена кворумная синхронная репликация.
Добавляет указанный узел в список синхронных резервных параметра synchronous_standby_names.names. Необходимо указывать узел, имени которого ещё нет в списке.
Например:
biha_db=# SELECT biha.add_to_ssn(3); add_to_ssn ------------- t (1 row)
biha.get_ssn () →#varcharОтображает текущее значение параметра synchronous_standby_names.
Например:
biha_db=# SELECT biha.get_ssn(); get_ssn --------------------------------------------- ANY 1 (biha_node_1,biha_node_2,biha_node_3) (1 row)
biha.set_deny_wal_sources (#idinteger,запрещённые_идентификаторыinteger[]) →booleanЗадаёт значение параметра конфигурации deny_wal_sources для указанного узла или сбрасывает существующее значение.
Массив
запрещённых_идентификаторовдолжен соответствовать следующим требованиям:Указанные узлы должны быть физическими и входить в кластер.
Идентификаторы должны соответствовать формату идентификаторов узлов и не должны повторяться.
Размер массива не должен превышать максимальное допустимое число узлов в кластере.
Например, чтобы запретить репликацию узла с идентификатором
3с узла с идентификатором1, выполните:biha_db=# SELECT biha.set_deny_wal_sources(3, ARRAY[1]); set_deny_wal_sources -------------- t (1 row)
Чтобы сбросить значение параметра и установить пустое значение, вызовите функцию с пустым массивом.
biha.set_max_replicas (#idinteger,max_replicas_numinteger) →booleanЗадаёт значение параметра конфигурации max_replicas.
Например, для узла с идентификатором
1настройте максимум3реплики:biha_db=# SELECT biha.set_max_replicas(1, 3); set_max_replicas ------------------ t (1 row)
biha.set_pref_roles (#идентификатор_узлаinteger,значениеtext) →booleanЗадаёт значение параметра конфигурации repl_pref_roles.
Например:
biha_db=# SELECT biha.set_pref_roles(1, 'LFR'); set_pref_roles ---------------- t (1 row)
biha.set_priority (#идентификатор_узлаinteger,значениеinteger) →booleanЗадаёт значение параметра конфигурации priority.
Например:
biha_db=# SELECT biha.set_priority(1, 10); set_priority -------------- t (1 row)
biha.remove_from_ssn (#idinteger) →booleanПримечание
Эту функцию можно вызвать, только если включена кворумная синхронная репликация.
Удаляет указанный узел из списка синхронных резервных узлов параметра synchronous_standby_names.names. Необходимо указать узел, имя которого уже есть в списке.
Например:
biha_db=# SELECT biha.remove_from_ssn(3); remove_from_ssn ------------- t (1 row)
biha.set_ssn (#VARIADIC idsinteger[]) →booleanПримечание
Эту функцию можно вызвать, только если включена кворумная синхронная репликация.
Задаёт значение параметра конфигурации synchronous_standby_names.names.
Например:
biha_db=# SELECT biha.set_ssn(1, 2, 3); set_ssn --------- t (1 row)
biha.set_sync_standbys (#sync_standbys_countinteger) →booleanЗадаёт значение параметра конфигурации synchronous_standby_names.count.
Важно
Используйте эту функцию с осторожностью, так как изменение количества синхронных резервных узлов может повлиять на работу системы приоритетов или вызвать зависание клиентских приложений при запросе данных с отстающего узла.
Например:
biha_db=# SELECT biha.set_sync_standbys(1); set_sync_standbys ------------------- t (1 row)
biha.set_sync_standbys_min (#sync_standbys_min_countinteger) →booleanПримечание
Эту функцию можно вызвать, только если включена кворумная синхронная репликация.
Задаёт значение параметра конфигурации synchronous_standby_names.min.
С помощью этой функции можно также управлять нестрогой кворумной синхронной репликацией. Чтобы отключить нестрогую кворумную синхронную репликацию, задайте значение
-1.Например:
biha_db=# SELECT biha.set_sync_standbys_min(1); set_sync_standbys_min ----------------------- f (1 row)
26.4.2.5. Выборы и кворум #
biha.set_minnodes (#idinteger,minnodesinteger) →booleanЗадаёт значение minnodes. Если
идентификатор_узла— физический узел, значениеbiha.minnodesзадаётся для сегмента, в котором узел расположен. Еслиидентификатор_узла— сегмент, значение задаётся для текущего сегмента и расположенных в нём узлов. Можно задать разные значения для каждого сегмента.Например:
biha_db=# SELECT biha.set_minnodes(3, 1); set_minnodes -------------------------- t (1 row)
biha.set_nquorum (#idinteger,nquoruminteger) →booleanЗадаёт значение nquorum. Если
идентификатор_узла— физический узел, значениеbiha.nquorumзадаётся для сегмента, в котором узел расположен. Еслиидентификатор_узла— сегмент, значение задаётся для текущего сегмента и расположенных в нём узлов. Для каждого сегмента можно задать разные значения.Например:
biha_db=# SELECT biha.set_nquorum(3, 3); set_nquorum -------------------------- t (1 row)
biha.set_nquorum_and_minnodes (#idinteger,nquoruminteger,minnodesinteger) →booleanЗадаёт значения параметров nquorum и minnodes. Если
node_id— физический узел, значенияnquorumиminnodesзадаются для сегмента, в котором узел расположен. Еслиnode_id— сегмент, значения задаются для текущего сегмента и расположенных в нём узлов. Для каждого сегмента можно задать разные значения.Например:
biha_db=# SELECT biha.set_nquorum_and_minnodes(3, 3, 1); set_nquorum_and_minnodes -------------------------- t (1 row)
biha.set_can_be_leader (#idinteger,can_be_leaderboolean) →booleanЗадаёт значение параметра конфигурации can_be_leader.
Например, чтобы разрешить узлу с идентификатором
4стать кандидатом на роль лидера, выполните:biha_db=# SELECT biha.set_can_be_leader(4,true); set_can_be_leader -------------- t (1 row)
biha.set_can_vote (#idinteger,can_voteboolean) →booleanЗадаёт значение параметра конфигурации can_vote.
Например, чтобы разрешить узлу с идентификатором
4голосовать, выполните:biha_db=# SELECT biha.set_can_vote(4,true); set_can_vote -------------- t (1 row)
26.4.2.6. Настройка сети #
biha.config_network () →#setof recordВыводит текущие значения сетевых параметров конфигурации. В выводе значение biha_listen_addresses отображается для других сетевых параметров конфигурации, если их значения не были заданы.
Например:
biha_db=# select * from biha.config_network(); id | biha_listen_addresses | biha_hosts | biha_port | replication_hosts | sql_hosts | port ----+-----------------------+------------+-----------+-------------------+-----------+------ 1 | biha-db-1 | biha-db-1 | 5433 | biha-db-1 | biha-db-1 | 5432 2 | biha-db-2 | biha-db-2 | 5433 | biha-db-2 | biha-db-2 | 5432 3 | biha-db-3 | biha-db-3 | 5433 | biha-db-3 | biha-db-3 | 5432 4 | biha-db-4 | biha-db-4 | 5433 | biha-db-4 | biha-db-4 | 5432 5 | biha-db-5 | biha-db-5 | 5433 | biha-db-5 | biha-db-5 | 5432 (5 rows)biha.set_biha_hosts (#idinteger,VARIADIC biha_hoststext[]) →booleanЗадаёт значение параметра конфигурации biha_hosts.
Например:
biha_db=# select biha.set_biha_hosts(1, 'biha-1:8080', 'biha-p', 'biha-2222:3333'); set_biha_hosts ---------------- t (1 row)
biha.set_sql_hosts (#idinteger,VARIADIC sql_hoststext[]) →booleanЗадаёт значение параметра конфигурации sql_hosts.
Например:
biha_db=# select biha.set_sql_hosts(1, 'bha-1:8080', 'bha-p', 'bha-2222:3333'); set_sql_hosts ---------------- t (1 row)
biha.set_replication_hosts (#idinteger,VARIADIC replication_hoststext[]) →booleanЗадаёт значение параметра конфигурации replication_hosts.
Например:
biha_db=# select biha.set_replication_hosts(1, 'bha-1:8080', 'bha-p', 'bha-2222:3333'); set_replication_hosts ----------------------- t (1 row)
26.4.2.7. Настройка безопасности #
biha.set_ssl_certificate (#text) →booleanЗадаёт значение параметра конфигурации ssl_certificate
Например:
biha_db=# SELECT biha.set_ssl_certificate('/tmp/install/share/extension/biha_pub_cert.pem'); WARNING: [BiHA] this parameter takes effect after node restart set_ssl_certificate --------------------- t (1 row)biha.set_ssl_mode (#text) →booleanЗадаёт значение параметра конфигурации ssl_mode.
Например:
biha_db=# SELECT biha.set_ssl_mode('verify-full'); WARNING: [BiHA] this parameter takes effect after node restart set_ssl_mode -------------- t (1 row)biha.set_ssl_private_key (#text) →booleanЗадаёт значение параметра конфигурации ssl_private_key.
Например:
biha_db=# SELECT biha.set_ssl_private_key('/tmp/install/share/extension/biha_priv_key.pem'); WARNING: [BiHA] this parameter takes effect after node restart set_ssl_private_key --------------------- t (1 row)biha.set_user_cert (#text) →booleanЗадаёт значение параметра конфигурации user_biha_cert.
Например:
biha_db=# SELECT biha.set_user_cert('/tmp/install/share/extension/biha_pub_cert.pem'); WARNING: [BiHA] this parameter takes effect after node restart set_user_cert --------------- t (1 row)biha.set_user_key (#text) →booleanЗадаёт значение параметра конфигурации user_biha_key.
Например:
biha_db=# SELECT biha.set_user_key('/tmp/install/share/extension/biha_priv_key.pem'); WARNING: [BiHA] this parameter takes effect after node restart set_user_key -------------- t (1 row)biha.set_use_ssl (#boolean) →booleanЗадаёт значение параметра конфигурации use_ssl.
Например:
biha_db=# SELECT biha.set_use_ssl(true) WARNING: [BiHA] this parameter takes effect after node restart set_use_ssl ------------- t (1 row)
26.4.2.8. Управление функциями-обработчиками #
biha.set_callbacks_timeout (#идентификатор_узлаinteger,значение_тайм_аутаinteger) →booleanЗадаёт значение параметра конфигурации callbacks_timeout.
biha.register_callback (#eventtext,functiontext,база_данныхtext,executortext,приоритетinteger) →integerДобавляет новый обработчик и возвращает его уникальный идентификатор. Функцию можно вызвать только на лидере в состоянии
LEADER_RW. Новый обработчик будет реплицирован на последователей.Примечание
Со стороны biha нет проверки наличия функции
funcв базе данныхdatabase. Если указанная функция не существует, исполнение обработчика завершится ошибкой.Пример использования
biha.register_callbackсм. в Регистрация функций-обработчиков.Таблица 26.3. Определения переменных
Имя Тип Описание eventtext Событие в BiHA-кластере, которое запускает функцию-обработчик. Подробнее о событиях и соответствующих типах функций-обработчиков читайте в Типы обработчиков. functiontext Название SQL-функции, которую расширение biha исполняет при наступлении события event. Функция должна находиться в базе данныхdatabase, иначе она не будет исполнена.база_данныхtext База данных, в которой исполняется функция func.executortext Пользователь, от имени которого исполняется функция
func. Это необязательный параметр. Значение по умолчанию —biha_callbacks_user.приоритетinteger Чем ниже значение, тем раньше исполнится обработчик. Это необязательный параметр. Значение по умолчанию — 0.biha.unregister_callback(#callback_id)Удаляет обработчик. Функцию можно вызвать только на лидере в состоянии
LEADER_RW. Пример использования функцииbiha.unregister_callbackсм. в разделе Отмена регистрации функции-обработчика.
26.4.2.9. Прочие функции #
biha.get_magic_string() →#stringГенерирует «магическую» строку для узла кластера. Например:
biha_db=# SELECT biha.get_magic_string(); get_magic_string ---------------------------------------------------------------------- dmVyc2lvbj0xIGhvc3Q9bG9jYWxob3N0IHBvcnQ9NjU0MzIgYmloYS1wb3J0PTEwMDAx (1 row)biha.set_asyncaction_timeout (#idinteger,значение_тайм_аутаinteger) →booleanЗадаёт значение параметра конфигурации asyncaction_timeout.
Например:
biha_db=# SELECT biha.set_asyncaction_timeout(1, 50000); set_asyncaction_timeout ------------------------- t (1 row)
biha.set_flw_ro (#idinteger,available_for_read_onlyboolean) →booleanЗадаёт значение параметра конфигурации flw_ro.
Например:
biha_db=# SELECT biha.set_flw_ro(1, true); set_flw_ro ------------ t (1 row)
biha.set_manage_slots_xmin (#idinteger,manage_slots_xminboolean) →booleanЗадаёт значение параметра конфигурации manage_slots_xmin.
biha.service_mode (#enable_service_modeboolean,forceboolean) →booleanВключает сервисный режим в BiHA-кластере. Эту функцию можно вызвать только на лидере. Функция принимает следующие параметры:
enable: если задано значениеtrue, сервисный режим включён. Если задано значениеfalse, сервисный режим отключён. Значение по умолчанию —false.force: если задано значениеtrue, позволяет отключить сервисный режим, игнорируя ошибки. Если значение не задано илиfalse, сервисный режим нельзя отключить до разрешения всех ошибок. Значение по умолчанию —false.
biha.set_heartbeat_max_lost (#integer) →booleanЗадаёт значение параметра конфигурации heartbeat_max_lost.
Например:
biha_db=# SELECT biha.set_heartbeat_max_lost(7); set_heartbeat_max_lost ------------- t (1 row)
biha.set_heartbeat_send_period (#integer) →booleanЗадаёт значение параметра heartbeat_send_period в миллисекундах.
Например:
biha_db=# SELECT biha.set_heartbeat_send_period(2000); set_heartbeat_send_period ------------- t (1 row)
biha.set_no_wal_on_follower (#integer) →booleanЗадаёт значение параметра конфигурации no_wal_on_follower.
Например:
biha_db=# SELECT biha.set_no_wal_on_follower(10000); set_no_wal_on_follower ------------------------ t (1 row)
biha.set_watchdog_timeout (#idinteger,значение_тайм_аутаinteger) →booleanЗадаёт значение параметра конфигурации watchdog_timeout.
Например:
biha_db=# SELECT biha.set_watchdog_timeout(1, 10); WARNING: [BiHA] this parameter takes effect after node restart set_watchdog_timeout ---------------------- t (1 row)
biha.reset_node_error () →#booleanСбрасывает состояние
NODE_ERRORна узле. Используйте эту функцию после того, как устранена причина перехода узла в состояниеNODE_ERROR. За подробной информацией обратитесь к разделу Восстановление узла из состояния NODE_ERROR.
26.4.3. Представления #
Чтобы обращаться к перечисленным ниже представлениям, необходимо подключиться к базе данных biha_db.
26.4.3.1. biha.config_v #
В этом представлении выводятся наиболее критичные параметры, возвращаемые функцией biha.config.
Например:
biha_db=# select * from biha.config_v;
id | unit_type | name | parent_id | mode | nquorum | minnodes | heartbeat_send_period | heartbeat_max_lost
------+-----------+----------------+-----------+---------+---------+----------+-----------------------+--------------------
1 | NODE | biha_node_1 | 111 | regular | 3 | 1 | 1000 | 10
3 | NODE | biha_node_3 | 111 | regular | 3 | 1 | 1000 | 10
4 | NODE | biha_node_4 | 111 | regular | 3 | 1 | 1000 | 10
111 | SEGMENT | biha_node_111 | 1111 | regular | 1 | 1 | 1000 | 10
1111 | SEGMENT | biha_node_1111 | | regular | 1 | 1 | 1000 | 10
(5 rows)Таблица 26.4. Представление biha.config_v
| Имя столбца | Описание |
|---|---|
id | Идентификатор узла (integer). |
unit_type | Тип узла. Возможные значения: NODE, SEGMENT. |
name | Имя узла (text). |
parent_id | Уникальный идентификатор узла, который является родительским для текущего (integer). |
mode | Текущее значение mode (text) |
nquorum | Текущее значение nquorum (integer). |
minnodes | Текущее значение minnodes (integer). |
heartbeat_send_period | Текущее значение heartbeat_send_period (integer). |
heartbeat_max_lost | Текущее значение heartbeat_max_lost (integer). |
26.4.3.2. biha.nodes_v #
В этом представлении показывается состояние подключения узлов в кластере. Для узла, на котором выполняется запрос для представления, следующие столбцы содержат NULL: state, since_conn_start, conn_count.
Например:
biha_db=# SELECT * FROM biha.nodes_v; id | host | port | state | since_conn_start | conn_count ----+-----------+-------+--------+------------------+------------ 1 | localhost | 10001 | ACTIVE | 00:02:28.42069 | 1 2 | localhost | 10002 | | | 3 | localhost | 10003 | ACTIVE | 00:02:23.42069 | 1 4 | localhost | 10004 | ACTIVE | 00:02:23.42069 | 1 5 | localhost | 10005 | ACTIVE | 00:02:23.42069 | 1 (4 rows)
Таблица 26.5. Представление biha.nodes_v
| Имя столбца | Описание |
|---|---|
id | Идентификатор узла. |
host | Адрес узла. |
port | Порт узла. |
state | Состояние соединения узла. В этом столбце может отображаться одно из следующих значений:
|
since_conn_start | Время, прошедшее с момента подключения узла к сети. |
conn_count | Сколько раз узел подключался к сети с момента запуска кластера. |
26.4.3.3. biha.status_v #
В этом представлении показывается состояние узлов в кластере.
Например:
biha_db=# SELECT * FROM biha.status_v; id | leader_id | term | online | state | last_known_state | since_last_hb ----+-----------+------+--------+-----------+------------------+----------------- 1 | 1 | 4 | t | LEADER_RW | LEADER_RW | 2 | 1 | 4 | t | FOLLOWER | FOLLOWER | 00:00:01.931472 3 | 1 | 4 | f | UNKNOWN | FOLLOWER | 00:00:18.931472 4 | 1 | 4 | t | FOLLOWER | FOLLOWER | 00:00:01.931472 5 | 1 | 4 | t | FOLLOWER | FOLLOWER | 00:00:01.931472 (5 rows)
Таблица 26.6. Представление biha.status_v
| Имя столбца | Описание |
|---|---|
id | Идентификатор узла (integer). |
leader_id | Идентификатор узла-лидера (integer). |
term | Поколение узла (integer). Используется при голосовании на выборах нового узла-лидера. |
online | Показывает, подключён ли узел к сети (boolean: t или f). |
state | Состояние узла (
|
last_known_state | Последнее известное состояние узла (text). |
since_last_hb | Время, прошедшее с момента получения последнего сообщения о контроле состояния (interval). |
26.4.3.4. biha.super_status_v #
Расширенная версия представления biha.status_v, которая дополнительно отображает данные для кластера GDBiHA.
Представление biha.super_status_v содержит следующие дополнительные столбцы:
name: имя узла (text).unit_type: тип юнита. Возможные значения:NODE,SEGMENT.parent_id: уникальный идентификатор узла, который является родительским для текущего узла (integer).segment_name: имя сегмента, к которому принадлежит узел (text).
26.4. Reference for the biha Extension #
biha is a Postgres Pro extension that allows managing a BiHA cluster.
This section contains information about the biha extension configuration parameters, functions, and views.
26.4.1. Configuration Parameters #
The biha extension provides a set of configuration parameters described below that are specific to the BiHA cluster:
26.4.1.1. Cluster Configuration Parameters #
Important
When setting the cluster configuration parameters, you must ensure network reliability for the changes to affect all cluster nodes without any errors.
Values of these configuration parameters must be the same on all cluster nodes.
It is not recommended to modify any cluster configuration parameters while one of the nodes is in the
NODE_ERRORstate, as the changes may fail to be applied on that node.
service_mode(boolean) #Determines weather the service mode is enabled in a BiHA cluster.
You can set the value with the biha.service_mode function.
Possible values:
f(default): The service mode is disabled.t: The service mode is enabled.
ssl_certificate(text) #Specifies the path to the SSL public certificate used to secure service connections between nodes of the initialized BiHA cluster. For more information, refer to Managing SSL for Service Connections.
You can set the value with the biha.set_ssl_certificate function. Node restart is required for the changes to take effect.
Default value:
/PGDATA/pg_biha/biha_pub_cert.pemssl_mode(text) #Specifies the authentication mode for the
biha_replication_userrole. For more information about SSL authentication configuration, refer to Configuring SSL for biha_replication_user. For more information about modes, refer to sslmode.You can set the value with the biha.set_ssl_mode function. Node restart is required for the changes to take effect.
Possible values:
verify-full(default)requireverify-ca
ssl_private_key(text) #Specifies the path to the SSL private key used to secure service connections between nodes of the initialized BiHA cluster. For more information, refer to Managing SSL for Service Connections.
You can set the value with the biha.set_ssl_private_key function. Node restart is required for the changes to take effect.
Default value:
/PGDATA/pg_biha/biha_priv_key.pemsynchronous_standby_names.count(integer) #Enables quorum-based synchronous replication by setting the synchronous_standby_names parameter and specifying the number of synchronous standbys (quorum) with the
ANYmethod.You can set the value with the biha.set_sync_standbys function.
The value must be integer and greater than zero, as well as higher than the value of synchronous_standby_names.min parameter if set, and must not exceed the number of followers excluding referee. It is recommended to set the
synchronous_standby_names.countvalue less than the value of minnodes.synchronous_standby_names.min(integer) #Enables 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 confirming transactions. If the parameter value 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.You can set the value with the biha.set_sync_standbys_min function.
The
synchronous_standby_names.minvalue must be integer and equal to or greater than zero, as well as lower than synchronous_standby_names.count. When set to-1, relaxed quorum-based synchronous replication is disabled.synchronous_standby_names.names(integer) #Specifies a list of synchronous standbys in the synchronous_standby_names configuration parameter.
You can set the value with the biha.set_ssn function, as well as modify the list of synchronous standbys with biha.add_to_ssn or biha.get_ssn functions.
use_ssl(boolean) #Specifies whether to use the protected mode of the service information exchange between cluster nodes with SSL/TLS over the biha control channel. For more information, refer to Managing SSL for Service Connections.
You can set the value with the biha.set_use_ssl function. Node restart is required for the changes to take effect.
Possible values:
false(default): SSL is disabled for BiHA service connections.true: BiHA service connections are secured with SSL.
user_biha_cert(text) #Specifies the path to the SSL public certificate used for the
biha_replication_userrole authentication. For more information about SSL authentication configuration, refer to Configuring SSL for biha_replication_user.You can set the value with the biha.set_user_cert function.
user_biha_key(text) #Specifies the path to the SSL private key used for the
biha_replication_userrole authentication. For more information about SSL authentication configuration, refer to Configuring SSL for biha_replication_user.You can set the value with the biha.set_user_key function.
26.4.1.2. Segment Configuration Parameters #
The following configuration parameters can be set individually for each logical node (segment). The parameter values are inherited by nodes within the segment.
heartbeat_max_lost(integer) #Specifies the maximum number of heartbeats that can be missed on BCP before the node is considered offline.
You can set the value with the biha.set_heartbeat_max_lost function.
Default value:
10Minimal value:
3Nodes in all states use the heartbeat timeout value calculated as
heartbeat_max_lost* heartbeat_send_period to determine if other nodes are online. For example, if Node A receives no heartbeats from Node B within the heartbeat timeout, the Node B state changes toUNKNOWNin the biha.status_v view of Node A indicating that Node A considers Node B offline. The leader in theLEADER_RWstate additionally uses the timeout specified in the no_wal_on_follower parameter.heartbeat_send_period(integer) #Specifies the heartbeat sending frequency, in milliseconds.
You can set the value with the biha.set_heartbeat_send_period function.
Default value:
1000Minimal value:
500Nodes in all states use the heartbeat timeout value calculated as heartbeat_max_lost *
heartbeat_send_periodto determine if other nodes are online. For example, if Node A receives no heartbeats from Node B within the heartbeat timeout, the Node B state changes toUNKNOWNin the biha.status_v view of Node A indicating that Node A considers Node B offline. The leader in theLEADER_RWstate additionally uses the timeout specified in the no_wal_on_follower parameter.minnodes(integer) #Specifies the minimum number of operational nodes for the leader node to be open for write transactions.
You can set the value with the biha.set_minnodes function.
Default value: equals nquorum
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, theminnodesvalue must be 2.Nodes with the can_vote parameter set to
falseare ignored byminnodes.no_wal_on_follower(integer) #Specifies the timeout of the replication slot position advancement, in milliseconds.
You can set the value with the biha.set_no_wal_on_follower function.
Default value:
20000Minimum value:
5000BiHA uses this configuration parameter for the following purposes:
When you nominate a follower as the new leader using the biha.set_leader function, the follower state changes to
FOLLOWER_OFFERED.A follower in the
FOLLOWER_OFFEREDstate checks whether its WAL location has been updated. Update of WAL location confirms that the follower keeps receiving replication data from the source. If the follower does not receive WAL records longer thanno_wal_on_follower, the follower state changes back toFOLLOWER. In this case, the log contains the following message: “Timed out waiting for new WAL records from current source”.The leader in the
LEADER_RWstate usesno_wal_on_followerin conjunction with the heartbeat timeout value (which is calculated as heartbeat_max_lost * heartbeat_send_period) to determine if other nodes are online.The leader checks the replication slot positions of other nodes. If the replication slot position updates, it means that the node receives replication data from the leader and the node is online. If the leader does not receive heartbeats from the node within the above mentioned heartbeat timeout and its replication slot position does not change within the
no_wal_on_followertimeout value, the leader considers the node offline and its state changes toUNKNOWNin the biha.status_v view of the leader.In a cascading BiHA cluster, if a node does not receive WAL within the time set in
no_wal_on_follower, it starts searching for a new replication source as configured in repl_pref_roles.
nquorum(integer) #Specifies the minimum number of nodes, which must vote for the new leader node if the current leader is down.
You can set the value with the biha.set_nquorum function.
Default value:
2When 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.Nodes with the can_vote parameter set to
falseare ignored bynquorum.
26.4.1.3. Node Configuration Parameters #
The following configuration parameters can be set individually for each physical node.
asyncaction_timeout(integer) #Specifies the waiting time for execution of asynchronous operations, such as adding segments and removing nodes, in milliseconds. If a segment or node is not added or removed within the specified time, BiHA terminates the SQL command.
The parameter value must be the same on all cluster nodes.
You can set the value with the biha.set_asyncaction_timeout function.
Default value:
30000Minimum value:
1000biha_hosts(string) #Used by other nodes to connect to the current node by internal control channel (BCP), for example, using a proxy server or a tunnel. If the
biha_hostsvalue is empty, by default, the biha_listen_addresses value of the current node is used.You can set the value with the biha.set_biha_hosts function.
Possible values: one or several comma-separated addresses in the
hostname:portformat.portis an optional value, if not specified or set to-1, the biha_port value of the current node is used.For example:
biha-db-1:5433,biha-proxy:8081,biha-node-1biha_listen_addresses(string) #Determines on which addresses listening sockets are open for the internal BCP control channel.
You can set the value only with the bihactl utility.
Possible values: one or several comma-separated addresses in the
hostname:portformat.portis an optional value, if not specified or set to-1, the biha_port value of the current node is used.For example:
biha-db-1:5433,biha-proxy:8081,biha-node-1biha_port(integer) #Specifies the port used by other nodes to connect to the current node by internal control channel (BCP).
The parameter value is set with the bihactl utility and can be overridden when modifying biha_hosts, biha_listen_addresses, or replication_hosts configuration parameters.
callbacks_timeout(integer) #Sets time for execution of all callbacks for a single event, in milliseconds.
You can set the value with the biha.set_callbacks_timeout.
Default value:
10000Minimum value:
1000config_send_period(integer) #Determines the timeout to broadcast message with cluster configuration.
You can set the value with the biha.set_config_send_period function.
Default value:
1000Minimum value:
500deny_wal_sources(string) #Specifies a list of nodes that cannot be used as replication sources for the current node. If a node identifier is in the list, the current node cannot replicate from such a node.
You can set the value with the biha.set_deny_wal_sources function.
Default value: empty
The
deny_wal_sourcesconfiguration parameter has higher priority than repl_pref_roles. For example, if the leader node ID is in thedeny_wal_sourceslist of a node, the node does not replicate from the leader even if itsrepl_pref_rolesvalue isLF.flw_ro(boolean) #Determines whether a follower is available for read operations.
You can set the value with the biha.set_flw_ro function.
Possible values:
on(default): The follower is available for read operations.off: Reading from this follower is allowed only for superusers, as well as for members ofBIHA_CLUSTER_MANAGEMENT_ROLEandpg_monitorroles.
leader_timeout(integer) #Determines the maximum time for the switchover process to complete when biha.set_leader is called, in milliseconds. If the operation does not complete within the specified time, the node returns to the
FOLLOWERstate.You can set the value with the biha.set_leader_timeout function.
Default value:
20000Minimum value:
0manage_slots_xmin(boolean) #Determines whether BiHA monitors the
xminvalue of replication slots.You can set the value with the biha.set_manage_slots_xmin function.
Possible values:
true(default): Monitoring ofxminis enabled.false: Monitoring ofxminis disabled.
max_replicas(integer) #Specifies the maximum number of biha replication connections to a node, i.e. the maximum number of walsenders where
application_nameisbiha_node_*. For more information, refer to Section 26.1.5.2.You can set the value with the biha.set_max_replicas function.
The value must be integer, greater than zero, and must not exceed the max_wal_senders value.
Other possible values:
INT_MAX(default): The number of connections is unlimited.0: No connections are allowed.
pg_port(integer) #Specifies the node port for incoming connections to Postgres Pro.
The parameter value is set with the bihactl utility and can be overridden when modifying biha_hosts, biha_listen_addresses, or replication_hosts configuration parameters.
replication_hosts(string) #Used by other nodes to connect to the current node by replication channel. If the
replication_hostsvalue is empty, by default, the biha_listen_addresses value of the current node is used.Note
If you change the default value of listen_addresses (
*), ensure that you configurereplication_hostsin such a way that the packets sent to it reach one of the interfaces covered bylisten_addresses, so that replication connections can reach the listening socket.You can set the value with the biha.set_replication_hosts function.
Possible values: one or several comma-separated addresses in the
hostname:portformat.portis an optional value, if not specified or set to-1, the biha_port value of the current node is used.The maximum string size is 1024 bytes, otherwise it is ignored.
For example:
biha-db-1:5433,biha-proxy:8081,biha-node-1sql_hosts(string) #Used by other nodes and bihactl to execute SQL queries to the current node. If the
sql_hostsvalue is empty, by default, the replication_hosts value of the current node is used.Note
If you change the default value of listen_addresses (
*), ensure that you configuresql_hostsin such a way that the packets sent to it reach one of the interfaces covered bylisten_addresses, so that SQL connections can reach the listening socket.You can set the value with the biha.set_sql_hosts function.
Possible values: one or several comma-separated addresses in the
hostname:portformat.portis an optional value, if not specified or set to-1, the biha_port value of the current node is used.The maximum string size is 1024 bytes, otherwise it is ignored.
For example:
biha-db-1:5433,biha-proxy:8081,biha-node-1watchdog_timeout(integer) #Specifies the timeout for a node to stop accepting queries if the biha process does not respond, in seconds. For more information, refer to Section 26.3.9.
You can set the value with the biha.set_watchdog_timeout function. Node restart is required for the changes to take effect.
Default value:
2Minimum value:
1
26.4.1.4. Configuration Parameters Common for Nodes and Segments #
The following configuration parameters can be set individually both for physical nodes or logical nodes (segments).
can_be_leader(boolean) #Determines the ability of a node or a segment to become the leader.
You can set the value with the biha.set_can_be_leader function.
Possible values:
true(default): The node or segment can stand as a candidate in elections of the new leader.false: The node or segment cannot stand as a candidate in elections of the new leader.
A node that cannot become the leader may have the largest WAL. In this case, if elections are required, those nodes that can stand as candidates attempt to receive missing data from that node. If they succeed, one of these nodes becomes the leader. If they fail to receive missing data, the automatic rewind process is launched on the node that cannot become the leader. If biha.autorewind is not enabled, the node state changes to
NODE_ERROR.can_vote(boolean) #Determines whether a node or a segment is allowed to vote.
You can set the value with the biha.set_can_vote function.
Possible values:
true(default): The node or segment is allowed to vote.false: The node or segment cannot vote, as well as cannot stand as a candidate in elections of the new leader.
mode(text) #Specifies the operation mode of a node or segment. The mode value is set with bihactl and cannot be modified after cluster initialization.
Possible values for a node:
regular(default): The node can operate as the leader or as a follower.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.
Possible values for a segment:
regularname(text) #Specifies the name of a node or segment. The name value is set with bihactl and cannot be modified after cluster initialization.
priority(integer) #Sets the node or segment priority that affects both elections and replication in a cluster, in seconds.
You can set the value with the biha.set_priority function.
The value must be integer and greater than or equal to zero. The
0value means the highest priority.Default value:
-1, meaning that the parameter is ignored.Note
Once you modify the default value, you cannot set it again, i.e. disabling
priorityis not supported.BiHA uses this configuration parameter for the following purposes:
To set the replication start timeout when selecting a replication source in a BiHA cluster with configured cascading replication. The higher the value, the later the node starts replication and allows connection of nodes with lower priority. The parameter is required for the nodes to establish the cascading replication schema automatically.
To set the node priority in a cluster with synchronous replication. The value determines the timeout that must be reached before the node stands as a candidate in elections. The zero value indicates the highest priority.
Important
To ensure correct operation of this parameter, set the --sync-standbys value one unit less than the total number of cluster nodes.
repl_pref_roles(text) #Specifies the preferred role of a node acting as a replication source for the current node in a BiHA cluster with cascading replication.
You can set the value with the biha.set_pref_roles function.
Possible values:
L(leader),F(follower), orR(referee), or their combinations. The value must be one to three symbols long and must not contain repeatable symbols. For example:L,F,LFR, orLF.Default value:
L, meaning that data is replicated from the leader or front follower depending on the segment where the node is located.
26.4.1.5. Optional Configuration Parameters #
The following configuration parameters are optional and can be modified with the ALTER SYSTEM SET command, for example:
ALTER SYSTEM SET biha.autorewind = true;
Values of these parameters can differ across cluster nodes.
biha.autorewind(boolean) #Controls the automatic rewind policy for that node, against which the
pg_rewindmust be executed. For example, for the old leader when synchronizing it with the new leader. For more information, refer to Automatic Cluster Synchronization after Failover.Possible values:
false(default): The automatic rewind is not performed.true: The automatic rewind is performed after the error that usually causes theNODE_ERRORstate of the node.
biha.autowaltrim(boolean) #Manages the automatic WAL trimming policy within a single node. For more information, refer to Automatic Cluster Synchronization after Failover.
Possible values:
true(default): BiHA automatically schedules and executes the WAL trimming procedure if possible.false: The WAL trimming procedure is not executed, cluster synchronization is performed by means of pg_rewind.
biha.wal_validation(boolean) #Manages the WAL validation mechanism. The WAL validation procedure runs on history update and during the
PRESTARTUPstate to avoid the recovery process abortion caused by WAL inconsistency.Possible values:
true(default): WAL validation is enabled.false: WAL validation is disabled.
The WAL validation mechanism performs the following:
Validates timelines. If a TLI lacks complete WAL segments up to the switchpoint or has no segments at all, it is considered invalid.
Hides invalid timelines from BiHA nodes. This prevents a node with a higher but invalid timeline from becoming a leader candidate.
Restarts Postgres Pro in case of WAL inconsistency on the node that is about to be promoted.
Checks WAL consistency during prestartup and attempts to repair WAL automatically if required.
26.4.1.6. biha Logging Levels #
26.4.1.6.1. General Logging Levels #
General logging levels are used for biha components that have no designated logging levels.
biha.BihaLog_log_level(enum) #Specifies the logging level to provide general information about the operation of biha components. The default value is
LOG.biha.BihaWarn_log_level(enum) #Specifies the logging level to provide warnings of likely problems about the operation of biha components. The default value is
WARNING.biha.BihaDetails_log_level(enum) #Specifies the logging level to provide detailed information about the operation of biha components. The default value is
DEBUG1.biha.BihaDebug_log_level(enum) #Specifies the logging level to provide debugging information about the operation of biha components. The default value is
DEBUG2.biha.BihaDebug2_log_level(enum) #Specifies the logging level to provide debugging information about the operation of biha components. The default value is
DEBUG3.
26.4.1.6.2. BCP and Transport Logging Levels #
biha.BcpTransportLog_log_level(enum) #Specifies the logging level to provide general information about the control channel operation. The default value is
LOG.biha.BcpTransportWarn_log_level(enum) #Specifies the logging level to provide warnings of likely problems in the control channel. The default value is
WARNING.biha.BcpTransportDetails_log_level(enum) #Specifies the logging level to provide detailed information about the control channel operation. The default value is
DEBUG1.biha.BcpTransportDebug_log_level(enum) #Specifies the logging level to provide debugging information about the control channel operation. The default value is
DEBUG2.
26.4.1.6.3. Node Controller Logging Levels #
The following logging levels provide information about the Node Controller component.
biha.NodeControllerLog_log_level(enum) #Specifies the logging level to provide general information about the the
Node Controllercomponent. The default value isLOG.biha.NodeControllerWarn_log_level(enum) #Specifies the logging level to provide warnings of likely problems in the
Node Controllercomponent. The default value isWARNING.biha.NodeControllerDetails_log_level(enum) #Specifies the logging level to provide detailed information about operation of the
Node Controllercomponent. The default value isDEBUG1.biha.NodeControllerDebug_log_level(enum) #Specifies the logging level to provide debugging information about the operation of the
Node Controllercomponent. The default value isDEBUG2.biha.NodeControllerDebug2_log_level(enum) #Specifies the logging level to provide debugging information about the operation of the
Node Controllercomponent. The default value isDEBUG3.
26.4.1.6.4. Postgres Controller Logging Levels #
The following logging levels provide information about the Postgres Controller component.
biha.PgControllerLog_log_level(enum) #Specifies the logging level to provide general information about the
Postgres Controllercomponent. The default value isLOG.biha.PgControllerWarn_log_level(enum) #Specifies the logging level to provide warnings of likely problems in the
Postgres Controllercomponent. The default value isWARNING.biha.PgControllerDetails_log_level(enum) #Specifies the logging level to provide detailed information about operation of the
Postgres Controllercomponent. The default value isDEBUG1.biha.PgControllerDebug_log_level(enum) #Specifies the logging level to provide debugging information about the operation of the
Postgres Controllercomponent. The default value isDEBUG2.biha.PgControllerDebug2_log_level(enum) #Specifies the logging level to provide debugging information about the operation of the
Postgres Controllercomponent. The default value isDEBUG3.
26.4.1.6.5. Config Controller Logging Levels #
The following logging levels provide information about the Config Controller component.
biha.BihaConfigLog_log_level(enum) #Specifies the logging level to provide general information about the
Config Controllercomponent. The default value isLOG.biha.BihaConfigWarn_log_level(enum) #Specifies the logging level to provide warnings of likely problems in the
Config Controllercomponent. The default value isWARNING.biha.BihaConfigDetails_log_level(enum) #Specifies the logging level to provide detailed information about operation of the
Config Controllercomponent. The default value isDEBUG1.biha.BihaConfigDebug_log_level(enum) #Specifies the logging level to provide debugging information about the operation the
Config Controllercomponent. The default value isDEBUG2.biha.BihaConfigDebug2_log_level(enum) #Specifies the logging level to provide debugging information about the operation of the
Config Controllercomponent. The default value isDEBUG3.
26.4.2. Functions #
All functions listed below must be called from the biha_db database, for example:
biha_db=# SELECT biha.add_node(222, 1111);
If otherwise is not specified in the function description, a function must be called on the leader node.
26.4.2.1. Cluster Composition #
biha.add_node (#idinteger,parent_idinteger) →booleanAdds a segment to the GDBiHA cluster. If
parent_idis not specified, by default the root node with ID 1111 is assigned as the parent. For more information about changing cluster composition, refer to Section 26.3.1.For example, add a segment with ID
222to a cluster with ID1111:biha_db=# SELECT biha.add_node(222, 1111); add_node ------------- t (1 row)
biha.set_leader (#idinteger,modestring) →booleanSets the leader, front follower, or the leader segment manually. For more information about the manual switchover procedure, refer to Manual Switchover.
Note
Call this function on the node that you want to set as the new leader or front follower. Do not call the function on the current leader.
The following switchover modes are supported:
graceful(default): The promoted node waits for demotion of the old leader or front follower and, if required, catches up on WAL records. This is the default value.immediate: The switchover occurs immediately, without waiting. The node with the specified ID changes its state directly toLEADER_RW/LEADER_ROorFRONT_FOLLOWERskipping theFOLLOWER_OFFEREDstate. In this mode, theLEADER_CHANGE_STARTEDcallback is not called. If the command in theimmediatemode is executed on the current leader or front follower, it immediately starts changing its state toFOLLOWERand broadcasts a message about the leader change to other nodes.Important
The
immediatemode is not safe, using it may lead to data loss. Before performing switchover in this mode, it is recommended to do the following:Enable automatic synchronization by setting the biha.autorewind configuration parameter to
true.Set the minnodes value to
1for the leader to ignore other cluster node states.
For example, nominate the node with ID
2as the new leader in theimmediatemode:biha_db=# SELECT biha.set_leader(2, 'immediate'); set_leader ------------- t (1 row)
biha.set_leader_timeout (#idinteger,timeout_valueinteger) →booleanSets the value of the leader_timeout configuration parameter.
For example, set the timeout of
10000ms for all nodes in segment222:biha_db=# SELECT * FROM biha.set_leader_timeout(222, 10000); set_leader_timeout ------------- t (1 row)
biha.remove_node (#idinteger) →booleanRemoves a node or a segment from the cluster. Before removing, the node must be stopped. You cannot remove a node if it is a parent of another node. For more information about changing cluster composition, refer to Section 26.3.1.
For example, remove a node with ID
3:biha_db=# SELECT biha.remove_node(3); remove_node ------------- t (1 row)
26.4.2.2. Cluster Configuration #
biha.config () →#setof recordReturns the configuration parameter values for every node and segment. You can also view the most critical configuration parameters using the Section 26.4.3.1 view.
The following parameters are displayed:
id: The node ID (integer).nquorum: The current value of nquorum (integer).minnodes: The current value of minnodes (integer).heartbeat_send_period: The current value of heartbeat_send_period (integer).heartbeat_max_lost: The current value of heartbeat_max_lost (integer).no_wal_on_follower: The current value of no_wal_on_follower (integer).sync_standbys_min: The current value of theMINfield of synchronous_standby_names (integer).priority: The current value of priority (integer).can_be_leader: The current value of can_be_leader (boolean).can_vote: The current value of can_vote (boolean).mode: The current value of mode (text).proxima_enabled: The current status of proxima if supported by the current version of Postgres Pro Standard (integer).name: The name of the node (text).repl_pref_roles: Preferred roles of nodes for replication set in the repl_pref_roles configuration parameter (text).max_replicas: The maximum number of replication connections to the node set in the max_replicas configuration parameter (integer).config_version: The current version of thepg_biha/biha_conf_configuration (config_version.jsoninteger).parent_id: The unique identifier of the node that is the parent to the current node (integer).service_mode: The current value of service_mode (boolean).unit_type: The type of the unit. Possible values:NODE,SEGMENT.deny_wal_sources: The current value of deny_wal_sources (string).biha_hosts: The current value of biha_hosts (string).replication_hosts: The current value of replication_hosts (string).sql_hosts: The current value of sql_hosts (string).leader_timeout: The current value of leader_timeout (integer).use_ssl: The current value of use_ssl (boolean).ssl_certificate: The current value of ssl_certificate (text).ssl_private_key: The current value of ssl_private_key (text).user_cert: The current value of user_biha_cert (text).user_key: The current value of user_biha_key (text).ssl_mode: The current value of ssl_mode (text).flw_ro: The current value of flw_ro (boolean).callbacks_timeout: The current value of callbacks_timeout (integer).watchdog_timeout: The current value of watchdog_timeout (integer).asyncaction_timeout: The current value of asyncaction_timeout (integer).manage_slots_xmin: The current value of manage_slots_xmin (boolean).config_send_period: The current value of config_send_period (integer).
For example, call the
biha.configfunction for a node with ID1:biha_db=# select * from biha.config() where id = 1 \gx -[ RECORD 1 ]---------+-------------------------- id | 1 nquorum | 3 minnodes | 1 heartbeat_send_period | 1000 heartbeat_max_lost | 10 no_wal_on_follower | 20000 sync_standbys_min | -2 priority | -1 can_be_leader | t can_vote | t mode | regular proxima_enabled | f name | biha_node_1 repl_pref_roles | L max_replicas | 2147483647 config_version | 12 parent_id | 111 service_mode | f unit_type | NODE deny_wal_sources | biha_hosts | biha-db-1:5433,biha-proxy:8081 replication_hosts | biha-db-1:5432,postgres-proxy:8081 sql_hosts | leader_timeout | 20000 use_ssl | f ssl_certificate | pg_biha/biha_pub_cert.pem ssl_private_key | pg_biha/biha_priv_key.pem user_cert | user_key | ssl_mode | flw_ro | t callbacks_timeout | 10000 watchdog_timeout | 2 asyncaction_timeout | 30000 manage_slots_xmin | t config_send_period | 10000
biha.config_json () →#setof recordReturns the configuration file content in the JSON format. To view the content of a JSON configuration tree branch at the specified JSON path, use the biha.get_option function.
For example:
biha_db=# select biha.config_json(); config_json ------------------------------------------------------- { + "unit": { + "id": 1111, + "mode": "regular", + "name": "biha_node_1111", + "nquorum": 1, + "can_vote": true, + "children": [ + { + "id": 111, + ... "proxima_enabled": false, + "ssl_certificate": "pg_biha/biha_pub_cert.pem", + "ssl_private_key": "pg_biha/biha_priv_key.pem", + "synchronous_standby_names": { + "min": -2, + "count": -1, + "names": [ + ] + } + } (1 row)biha.get_option (#json_pathtext) →setof recordReturns the content of a JSON configuration tree branch at the specified JSON path. To view the full JSON configuration file, use the biha.config_json function.
For example:
biha_db=# select biha.get_option('$.unit.children.[0].children.[1].biha_listen_addresses.[0].address'); get_option ------------ "node-3" (1 row)biha.set_config_send_period (#idinteger,config_send_periodinteger) →booleanSets the value of the config_send_period configuration parameter.
26.4.2.3. Cluster Monitoring #
biha.error_details () →#setof recordReturns the description of why the node transferred to the
NODE_ERRORstate. The returned record contains the type of the error, its details, the place it occurred specifyingbegin_lsn,end_lsn, and identifier of the current and the next timeline, as well asreplay_lsn.For example:
biha_db=# \x biha_db=# SELECT * FROM biha.error_details(); -[ RECORD 1 ]--+------------------------------------------------------------------------------------- │ type | TIMELINE_ERROR │ details | Timeline divergence detected: current timeline ended before replayLSN, rewind needed │ next_tli | 3 │ next_begin_lsn | │ next_end_lsn | │ cur_tli | 2 │ cur_begin_lsn | 0/17F53A0 │ cur_end_lsn | 0/3455FC8 │ replay_lsn | 0/34593B8
biha.monitoring () →#setof recordDisplays a table that contains the monitoring data about the current status of cluster nodes. The table consists of the following columns:
id: The unique identifier of the node.time: The time where the monitoring data was received.biha_state: The current state of the node. For more information about possible states, see biha.status_v.pg_state: The current state of Postgres Pro. Possible values:Prestartup,Startup,Recovery,Recovery_Pause,Promoting,Promoted.online: Shows whether the node is online.startup_progress: Shows percentage of the current startup progress whenpg_stateisStartup.
For example:
biha_db=# select * from biha.monitoring(); id | time | biha_state | pg_state | online | startup_progress ----+------------------------+----------------+----------+--------+----------------- 3 | 2025-09-02 13:49:57+03 | LEADER_RW | Promoted | t | 1 | 2025-09-02 13:49:57+03 | CSTATE_FORMING | Startup | t | 81 2 | 2025-09-02 13:49:57+03 | FOLLOWER | Recovery | t | (3 rows)
biha.nodes () →#setof recordDisplays the BiHA transport channel state of the current node to other nodes and defines the
biha.nodes_vview, which is described in detail in the biha.nodes_v section.The function displays a table with the following columns:
id: The node ID.host: The host of the node.port: The port of the node.state: The connection state of the node. This column may contain one of the following values:ACTIVE: The node has active client connections. Read-write operations are performed in this state.CONNECTING: An attempt to establish a client connection with the node.IDLE: The node is in the passive waiting state.INIT: A client connection initialization.SSLCONNECT: An attempt to establish a secure connection. This state is only displayed when SSL is enabled.SSLACCEPT: An attempt to accept a secure connection. This state is only displayed when SSL is enabled.
conn_start: The time of connection start.conn_count: The number of times the node was connected since the start of the cluster.
For example:
biha_db=# SELECT * FROM biha.nodes(); id | host | port | state | conn_start | conn_count ----+-----------+-------+--------+------------------------+------------ 1 | localhost | 10001 | ACTIVE | 2023-07-05 17:17:17+07 | 1 2 | localhost | 10002 | | | 5 | localhost | 10005 | ACTIVE | 2023-07-05 17:17:17+07 | 1 3 | localhost | 10003 | ACTIVE | 2023-07-05 17:17:17+07 | 1 4 | localhost | 10004 | ACTIVE | 2023-07-05 17:17:17+07 | 1 (4 rows)
biha.status () →#setof recordDefines the
biha.status_vview, which is described in detail in the biha.status_v section. It is not recommended to use this function as it provides raw data for the view.
26.4.2.4. Replication #
The following functions are used to configure and manage replication.
biha.add_to_ssn (#idinteger) →booleanNote
You can call this function only when quorum-based synchronous replication is enabled.
Adds the specified node to the list of synchronous standbys listed by synchronous_standby_names.names. You must specify the node whose name is not yet in the list.
For example:
biha_db=# SELECT biha.add_to_ssn(3); add_to_ssn ------------- t (1 row)
biha.get_ssn () →#varcharDisplays the current value of the synchronous_standby_names parameter.
For example:
biha_db=# SELECT biha.get_ssn(); get_ssn --------------------------------------------- ANY 1 (biha_node_1,biha_node_2,biha_node_3) (1 row)
biha.set_deny_wal_sources (#idinteger,prohibited_idsinteger[]) →booleanSets the value of the deny_wal_sources configuration parameter for a specified node or resets the existing value.
The
prohibited_idsarray must meet the following requirements:The specified nodes must be physical and be present in the cluster.
IDs must meet the node ID format and must not repeat.
The array size must not exceed the maximum allowed number of nodes in the cluster.
For example, you can prevent the node with ID
3to replicate from the node with ID1as follows:biha_db=# SELECT biha.set_deny_wal_sources(3, ARRAY[1]); set_deny_wal_sources -------------- t (1 row)
To reset the parameter to an empty value, call the function with an empty array.
biha.set_max_replicas (#idinteger,max_replicas_numinteger) →booleanSets the value of the max_replicas configuration parameter.
For example, configure the node with ID
1to have the maximum of3replicas:biha_db=# SELECT biha.set_max_replicas(1, 3); set_max_replicas ------------------ t (1 row)
biha.set_pref_roles (#node_idinteger,valuetext) →booleanSets the value of the repl_pref_roles configuration parameter.
For example:
biha_db=# SELECT biha.set_pref_roles(1, 'LFR'); set_pref_roles ---------------- t (1 row)
biha.set_priority (#node_idinteger,valueinteger) →booleanSets the value of the priority configuration parameter.
For example:
biha_db=# SELECT biha.set_priority(1, 10); set_priority -------------- t (1 row)
biha.remove_from_ssn (#idinteger) →booleanNote
You can call this function only when quorum-based synchronous replication is enabled.
Removes the specified node from the list of synchronous standbys listed by synchronous_standby_names.names. You must specify the node which name is already in the list.
For example:
biha_db=# SELECT biha.remove_from_ssn(3); remove_from_ssn ------------- t (1 row)
biha.set_ssn (#VARIADIC idsinteger[]) →booleanNote
You can call this function only when quorum-based synchronous replication is enabled.
Sets the value of the synchronous_standby_names.names configuration parameter.
For example:
biha_db=# SELECT biha.set_ssn(1, 2, 3); set_ssn --------- t (1 row)
biha.set_sync_standbys (#sync_standbys_countinteger) →booleanSets the value of the synchronous_standby_names.count configuration parameter.
Important
Use this function carefully, as modifying the number of synchronous standbys may affect operation of the priority system or cause hanging of client application when requesting data from a lagging node.
For example:
biha_db=# SELECT biha.set_sync_standbys(1); set_sync_standbys ------------------- t (1 row)
biha.set_sync_standbys_min (#sync_standbys_min_countinteger) →booleanNote
You can call this function only when quorum-based synchronous replication is enabled.
Sets the value of the synchronous_standby_names.min configuration parameter.
Using this function, you can also manage relaxed quorum-based synchronous replication. To disable relaxed quorum-based synchronous replication, set the
-1value.For example:
biha_db=# SELECT biha.set_sync_standbys_min(1); set_sync_standbys_min ----------------------- f (1 row)
26.4.2.5. Elections and Quorum #
biha.set_minnodes (#idinteger,minnodesinteger) →booleanSets the value of the minnodes configuration parameter. If
idbelongs to a physical node, theminnodesvalue is set for the segment where the node is located. Ifidbelongs to a segment, the value is set for this segment and the nodes located in it. You can set different values for each segment.For example:
biha_db=# SELECT biha.set_minnodes(3, 1); set_minnodes -------------------------- t (1 row)
biha.set_nquorum (#idinteger,nquoruminteger) →booleanSets the value of the nquorum configuration parameter. If
idbelongs to a physical node, thenquorumvalue is set for the segment where the node is located. Ifidbelongs to a segment, the value is set for this segment and the nodes located in it. You can set different values for each segment.For example:
biha_db=# SELECT biha.set_nquorum(3, 3); set_nquorum -------------------------- t (1 row)
biha.set_nquorum_and_minnodes (#idinteger,nquoruminteger,minnodesinteger) →booleanSets nquorum and minnodes values. If
idbelongs to a physical node, thenquorumandminnodesvalues are set for the segment where the node is located. Ifidbelongs to a segment, the values are set for this segment and the nodes located in it. You can set different values for each segment.For example:
biha_db=# SELECT biha.set_nquorum_and_minnodes(3, 3, 1); set_nquorum_and_minnodes -------------------------- t (1 row)
biha.set_can_be_leader (#idinteger,can_be_leaderboolean) →booleanSets the value of the can_be_leader configuration parameter.
For example, you can allow the node with ID
4to become a leader candidate as follows:biha_db=# SELECT biha.set_can_be_leader(4,true); set_can_be_leader -------------- t (1 row)
biha.set_can_vote (#idinteger,can_voteboolean) →booleanSets the value of the can_vote configuration parameter.
For example, you can allow the node with ID
4to vote as follows:biha_db=# SELECT biha.set_can_vote(4,true); set_can_vote -------------- t (1 row)
26.4.2.6. Network Configuration #
biha.config_network () →#setof recordDisplays the current values of network configuration parameters for physical nodes only. In the output, the biha_listen_addresses value is displayed for other network configuration parameter if their values were not specified.
For example:
biha_db=# select * from biha.config_network(); id | biha_listen_addresses | biha_hosts | biha_port | replication_hosts | sql_hosts | port ----+-----------------------+------------+-----------+-------------------+-----------+------ 1 | biha-db-1 | biha-db-1 | 5433 | biha-db-1 | biha-db-1 | 5432 2 | biha-db-2 | biha-db-2 | 5433 | biha-db-2 | biha-db-2 | 5432 3 | biha-db-3 | biha-db-3 | 5433 | biha-db-3 | biha-db-3 | 5432 4 | biha-db-4 | biha-db-4 | 5433 | biha-db-4 | biha-db-4 | 5432 5 | biha-db-5 | biha-db-5 | 5433 | biha-db-5 | biha-db-5 | 5432 (5 rows)biha.set_biha_hosts (#idinteger,VARIADIC biha_hoststext[]) →booleanSets the value of the biha_hosts configuration parameter.
For example:
biha_db=# select biha.set_biha_hosts(1, 'biha-1:8080', 'biha-p', 'biha-2222:3333'); set_biha_hosts ---------------- t (1 row)
biha.set_sql_hosts (#idinteger,VARIADIC sql_hoststext[]) →booleanSets the value of the sql_hosts configuration parameter.
For example:
biha_db=# select biha.set_sql_hosts(1, 'bha-1:8080', 'bha-p', 'bha-2222:3333'); set_sql_hosts ---------------- t (1 row)
biha.set_replication_hosts (#idinteger,VARIADIC replication_hoststext[]) →booleanSets the value of the replication_hosts configuration parameter.
For example:
biha_db=# select biha.set_replication_hosts(1, 'bha-1:8080', 'bha-p', 'bha-2222:3333'); set_replication_hosts ----------------------- t (1 row)
26.4.2.7. Security Configuration #
biha.set_ssl_certificate (#text) →booleanSets the value of the ssl_certificate configuration parameter.
For example:
biha_db=# SELECT biha.set_ssl_certificate('/tmp/install/share/extension/biha_pub_cert.pem'); WARNING: [BiHA] this parameter takes effect after node restart set_ssl_certificate --------------------- t (1 row)biha.set_ssl_mode (#text) →booleanSets the value of the ssl_mode configuration parameter.
For example:
biha_db=# SELECT biha.set_ssl_mode('verify-full'); WARNING: [BiHA] this parameter takes effect after node restart set_ssl_mode -------------- t (1 row)biha.set_ssl_private_key (#text) →booleanSets the value of the ssl_private_key configuration parameter.
For example:
biha_db=# SELECT biha.set_ssl_private_key('/tmp/install/share/extension/biha_priv_key.pem'); WARNING: [BiHA] this parameter takes effect after node restart set_ssl_private_key --------------------- t (1 row)biha.set_user_cert (#text) →booleanSets the value of the user_biha_cert configuration parameter.
For example:
biha_db=# SELECT biha.set_user_cert('/tmp/install/share/extension/biha_pub_cert.pem'); WARNING: [BiHA] this parameter takes effect after node restart set_user_cert --------------- t (1 row)biha.set_user_key (#text) →booleanSets the value of the user_biha_key configuration parameter.
For example:
biha_db=# SELECT biha.set_user_key('/tmp/install/share/extension/biha_priv_key.pem'); WARNING: [BiHA] this parameter takes effect after node restart set_user_key -------------- t (1 row)biha.set_use_ssl (#boolean) →booleanSets the value of the use_ssl configuration parameter.
For example:
biha_db=# SELECT biha.set_use_ssl(true) WARNING: [BiHA] this parameter takes effect after node restart set_use_ssl ------------- t (1 row)
26.4.2.8. Callback Management #
biha.set_callbacks_timeout (#node_idinteger,timeout_valueinteger) →booleanSets the value of the callbacks_timeout configuration parameter.
biha.register_callback (#eventtext,functiontext,databasetext,executortext,priorityinteger) →integerAdds a new callback and returns its unique ID. This function can only be called from the leader node in the
LEADER_RWstate. The new callback is replicated to the followers.Note
On the biha side, there is no check that
funcexists indatabase. If the specified function does not exist, the callback fails.See Registering Callbacks for the example of using the
biha.register_callbackfunction.Table 26.3. Variable Definitions
Name Type Description eventtext Event of the BiHA cluster that triggers a callback. For more information about events and corresponding callback types, see Callback Types. functiontext Name of the SQL function that biha executes when eventhappens. This function must be located indatabase, otherwise it cannot be executed.databasetext Database where funcis executed.executortext User that executes
func. This parameter is optional. The default value isbiha_callbacks_user.priorityinteger The lower the value, the sooner the callback is executed. This parameter is optional. The default value is 0.biha.unregister_callback(#callback_id)Deletes a callback. This function can only be called on the leader node in the
LEADER_RWstate. Refer to Unregistering Callbacks for the example of using thebiha.unregister_callbackfunction.
26.4.2.9. Other Functions #
biha.get_magic_string() →#stringGenerates a magic string for the cluster node. For example:
biha_db=# SELECT biha.get_magic_string(); get_magic_string ---------------------------------------------------------------------- dmVyc2lvbj0xIGhvc3Q9bG9jYWxob3N0IHBvcnQ9NjU0MzIgYmloYS1wb3J0PTEwMDAx (1 row)biha.set_asyncaction_timeout (#idinteger,timeout_valueinteger) →booleanSets the value of the asyncaction_timeout configuration parameter.
For example:
biha_db=# SELECT biha.set_asyncaction_timeout(1, 50000); set_asyncaction_timeout ------------------------- t (1 row)
biha.set_flw_ro (#idinteger,available_for_read_onlyboolean) →booleanSets the value of the flw_ro configuration parameter.
For example:
biha_db=# SELECT biha.set_flw_ro(1, true); set_flw_ro ------------ t (1 row)
biha.set_manage_slots_xmin (#idinteger,manage_slots_xminboolean) →booleanSets the value of the manage_slots_xmin configuration parameter.
biha.service_mode (#enable_service_modeboolean,forceboolean) →booleanEnables the service mode in a BiHA cluster. This function can only be called on the leader node. The function takes the following parameters:
enable: When set totrue, the service mode is enabled. When not set or set tofalse, the service mode is disabled. Default isfalse.force: When set totrue, allows to disable the service mode ignoring all errors. When not set or set tofalse, the service mode cannot be disabled until you resolve all errors. Default isfalse.
biha.set_heartbeat_max_lost (#integer) →booleanSets the value of the heartbeat_max_lost configuration parameter.
For example:
biha_db=# SELECT biha.set_heartbeat_max_lost(7); set_heartbeat_max_lost ------------- t (1 row)
biha.set_heartbeat_send_period (#integer) →booleanSets the value of the heartbeat_send_period configuration parameter, in milliseconds.
For example:
biha_db=# SELECT biha.set_heartbeat_send_period(2000); set_heartbeat_send_period ------------- t (1 row)
biha.set_no_wal_on_follower (#integer) →booleanSets the value of the no_wal_on_follower configuration parameter, in milliseconds.
For example:
biha_db=# SELECT biha.set_no_wal_on_follower(10000); set_no_wal_on_follower ------------------------ t (1 row)
biha.set_watchdog_timeout (#idinteger,timeout_valueinteger) →booleanSets the value of the watchdog_timeout configuration parameter.
For example:
biha_db=# SELECT biha.set_watchdog_timeout(1, 10); WARNING: [BiHA] this parameter takes effect after node restart set_watchdog_timeout ---------------------- t (1 row)
biha.reset_node_error () →#booleanResets the
NODE_ERRORstate on a node. Use this function after you fix the issue that caused theNODE_ERRORstate. For more information, see Restoring the Node from the NODE_ERROR State.
26.4.3. Views #
To query the views listed below, you must first connect to the biha_db database.
26.4.3.1. biha.config_v #
This view displays the most critical parameters listed by the biha.config function.
For example:
biha_db=# select * from biha.config_v;
id | unit_type | name | parent_id | mode | nquorum | minnodes | heartbeat_send_period | heartbeat_max_lost
------+-----------+----------------+-----------+---------+---------+----------+-----------------------+--------------------
1 | NODE | biha_node_1 | 111 | regular | 3 | 1 | 1000 | 10
3 | NODE | biha_node_3 | 111 | regular | 3 | 1 | 1000 | 10
4 | NODE | biha_node_4 | 111 | regular | 3 | 1 | 1000 | 10
111 | SEGMENT | biha_node_111 | 1111 | regular | 1 | 1 | 1000 | 10
1111 | SEGMENT | biha_node_1111 | | regular | 1 | 1 | 1000 | 10
(5 rows)
Table 26.4. The biha.config_v view
| Column Name | Description |
|---|---|
id | The node ID (integer). |
unit_type | The type of the node. Possible values: NODE, SEGMENT. |
name | The name of the node (text). |
parent_id | The unique identifier of the node that is the parent to the current node (integer). |
mode | The current value of mode (text) |
nquorum | The current value of nquorum (integer). |
minnodes | The current value of minnodes (integer). |
heartbeat_send_period | The current value of heartbeat_send_period (integer). |
heartbeat_max_lost | The current value of heartbeat_max_lost (integer). |
26.4.3.2. biha.nodes_v #
This view displays the connection status of nodes in the cluster. For the node that the view is queried on, the following columns contain NULL: state, since_conn_start, conn_count.
For example:
biha_db=# SELECT * FROM biha.nodes_v; id | host | port | state | since_conn_start | conn_count ----+-----------+-------+--------+------------------+------------ 1 | localhost | 10001 | ACTIVE | 00:02:28.42069 | 1 2 | localhost | 10002 | | | 3 | localhost | 10003 | ACTIVE | 00:02:23.42069 | 1 4 | localhost | 10004 | ACTIVE | 00:02:23.42069 | 1 5 | localhost | 10005 | ACTIVE | 00:02:23.42069 | 1 (4 rows)
Table 26.5. The biha.nodes_v view
| Column Name | Description |
|---|---|
id | The node ID. |
host | The host of the node. |
port | The port of the node. |
state | The connection state of the node. This column may contain one of the following values:
|
since_conn_start | The time since the node connection. |
conn_count | The number of times the node was connected since the start of the cluster. |
26.4.3.3. biha.status_v #
This view displays the state of nodes in the cluster.
For example:
biha_db=# SELECT * FROM biha.status_v; id | leader_id | term | online | state | last_known_state | since_last_hb ----+-----------+------+--------+-----------+------------------+----------------- 1 | 1 | 4 | t | LEADER_RW | LEADER_RW | 2 | 1 | 4 | t | FOLLOWER | FOLLOWER | 00:00:01.931472 3 | 1 | 4 | f | UNKNOWN | FOLLOWER | 00:00:18.931472 4 | 1 | 4 | t | FOLLOWER | FOLLOWER | 00:00:01.931472 5 | 1 | 4 | t | FOLLOWER | FOLLOWER | 00:00:01.931472 (5 rows)
Table 26.6. The biha.status_v View
| Column Name | Description |
|---|---|
id | The node ID (integer). |
leader_id | The leader node ID (integer). |
term | The term of the node (integer). This is used for the purposes of the leader election. |
online | Shows whether the node is online (boolean: t or f). |
state | The state of the node (
|
last_known_state | The last known state of the node (text). |
since_last_hb | The time since the last received heartbeat message (interval). |
26.4.3.4. biha.super_status_v #
The extended version of the biha.status_v view that additionally displays data for GDBiHA cluster.
The biha.super_status_v view contains the following additional columns:
name: The name of the node (text).unit_type: The type of the unit. Possible values:NODE,SEGMENT.parent_id: The unique identifier of the node that is the parent to the current node (integer).segment_name: The name of the segment where the node belongs to (text).