27.4. Справка по расширению biha #

biha — расширение Postgres Pro для управления BiHA-кластером.

В этом разделе содержится информация о параметрах конфигурации, функциях и представлениях расширения biha.

27.4.1. Параметры конфигурации #

Расширение biha поддерживает ряд описанных ниже конфигурационных параметров, специфичных для BiHA-кластера.

27.4.1.1. Конфигурирование кластера #

Важно

  • При настройке параметров конфигурации кластера нужно обязательно обеспечить надёжность сети, чтобы изменения затронули все узлы кластера без возникновения ошибок.

  • Не рекомендуется изменять какие-либо параметры конфигурации кластера, пока один из узлов находится в состоянии NODE_ERROR, так как на этом узле изменения могут не примениться.

biha.autorewind (boolean) #

Необязательный параметр, который управляет политикой автоматической синхронизации для узла, в отношении которого должен быть выполнен pg_rewind. Например, для старого лидера при его синхронизации с новым лидером. При значении по умолчанию — false — автоматическая синхронизация не выполняется. Если установлено значение true, автоматическая синхронизация выполняется после ошибки, которая обычно приводит к переходу узла в состояние NODE_ERROR.

За подробной информацией обратитесь к Автоматическая синхронизация кластера после аварийного переключения.

biha.callbacks_timeout (integer) #

Задаёт время исполнения всех функций-обработчиков для одного события в миллисекундах. Значение по умолчанию — 10000 (10 секунд). Минимальное значение — 1000 (1 секунда).

Значение параметра biha.callbacks_timeout может различаться для разных узлов. Изменение параметра на лидере не изменяет его на последователях.

biha.can_be_leader (boolean) #

Определяет возможность узла стать лидером. Значение по умолчанию — true. Если задано значение false, узел не может предлагать себя в качестве кандидата на выборах лидера.

Самый большой объём WAL может быть на том узле, который не может стать лидером. В этой ситуации при необходимости выборов другие узлы, которые могут предлагать себя в качестве кандидатов в лидеры, попытаются получить недостающие данные с этого узла. В случае успеха один из этих узлов станет лидером. Если данные получить не удалось, на узле, который не может стать лидером, запустится процесс автоматической синхронизации. Если параметр biha.autorewind не включён, состояние этого узла изменится на NODE_ERROR.

biha.can_vote (boolean) #

Определяет возможность узла голосовать. Значение по умолчанию — true. Если задать значение false, узел не сможет принимать участие в голосовании, а также не сможет предлагать себя в качестве кандидата в лидеры.

biha.flw_ro (boolean) #

Определяет доступность последователя для операций на чтение. Если задано значение off, чтение с этого последователя запрещено. Значение по умолчанию — on.

biha.heartbeat_max_lost (integer) #

Указывает максимальное число сообщений о контроле состояния, которые можно не получить до того, как узел будет считаться недоступным. Этот параметр может задаваться функцией biha.set_heartbeat_max_lost. Значение по умолчанию — 10.

Узлы во всех состояниях используют значение тайм-аута сообщений о контроле состояния, который рассчитывается как biha.heartbeat_max_lost * biha.heartbeat_send_period, для определения доступности других узлов. Например, если Узел A не получает сообщения о контроле состояния от Узла B в течение вышеупомянутого тайм-аута, состояние Узла B изменится на UNKNOWN в представлении biha.status_v Узла A, что будет означать, что Узел A считает Узел B недоступным. Лидер в состоянии LEADER_RW дополнительно использует тайм-аут, указанный в параметре biha.no_wal_on_follower.

biha.heartbeat_send_period (integer) #

Указывает частоту отправки сообщений о контроле состояния в миллисекундах. Этот параметр может задаваться функцией biha.set_heartbeat_send_period. Значение по умолчанию — 1000.

Узлы во всех состояниях используют значение тайм-аута сообщений о контроле состояния, который рассчитывается как biha.heartbeat_max_lost * biha.heartbeat_send_period, для определения доступности других узлов. Например, если Узел A не получает сообщения о контроле состояния от Узла B в течение вышеупомянутого тайм-аута, состояние Узла B изменится на UNKNOWN в представлении biha.status_v Узла A, что будет означать, что Узел A считает Узел B недоступным. Лидер в состоянии LEADER_RW дополнительно использует тайм-аут, указанный в параметре biha.no_wal_on_follower.

biha.host (text) #

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

biha.id (integer) #

Указывает идентификатор узла отказоустойчивого кластера. Этот параметр уникален для каждого узла. Этот параметр не рекомендуется изменять.

biha.minnodes (integer) #

Указывает минимальное число работающих узлов, при котором лидер будет открыт для пишущих транзакций. Этот параметр может быть задан с помощью функции biha.set_minnodes. Если не задать параметр --minnodes в команде bihactl init, значение biha.minnodes будет равно значению biha.nquorum.

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

Если на узле для параметра biha.can_vote установлено значение false, такой узел игнорируется.

biha.no_wal_on_follower (integer) #

Указывает тайм-аут продвижения слота репликации в миллисекундах. Этот параметр может задаваться функцией biha.set_no_wal_on_follower. Значение по умолчанию — 20000.

BiHA использует этот параметр конфигурации для следующих целей:

  • Когда вы вручную назначаете узел-последователь в качестве нового лидера с помощью функции biha.set_leader, состояние последователя изменяется на FOLLOWER_OFFERED. В этом состоянии последователь с помощью параметра biha.no_wal_on_follower определяет, что пора прекратить ожидание записей WAL от текущего лидера и можно становиться новым лидером.

    Последователь в состоянии FOLLOWER_OFFERED проверяет, обновилась ли его позиция WAL. Обновление позиции WAL подтверждает, что последователь продолжает получать данные репликации от лидера. Если последователь не получает записи WAL дольше, чем задано в параметре biha.no_wal_on_follower, состояние последователя изменяется на LEADER_RO. В этом случае в журнале появляется следующее сообщение: «Timed out waiting for new WAL records from current leader» (Истёк тайм-аут ожидания записей WAL от текущего лидера).

  • Лидер в состоянии LEADER_RW использует параметр biha.no_wal_on_follower в связке со значением тайм-аута сообщений о контроле состояния (который рассчитывается как biha.heartbeat_max_lost * biha.heartbeat_send_period) для определения доступности других узлов.

    Лидер проверяет позиции слотов репликации других узлов. Если позиция слота репликации узла обновляется, это означает, что узел получает данные репликации от лидера и доступен. Если лидер не получает от узла сообщения о контроле состояния в течение вышеупомянутого тайм-аута, а позиция слота репликации узла не меняется в течение тайм-аута, заданного в biha.no_wal_on_follower, лидер будет считать узел недоступным, а состояние узла изменится на UNKNOWN в представлении biha.status_v лидера.

biha.node_priority (integer) #

Устанавливает приоритет узла в кластере с синхронной репликацией, в секундах. Значение определяет тайм-аут, по истечении которого узел предложит себя в качестве кандидата на выборах. Нулевое значение означает самый высокий приоритет. Значение по умолчанию — -1, означающее, что параметр игнорируется.

Важно

Чтобы обеспечить корректную работу параметра, установите значение параметра --sync-standbys на единицу меньше общего количества узлов кластера.

biha.nquorum (integer) #

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

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

Если на узле для параметра biha.can_vote установлено значение false, такой узел игнорируется.

biha.port (integer) #

Указывает порт, используемый для обмена служебной информацией между узлами. Этот параметр необходим, чтобы установить соединение с кластером. Этот параметр не рекомендуется изменять.

biha.use_ssl (boolean) #

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

biha.autowaltrim (boolean) #

Управляет политикой выравнивания WAL в рамках одного узла. Если задано значение true (по умолчанию), BiHA автоматически планирует и выполняет процедуру выравнивания WAL по возможности. Если задано значение false, процедура выравнивания WAL не выполняется, а синхронизация кластера проводится с помощью pg_rewind.

За подробной информацией обратитесь к Автоматическая синхронизация кластера после аварийного переключения.

27.4.1.2. Настройка аутентификации по SSL #

Перечисленные ниже параметры конфигурации относятся к SSL-аутентификации для роли biha_replication_user. За подробной информацией о настройке аутентификации по SSL обратитесь к Настройка SSL для biha_replication_user.

biha.user_biha_cert (text) #

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

biha.user_biha_key (text) #

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

biha.ssl_mode (text) #

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

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

  • require

  • verify-ca

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

27.4.1.3. Уровни протоколирования biha #

biha.BihaLog_log_level (enum) #

Задаёт уровень протоколирования для предоставления общей информации о работе компонентов biha. Значение по умолчанию — LOG.

biha.BcpTransportDebug_log_level (enum) #

Задаёт уровень протоколирования для предоставления отладочной информации о работе канала управления. Значение по умолчанию — DEBUG4.

biha.BcpTransportDetails_log_level (enum) #

Задаёт уровень протоколирования для предоставления подробной информации о работе канала управления. Значение по умолчанию — DEBUG4.

biha.BcpTransportLog_log_level (enum) #

Задаёт уровень протоколирования для предоставления общей информации о работе канала управления. Значение по умолчанию — DEBUG4.

biha.BcpTransportWarn_log_level (enum) #

Задаёт уровень протоколирования для вывода предупреждений о возможных проблемах в канале управления. Значение по умолчанию — DEBUG4.

biha.BcpTransportSSLDebug_log_level (enum) #

Задаёт уровень протоколирования для предоставления отладочной информации о работе канала управления в режиме SSL. Значение по умолчанию — DEBUG4.

biha.NodeControllerDebug_log_level (enum) #

Задаёт уровень протоколирования для предоставления отладочной информации о работе контроллера узла. Значение по умолчанию — DEBUG4.

biha.NodeControllerDetails_log_level (enum) #

Задаёт уровень протоколирования для предоставления подробной информации о работе контроллера узла. Значение по умолчанию — DEBUG4.

biha.NodeControllerLog_log_level (enum) #

Задаёт уровень протоколирования для предоставления общей информации о работе контроллера узла. Значение по умолчанию — DEBUG4.

biha.NodeControllerWarn_log_level (enum) #

Задаёт уровень протоколирования для вывода предупреждений о возможных проблемах в контроллере узла. Значение по умолчанию — DEBUG4.

27.4.2. Функции #

Все перечисленные ниже функции необходимо вызывать из базы данных biha_db, например:

psql biha_db -c "SELECT biha.set_leader(2)"

27.4.2.1. Состав кластера #

biha.set_leader (id integer) returns boolean #

Устанавливает лидера вручную. Рекомендуется вызывать эту функцию на том узле, который вы собираетесь сделать лидером.

Примечание

Не рекомендуется вызывать функцию biha.set_leader на текущем лидере. Если вызвать функцию на текущем лидере в состоянии LEADER_RW, в случае успешного запроса на переключение может случиться так, что результат запроса не успеет отправиться клиенту до начала перезагрузки текущего лидера для понижения.

biha.remove_node (id integer) returns boolean #

Удаляет узел из кластера. Перед удалением узел необходимо остановить. Данную функцию можно вызвать только на узле-лидере.

27.4.2.2. Общая конфигурация кластера #

Следующие функции используются для изменения параметров конфигурации, значения которых должны быть одинаковыми на всех узлах кластера. Эти функции необходимо вызывать только на лидере. Изменения будут применены на всех узлах.

Перезапуск узлов кластера не требуется, чтобы после вызова функции изменения вступили в силу, если в описании функции явно не указано обратное.

biha.set_heartbeat_max_lost (integer) returns boolean #

Задаёт значение параметра biha.heartbeat_max_lost.

biha.set_heartbeat_send_period (integer) returns boolean #

Задаёт значение параметра biha.heartbeat_send_period в миллисекундах.

biha.set_no_wal_on_follower (integer) returns boolean #

Задаёт значение параметра biha.no_wal_on_follower в миллисекундах.

biha.set_minnodes (integer) returns boolean #

Задаёт значение параметра biha.minnodes.

biha.set_nquorum (integer) returns boolean #

Задаёт значение параметра biha.nquorum.

biha.set_nquorum_and_minnodes (integer, integer) returns boolean #

Задаёт значения параметров biha.nquorum и biha.minnodes.

27.4.2.3. Репликация #

Следующие функции используются для настройки репликации и управления ею.

biha.add_to_ssn (id integer) returns boolean #

Примечание

Эту функцию можно вызвать, только если включена кворумная синхронная репликация.

Добавляет узел с указанным идентификатором в список синхронных резервных узлов параметра synchronous_standby_names. Необходимо указывать узел, имени которого ещё нет в списке.

biha.get_ssn() returns varchar #

Отображает текущее значение параметра synchronous_standby_names.

biha.remove_from_ssn (id integer) returns boolean #

Примечание

Эту функцию можно вызвать, только если включена кворумная синхронная репликация.

Удаляет узел с указанным идентификатором из списка синхронных резервных узлов параметра synchronous_standby_names. Необходимо указать узел, имя которого уже есть в списке.

biha.set_ssn (VARIADIC ids integer) returns boolean #

Примечание

Эту функцию можно вызвать, только если включена кворумная синхронная репликация.

Устанавливает узлы с идентификаторами, указанными в массиве ids, в качестве списка синхронных резервных узлов параметра synchronous_standby_names.

biha.set_sync_standbys (integer) returns boolean #

Включает кворумную синхронную репликацию, устанавливая параметр synchronous_standby_names и указывая число синхронных резервных узлов (кворум) с методом ANY. Значение должно быть положительным, выше значения поля MIN параметра synchronous_standby_names (если оно задано) и не должно превышать число последователей без учёта рефери. За подробной информацией обратитесь к Настройка репликации.

biha.set_sync_standbys_min (integer) returns boolean #

Примечание

Эту функцию можно вызвать, только если включена кворумная синхронная репликация.

Задаёт значение поля MIN параметра synchronous_standby_names, т.е. минимальное число синхронных резервных узлов, которые должны быть доступны, чтобы лидер продолжал работать.

С помощью этой функции можно также управлять нестрогой кворумной синхронной репликацией. Чтобы отключить нестрогую кворумную синхронную репликацию, задайте значение -1.

27.4.2.4. Мониторинг кластера #

biha.config () returns setof record #

Возвращает значения параметров конфигурации для каждого узла:

  • id: идентификатор узла (integer).

  • term: поколение узла (integer).

  • nquorum: текущее значение biha.nquorum (integer).

  • minnodes: текущее значение biha.minnodes (integer).

  • heartbeat_send_period: текущее значение biha.heartbeat_send_period (integer).

  • heartbeat_max_lost: текущее значение biha.heartbeat_max_lost (integer).

  • no_wal_on_follower: текущее значение biha.no_wal_on_follower (integer).

  • sync_standbys_min: текущее значения поля MIN параметра synchronous_standby_names (integer).

  • priority: текущее значение biha.node_priority (integer).

  • can_be_leader: текущее значение biha.can_be_leader (boolean).

  • can_vote: текущее значение biha.can_vote (boolean).

  • mode: текущий режим работы узла (text). Возможные значения: regular, referee или referee_with_wal.

biha.error_details () returns setof record #

Возвращает описание причины, по которой узел перешёл в состояние NODE_ERROR. Возвращаемая запись содержит тип ошибки, подробную информацию о ней, место возникновения с указанием begin_lsn, end_lsn и идентификаторов текущей и следующей линии времени, а также replay_lsn.

biha.nodes () returns setof record #

Определяет представление biha.nodes_v, подробно описанное в biha.nodes_v.

biha.status () returns setof record #

Определяет представление biha.status_v, подробно описанное в biha.status_v. Использовать эту функцию не рекомендуется, так как она предоставляет необработанные данные для представления.

27.4.2.5. Управление функциями-обработчиками #

biha.register_callback (event text, func text, database text, executor text, priority integer) returns integer #

Добавляет новый обработчик и возвращает его уникальный идентификатор. Функцию можно вызвать только на лидере в состоянии LEADER_RW. Новый обработчик будет реплицирован на последователей.

Примечание

Со стороны biha нет проверки наличия функции func в базе данных database. Если указанная функция не существует, исполнение обработчика завершится ошибкой.

Пример использования biha.register_callback см. в Регистрация функций-обработчиков.

Таблица 27.3. Определения переменных

ИмяТипОписание
eventtextСобытие в BiHA-кластере, которое запускает функцию-обработчик. Подробнее о событиях и соответствующих типах функций-обработчиков читайте в Типы обработчиков.
functextНазвание SQL-функции, которую расширение biha исполняет при наступлении события event. Функция должна находиться в базе данных database, иначе она не будет исполнена.
databasetextБаза данных, в которой исполняется функция func.
executortext

Пользователь, от имени которого исполняется функция func. Это необязательный параметр. Значение по умолчанию — biha_callbacks_user.

priorityintegerЧем ниже значение, тем раньше исполнится обработчик. Это необязательный параметр. Значение по умолчанию — 0.

biha.unregister_callback(callback_id) #

Удаляет обработчик. Функцию можно вызвать только на лидере в состоянии LEADER_RW. Пример использования функции biha.unregister_callback см. в разделе Отмена регистрации функции-обработчика.

27.4.2.6. Прочие функции #

biha.get_magic_string () returns string #

Генерирует «‎‎магическую» строку для узла кластера.

biha.reset_node_error () returns boolean #

Сбрасывает состояние NODE_ERROR на узле. Используйте эту функцию после того, как устранена причина перехода узла в состояние NODE_ERROR. За подробной информацией обратитесь к разделу Восстановление узла из состояния NODE_ERROR.

27.4.3. Представления #

Чтобы обращаться к перечисленным ниже представлениям, необходимо подключиться к базе данных biha_db.

27.4.3.1. biha.nodes_v #

В этом представлении показывается состояние подключения узлов в кластере. Для узла, на котором выполняется запрос для представления, следующие столбцы содержат NULL: state, since_conn_start, conn_count.

Таблица 27.4. Представление biha.nodes_v

Имя столбцаОписание
idИдентификатор узла.
hostАдрес узла.
portПорт узла.
stateСостояние соединения узла. В этом столбце может отображаться одно из следующих значений:
  • ACTIVE: есть активные клиентские подключения к узлу. В этом состоянии выполняются операции на чтение и запись.

  • CONNECTING: попытка установить клиентское соединение с узлом.

  • IDLE: узел находится в состоянии пассивного ожидания.

  • INIT: инициализация клиентского соединения.

  • SSLCONNECT: попытка установить защищённое соединение. Это состояние отображается только при включённом SSL.

  • SSLACCEPT: попытка принять защищённое соединение. Это состояние отображается только при включённом SSL.

since_conn_startВремя, прошедшее с момента подключения узла к сети.
conn_countСколько раз узел подключался к сети с момента запуска кластера.

27.4.3.2. biha.status_v #

В этом представлении показывается состояние узлов в кластере.

Таблица 27.5. Представление biha.status_v

Имя столбцаОписание
idИдентификатор узла (integer).
leader_idИдентификатор узла-лидера (integer).
termПоколение узла (integer). Используется при голосовании на выборах нового узла-лидера.
onlineПоказывает, подключён ли узел к сети (boolean: t или f).
state

Состояние узла (text). В этом столбце может отображаться одно из следующих значений:

  • PRESTARTUP: начальное состояние узла при запуске BiHA-кластера. Узел отправляет сообщения о контроле состояния и запускает pg_rewind, если это было запланировано. В других случаях узел переходит в состояние STARTUP.

  • STARTUP: узел ожидает, пока процесс запуска Postgres Pro достигнет точки согласованности.

  • CSTATE_FORMING: узел получает и отправляет сообщения о контроле состояния, чтобы определить, в какое состояние он должен перейти.

  • LEADER_RO: узел является лидером, доступным только для операций чтения.

  • LEADER_RW: узел является лидером, доступным для операций на чтение и запись.

  • FOLLOWER: узел является последователем, т.е. репликой лидера. Если biha.can_be_leader и biha.can_vote имеют значение true, последователь может быть избран новым лидером.

  • FOLLOWER_OFFERED: узел был вручную назначен новым лидером с помощью функции biha.set_leader. В этом состоянии назначенный лидером узел получает недостающие данные со старого лидера.

  • CANDIDATE: узел предложил себя в качестве кандидата на выборах нового лидера.

  • REFEREE: узел является рефери кластера. Это единое состояние для режимов referee и referee_with_wal.

  • NODE_ERROR: узел в нерабочем состоянии из-за ошибки. Узлы в этом состоянии не могут голосовать на выборах. Чтение с таких узлов запрещено. Чтобы получить больше информации об ошибке, используйте функцию biha.error_details. О восстановлении дефектных узлов читайте в разделе Восстановление узла из состояния NODE_ERROR.

  • UNKNOWN: узел недоступен для текущего узла.

last_known_stateПоследнее известное состояние узла (text).
since_last_hbВремя, прошедшее с момента получения последнего сообщения о контроле состояния (timestamptz).

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

27.4.1. Configuration Parameters #

The biha extension provides a set of configuration parameters described below that are specific to the BiHA cluster.

27.4.1.1. Cluster Configuration #

Important

  • When setting the cluster configuration parameters, you must ensure network reliability for the changes to affect all cluster nodes without any errors.

  • It is not recommended to modify any cluster configuration parameters while one of the nodes is in the NODE_ERROR state, as the changes may fail to be applied on that node.

biha.autorewind (boolean) #

An optional parameter that controls the automatic rewind policy for that node, against which the pg_rewind must be executed. For example, for the old leader when synchronizing it with the new leader. The default value is false meaning that the automatic rewind is not performed. When the value is set to true, the automatic rewind is performed after the error that usually causes the NODE_ERROR state of the node.

For more information, see Automatic Cluster Synchronization after Failover.

biha.callbacks_timeout (integer) #

Sets time for execution of all callbacks for a single event, in milliseconds. The default value is 10000 (10 seconds). The minimum value is 1000 (1 second).

The value of the biha.callbacks_timeout parameter can be different for different nodes. Changing the value for the leader does not change it for the followers.

biha.can_be_leader (boolean) #

Determines the ability of a node to become the leader. The default value is true. If set to false, the node 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.

biha.can_vote (boolean) #

Determines whether a node is allowed to vote. The default value is true. If set to false, the node cannot vote, as well as cannot stand as a candidate in elections of the new leader.

biha.flw_ro (boolean) #

Determines whether a follower is available for read operations. If set to off, reading from this follower is prohibited. The default value is on.

biha.heartbeat_max_lost (integer) #

Specifies the maximum number of heartbeats that can be missed before the node is considered offline. This parameter can be set with the biha.set_heartbeat_max_lost function. The default value is 10.

Nodes in all states use the heartbeat timeout value calculated as biha.heartbeat_max_lost * biha.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 to UNKNOWN in the biha.status_v view of Node A indicating that Node A considers Node B offline. The leader in the LEADER_RW state additionally uses the timeout specified in the biha.no_wal_on_follower parameter.

biha.heartbeat_send_period (integer) #

Specifies the heartbeat sending frequency, in milliseconds. This parameter can be set with the biha.set_heartbeat_send_period function. The default value is 1000.

Nodes in all states use the heartbeat timeout value calculated as biha.heartbeat_max_lost * biha.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 to UNKNOWN in the biha.status_v view of Node A indicating that Node A considers Node B offline. The leader in the LEADER_RW state additionally uses the timeout specified in the biha.no_wal_on_follower parameter.

biha.host (text) #

Specifies the host of the cluster node. It is not recommended to modify this parameter.

biha.id (integer) #

Specifies the ID of the high-availability cluster node. This parameter is unique for each node of the cluster. It is not recommended to modify this parameter.

biha.minnodes (integer) #

Specifies the minimum number of operational nodes for the leader node to be open for write transactions. This parameter can be set with the biha.set_minnodes function. If you do not specify the --minnodes option in bihactl init command, the biha.minnodes value equals the biha.nquorum value.

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

Nodes with the biha.can_vote parameter set to false are ignored.

biha.no_wal_on_follower (integer) #

Specifies the timeout of the replication slot position advancement, in milliseconds. This parameter can be set with the biha.set_no_wal_on_follower function. The default value is 20000.

BiHA 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. The follower in this state uses biha.no_wal_on_follower to determine if it must stop waiting for missing WAL records from the current leader and can become the new leader.

    A follower in the FOLLOWER_OFFERED state checks whether its WAL location has been updated. Update of WAL location confirms that the follower keeps receiving replication data from the leader. If the follower does not receive WAL records longer than biha.no_wal_on_follower, the follower state changes to LEADER_RO. In this case, the log contains the following message: “Timed out waiting for new WAL records from current leader”.

  • The leader in the LEADER_RW state uses biha.no_wal_on_follower in conjunction with the heartbeat timeout value (which is calculated as biha.heartbeat_max_lost * biha.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 biha.no_wal_on_follower timeout value, the leader considers the node offline and its state changes to UNKNOWN in the biha.status_v view of the leader.

biha.node_priority (integer) #

Sets the node priority in a cluster with synchronous replication, in seconds. 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. The default value is -1, meaning that the parameter is ignored.

Important

To ensure correct operation of this parameter, set the --sync-standbys value one unit less than the total number of cluster nodes.

biha.nquorum (integer) #

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

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

Nodes with the biha.can_vote parameter set to false are ignored.

biha.port (integer) #

Specifies the port used to exchange service information between nodes. This parameter is required to establish a connection with the cluster. It is not recommended to modify this parameter.

biha.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. It is not recommended to modify this parameter.

biha.autowaltrim (boolean) #

Manages the automatic WAL trimming policy within a single node. When set to true (default), BiHA automatically schedules and executes the WAL trimming procedure if possible. If set to false, the WAL trimming procedure is not executed and cluster synchronization is performed by means of pg_rewind.

For more information, see Automatic Cluster Synchronization after Failover.

27.4.1.2. SSL Authentication Configuration #

Configuration parameters listed below relate to the SSL authentication of the biha_replication_user role. For more information about SSL authentication configuration, see Configuring SSL for biha_replication_user.

biha.user_biha_cert (text) #

Specifies the path to the SSL public certificate used for the biha_replication_user role authentication.

biha.user_biha_key (text) #

Specifies the path to the SSL private key used for the biha_replication_user role authentication.

biha.ssl_mode (text) #

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

  • verify-full (default)

  • require

  • verify-ca

For more information about modes, see sslmode.

27.4.1.3. biha 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.BcpTransportDebug_log_level (enum) #

Specifies the logging level to provide debugging information about the control channel operation. The default value is DEBUG4.

biha.BcpTransportDetails_log_level (enum) #

Specifies the logging level to provide detailed information about the control channel operation. The default value is DEBUG4.

biha.BcpTransportLog_log_level (enum) #

Specifies the logging level to provide general information about the control channel operation. The default value is DEBUG4.

biha.BcpTransportWarn_log_level (enum) #

Specifies the logging level to provide warnings of likely problems in the control channel. The default value is DEBUG4.

biha.BcpTransportSSLDebug_log_level (enum) #

Specifies the logging level to provide debugging information about the control channel operation in the SSL mode. The default value is DEBUG4.

biha.NodeControllerDebug_log_level (enum) #

Specifies the logging level to provide debugging information about the node controller operation. The default value is DEBUG4.

biha.NodeControllerDetails_log_level (enum) #

Specifies the logging level to provide detailed information about the node controller operation. The default value is DEBUG4.

biha.NodeControllerLog_log_level (enum) #

Specifies the logging level to provide general information about the node controller operation. The default value is DEBUG4.

biha.NodeControllerWarn_log_level (enum) #

Specifies the logging level to provide warnings of likely problems in the node controller. The default value is DEBUG4.

27.4.2. Functions #

All functions listed below must be called from the biha_db database, for example:

psql biha_db -c "SELECT biha.set_leader(2)"

27.4.2.1. Cluster Composition #

biha.set_leader (id integer) returns boolean #

Sets the leader node manually. It is recommended to call this function on the node that you want to set as the new leader.

Note

Calling the biha.set_leader function on the current leader is not recommended. If you call the function on the current leader in the LEADER_RW state, in case of a successful switchover request, there may not be enough time for the request result to be sent to the client before the current leader reboots for demotion.

biha.remove_node (id integer) returns boolean #

Removes the node from the cluster. Before removing, the node must be stopped. This function can only be called on the leader node.

27.4.2.2. Common Cluster Configuration #

The following functions are used to change configuration parameters that must have the same values on all cluster nodes. These functions must only be called on the leader node. The changes are applied to all cluster nodes.

You do not need to restart the cluster nodes after calling a function for the changes to take effect unless the function description explicitly specifies otherwise.

biha.set_heartbeat_max_lost (integer) returns boolean #

Sets the biha.heartbeat_max_lost value.

biha.set_heartbeat_send_period (integer) returns boolean #

Sets the biha.heartbeat_send_period value, in milliseconds.

biha.set_no_wal_on_follower (integer) returns boolean #

Sets the biha.no_wal_on_follower value, in milliseconds.

biha.set_minnodes (integer) returns boolean #

Sets the biha.minnodes value.

biha.set_nquorum (integer) returns boolean #

Sets the biha.nquorum value.

biha.set_nquorum_and_minnodes (integer, integer) returns boolean #

Sets the biha.nquorum and biha.minnodes values.

27.4.2.3. Replication #

The following functions are used to configure and manage replication.

biha.add_to_ssn (id integer) returns boolean #

Note

You can call this function only when quorum-based synchronous replication is enabled.

Adds a node with the specified ID to the list of synchronous standbys of the synchronous_standby_names parameter. You must specify the node which name is not yet in the list.

biha.get_ssn() returns varchar #

Displays the current value of the synchronous_standby_names parameter.

biha.remove_from_ssn (id integer) returns boolean #

Note

You can call this function only when quorum-based synchronous replication is enabled.

Removes the node with the specified ID from the list of synchronous standbys of the synchronous_standby_names parameter. You must specify the node which name is already in the list.

biha.set_ssn (VARIADIC ids integer) returns boolean #

Note

You can call this function only when quorum-based synchronous replication is enabled.

Sets nodes with the IDs specified in the ids array as the list of synchronous standbys of the synchronous_standby_names parameter.

biha.set_sync_standbys (integer) returns boolean #

Enables quorum-based synchronous replication by setting the synchronous_standby_names parameter and specifying the number of synchronous standbys (quorum) with the ANY method. The value must be positive, higher than the MIN field value of the synchronous_standby_names parameter if set, and must not exceed the number of followers excluding referee. For more information, see Replication Configuration.

biha.set_sync_standbys_min (integer) returns boolean #

Note

You can call this function only when quorum-based synchronous replication is enabled.

Sets the MIN field value of the synchronous_standby_names parameter, i.e. the minimum number of synchronous standbys that must be available for the leader node to continue operation.

Using this function, you can also manage relaxed quorum-based synchronous replication. To disable relaxed quorum-based synchronous replication, set the -1 value.

27.4.2.4. Cluster Monitoring #

biha.config () returns setof record #

Returns the cluster configuration parameter values for every node:

biha.error_details () returns setof record #

Returns the description of why the node transferred to the NODE_ERROR state. The returned record contains the type of the error, its details, the place it occurred specifying begin_lsn, end_lsn, and identifier of the current and the next timeline, as well as replay_lsn.

biha.nodes () returns setof record #

Defines the biha.nodes_v view, which is described in detail in the biha.nodes_v section.

biha.status () returns setof record #

Defines the biha.status_v view, 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.

27.4.2.5. Callback Management #

biha.register_callback (event text, func text, database text, executor text, priority integer) returns integer #

Adds a new callback and returns its unique ID. This function can only be called from the leader node in the LEADER_RW state. The new callback is replicated to the followers.

Note

On the biha side, there is no check that func exists in database. If the specified function does not exist, the callback fails.

See Registering Callbacks for the example of using the biha.register_callback function.

Table 27.3. Variable Definitions

NameTypeDescription
eventtext Event of the BiHA cluster that triggers a callback. For more information about events and corresponding callback types, see Callback Types.
functext Name of the SQL function that biha executes when event happens. This function must be located in database, otherwise it cannot be executed.
databasetextDatabase where func is executed.
executortext

User that executes func. This parameter is optional. The default value is biha_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_RW state. See Unregistering Callbacks for the example of using the biha.unregister_callback function.

27.4.2.6. Other Functions #

biha.get_magic_string () returns string #

Generates a magic string for the cluster node.

biha.reset_node_error () returns boolean #

Resets the NODE_ERROR state on a node. Use this function after you fix the issue that caused the NODE_ERROR state. For more information, see Restoring the Node from the NODE_ERROR State.

27.4.3. Views #

To query the views listed below, you must first connect to the biha_db database.

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

Table 27.4. The biha.nodes_v view

Column NameDescription
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.

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.

27.4.3.2. biha.status_v #

This view displays the state of nodes in the cluster.

Table 27.5. The biha.status_v View

Column NameDescription
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 (text). This column may contain one of the following values:

  • PRESTARTUP: The initial state of the node at the BiHA cluster launch. The node sends heartbeats and executes pg_rewind if scheduled. Otherwise, the node proceeds to STARTUP.

  • STARTUP: The node waits for the Postgres Pro startup process to reach the consistency point.

  • CSTATE_FORMING: The node receives and sends heartbeats to determine what state it must transfer to.

  • LEADER_RO: The node is the leader available for read-only operations.

  • LEADER_RW: The node is the leader available for read and write operations.

  • FOLLOWER: The node is a replica of the leader. If biha.can_be_leader and biha.can_vote are set to true, the follower can be elected as the new leader.

  • FOLLOWER_OFFERED: The node was manually nominated as the new leader by means of the biha.set_leader function. This state is required for the nominated node to receive missing data from the old leader.

  • CANDIDATE: The node stands as a candidate in elections of the new leader.

  • REFEREE: The node is the cluster referee. The state is the same both for the referee and referee_with_wal modes.

  • NODE_ERROR: The node is non-operational due to an error. Nodes in this state are unable to vote during elections. Reading from such nodes is prohibited. To get more information about the error, use the biha.error_details function. To restore the faulty node, see Restoring the Node from the NODE_ERROR State.

  • UNKNOWN: The node is offline for the current node.

last_known_state The last known state of the node (text).
since_last_hb The time since the last received heartbeat message (timestamptz).

FAQ