26.1. Архитектура #
Благодаря встроенным возможностям отказоустойчивости Postgres Pro позволяет создать кластер с одним узлом-лидером и несколькими узлами-последователями. Лидер является ведущим узлом BiHA-кластера, а последователи — репликами лидера.
Утилита bihactl позволяет инициализировать кластер и создавать узел-лидер, добавлять узлы-последователи, преобразовывать существующий узел в узел-лидер или узел-последователь в BiHA-кластере, а также проверять статус узлов кластера. Лидер доступен для чтения и записи, в то время как последователи доступны только для чтения и реплицируют данные с лидера в синхронном или асинхронном режиме.
Физическая потоковая репликация, реализованная в BiHA , обеспечивает отказоустойчивость, защищая от отказов серверов и системы хранения данных. При физической репликации файлы WAL узла-лидера синхронно или асинхронно отправляются на узел-последователь и применяются на нём. При синхронной репликации для каждой фиксации транзакции пользователь ожидает подтверждения от узла-последователя. Узел-последователь BiHA-кластера может использоваться для выполнения следующих задач:
Выполнение читающих транзакций в базе данных.
Подготовка отчётов.
Создание таблиц в оперативной памяти для пишущих транзакций.
Подготовка резервной копии узла-последователя.
Восстановление повреждённых блоков данных на узле-лидере путём получения этих блоков с узла-последователя.
Проверка повреждённых записей в файлах WAL.
Физическая потоковая репликация, реализованная в BiHA, обеспечивает защиту от следующих видов отказов:
Отказ узла-лидера. В этом случае статус узла-последователя повышается, и он становится новым лидером кластера. Повышение выполняется либо вручную с помощью функции biha.set_leader, либо автоматически с помощью выборов.
Отказ узла-последователя. Если последователь настроен как асинхронный, отказ никак не отразится на лидере. Если для последователя используется синхронная репликация, отказ приведёт к остановке транзакции на лидере, так как он перестанет получать подтверждение транзакций от последователя и транзакция не сможет завершиться. Подробное описание того, как настроить синхронную репликацию в BiHA-кластере, находится в Настройка репликации.
Сбой соединения между узлом-лидером и узлом-последователем. В этом случае лидер не может отправить, а последователь не может получить данные. Обратите внимание, что если пользователи подключены к лидеру, разрешать пишущие транзакции на последователе нельзя. Любые изменения, сделанные на последователях, нельзя будет восстановить на лидере. Чтобы избежать потери изменений, настраивайте сеть с резервными каналами. Лучше всего настроить свой канал передачи данных для каждого последователя, чтобы предупредить проблемы, связанные с единой точкой отказа.
В аварийной ситуации, например отказе операционной системы или оборудования, можно переустановить Postgres Pro и удалить расширение biha из shared_preload_libraries, чтобы вернуться к работе в максимально короткие сроки.
26.1.1. Конфигурация Postgres Pro #
Для корректной работы BiHA устанавливает некоторые параметры конфигурации Postgres Pro и создаёт ряд вспомогательных объектов:
Утилита bihactl добавляет
bihaв переменную shared_preload_libraries в файле postgresql.conf и, если применимо, в файле postgresql.auto.conf:shared_preload_libraries = 'biha'
Этот параметр необходим для работы BiHA-кластера. Если в shared_preload_libraries уже имеются другие библиотеки,
bihaбудет добавлена в конец списка.Утилита bihactl создаёт следующие файлы:
pg_hba.biha.confдобавляется в файл pg_hba.conf с помощью директивы включения. Файлpg_hba.biha.confсодержит правила аутентификации для роли biha_replication_user на узлах BiHA-кластера:host postgres biha_replication_user all scram-sha-256 host biha_db biha_replication_user all scram-sha-256 host replication biha_replication_user all scram-sha-256
Метод аутентификации по умолчанию — scram-sha-256. Однако, если параметр password_encryption уже был задан в файле postgresql.conf, BiHA будет использовать имеющееся значение. Если вы используете SSL для аутентификации пользователей, метод изменится на
cert.postgresql.biha.confдобавляется в файл postgresql.conf с помощью директивы включения.
Создаётся база данных
biha_db, расширение biha и ряд ролей, специфичных для BiHA. За дополнительной информацией обратитесь к Роли.Создаются слоты репликации с именами формата
biha_node_. Слоты управляются автоматически, изменять или удалять их вручную не нужно.idВ файле
postgresql.biha.confутилита bihactl устанавливает следующие параметры конфигурации Postgres Pro:hot_standby —
on(значение по умолчанию). Этот параметр не рекомендуется изменять.wal_level —
replica(значение по умолчанию). Если уже было задано значениеlogical, BiHA будет использовать имеющееся значение. Этот параметр не рекомендуется изменять.max_wal_senders устанавливается с учётом числа процессов-передатчиков WAL, необходимых для корректной работы BiHA, которое зависит от кворума, заданного в параметре biha.nquorum. Если значение
biha.nquorumравно3или меньше, значениеmax_wal_sendersбудет равно10. В иных случаях значение рассчитывается по следующей формуле:. Имейте это в виду при изменении значения параметракворум_BiHA* 2 + 3max_wal_senders. За подробной информацией об уменьшении значенияmax_wal_sendersи некоторых других параметров конфигурации Postgres Pro обратитесь к Подразделу 26.1.1.1.max_replication_slots — значение равно
max_wal_senders + 1. Минимальное значение —11. Этот параметр не рекомендуется изменять. Учитывайте эту информацию при изменении значения параметраmax_replication_slots.max_slot_wal_keep_size —
5GB. Если значение уже было задано, BiHA будет использовать имеющееся значение. При необходимости значение можно изменить.В отличие от кластера стандартной конструкции ведущий-ведомый, BiHA-кластер хранит файлы WAL на всех узлах, чтобы отстающий узел мог нагнать остальные узлы. Для этого каждый узел использует слоты репликации, определяет самый отстающий узел и сохраняет столько файлов WAL, сколько может потребоваться для отстающего узла.
При настройке BiHA-кластера убедитесь, что вы выбрали оптимальное значение для этого параметра во избежание следующих проблем:
Если количество необходимых файлов WAL превышает значение max_slot_wal_keep_size, старые файлы WAL будут удалены. В результате отстающий узел не получит необходимые данные, изменит своё состояние на NODE_ERROR и остановит репликацию данных.
Если значение параметра max_slot_wal_keep_size равно
-1(что означает, что файлы WAL никогда не удаляются) или превышает доступное дисковое пространство, это может привести к переполнению дискового хранилища.Если значение параметра max_slot_wal_keep_size слишком мало, заданного в нём пространства может оказаться недостаточно для хранения файлов WAL, необходимых, чтобы отстающий узел нагнал остальные узлы и продолжил работу.
wal_keep_size —
1GB. Если значение уже было задано, BiHA будет использовать имеющееся значение. Параметр конфигурацииwal_keep_sizeпомогает сохранять файлы WAL для возможного запуска pg_rewind. Можно изменять его значение в зависимости от нагрузки. Чем больше файлов WAL генерируется, тем выше должно быть значениеwal_keep_size.application_name задан в формате
biha_node_. Этот параметр не рекомендуется изменять.идентификаторlisten_addresses —
*. Этот параметр не рекомендуется изменять.port — устанавливается порт Postgres Pro по умолчанию. Если порт по умолчанию был изменён, BiHA будет использовать имеющееся значение. Этот параметр не рекомендуется изменять.
primary_conninfo, primary_slot_name, synchronous_standby_names изменяются и управляются только через BiHA.
Когда расширение biha загружено и настроено, эти параметры нельзя изменить с помощью ALTER SYSTEM.
Эти параметры хранятся в файле
pg_biha/biha.confа также в разделяемой памяти процесса biha. Когда эти параметры изменяются, biha отправляет сигналSIGHUP, чтобы проинформировать другие процессы об изменениях. Если в это время изменить какие-либо другие параметры и не перечитать конфигурацию, изменённые параметры могут быть перечитаны неожиданно.Postgres Pro ведёт себя вышеописанным образом, только когда расширение biha загружено и настроено, то есть когда библиотека указана в переменной
shared_preload_librariesи установлены необходимые параметры biha.*. В других случаях Postgres Pro работает, как обычно.
Во время работы BiHA создаёт следующие служебные файлы в каталоге данных:
standby.signal — используется для запуска узлов в режиме резервного сервера. Файл необходим для того, чтобы сделать расширение biha доступным только для чтения при запуске Postgres Pro. Файл удаляется с лидера, когда лидер переходит в состояние
LEADER_RW.biha.stateиbiha.conf— файлы в каталогеpg_biha, необходимые для сохранения внутреннего состояния и конфигурации расширения biha.
26.1.1.1. Уменьшение значений параметров Postgres Pro #
В BiHA-кластере успешно уменьшить значения некоторых параметров конфигурации Postgres Pro возможно только с помощью приведённой ниже инструкции.
Используйте эту инструкцию для уменьшения значений следующих параметров:
Предупреждение
Изменяйте эти параметры конфигурации с осторожностью и убедитесь, что они имеют одинаковые значения на всех узлах BiHA-кластера. В противном случае некоторые узлы не смогут продолжить работу.
Уменьшить значения вышеупомянутых параметров конфигурации кластера можно следующим образом:
Включите сервисный режим:
SELECT biha.service_mode(true);
На лидере уменьшите значение необходимого параметра конфигурации.
Остановите и запустите узел-лидер с помощью pg_ctl.
Во время запуска лидер проверяет, что другие узлы работоспособны и продолжают считать его лидером. Если все узлы работают корректно, лидер применяет изменённые значения и успешно запускается. В противном случае лидер завершает работу и выводит в журнал соответствующее сообщение.
Убедитесь, что все узлы получили информацию об изменении параметра конфигурации на лидере.
Для этого можно использовать утилиту pg_controldata или выдержать паузу после перезапуска лидера, чтобы у других узлов было достаточно времени для получения обновлений.
На других узлах уменьшите значение параметра конфигурации таким же образом, как и на лидере.
Остановите и запустите узлы с помощью pg_ctl.
Отключите сервисный режим:
SELECT biha.service_mode(false);
26.1.2. Варианты конфигурации кластера #
Есть несколько вариантов конфигурации кластера.
Три и более узлов, один из которых является лидером, а остальные — последователями.
Ниже представлены возможные сценарии при отказе лидера или сбое сетевого подключения:
При отказе текущего лидера новый лидер избирается автоматически. Чтобы стать лидером, последователь должен получить максимальное количество голосов. Количество голосов должно быть больше или равно значению, заданному в параметре biha.nquorum.
При сбоях сетевого соединения внутри кластера BiHA кластер может разделиться на несколько групп узлов. В этом случае новый лидер избирается во всех группах, в которых количество узлов больше или равно значению biha.nquorum. После восстановления соединения лидер кластера выбирается между старым и новоизбранным лидером в зависимости от значения
term. Узел с наибольшим значениемtermстановится новым лидером. Рекомендуется установить значение biha.minnodes равным значению biha.nquorum.
Кластер из двух узлов, состоящий из лидера и последователя.
Примечание
Не рекомендуется использовать кластер из двух узлов, поскольку такая конфигурация может вызвать проблемы разделения кластера. Чтобы их избежать, добавьте узел-рефери.
Ниже представлены возможные сценарии при отказе лидера или сбоях сети:
При отказе лидера узел-последователь автоматически становится новым лидером, если для параметра конфигурации biha.nquorum установлено значение
1.Если между лидером и последователем происходят сетевые сбои, и для обоих параметров конфигурации biha.nquorum и biha.minnodes установлено значение
1, кластер может разделиться на двух лидеров, доступных для чтения и записи. Подобных проблем позволяет избежать узел-рефери.
Конфигурация с одним узлом-лидером. Этот вариант возможно использовать, пока не будут настроены последователи. Логично, что узел нельзя заменить при сбое ввиду отсутствия последователей, которые могут стать лидером.
Кластер с тремя узлами, состоящий из лидера, последователя и рефери. Узел-рефери используется для голосования при выборе нового лидера, но сам не может стать лидером. При возникновении сбоев кластер с рефери ведёт себя как кластер с тремя узлами (лидером и двумя последователями). Чтобы подробнее узнать о рефери, обратитесь к Узел-рефери в BiHA-кластере.
Каскадный BiHA-кластер, состоящий из лидера и двух последователей, где Последователь 1 реплицирует данные с лидера, а Последователь 2 реплицирует данные с Последователя 1. Используя каскадную репликацию, можно развернуть BiHA-кластер в разных центрах обработки данных.
Многоуровневый геораспределённый и катастрофоустойчивый кластер BiHA (geo-distributed and disaster-resilient BiHA, GDBiHA). Кластер GDBiHA состоит из двух или более сегментов — логических узлов, которые объединяют один или несколько физических узлов кластера BiHA, размещённых в одном центре обработки данных (ЦОД). За подробной информацией обратитесь к Подразделу 26.1.5.3.
Примечание
Вы можете вручную назначить лидера или главного последователя с помощью функции biha.set_leader.
Рекомендуется установить для параметра biha.nquorum значение, большее или равное половине числа узлов в кластере.
При добавлении или удалении узлов из кластера всегда проверяйте значение biha.nquorum, учитывая наибольшее количество узлов, но не меньше, чем установлено в
biha.nquorum.
26.1.3. Выборы #
Elections — это процесс определения лидера, который проводят последователи при отказе текущего лидера. Если в кластере несколько сегментов, выборы для определения лидера или главного последователя проводятся независимо в каждом сегменте.
Основные условия для выборов следующие:
Выборы проводятся с учётом кворума кластера, то есть минимального количества узлов, участвующих в выборах. Значение кворума задаётся в параметре biha.nquorum при инициализации кластера командой bihactl cluster init.
В выборах принимают участие только узлы, расположенные в одном сегменте. Узлы, в которых для параметра biha.can_vote установлено значение
false, а также узлы в состоянииNODE_ERRORисключаются из голосования и игнорируются параметромbiha.nquorum.Чтобы выборы начались, последователи должны считать, что лидер не в сети, то есть не получить максимальное количество сообщений контроля состояния, заданное в параметре biha.heartbeat_max_lost.
Чтобы предложить себя в качестве кандидата в лидеры, узел должен иметь самый большой LSN в кластере. В синхронном кластере можно также использовать параметр biha.priority для приоритизации узлов.
Чтобы узел мог быть избранным, для его параметров biha.can_be_leader и biha.can_vote должно быть установлено значение
true.
Если в кластере только два узла, и вы хотите избежать возможных проблем разделения кластера во время выборов, создайте рефери, который участвует в голосовании так же, как последователи. За подробной информацией обратитесь к Узел-рефери в BiHA-кластере.
Например, в случае отказа одного узла-последователя в кластере из трёх узлов, где значение , узел-лидер продолжит работать. При отказе лидера в таком кластере два оставшихся последователя начнут выборы. После избрания нового лидера значение поколения кластера term увеличивается на единицу для всех узлов, то есть для нового лидера и оставшихся последователей biha.nquorum=2, а для старого лидера останется равным term=2. Когда старый лидер возвращается в кластер, происходит его понижение, то есть старый лидер становится последователем.term=1
После избрания нового лидера последователи начинают получать файлы WAL уже от него. Обратите внимание, что при выборе нового лидера старый лидер понижается и становится недоступным для пишущих транзакций, чтобы избежать проблем разделения кластера (split brain). Вы можете вручную повысить старого лидера, используя функцию biha.set_leader. Механизмы кворума и поколения реализованы в BiHA на базе алгоритма консенсуса Raft.
26.1.4. Узел-рефери в BiHA-кластере #
В отказоустойчивом кластере можно создать узел-рефери, который участвует в выборах и помогает избежать потенциальной проблемы разделения кластера (split brain), состоящего только из лидера и последователя. В этом случае после создания рефери установите значение 2 для обоих параметров конфигурации biha.nquorum и biha.minnodes.
Для рефери требуется намного меньше дискового пространства, ресурсов процессора и памяти, чем для обычных узлов BiHA. За подробной информацией обратитесь к разделу Минимальные аппаратные требования для рефери.
По умолчанию на рефери отсутствует база данных postgres и пользовательские данные. За подробной информацией обратитесь к разделу База данных postgres на рефери.
Расширение biha поддерживает следующие режимы работы рефери:
Режим
referee. В этом режиме узел принимает участие только в выборах лидера, но не в репликации данных. Кроме того, для рефери не создаются слоты репликации ни на лидере, ни на последователях.Режим
referee_with_wal. В этом режиме узел участвует не только в выборах лидера таким же образом, как и в режимеreferee, но и в репликации данных, и получает весь WAL с узла-лидера. Если на момент начала выборов больше всего записей WAL среди узлов кластера накопится на узле-рефери, то есть у рефери будет наибольший LSN, узел-последователь будет пытаться получить недостающие файлы WAL с рефери. Этот процесс важен для того, чтобы узел-рефери не перешел в состояниеNODE_ERROR, что возможно при расхождении WAL. Дляreferee_with_wal,apply lagравенNULLиapply ptrневозможно изменить, так как рефери не применяет данные пользователя.
Вне зависимости от установленного режима работы узла-рефери, он отправляет и получает сообщения о контроле состояния по каналу управления, в том числе с использованием SSL, участвует в выборах так же, как и узлы-последователи, поддерживает функции мониторинга кластера и должен учитываться, когда задаётся значение параметра biha.minnodes. Обратите внимание, что рефери — это конечное состояние узла: его нельзя сделать лидером при помощи функции biha.set_leader, и он не может стать узлом-последователем. Если по какой-либо причине последователь «не видит» лидера, но его видит рефери, рефери не позволит последователю стать лидером. Если лидер с более высоким значением поколения term подключится к рефери, рефери понизит статус лидера с более низким значением term до последователя.
26.1.4.1. Минимальные аппаратные требования для рефери #
В системах Linux для минимальной конфигурации узла-рефери в режиме referee требуется 1 ядро ЦП и 1 ГБ ОЗУ. Этого достаточно для участия в выборах.
Если рефери используется в режиме referee_with_wal, при котором рефери участвует в репликации данных и получает от лидера WAL в полном объёме, ресурсы для рефери необходимо выделять с учётом нагрузки на кластер.
Для операционных систем, отличных от Linux, необходимо выделять ресурсы в соответствии с минимальными требованиями используемой операционной системы.
Примечание
Так как рефери создаётся через частичное копирование лидера, он наследует и параметры конфигурации лидера. Чтобы избежать избыточного потребления ресурсов, перед первым запуском рефери убедитесь, что его параметры конфигурации соответствуют реальным аппаратным ресурсам сервера, на котором запущен рефери. Например, установите для параметра shared_buffers значение по умолчанию 128 МБ.
26.1.4.2. База данных postgres на рефери #
При добавлении рефери, утилита pg_basebackup создаёт частичную резервную копию лидера. Это значит, что, по умолчанию, на рефери с лидера копируются только база данных biha_db и системные таблицы. База данных postgres и пользовательские данные не копируются. Это сделано намеренно для уменьшения потребления ресурсов.
Однако некоторые утилиты и системы мониторинга используют базу данных postgres для подключения к узлам. Если необходимо, чтобы база данных postgres присутствовала на рефери, вы можете указать параметр --referee-with-postgres-db при добавлении узла в режиме referee или referee_with_wal. Этот параметр копирует на рефери базу данных postgres со всеми объектами. Для рефери в режиме referee_with_wal также применяются записи WAL, относящиеся к базе данных postgres. Это значит, что все новые объекты, созданные в базе данных postgres, будут также созданы на рефери в режиме referee_with_wal.
Примечание
Обратите внимание, что вышесказанное относится к базе данных postgres, создаваемой при инициализации экземпляра. Если удалить базу данных postgres на лидере, она также будет удалена и на рефери без возможности восстановления.
26.1.5. Геораспределённость и катастрофоустойчивость #
BiHA предоставляет следующие возможности географической распределённости и катастрофоустойчивости, которые позволяют разворачивать BiHA-кластеры в разных географических локациях для обеспечения доступности во время региональных сбоев:
26.1.5.1. Базовая функциональность геораспределённости и катастрофоустойчивости #
Базовая функциональность BiHA позволяет размещать узлы кластера в разных удалённых центрах обработки данных. По умолчанию, в таких кластерах лидер является источником репликации для всех последователей. Однако можно настроить каскадную репликацию, чтобы сократить нагрузку на лидера.
Например, можно распределить узлы трёхузлового BiHA-кластера по трём разным центрам обработки данных, где можно быстро переключиться на любого из последователей в случае отказа лидера:
Рисунок 26.1. Базовая геораспределённость в трёх центрах обработки данных
Можно также разместить лидера и двух последователей BiHA-кластера в ЦОДе 1, а дополнительного Последователя 3 в удалённом ЦОДе 2 использовать как георезерв. Последователь 3 работает лишь в качестве резерва и не может ни участвовать в выборах, ни стать лидером:
Рисунок 26.2. Базовая геораспределённость с последователем в качестве георезерва
26.1.5.2. Каскадная репликация #
Каскадная репликация позволяет снизить сетевую нагрузку в кластерах, распределённых между разными центрами обработки данных, а также снизить нагрузку на лидера.
Решение BiHA предоставляет ряд параметров, таких как biha.max_replicas и biha.preferred_roles, предназначенных для автоматической настройки каскадной репликации. После настройки этих параметров каждый узел кластера независимо выбирает свой источник репликации. В случае обновления топологии кластера, например, изменения лидера или количества узлов, каскадная репликация устанавливается автоматически.
За подробной информацией о том, как настроить каскадную репликацию в BiHA-кластере, обратитесь к Настройка каскадной репликации.
На следующей схеме изображён пример каскадного BiHA-кластера, состоящего из пяти узлов, распределённых между двумя центрами обработки данных:
Рисунок 26.3. Репликация в каскадном BiHA-кластере
BiHA-кластер на схеме выше работает следующим образом:
Лидери два последователя находятся вЦОДе 1, который является главным центром обработки данных.Последователь 1иПоследователь 2реплицируют данные напрямую сЛидера.Для всех трёх узлов заданы одинаковые значения параметров конфигурации biha.preferred_roles и biha.max_replicas.
biha.preferred_roles = LFозначает, что эти узлы всегда будут предпочитать лидера в качестве источника репликации.biha.max_replicas = 2означает, что эти узлы могут одновременно реплицировать данные не более чем на двух последователей.Последователь 3иПоследователь 4находятся вЦОДе 2, который является резервным центром обработки данных.Последователь 3реплицирует данные сПоследователя 2и является источником репликации дляПоследователя 4.Для обоих узлов задано одинаковое значение параметров конфигурации biha.preferred_roles и biha.max_replicas.
biha.preferred_roles = FLозначает, что эти узлы всегда будут предпочитать последователя в качестве источника репликации.biha.max_replicas = 1означает, что эти узлы могут одновременно реплицировать данные только на одного последователя.Помимо этого, для их параметров конфигурации biha.can_vote и biha.can_be_leader задано значение
false. Это сделано для того, чтобы узлы, размещённые в резервном центре обработки данных, не могли ни голосовать, ни выдвигать себя в качестве кандидатов на выборах.
Предположим, что произошёл отказ Лидера:
Рисунок 26.4. Репликация в каскадном BiHA-кластере в случае отказа лидера
Каскадная репликация автоматически перенастраивается следующим образом:
Последователь 1избирается в качестве новогоЛидера.Последователь 2выбирает новогоЛидерасвоим источником репликации.Лидертеперь реплицирует данные только наПоследователя 2.Последователь 3иПоследователь 4продолжают репликацию как и прежде, так как их источники репликации не изменились.
26.1.5.3. Многоуровневая геораспределённость и катастрофоустойчивость #
Решение BiHA позволяет создать многоуровневый геораспределённый и катастрофоустойчивый кластер (GDBiHA) для обеспечения эффективной работы 24/7 при высоких нагрузках. Кластер GDBiHA разделён на сегменты — логические узлы, которые объединяют один или несколько узлов кластера BiHA. Сегменты расположены в географически удалённых центрах обработки данных и имеют собственные системы выборов: параметры biha.minnodes и biha.nquorum настраиваются на каждом сегменте и наследуются узлами этих сегментов.
На следующей схеме изображена типичная структура кластера GDBiHA, распределённого между двумя центрами обработки данных:
Рисунок 26.5. Схема многоуровневого геораспределённого и катастрофоустойчивого кластера BiHA (GDBiHA)
Кластер GDBiHA на схеме выше состоит из следующих компонентов:
Кластер GDBiHA— логический корневой узел с идентификатором 1111, который объединяет два сегмента. Корневой узел является родительским для сегментов. У корневого узла нет родителя, и его нельзя удалить.Сегмент-лидер— логический узел, который объединяет физические узлы, расположенные в центре обработки данныхЦОД 1. Этот сегмент создаётся по умолчанию при инициализации кластера и всегда имеет идентификатор 111. Этот сегмент является лидером, так как в нём расположен лидер кластера GDBiHA (Узел-лидер) и поддерживаются операции записи. В случае отказаСегмента-лидеранеобходимо вручную переключиться наСегмент-последовательс помощью функции biha.set_leader.Сегмент-последователь— логический узел, который объединяет физические узлы, расположенные в центре обработки данныхЦОД 2. Этот сегмент создаётся вручную, а его идентификатор задаётся пользователем (в данном случае 222). Этот сегмент не поддерживает операции записи.Узел-лидер— физический узел, лидерКластера GDBiHA. В случае отказаУзла-лидерановый лидер избирается из узловСегмента-лидерас помощью стандартной процедуры выборов BiHA.Главный узел-последователь 3— физический узел-последователь, который исполняет функции лидера вСегменте-последователе. В случае отказаГлавного узла-последователя 3новый главный последователь избирается из узловСегмента-последователяс помощью стандартной процедуры выборов BiHA.Узел-последователь 1,Узел-последователь 2,Узел-последователь 4иУзел-последователь 5— физические узлы-последователи в кластере GDBiHA.
Узлы в GDBiHA-кластере могут работать на разных уровнях. Физические узлы (с идентификаторами 1-6) работают на уровне 1 (физический уровень). Сегменты (с идентификаторами 111 и 222) работают на уровне 2 (сегментный уровень). Кластер (с идентификатором 1111) работает на уровне 3 (кластерный уровень).
Чтобы проверить, на каком уровне работает узел, а также посмотреть другие детали конфигурации всех узлов, вызовите функцию biha.config:
id | term | nquorum | minnodes | heartbeat_send_period | heartbeat_max_lost | no_wal_on_follower | sync_standbys_min | priority | can_be_leader | can_vote | mode | proxima_status | name | repl_pref_roles | max_replicas | config_version | level | parent_id
------+------+---------+----------+-----------------------+--------------------+--------------------+-------------------+----------+---------------+----------+---------+----------------+----------------+-----------------+--------------+----------------+-------+-----------
1 | 1 | 2 | 2 | 1000 | 10 | 20000 | -2 | -1 | t | t | regular | 0 | biha_node_1 | L | 2147483647 | 17 | 1 | 111
2 | 1 | 2 | 2 | 1000 | 10 | 20000 | -2 | -1 | t | t | regular | 0 | biha_node_2 | L | 2147483647 | 17 | 1 | 111
3 | 1 | 2 | 2 | 1000 | 10 | 20000 | -2 | -1 | t | t | regular | 0 | biha_node_3 | L | 2147483647 | 17 | 1 | 111
4 | 1 | 2 | 2 | 1000 | 10 | 20000 | -2 | -1 | t | t | regular | 0 | biha_node_4 | L | 2147483647 | 17 | 1 | 222
5 | 1 | 2 | 2 | 1000 | 10 | 20000 | -2 | -1 | t | t | regular | 0 | biha_node_5 | L | 2147483647 | 17 | 1 | 222
6 | 1 | 2 | 2 | 1000 | 10 | 20000 | -2 | -1 | t | t | regular | 0 | biha_node_6 | L | 2147483647 | 17 | 1 | 222
111 | 1 | 2 | 2 | 1000 | 10 | 20000 | -2 | -1 | t | t | regular | 0 | biha_node_111 | L | 2147483647 | 17 | 2 | 1111
222 | 1 | 2 | 2 | 1000 | 10 | 20000 | -2 | -1 | t | t | regular | 0 | biha_node_222 | L | 2147483647 | 17 | 2 | 1111
1111 | 1 | 1 | 1 | 1000 | 10 | 20000 | -2 | -1 | t | t | regular | 0 | biha_node_1111 | L | 2147483647 | 17 | 3 |
(9 rows)Вы можете настраивать узлы, сегменты и кластер GDBiHA с помощью функций расширения biha.
За подробной информацией о развёртывании кластера GDBiHA обратитесь к Подготовка многоуровневого геораспределённого и катастрофоустойчивого кластера BiHA (GDBiHA).
26.1.5.3.1. Репликация в кластере GDBiHA #
По умолчанию репликация в кластере GDBiHA является каскадной и работает следующим образом:
Узел-последователь 1иУзел-последователь 2реплицируют данные сУзла-лидера.Главный последователь 3реплицирует данные сУзла-лидера.Узел-последователь 4иУзел-последователь 5реплицируют данные сГлавного узла-последователя 3.
За подробной информацией о том, как настроить каскадную репликацию, обратитесь к Настройка каскадной репликации.
26.1.5.3.2. Особенности и ограничения #
Автоматические выборы на уровне сегментов не поддерживаются. Вы можете изменить сегмент-лидер вручную с помощью функции biha.set_leader.
GDBiHA поддерживает стандартную каскадную репликацию PostgreSQL, включая все указанные ограничения. За подробной информацией обратитесь к Подразделу 25.2.7.
Перемещение одного узла или всех узлов из одного сегмента в другой не поддерживается.
Рефери в режиме
referee_with_walне поддерживается в качестве источника репликации в сегменте-последователе. Поэтому на узлах, размещённых в сегменте-последователе, для параметра biha.preferred_roles не указывайте значениеR.В следующих сценариях автоматического переключения возможен сбой процесса назначения нового лидера, что потребует вмешательства со стороны администратора:
одновременная потеря лидера и главного последователя до завершения процесса выборов;
выборочная изоляция сегментов, при которой разные узлы одного сегмента видят разный набор узлов из другого сегмента;
длительный процесс деградации сети, сопровождающийся постепенным снижением пропускной способности с последующим полным отключением.
26.1. Architecture #
With built-in high-availability capabilities, Postgres Pro allows creating a cluster with one leader node and several follower nodes. The leader is the primary node of the BiHA cluster, while followers are its replicas.
The bihactl utility is used to initialize the cluster and create the leader, add followers, convert existing cluster nodes into the leader or the follower in the BiHA cluster as well as check the cluster node status. The leader is available for read and write transactions, while followers are read-only and replicate data from the leader in the synchronous or asynchronous mode.
Physical streaming replication implemented in BiHA ensures high availability by providing protection against server failures and data storage system failures. During physical replication, WAL files of the leader node are sent, synchronously of asynchronously, to the follower node and applied there. In case of synchronous replication, with each commit a user waits for the confirmation from the follower that the transaction is committed. The follower in the BiHA cluster can be used to:
Perform read transactions in the database.
Prepare reports.
Create in-memory tables open for write transactions.
Prepare a follower node backup.
Restore bad blocks of data on the leader node by receiving them from the follower node.
Check corrupt records in WAL files.
Physical streaming replication implemented in BiHA provides protection against several types of failures:
Leader node failure. In this case, a follower node is promoted and becomes the new leader of the cluster. The promotion can be done both manually using the biha.set_leader function or automatically by means of elections.
Follower node failure. If a follower node uses asynchronous replication, the failure by no means affects the leader node. If a follower node uses synchronous replication, this failure causes the transaction on the leader node to stop. This happens because the leader stops receiving transaction confirmations from the follower and the transaction fails to end. For details on how to set up synchronous replication in the BiHA cluster, see Replication Configuration.
Network failure between the leader node and follower nodes. In this case, the leader node cannot send and follower nodes cannot receive any data. Note that you cannot allow write transactions on follower nodes if users are connected to the leader node. Any changes made on follower nodes will not be restored on the leader node. To avoid this, configure your network with redundant channels. It is best to provide each follower with its own communication channel to avoid single point of failure issues.
In case of an emergency, such as operating system or hardware failure, you can reinstall Postgres Pro and remove the biha extension from shared_preload_libraries to go back to work as soon as possible.
26.1.1. Postgres Pro Configuration #
For proper operation, BiHA sets some Postgres Pro configuration parameters and creates a number of auxiliary objects:
The bihactl utility adds
bihato the shared_preload_libraries variable of the postgresql.conf file and, if applicable, of the postgresql.auto.conf file:shared_preload_libraries = 'biha'
This parameter is required for operation of the BiHA cluster. If shared_preload_libraries already contains other preloaded libraries,
bihais added to the end of the list.The bihactl utility creates the following files:
pg_hba.biha.confis added to the pg_hba.conf file by means of the include directive. Thepg_hba.biha.conffile contains authentication rules for the biha_replication_user role on the BiHA cluster nodes:host postgres biha_replication_user all scram-sha-256 host biha_db biha_replication_user all scram-sha-256 host replication biha_replication_user all scram-sha-256
The default authentication method is scram-sha-256. However, if the password_encryption parameter has been already set in postgresql.conf, BiHA uses the existing value. If you use SSL for user authentication, the method changes to
cert.postgresql.biha.confis added to the postgresql.conf file by means of the include directive.
The
biha_dbdatabase, the biha extension, and a number of BiHA-specific roles are created. For more information, see Roles.Replication slots with names set in the
biha_node_format are created. These slots are managed automatically without the need to modify or delete them manually.idIn the
postgresql.biha.conffile, bihactl sets the following Postgres Pro configuration parameters:hot_standby is set to
on(the default). It is not recommended to modify this parameter.wal_level is set to
replica(the default). If the value has already been set tological, BiHA uses the existing value. It is not recommended to modify this parameter.max_wal_senders is set based on the number of WAL senders required for proper operation of BiHA that depends on the quorum set in biha.nquorum. If the
biha.nquorumvalue is3or less, themax_wal_sendersvalue is10. Otherwise, the value is calculated based on the following formula:. Consider this when modifying theBiHA_quorum* 2 + 3max_wal_sendersvalue. For more information about decreasingmax_wal_sendersand some other Postgres Pro configuration parameters, see Section 26.1.1.1.max_replication_slots is
max_wal_senders + 1. The minimum value is11. Consider this when modifying themax_replication_slotsvalue.max_slot_wal_keep_size is set to
5GB. If the value has already been set, BiHA uses the existing value. You can modify the value if required.Unlike standard primary-standby configuration, the BiHA cluster stores WAL files on all nodes to ensure that a lagging node can catch up. To achieve this, each node uses replication slots, identifies the node that is lagging the most, and retains as many WAL files as the lagging node might require.
When setting up the BiHA cluster, ensure that you select the optimal value for this parameter to avoid the following issues:
If the number of required WAL files is higher than the max_slot_wal_keep_size value, the old WAL files are deleted. As a result, the lagging node cannot receive the required data, changes its state to NODE_ERROR, and stops data replication.
If the max_slot_wal_keep_size value is set to
-1(which means that WAL files are never deleted) or if it exceeds the available disk size, this may lead to disk storage overflow.If the max_slot_wal_keep_size value is too small, there may not be enough space to keep WAL files required for the lagging node to catch up and continue operation.
wal_keep_size is set to
1GB. If the value has already been set, BiHA uses the existing value. Thewal_keep_sizeconfiguration parameter helps to keep WAL files for a potential run of pg_rewind. You can modify the value depending on the workload. The more WAL files are generated, the higher thewal_keep_sizevalue must be set.application_name is set in the
biha_node_format. It is not recommended to modify this parameter.idlisten_addresses is set to
*. It is not recommended to modify this parameter.port is set to the default Postgres Pro value. If the default port has been changed, BiHA uses the existing value. It is not recommended to modify this parameter.
primary_conninfo, primary_slot_name, synchronous_standby_names are modified and managed by BiHA only.
When biha is loaded and configured, you cannot modify these parameters using ALTER SYSTEM.
These parameters are stored in the
pg_biha/biha.conffile, as well as in the shared memory of the biha process. When these parameters are modified, biha sends theSIGHUPsignal for other processes to be informed about the changes. If you modify any other parameters during this change and do not send a signal to reread the configuration, the parameters that you have changed may be unexpectedly reread.Postgres Pro behaves as described above only when biha is loaded and configured, i.e. when the extension is present in the
shared_preload_librariesvariable and the required biha.* parameters are configured. Otherwise, Postgres Pro operates normally.
During operation, BiHA creates the following service files in the database directory:
standby.signal is used to start nodes in standby mode. It is required to make biha read-only at the start of Postgres Pro. This file is deleted from the leader node when its state changes to
LEADER_RW.biha.stateandbiha.confare files in thepg_bihadirectory required to save the internal state and configuration of biha.
26.1.1.1. Decreasing Postgres Pro Parameter Values #
In a BiHA cluster, some Postgres Pro configuration parameter values can only be successfully decreased using the procedure described in this section.
Use this procedure if you need to decrease any of the following parameters:
Warning
Be careful when modifying these configuration parameters and ensure their values are the same on all BiHA cluster nodes. Otherwise, some of the nodes may fail to continue operation.
You can decrease the above mentioned configuration parameters as follows:
Enable the service mode:
SELECT biha.service_mode(true);
On the leader, decrease the value of the required configuration parameter.
Stop and start the leader using pg_ctl.
During startup, the leader verifies other nodes are operational and continue recognizing its leader role. If all nodes operate correctly, the leader applies the modified value and starts successfully. Otherwise, the leader shuts down and provides the corresponding log message.
Ensure that all nodes receive information that the configuration parameter has been modified on the leader.
You can use the pg_controldata utility or, alternatively, make a pause after the leader restarts so that other nodes could have enough time to receive the updates.
On other nodes, decrease the configuration parameter to the value you have just set on the leader.
Stop and start the nodes using pg_ctl.
Disable the service mode:
SELECT biha.service_mode(false);
26.1.2. Variants of Cluster Configuration #
There are several variants of cluster configuration.
Three and more nodes where one node is the leader and the rest are the followers.
Below are possible scenarios for the cases of the leader failure or network connection interruption:
When the current leader is down, the new leader is elected automatically. To become the leader, a follower must have the highest number of votes. The number of votes must be higher or equal to the value configured in biha.nquorum.
In case of network connection interruptions inside the BiHA cluster, the cluster may split into several groups of nodes. In this case, the new leader node is elected in all groups, where the number of nodes is higher or equal to the biha.nquorum value. After the connection is restored, the new leader will be chosen between the old one and the newly elected one depending on the
termvalue. The node with the highesttermbecomes the new leader. It is recommended to set the biha.minnodes value equal to the biha.nquorum value.
Two-node cluster consisting of the leader and the follower.
Note
Using two-node clusters is not recommended as such configurations can cause split-brain issues. To avoid such issues, you can add a referee node.
Below are possible scenarios for the leader or network failures:
When the leader is down, the follower node becomes the new leader automatically if the biha.nquorum configuration parameter is set to
1.When network interruptions occur between the leader and the follower, and both the biha.nquorum and biha.minnodes configuration parameters are set to
1, the cluster may split into two leaders available for reads and writes. The referee node helps avoiding such issues.
Single-node configuration consisting of the leader only. A possible variant that can be used to wait until follower nodes are configured. Logically, the node cannot be replaced once down, since there are no follower nodes that can become the leader node.
Three-node cluster consisting of the leader, the follower, and the referee. The referee is a node used for voting in elections of the new leader, but it cannot become the leader. In case of faults, the cluster with the referee behaves the same way as the three-node cluster (the leader and two followers). To learn more about the referee, see The Referee Node in the BiHA Cluster.
Cascading BiHA cluster consisting of the leader and two followers where Follower 1 replicates data from the leader and Follower 2 replicates data from Follower 1. Using cascading replication, you can deploy your BiHA cluster in different data centers.
Multi-level geo-distributed and disaster-resilient BiHA (GDBiHA) cluster. The GDBiHA cluster consists of two or more segments — logical nodes that unite one or more physical BiHA cluster nodes located in one data center. For more information, see Section 26.1.5.3.
Note
You can set the leader or front follower manually with the biha.set_leader function.
The recommended value of biha.nquorum is higher or equal to the half of the cluster nodes.
When you add or remove nodes from your cluster, always revise the biha.nquorum value considering the highest number of nodes, but not less than set in
biha.nquorum.
26.1.3. Elections #
Elections are a process conducted by the follower nodes to determine a new leader node when the current leader is down. If your cluster have multiple segments, elections are held in each segment independently to elect either the leader or the front follower.
Basic conditions of the elections are the following:
Elections are held based on the cluster quorum, which is the minimum number of nodes that participate in the elections. The quorum value is set in the biha.nquorum parameter when initializing the cluster with the bihactl cluster init command.
Only nodes located in the same segment are able to participate in elections. Nodes with the biha.can_vote parameter set to
falseand nodes in theNODE_ERRORstate are excluded from voting and ignored bybiha.nquorum.For the elections to begin, the followers must consider the leader offline, i.e., miss the maximum number of heartbeats from the leader set in biha.heartbeat_max_lost.
To propose itself as a candidate for leader, a node must have the greatest LSN in the cluster. In a synchronous cluster, you can also use the biha.priority parameter to prioritize the nodes.
To be elected, a node must have the biha.can_be_leader and biha.can_vote parameters set to
true.
If your cluster has only two nodes and you want to avoid potential split-brain issues in case of elections, you can set up a referee node that participates in the elections in the same way as followers. To learn more, see The Referee Node in the BiHA Cluster.
For example, if you have a cluster with three nodes where and one follower node is down, the cluster leader will continue to operate. If the leader is down in such a cluster, two remaining followers start elections. After the new leader node is elected, the node generation specified in the term is incremented for all cluster nodes. More specifically, the new leader and the remaining followers have biha.nquorum=2, while for the old leader the value is left as term=2. Therefore, when the old leader is back in the cluster, it goes through demotion, i.e. turns into a follower. term=1
After the new leader is set, followers of the cluster start receiving WAL files from this new cluster leader. Note that once the new leader is elected, the old leader is demoted and is not available for write transactions to avoid split-brain issues. You can promote the old leader manually using the biha.set_leader function. Both the cluster quorum and the term concepts are implemented in BiHA based on the Raft consensus algorithm.
26.1.4. The Referee Node in the BiHA Cluster #
The biha extension allows you to set up the referee node that participates in elections and helps to avoid potential split-brain issues if your cluster has only two nodes, i.e. the leader and one follower. In this case, use the referee node and set both biha.nquorum and biha.minnodes configuration parameters to 2.
The referee node requires much less disk space, CPU, and RAM than regular BiHA nodes. For more information, refer to Minimum Hardware Requirements for the Referee.
By default, the postgres database and user data are not present on the referee node. For more information, refer to The postgres Database on the Referee.
The biha extension provides the following referee operation modes:
The
refereemode. In this mode, the node only takes part in elections of the leader and does not participate in data replication, and no replication slots are created on the leader and follower nodes for the referee.The
referee_with_walmode. In this case, the node participates both in the leader elections, in the same way as in therefereemode, and data replication and receives the entire WAL from the leader node. If the referee node has the most WAL records in the cluster when the elections begin, i.e. has the greatest LSN, the follower node tries to get missing WAL files from the referee. This process is also important for the referee node to avoid entering theNODE_ERRORstate, which may be the case if WALs diverge. For thereferee_with_wal,apply lagisNULLandapply ptrcannot be monitored, as the referee does not apply user data.
Regardless of the mode set for the referee, it sends and receives heartbeats over the control channel, including using SSL, participates in the elections in the same way as follower nodes, supports cluster monitoring functions, and must be taken into account when setting the biha.minnodes configuration parameter. Note that the referee is the final state of the node and it cannot be switched to the leader node using the biha.set_leader function, nor can it become the follower node. If for some reason the follower does not “see” the leader but the referee does, the referee does not allow the follower to become the leader. If the leader node with greater term connects to the referee node, the referee demotes the leader with lower term and makes it the follower.
26.1.4.1. Minimum Hardware Requirements for the Referee #
On Linux systems, the minimum configuration of the referee node in the referee mode requires 1 CPU core and 1 GB RAM, which is enough for participating in elections.
If you use the referee in the referee_with_wal mode, where the referee participates in data replication and receives the entire WAL from the leader, you must allocate resources for the referee considering workloads of your cluster.
For operating systems other than Linux, you must allocate resources according to the minimum requirements for your specific operating system.
Note
Note that the referee is created via partial copy of the leader and, as a result, inherits its configuration parameters. To avoid unnecessary resource consumption, before you start the referee for the first time, ensure its configuration parameters are aligned with the actual hardware resources of the server the referee is running on. For example, set shared_buffers to the default 128 MB.
26.1.4.2. The postgres Database on the Referee #
When adding the referee node, the pg_basebackup utility makes a partial backup of the leader. It means that, by default, only the biha_db database and system tables are copied to the referee node from the leader, while the postgres database and user data are not copied. It was designed intentionally to decrease resource consumption.
However, some utilities and monitoring systems connect to nodes via the postgres database. If you need the postgres database to be present on the referee node, you can specify the --referee-with-postgres-db option when adding a node in referee or referee_with_wal modes. This option copies the postgres database with all the objects to the referee node. For referee_with_wal, WAL records related to the postgres database are also applied, meaning that all new objects created in the postgres database are also created on the referee in the referee_with_wal mode.
Note
Note that this refers to the postgres database created during instance initialization. If you delete the postgres database from the leader, it is also deleted on the referee, and you cannot recreate it.
26.1.5. Geographical Distribution and Disaster Resilience #
BiHA provides the following geographical distribution and disaster resilience features that allow deploying BiHA clusters in different geographic locations to ensure availability during regional failures:
26.1.5.1. Basic Geographical Distribution and Disaster Resilience Functionality #
The basic BiHA functionality allows locating cluster nodes in different redundant data centers. By default, in such clusters, the leader is the replication source for all followers. However, you can configure cascading replication to reduce workloads on the leader.
For example, you can distribute nodes of your three-node BiHA cluster across three different data centers where each follower can quickly take over if the leader fails:
Figure 26.1. Basic Geographical Distribution across Three Data Centers
You can also locate the leader and two followers of your BiHA cluster in Data Center 1 while keeping another additional Follower 3 in a geo-redundant Data Center 2. Follower 3 only operates as a standby and cannot participate in elections or become the leader:
Figure 26.2. Basic Geographical Distribution with a Geo-Redundant Follower
26.1.5.2. Cascading Replication #
Cascading replication allows decreasing network workloads in clusters distributed across different data centers, as well as decreasing workloads on the leader.
The BiHA solution provides a set of parameters, such as biha.max_replicas and biha.preferred_roles, designed to automatically configure cascading replication. Once you set these parameters, each node of your cluster independently selects its replication source. In case of cluster topology updates, for example, change of the leader or number of nodes, cascading replication is established automatically.
For more information on how to configure cascading replication in your BiHA cluster, refer to Configuring Cascading Replication.
The following diagram shows an example of a cascading BiHA cluster consisting of five nodes distributed across two data centers:
Figure 26.3. Replication in a Cascading BiHA Cluster
The BiHA cluster on the diagram above operates as follows:
Leaderand two followers locate inData Center 1, which is the primary data center.Follower 1andFollower 2replicate data directly fromLeader.All three nodes have the same values of biha.preferred_roles and biha.max_replicas configuration parameters.
biha.preferred_roles = LFmeans that these nodes would always prefer the leader as their replication source.biha.max_replicas = 2means that these nodes can replicate data to no more than two followers at once.Follower 3andFollower 4locate inData Center 2, which is the standby data center.Follower 3replicate data fromFollower 2and is a replication source forFollower 4.Both nodes have the same values of biha.preferred_roles and biha.max_replicas configuration parameters.
biha.preferred_roles = FLmeans that these nodes would always prefer a follower as their replication source.biha.max_replicas = 1means that these nodes can replicate data to no more than one follower at once.Additionally, their biha.can_vote and biha.can_be_leader configuration parameters are set to
false. This is to ensure that nodes located in the standby data center cannot participate in elections as either voters or candidates.
Assume that Leader fails:
Figure 26.4. Replication in a Cascading BiHA Cluster in Case of Leader Failure
Cascading replication automatically reestablishes as follows:
Follower 1is elected as the newLeader.Follower 2selects the newLeaderas its replication source.Leadernow replicates data only toFollower 2.Follower 3andFollower 4continue replicating as before, because their replication sources remain the same.
26.1.5.3. Multi-Level Geographical Distribution and Disaster Resilience #
The BiHA solution allows creating a multi-level geographically distributed and disaster-resilient (GDBiHA) cluster to provide efficient 24/7 operation at heavy workload. The GDBiHA cluster is divided into segments — logical nodes that unite one or more physical BiHA cluster nodes. Segments are located in different geographically redundant data centers and have their own election systems: biha.minnodes and biha.nquorum are configured on every segment and inherited by its physical nodes.
The following diagram shows the typical structure of the GDBiHA cluster distributed across two data centers:
Figure 26.5. Multi-Level Geo-Distributed and Disaster-Resilient BiHA Cluster Diagram
The GDBiHA cluster on the diagram above consists of the following components:
GDBiHA Clusteris a logical root node with ID 1111 that unites two segments. The root node is the parent node for segments. This node has no parent and cannot be deleted.Leader Segmentis a logical node that unite physical nodes located inData Center 1. This segment is created by default when you initialize the cluster and always has ID 111. It owns the leader role because it contains the leader of the GDBiHA cluster (Leader Node) and supports write operations. IfLeader Segmentfails, you must perform manual switchover toFollower Segmentusing biha.set_leader.Follower Segmentis a logical node that unite physical nodes located inData Center 2. This segment is created manually and has the user-set ID, in this case, it is 222. This segment does not support write operations.Leader Nodeis the physical leader node of theGDBiHA Cluster. IfLeader Nodefails, the new leader is elected from theLeader Segmentnodes by means of the standard BiHA elections procedure.Front Follower Node 3is a physical follower node that fulfills leader functions inFollower Segment. IfFront Follower Node 3fails, the new front follower is elected from theFollower Segmentnodes by means of the standard BiHA elections procedure.Follower Node 1,Follower Node 2,Follower Node 4, andFollower Node 5are physical follower nodes of the GDBiHA cluster.
Nodes in the GDBiHA cluster operate on different levels. Physical nodes (IDs 1-6) operate on the level 1 (physical level). Segments (IDs 111 and 222) operate on the level 2 (segment level). Cluster (ID 1111) operates on the level 3 (cluster level).
To view the level where node operate, as well as other configuration details of all nodes, call the biha.config function:
id | term | nquorum | minnodes | heartbeat_send_period | heartbeat_max_lost | no_wal_on_follower | sync_standbys_min | priority | can_be_leader | can_vote | mode | proxima_status | name | repl_pref_roles | max_replicas | config_version | level | parent_id
------+------+---------+----------+-----------------------+--------------------+--------------------+-------------------+----------+---------------+----------+---------+----------------+----------------+-----------------+--------------+----------------+-------+-----------
1 | 1 | 2 | 2 | 1000 | 10 | 20000 | -2 | -1 | t | t | regular | 0 | biha_node_1 | L | 2147483647 | 17 | 1 | 111
2 | 1 | 2 | 2 | 1000 | 10 | 20000 | -2 | -1 | t | t | regular | 0 | biha_node_2 | L | 2147483647 | 17 | 1 | 111
3 | 1 | 2 | 2 | 1000 | 10 | 20000 | -2 | -1 | t | t | regular | 0 | biha_node_3 | L | 2147483647 | 17 | 1 | 111
4 | 1 | 2 | 2 | 1000 | 10 | 20000 | -2 | -1 | t | t | regular | 0 | biha_node_4 | L | 2147483647 | 17 | 1 | 222
5 | 1 | 2 | 2 | 1000 | 10 | 20000 | -2 | -1 | t | t | regular | 0 | biha_node_5 | L | 2147483647 | 17 | 1 | 222
6 | 1 | 2 | 2 | 1000 | 10 | 20000 | -2 | -1 | t | t | regular | 0 | biha_node_6 | L | 2147483647 | 17 | 1 | 222
111 | 1 | 2 | 2 | 1000 | 10 | 20000 | -2 | -1 | t | t | regular | 0 | biha_node_111 | L | 2147483647 | 17 | 2 | 1111
222 | 1 | 2 | 2 | 1000 | 10 | 20000 | -2 | -1 | t | t | regular | 0 | biha_node_222 | L | 2147483647 | 17 | 2 | 1111
1111 | 1 | 1 | 1 | 1000 | 10 | 20000 | -2 | -1 | t | t | regular | 0 | biha_node_1111 | L | 2147483647 | 17 | 3 |
(9 rows)
You can configure nodes, segments, and the GDBiHA cluster by means of biha extension functions.
For more information about deploying the GDBiHA cluster, see Setting Up a Multi-Level Geo-Distributed and Disaster-Resilient BiHA Cluster.
26.1.5.3.1. Replication in the GDBiHA Cluster #
By default, replication in the GDBiHA cluster is cascading and operates as follows:
Follower Node 1andFollower Node 2replicate data fromLeader Node.Front Follower 3replicates data fromLeader Node.Follower Node 4andFollower Node 5replicate data fromFront Follower 3.
For more information on how to configure cascading replication, see Configuring Cascading Replication.
26.1.5.3.2. Considerations and Limitations #
Automatic segment-level elections are not supported. You can change the leader segment manually using the biha.set_leader function.
GDBiHA supports standard PostgreSQL cascading replication including all the listed limitations. For more information, refer to Section 25.2.7.
Moving a single node or all nodes from one segment to another is not supported.
referee_with_walis not supported as a replication source in the follower segment. Therefore, avoid specifying theRvalue in the biha.preferred_roles parameter for nodes located in the follower segment.In the following failure scenarios, the process of the new leader nomination may fail requiring manual actions from an administrator:
simultaneous loss of the leader and the front follower before the election process completes
selective isolation of segments where different nodes of one segment see a different set of nodes from another segment
a long network degradation process accompanied by a gradual decrease in bandwidth followed by a complete disconnection