F.72. proxima — комбинация прокси, балансировщика нагрузки и пула соединений #
proxima — это расширение Postgres Pro Enterprise, объединяющее функциональность прокси-сервера, балансировщика нагрузки и пула соединений.
F.72.1. Обзор #
Расширение proxima можно использовать на одноузловом сервере Postgres Pro Enterprise, в стандартном кластере Postgres Pro Enterprise конструкции ведущий-ведомый, а также в BiHA-кластере. Расширение предоставляет следующие возможности:
Прокси-сервер: proxima становится единой точкой клиентских подключений и перенаправляет запросы на ведущий сервер или лидеру BiHA-кластера.
Пул соединений: proxima управляет обслуживающими процессами, чтобы сократить потребление системных ресурсов и предотвратить снижение производительности.
Балансировщик нагрузки: встроенная функциональность для балансировки нагрузки на чтение между репликами кластера по заданному алгоритму балансировки.
Поддержка SSL: расширение proxima можно настроить для работы с SSL-соединениями.
Мониторинг: при использовании расширения proxima с решением BiHA доступно множество метрик для отслеживания состояния proxima.
Динамический выделенный сеанс: proxima поддерживает сеанс между клиентом и обслуживающим процессом на протяжении всего времени существования клиентского подключения.
F.72.2. Особенности и ограничения #
В этом разделе перечислены особенности и ограничения, которые необходимо учитывать при использовании proxima.
F.72.2.1. Общие особенности и ограничения #
Расширение proxima не управляет репликацией между узлами кластера. Для обеспечения согласованности данных на всех узлах используйте Встроенная отказоустойчивость (BiHA) или настройте репликацию вручную.
Архитектуры процессоров Эльбрус, ppc64le и s390x не поддерживаются.
При использовании в стандартном кластере конструкции ведущий-ведомый или в BiHA-кластере сразу после запуска расширение proxima может записывать в журнал сообщения об ошибках подключения или синхронизации. Это нормальное поведение, потому что узлы запускаются в разное время. Сообщения об ошибках прекратятся вскоре после запуска.
На текущий момент в proxima отсутствует механизм автоматической установки динамических выделенных сеансов при использовании расширений, которые хранят своё состояние в рамках сеанса. В таких случаях необходимо вручную включить принудительный динамический выделенный сеанс.
Динамический выделенный сеанс не устанавливается при выполнении команды
CREATE STATISTICSво временном пространстве имён.Чтобы пул соединений обрабатывал большое число клиентских подключений, установите предел количества открытых файлов, превышающий число планируемых подключений:
sudo echo '* soft nofile
{значение}' >> /etc/security/limits.conf sudo echo '* hard nofile{значение}' >> /etc/security/limits.conf ulimit -n{значение}Например, если планируемое число клиентских подключений —
10000, в{значении}укажите11000.
F.72.2.2. Особенности и ограничения при работе в BiHA-кластере #
В расширении proxima есть специальный режим работы для BiHA-кластера. При установке в BiHA-кластере proxima автоматически получает от biha все необходимые конфигурационные параметры, например:
количество узлов кластера
идентификаторы, адреса и порты узлов
роли узлов (лидер, последователь или главный последователь)
Вы можете установить расширение proxima в существующий BiHA-кластер или включить расширение при подготовке кластера с нуля.
Расширение proxima регистрирует ряд функций-обработчиков для получения уведомлений о событиях в кластере. Например, при смене лидера proxima получает уведомление об этом событии и автоматически перенаправляет трафик на нового лидера. Функции-обработчики размещаются в таблице
biha.callbacksбазы данныхbiha_dbна узлах BiHA-кластера. Не удаляйте функции-обработчики, так как в этом случае proxima не сможет реагировать на события в кластере.Когда расширение proxima включено в BiHA-кластере, узлы кластера подключаются друг к другу с помощью порта P2L + 1. Чтобы обеспечить нормальную работу, номер порта P2L должен быть одинаковым на всех узлах, а порт P2L + 1 должен быть свободен. За подробной информацией о портах P2L и P2F обратитесь к Подразделу F.72.6.
Если состояние узла изменяется на
FRONT FOLLOWERилиLEADER, proxima на этом узле перестаёт видеть другие узлы до тех пор, пока они не выйдут из состоянияUNKNOWN. Это значит, что этот экземпляр proxima завершает подключения к другим экземплярам proxima, что, в свою очередь, отключает все активные клиенты от этого узла.Расширение proxima балансирует нагрузку по всем узлам кластера в соответствии с заданным алгоритмом балансировки. Если используется несколько сегментов, запросы на порт P2F в сегменте-лидере могут также перенаправляться на узлы в сегменте-последователе, работающие только на чтение. Чтобы расширение proxima не перенаправляло запросы на узлы сегмента-последователя, можно задать алгоритм балансировки
weighted_round_robinв параметре proxima.load_balancer_algorithm и указать веса узлов с помощью параметра proxima.load_balancer_node_weight. Для узлов, на которые расширение proxima не должно перенаправлять нагрузку, необходимо задать наименьший вес, а для узлов, на которые нужно перенаправлять нагрузку, — наибольший. Это решение полностью не исключает возможность перенаправления запросов на нежелательные узлы, но помогает свести её к минимуму.
F.72.3. Установка и настройка #
Расширение proxima — это встроенное расширение Postgres Pro Enterprise. Чтобы включить и настроить proxima, выполните следующие действия:
Остановите сервер Postgres Pro Enterprise с помощью pg_ctl:
pg_ctl stop -D
каталог_PGDATAДобавьте proxima в shared_preload_libraries в файле postgresql.conf:
shared_preload_libraries = 'proxima'
При использовании многоузлового кластера повторите этот шаг для каждого узла.
В зависимости от конфигурации Postgres Pro Enterprise задайте параметры конфигурации proxima в postgresql.conf:
Для одноузлового сервера задайте следующий параметр конфигурации:
proxima.cluster_mode = 'standalone'
Для стандартного кластера конструкции ведущий-ведомый задайте следующие параметры конфигурации:
proxima.cluster_mode = 'guc' proxima.cluster_config = '
id_узла0,адрес_узла0,порт_узла0,роль_узла0;id_узла1,адрес_узла1,порт_узла1,роль_узла1;' proxima.cluster_node_id =id_узлаНапример:
proxima.cluster_mode = 'guc' proxima.cluster_config = '0,192.168.0.57,4590,P;1,192.168.0.77,4590,S;' proxima.cluster_node_id = 0
Убедитесь, что на всех узлах указаны одинаковые значения proxima.cluster_config, а значения proxima.cluster_node_id уникальны для каждого узла.
Для BiHA-кластера задайте следующий параметр конфигурации:
proxima.cluster_mode = 'biha'
При использовании proxima с biha не требуется указывать параметры конфигурации кластера, так как proxima получает эту информацию напрямую от biha.
(Необязательно) При необходимости задайте прочие параметры конфигурации.
Если никакие параметры не заданы, proxima использует значения по умолчанию. За подробной информацией о конфигурационных параметрах и их значениях по умолчанию обратитесь к Подразделу F.72.11.1.
Запустите узел с помощью pg_ctl:
pg_ctl start -D
каталог_PGDATA
F.72.4. Подключение к proxima #
В этом разделе приведены примеры строк подключения к proxima для различных языковых интерфейсов.
В примерах ниже используется порт P2L (по умолчанию 4545), где все подключения перенаправляются на ведущий узел кластера (лидер). Однако, чтобы использовать расширение proxima в качестве балансировщика нагрузки и распределять нагрузку на чтение между репликами кластера, необходимо также настроить подключение через порт P2F (по умолчанию 4547). За подробной информацией обратитесь к Подразделу F.72.6.1.
В строках подключения, созданных специально для подключений на чтение и запись или только на чтение, т.е. с использованием либо порта P2L, либо порта P2F, не обязательно указывать параметры target_session_attrs (psql/libpq, Python, Go) или targetServerType (JDBC), так как подключения распределяются силами proxima.
F.72.4.1. psql/libpq #
Подключение к proxima с помощью библиотеки psql/libpq выглядит следующим образом:
psql -d "dbname=postgres host=node3,node4,node2,node1 port=4545,4545,4545,4545 user=username password=password"
psql postgres://username:password@node1:4545,node2:4545,node3:4545,node4:4545/postgres
F.72.4.2. Python #
Подключение к proxima с помощью библиотеки psycopg2 выглядит следующим образом:
import psycopg2
from psycopg2 import pool
pool = psycopg2.pool.SimpleConnectionPool(
min_size=1,
max_size=5,
user="pguser",
password="*****",
host="node1,node2,node3,node4",
port="4545,4545,4545,4545",
database="postgres")
connection = pool.getconn()F.72.4.3. JDBC #
Подключение к proxima с помощью JDBC выглядит следующим образом:
String url = "jdbc:postgresql://node1:4545,node2:4545,node3:4545,node4:4545/postgres?loadBalanceHosts=true";
Properties props = new Properties();
props.setProperty("user","postgres");
props.setProperty("password","********");
Connection conn = DriverManager.getConnection(url, props);Здесь в переменной url содержится строка подключения, где перечислены все доступные узлы. Если не указывать дополнительные параметры подключения драйвера JDBC, то подключение к кластеру будет происходить через первый доступный для подключения узел. Данный вариант не всегда может быть удобным. Поэтому в строке подключения добавлены параметры, позволяющие использовать разные узлы для разных подключений.
Параметр loadBalanceHosts со значением true позволяет перебирать узлы, подключаясь к какому-то одному из них.
F.72.4.4. Go #
Способы подключения к proxima для Go схожи со способами, принятыми в JDBC или Python. Необходимо использовать перечисление узлов, их TCP-портов, параметры подключения, а также выбрать подходящий драйвер.
Одним из таких драйверов для Go является pgx версий 4 или 5.
Ниже представлен пример строки подключения и создания пула для подключения к кластеру:
dbURL := "postgres://username:password@node1:4545,node2:4545,node3:4545,node4:4545/postgres" dbPool, err := pgxpool.New(context.Background(), dbURL)
F.72.5. Аутентификация #
Расширение proxima использует правила аутентификации, указанные в файле pg_hba.conf. Поддерживаются следующие методы аутентификации:
F.72.5.1. Проксирование аутентификации на главный узел (лидер) #
По умолчанию аутентификация пользователей производится локально на узлах. Однако в некоторых случаях необходимо выполнять аутентификацию на главном узле (лидере). Расширение proxima предоставляет возможность проксировать аутентификацию пользователей с любого узла кластера на главный узел (лидер).
Указать, где должна выполняться аутентификация пользователей, можно с помощью параметра конфигурации proxima.auth_policy, который поддерживает режимы local и leader.
Режим leader автоматически устанавливается на рефери BiHA-кластера и означает, что аутентификация выполняется на лидере. Это необходимо, так как на узле-рефери недостаточно информации для локальной аутентификации пользователей.
Примечание
Рефери можно развернуть в режимах работы referee или referee_with_wal. Если используется режим referee, рекомендуется сначала запустить лидера с включённым расширением proxima, а затем добавить рефери. Это необходимо потому, что proxima создаёт функции-обработчики на лидере кластера, которые затем реплицируются на другие узлы, кроме рефери в режиме referee. Однако если добавить рефери после включения proxima, все необходимые функции-обработчики будут скопированы утилитой bihactl.
На других узлах кластера для параметра proxima.auth_policy по умолчанию задано значение local. Это означает, что аутентификация производится локально на узлах. Однако, если в кластере часто создаются базы данных или пользователи, отстающие асинхронные реплики могут не аутентифицировать нового пользователя сразу после создания пользователя или базы данных на главном узле (лидере), так как они ещё отсутствуют на реплике. Чтобы избежать такой проблемы, можно задать значение leader для параметра proxima.auth_policy на всех узлах кластера.
F.72.6. Балансировщик нагрузки #
Функциональность балансировки нагрузки позволяет распределять нагрузку на чтение между репликами кластера по заданному алгоритму балансировки.
Расширение proxima предоставляет следующие порты для обработки клиентских сеансов:
Порт Proxy-to-Leader (P2L) перенаправляет всю нагрузку на ведущий узел (лидер). Номер порта по умолчанию — 4545, его можно изменить с помощью параметра proxima.port. Номер порта P2L должен быть одинаковым на всех узлах кластера.
Порт Proxy-to-Follower (P2F) распределяет читающую нагрузку между репликами в кластере. Номер порта по умолчанию — 4547, его можно изменить с помощью параметра proxima.p2f_port.
Примечание
В BiHA-кластере запросы перенаправляются на лидера в состоянии LEADER_RW. Однако читающая нагрузка, направленная на порт P2F, может также перенаправляться на лидера в состоянии LEADER_RO. За подробной информацией о состояниях узлов BiHA-кластера обратитесь к таблице biha.status_v.
Чтобы распределить нагрузку между узлами кластера, настройте клиентское приложение таким образом, чтобы нагрузка на запись направлялась на порт P2L, а на чтение — на порт P2F. За подробной информацией обратитесь к разделу Подразделу F.72.6.1.
Важно
Расширение proxima прикрепляет клиентский сеанс к определённому узлу кластера и таким образом обеспечивает выполнение всех транзакций в рамках этого сеанса на одном узле. Если узел выйдет из строя во время сеанса, клиентское соединение будет разорвано.
F.72.6.1. Настройка балансировщика нагрузки #
Расширение proxima позволяет настроить распределение нагрузки между узлами кластера. В примере ниже вы настроите распределение нагрузки для кластера из трёх узлов с адресами 192.168.0.1, 192.168.0.2 и 192.168.0.3, используя порты proxima по умолчанию — 4545 (P2L) и 4547 (P2F).
Настройте клиентское приложение таким образом, чтобы пишущая нагрузка направлялась на порт P2L , а читающая — на порт P2F.
На стороне клиента можно использовать параметр target_session_attrs, чтобы указать тип узла, на котором клиент должен выполнять транзакции и запросы при подключении к базе данных.
Например, можно указать, что запросы должны выполняться только на репликах, и тогда в рамках текущего соединения клиент будет выполнять читающие запросы на порту P2F.
(Необязательно) Укажите алгоритм балансировки нагрузки на чтение с помощью параметра proxima.load_balancer_algorithm.
В строке подключения перечислите следующие адреса узлов в формате, который отвечает требованиям используемой библиотеки:
192.168.0.1:4545 192.168.0.1:4547 192.168.0.2:4545 192.168.0.2:4547 192.168.0.3:4545 192.168.0.3:4547
Если вы используете libpq, обратитесь к Подразделу 36.1.1.3, чтобы узнать требования и синтаксис для указания множества адресов в строке подключения.
В результате при подключении к порту 4545 (P2L) пишущая нагрузка будет перенаправлена на ведущий узел (лидер). При подключении к порту 4547 (P2F) читающая нагрузка будет перенаправлена на одну из реплик в соответствии с выбранным алгоритмом.
F.72.7. Динамический выделенный сеанс #
При выполнении запросов обслуживающий процесс может хранить временное состояние и создавать объекты, такие как временные таблицы, временные представления и так далее, в рамках одного сеанса. Эта информация и объекты недоступны другим обслуживающим процессам. Если пул соединений перенаправляет клиента на другой обслуживающий процесс после создания такого объекта, клиент теряет доступ к этому объекту. Чтобы избежать этого, в proxima применяется функциональность динамического выделенного сеанса, позволяющая удерживать сеансы между клиентами и отдельными обслуживающими процессами на протяжении времени жизни клиентского подключения.
Примечание
Если вы используете расширения, которые хранят своё состояние в рамках сеанса, вам нужно вручную включить принудительный динамический выделенный сеанс. За дополнительной информацией обратитесь к Подразделу F.72.7.2.
Расширение proxima автоматически устанавливает динамический выделенный сеанс, если запрос содержит следующие объекты или функции SQL:
подготовленные операторы, которые также создаются в рамках сообщения Parse расширенного протокола запросов. Чтобы не устанавливать динамический выделенный сеанс для подготовленных операторов, используйте функциональность хранилища подготовленных операторов.
SET SESSION,SET SESSION AUTHORIZATIONиSET SESSION CHARACTERISTICS AS TRANSACTIONПримечание
Выделенный динамический сеанс не устанавливается, если эти команды изменяют какой-либо из следующих параметров конфигурации: application_name, client_encoding, scram_iterations, DateStyle, default_transaction_read_only,
session-authorization, standard_conforming_strings, IntervalStyle или TimeZone.Примечание
При использовании функции
pg_backend_set_configдинамический выделенный сеанс устанавливается для целевого обслуживающего процесса с указанным PID, а не для того, из которого вызывается функция.CREATE STATISTICSво временной схеме, например:CREATE TABLE my_table (id1 int, id2 int); CREATE STATISTICS pg_temp.my_stats ON id1, id2 FROM my_table;
Сеанс остаётся выделенным, пока упомянутые выше объекты не будут удалены.
Функция DISCARD удаляет объекты сеанса. После выполнения функции DISCARD ALL обслуживающий процесс выходит как из динамического выделенного сеанса, так и принудительного динамического выделенного сеанса.
F.72.7.1. Хранилище подготовленных операторов #
Предупреждение
В настоящее время функциональность хранилища подготовленных операторов является экспериментальной и не рекомендована для использования в производственной среде.
Чтобы не устанавливать динамический выделенный сеанс для запросов с подготовленными операторами, proxima предоставляет функциональность хранилища подготовленных операторов. Когда клиент создаёт подготовленный оператор, его текст и параметры сохраняются в хранилище proxima. Если proxima перенаправляет клиента на другой обслуживающий процесс, новый обслуживающий процесс извлекает подготовленный оператор из хранилища и подготавливает его локально. Таким образом, при работе с подготовленными операторами установка выделенного сеанса не требуется.
Хранилище подготовленных операторов находится в процессе proxima, и управлять им напрямую невозможно. Когда клиент создаёт или удаляет подготовленный оператор, обслуживающий процесс передаёт proxima информацию о необходимости обновить хранилище соответствующим образом. Размер хранилища зависит от количества подключённых клиентов и созданных подготовленных операторов. Каждый клиент использует примерно 104 байта памяти для системной информации. Каждый хранимый подготовленный оператор использует примерно 58 байт, а общее количество потребляемой памяти зависит от имени запроса, текста запроса, указания типов параметров и т.д. Учитывайте эту информацию при выделении оперативной памяти для вашего кластера.
Функциональностью хранилища подготовленных операторов можно управлять следующим образом:
Чтобы включить хранилище подготовленных операторов, используйте параметр конфигурации proxima.ps_enabled. Когда для параметра
proxima.ps_enabledзадано значениеon, proxima назначает каждому клиенту уникальный идентификатор сеанса и передаёт этот идентификатор обслуживающему процессу. Обслуживающие процессы извлекают подготовленные операторы из хранилища с учётом полученных идентификаторов. Этот механизм обеспечивает недоступность подготовленных операторов определённого клиента для клиентов с другими идентификаторами сеанса.Чтобы сделать подготовленные операторы, созданные одним клиентом, доступными для всех, используйте параметр конфигурации proxima.ps_shared. Когда для параметра
proxima.ps_sharedзадано значениеon, все клиенты используют единый идентификатор сеанса, а подготовленные операторы становятся видимыми для всех обслуживающих процессов в рамках одного узла.Важно
Подготовленные операторы могут быть общими только в рамках одного узла. Так как proxima распределяет нагрузку на чтение между репликами кластера в соответствии с заданным алгоритмом балансировки, разные клиенты могут быть перенаправлены на разные узлы. Соответственно, подготовленный оператор, созданный
Клиентом 1наУзле 1, будет недоступен дляКлиента 2, подключённого кУзлу 2.Когда для параметра
proxima.ps_sharedзадано значениеon, командаDEALLOCATE ALLне очищает хранилище proxima, так как подготовленные операторы являются общими и могут быть использованы другими клиентами.
Чтобы изменить максимальное количество подготовленных операторов в обслуживающем процессе, задайте значение для параметра конфигурации proxima.ps_cache_size с помощью команды
SET, например:SET proxima.ps_cache_size = 64;
Примечание
Параметры конфигурации proxima.ps_enabled и proxima.ps_shared контролируют только процесс выдачи идентификаторов сеанса расширением proxima, а не поведение обслуживающих процессов. Изменение этих параметров, включая изменение через SIGHUP, не влияет на ранее подключившихся клиентов, так как их идентификаторы сеанса остаются неизменными. Изменения применяются только к новым клиентам.
F.72.7.2. Управление динамическими выделенными сеансами вручную #
Некоторые расширения хранят своё состояние в рамках сеанса, для чего требуется удерживать сеанс между клиентом и обслуживающим процессом. При использовании таких расширений необходимо вручную включать динамический выделенный сеанс при каждом подключении с помощью параметра proxima.force_dedicated.
Управлять принудительным динамическим выделенным сеансом можно следующим образом:
Чтобы включить принудительный динамический выделенный сеанс, выполните следующую команду:
SET proxima.force_dedicated = true;
Чтобы отключить принудительный динамический выделенный сеанс, выполните следующую команду:
SET proxima.force_dedicated = false;
Чтобы проверить, является ли текущий сеанс выделенным, используйте параметр proxima.is_dedicated:
SHOW proxima.is_dedicated;
Возвращённое значение
tозначает, что сеанс выделенный, в то время какfозначает, что сеанс не выделенный.
F.72.8. Мониторинг #
Расширение proxima предоставляет функциональность мониторинга для отслеживания состояния proxima с помощью ряда метрик. Сейчас мониторинг доступен для BiHA-кластеров с включённым расширением proxima.
Расширение proxima регистрирует схему proxima в базе данных biha_db, где создаёт специальные представления для запросов метрик. За подробной информацией о просмотре метрик и примером SQL-запроса обратитесь к Подразделу F.72.8.3.
F.72.8.1. Передача метрик между узлами кластера #
Чтобы все метрики кластера были доступны на всех узлах, каждый узел раз в секунду передаёт свои метрики другим узлам. Если от узла в течение десяти секунд не поступали метрики, например, из-за потери соединения или падения узла, запрос не будет возвращать значения счётчиков с этого узла.
F.72.8.2. Особенности запросов через порты P2L и P2F #
Так как метрики запрашиваются с помощью обычного SQL, источником метрик всегда выступает узел, на котором выполняется запрос. При выполнении запроса учитывайте следующее:
При подключении через порт P2L метрики будут получены с лидера кластера.
При подключении к порту P2F proxima может распределить идущие подряд запросы между разными узлами. Так как доставка метрик происходит с задержкой, в некоторых случаях идущие подряд запросы могут показывать уменьшение интегральных счётчиков.
За подробной информацией о портах P2L и P2F обратитесь к Подразделу F.72.6.
Чтобы обеспечить монотонность роста счётчиков, при обработке результата всегда берите максимальное значение между текущими и ранее полученными значениями метрик.
F.72.8.3. Просмотр метрик мониторинга #
Просматривать метрики мониторинга в BiHA-кластере можно с помощью стандартных SQL-запросов к представлениям метрик:
Чтобы просмотреть все метрики кластера:
SELECT * FROM proxima.proxima_metrics;
Чтобы просмотреть все метрики определённого узла:
SELECT * FROM proxima.proxima_metrics WHERE node_id =
идентификатор_узла;Чтобы просмотреть метрики определённого класса, выполните запрос к представлению соответствующего класса. Например:
SELECT * FROM proxima.proxima_metrics_client;
За подробной информацией о возможностях мониторинга обратитесь к Подразделу F.72.8.
За подробной информацией о доступных метриках обратитесь к Подразделу F.72.11.2.
Ниже приведён пример запроса на просмотр всех метрик узла с идентификатором 0, а также результат запроса (обрезан, так как метрик очень много):
postgres=# SELECT * FROM proxima.proxima_metrics WHERE node_id = 0;
name | class | node_id | value
-------------------------------------------+--------------+---------+----------------------
thread.1.active_time_ns | thread-load | 0 | 12590006201
thread.1.purged_coroutines | thread-load | 0 | 6
thread.1.transferred_coroutines_accepted | thread-load | 0 | 2
thread.1.wakeup_requests_accepted | thread-load | 0 | 0
thread.1.futex_wakeup_requests_accepted | thread-load | 0 | 22752
thread.1.active_coroutines_called | thread-load | 0 | 72905
thread.1.evrun_once | thread-load | 0 | 38456
thread.1.evrun_nowait | thread-load | 0 | 8700
thread.1.scheduler.coroctx_in_use | thread-load | 0 | 19
thread.1.scheduler.coroctx_cached | thread-load | 0 | 6
thread.1.scheduler.cs_active | thread-load | 0 | 1
thread.1.scheduler.cs_inactive | thread-load | 0 | 1
thread.1.scheduler.cs_waiting_futex | thread-load | 0 | 5
thread.1.scheduler.cs_wakeup_futex | thread-load | 0 | 0
thread.1.scheduler.cs_waiting_io | thread-load | 0 | 12
memory.lgist-0 | memory | 0 | 0
memory.lgist-1 | memory | 0 | 8
memory.lgist-2 | memory | 0 | 15
memory.lgist-3 | memory | 0 | 162
memory.lgist-4 | memory | 0 | 737
memory.lgist-5 | memory | 0 | 1490
memory.lgist-6 | memory | 0 | 174
memory.lgist-7 | memory | 0 | 295
memory.lgist-8 | memory | 0 | 70
memory.lgist-9 | memory | 0 | 32
memory.lgist-10 | memory | 0 | 20
memory.lgist-11 | memory | 0 | 9
memory.lgist-12 | memory | 0 | 1
memory.lgist-13 | memory | 0 | 71
memory.lgist-14 | memory | 0 | 61
memory.lgist-15 | memory | 0 | 0
memory.lgist-16 | memory | 0 | 6
memory.lgist-17 | memory | 0 | 1
memory.lgist-18 | memory | 0 | 0
memory.lgist-19 | memory | 0 | 0
memory.lgist-20 | memory | 0 | 0
memory.lgist-21 | memory | 0 | 0
memory.lgist-22 | memory | 0 | 1
memory.lgist-23 | memory | 0 | 0
memory.lgist-24 | memory | 0 | 0
memory.usage | memory | 0 | 6581078
memory.traffic | memory | 0 | 7983836
client.lfe.now_connected | client | 0 | 1
client.lfe.accepted | client | 0 | 1
client.lfe.rejected | client | 0 | 0
client.lfe.disconnected | client | 0 | 0
client.lfe.auth_password | client | 0 | 0
client.lfe.auth_md5 | client | 0 | 0
client.lfe.auth_scram_sha256 | client | 0 | 0
client.lfe.auth_trust | client | 0 | 1
client.lfe.auth_tls_accepted | client | 0 | 0
client.lfe.auth_tls_rejected | client | 0 | 0
client.rfe.now_connected | client | 0 | 0
client.rfe.connected | client | 0 | 0
client.rfe.disconnected | client | 0 | 0
client.lbe.enter_dedicated | client | 0 | 0F.72.9. Общее администрирование #
В этом разделе приведены инструкции по администрированию proxima.
F.72.9.1. Конфигурирование SSL #
SSL можно включить как для входящих клиентских подключений, так и для внутреннего взаимодействия между узлами кластера.
F.72.9.1.1. Включение SSL для входящих клиентский подключений #
Включите SSL для входящих клиентский подключений:
Остановите узлы кластера с помощью pg_ctl.
Получите и установите сертификат и закрытый ключ.
Их можно либо получить в независимом центре сертификации (CA), либо сгенерировать самостоятельно с помощью утилиты для управления сертификатами, такой как OpenSSL.
В postgresql.conf укажите пути к сертификату и закрытому ключу:
proxima.ssl_key = '
/путь/к/key.pem' proxima.ssl_cert = '/путь/к/cert.pem'Если параметры proxima.ssl_cert и proxima.ssl_key не заданы, proxima использует сертификат и ключ, настроенные для Postgres Pro в
ssl_cert_fileиssl_key_file.Включите SSL для входящих подключений с помощью proxima.ssl_enabled:
proxima.ssl_enabled = on
(Необязательно) Чтобы проверить клиентские сертификаты, укажите путь к файлу с публичными сертификатами центра сертификации с помощью параметра конфигурации proxima.ssl_ca.
Этот параметр обязателен, если вы используете метод аутентификации по сертификату.
Запустите узлы с помощью pg_ctl.
Все клиентские подключения к порту proxima теперь защищены SSL.
F.72.9.1.2. Включение SSL-аутентификации для внутренних подключений #
Настройте SSL-аутентификацию для внутренних подключений между узлами кластера. В этой процедуре описана настройка SSL-аутентификации для кластера из двух узлов.
Остановите узлы кластера с помощью pg_ctl.
Для каждого узла кластера получите и установите сертификат и закрытый ключ.
Их можно либо получить в независимом центре сертификации (CA), либо сгенерировать самостоятельно с помощью утилиты для управления сертификатами, такой как OpenSSL.
Включите SSL для взаимодействия между узлами кластера с помощью параметра proxima.p2p_ssl_enabled:
proxima.p2p_ssl_enabled = on
Задайте параметры конфигурации proxima.p2p_auth_methods и proxima.ssl_trusted_certs_dir следующим образом:
proxima.p2p_auth_methods = 'ssl' proxima.ssl_trusted_certs_dir =
путь_к_каталогу_с_сертификатамиЗапустите узлы с помощью pg_ctl.
Проверьте журнал, чтобы убедиться, что SSL-аутентификация прошла успешно.
Следующие записи в журнале свидетельствуют о том, что в качестве метода аутентификации используется SSL и что аутентификация прошла успешно:
[auth]: using SSL authentication [auth]: authentication success
F.72.9.2. Отключение и включение расширения proxima #
Расширение proxima можно временно отключить и затем вновь включить с помощью параметра конфигурации proxima.enabled:
В файле postgresql.conf установите параметр
proxima.enabledс необходимым значением:Чтобы отключить proxima, установите параметр
proxima.enabledсо значениемoff:proxima.enabled = off
Чтобы включить proxima, установите параметр
proxima.enabledсо значениемon:proxima.enabled = on
Отправьте сигнал SIGHUP процессу
proxima:kill -SIGHUP
proxima_pidЗдесь
proxima_pid— ID процессаproxima.
F.72.9.3. Миграция #
При миграции кластера Postgres Pro Enterprise с proxima всегда отключайте proxima перед началом миграции BiHA-кластера. По окончании миграции повторно включите proxima. Расширение proxima в BiHA-кластере можно включать и отключать с помощью функции biha.enable_proxima.
F.72.9.4. Удаление proxima #
Чтобы отключить использование proxima:
На всех узлах кластера удалите расширение из shared_preload_libraries в файле postgresql.conf.
Перезапустите узлы с помощью команды
pg_ctl.
F.72.10. Устранение неполадок #
В этом разделе содержится информация о типичных неполадках, с которыми можно столкнуться при использовании proxima, и способах их устранения.
F.72.10.1. База данных или пользователь не найдены #
Расширение proxima выполняет аутентификацию локально на узле, а не перенаправляет запрос доступа на ведущий узел или лидера. Если база данных или пользователь, к которым вы пытаетесь подключиться, не найдены, выполните следующие действия:
Убедитесь, что между узлами настроена репликация с помощью стандартного механизма репликации или с помощью BiHA.
Если репликация настроена и работает, подождите некоторое время, так как данные могли ещё не дойти до реплики.
F.72.10.2. Не удалось подключиться к proxima #
Если не удаётся подключиться к proxima, выполните следующие действия:
Убедитесь, что для подключения используется порт proxima.port.
Убедитесь, что файл pg_hba.conf настроен корректно.
F.72.10.3. Сообщение в журнале: «connection cannot be established» (невозможно установить соединение) #
Если вы видите в журнале это сообщение от proxima, выполните следующие действия:
Убедитесь, что все узлы включены и нет проблем с сетью.
Если вы используете режим работы кластера
guc, убедитесь, что значения proxima.cluster_node_id настроены верно и совпадают с ID, указанными в proxima.cluster_config.
F.72.10.4. Сообщение в журнале: «failed to create cluster manager» (не удалось создать менеджер кластера) #
Если вы используете режим работы кластера guc , убедитесь, что proxima.cluster_config настроен корректно:
указаны все необходимые значения
набор значений для каждого узла оканчивается точкой с запятой (
;)
F.72.10.5. Сообщение в журнале: «postgres: cannot accept new connection, error: Too many open files» (невозможно принять новое подключение, ошибка: Слишком много открытых файлов) #
Увеличьте максимальное число открытых файлов с помощью команды ulimit -S -n.
F.72.10.6. Сообщение в журнале: «router: trying to route session, last error: сообщение_об_ошибке» (попытка маршрутизировать сеанс, последняя ошибка: сообщение_об_ошибке) #
Это сообщение в журнале может появиться при подключении к узлам кластера.
Выполните следующие действия:
При работе с BiHA-кластером убедитесь, что значение параметра конфигурации proxima.port (порт P2L) одинаковое на всех узлах кластера. После того как вы задали одинаковые номера портов P2L, повторите попытку подключения.
Если дело не в разных номерах портов P2L, проверьте
сообщение_об_ошибке:Если сообщение содержит «failed to find leader config» (не удалось обнаружить конфигурацию лидера), дождитесь, когда узел получит информацию о ведущем узле (лидере). После получения информации подключение будет установлено.
Если сообщение содержит «load balancer error: are there any RO nodes in the cluster? Aborting» (ошибка балансировщика нагрузки: в кластере есть узлы в состоянии RO? Прерывание выполнения), убедитесь, что в кластере есть узлы в состоянии
RO, и подключитесь повторно.
F.72.11. Справка #
F.72.11.1. Параметры конфигурации #
F.72.11.1.1. Общие параметры #
proxima.address(text) #Указывает IP-адреса, на которых proxima принимает подключения. Можно указать адреса IPv4 или IPv6, а также каталоги Unix-сокетов. Значения должны быть разделены запятыми. Адреса можно указать следующим образом:
Любое количество IPv4-адресов, каждый из которых должен соответствовать адресу одного из локальных сетевых интерфейсов. Адрес
0.0.0.0представляет все интерфейсы. Если он указан, все прочие указанные IPv4-адреса игнорируются.Любое количество IPv6-адресов, каждый из которых должен соответствовать адресу одного из локальных сетевых интерфейсов. Адрес
::0представляет все интерфейсы. Если он указан, все прочие указанные IPv6-адреса игнорируются.Любое количество путей к каталогам Unix-сокетов. Имя Unix-сокета указывается в формате
.s.PGSQL., гдепортпорт— это номер, соответствующий одному из портов P2L или P2F. Имена сокетов имитируют сокеты PostgreSQL, чтобы для подключения через proxima можно было использовать psql или pgbench .Указанные пути должны быть абсолютными и начинаться с косой черты. Можно также указать макрос
/$[, гдеиндекс]индекс— это номер каталога из списка, заданного в параметре конфигурации unix_socket_directories. Если значениеunix_socket_directoriesне задано илииндекспревышает количество каталогов, используется каталог/tmp. Имена каталогов не должны содержать пробелы, все пробелы игнорируются при разборе.
Значение по умолчанию —
0.0.0.0,::0,$/[0].proxima.enabled(boolean) #Временно включает и отключает расширение proxima. Доступны следующие значения:
off: временно останавливает расширение proxima.on: запускает расширение proxima после временной остановки.
proxima.force_dedicated(boolean) #Включает и отключает принудительные динамические выделенные сеансы. Доступны следующие значения:
true: включает принудительный динамический выделенный сеанс.false: отключает принудительный динамический выделенный сеанс.
За подробной информацией обратитесь к разделу Подраздел F.72.7.2.
proxima.is_dedicated(boolean) #Позволяет проверить, является ли текущий сеанс выделенным. Возвращает одно из следующих значений:
t: сеанс выделенный.f: сеанс не выделенный.
За подробной информацией обратитесь к разделу Подраздел F.72.7.2.
proxima.load_balancer_algorithm(text) #Определяет алгоритм балансировки для распределения нагрузки на чтение между репликами в кластере. Поддерживаются следующие значения:
round-robin: нагрузка распределяется между репликами по очереди.weighted-round-robin: нагрузка распределяется между репликами по очереди, пропорционально их настроенным весам. Если выбран этот алгоритм, задайте веса узлов с помощью параметра конфигурации proxima.load_balancer_node_weight.adaptive: нагрузка распределяется по репликам аналогично алгоритмуweighted-round-robin. Однако для алгоритмаadaptiveзначения весов реплик зависят от нагрузки на процессор, оперативную память и ввод-вывод диска в каждый момент времени. Чем выше нагрузка на реплике, тем меньше запросов будет на неё перенаправляться. Алгоритмadaptiveопределяет, как потребление каждого ресурса влияет на выбор узла во время балансировки. Долю каждого ресурса можно указать с помощью параметров proxima.load_balancer_cpu_weight, proxima.load_balancer_io_weight и proxima.load_balancer_ram_weight.adaptive-cpu: нагрузка распределяется между репликами в зависимости от загрузки процессора. Чем выше загрузка на реплике, тем меньше запросов на неё перенаправляется.adaptive-io: нагрузка распределяется по репликам в зависимости от загрузки ввода-вывода диска. Чем выше загрузка на реплике, тем меньше запросов на неё перенаправляется. Можно также задать среднее время ожидания на выполнение одной операции при обращении к диску с помощью параметров proxima.load_balancer_io_max_latency_ms и proxima.load_balancer_io_min_latency_ms.adaptive-ram: нагрузка распределяется по репликам в зависимости от потребления оперативной памяти. Чем выше потребление на реплике, тем меньше запросов на неё перенаправляется.least-connections: нагрузка распределяется на реплику с самым низким числом активных подключений.random: нагрузка распределяется между репликами в случайном порядке.
Значение по умолчанию —
round-robin.proxima.load_balancer_node_weight(integer) #Указывает вес текущего узла для алгоритма
weighted-round-robin, заданного в параметре конфигурации proxima.load_balancer_node_weight. Процент запросов, перенаправленных на узелk, вычисляется по следующей формуле:Pk = (nodek.weight / Σi nodei.weight) × 100%В расчёте учитываются только узлы, являющиеся репликами.
Значение параметра можно изменить без перезапуска узла, отправив сигнал SIGHUP.
Диапазон допустимых значений: от
1до10000. Значение по умолчанию —100.proxima.load_balancer_cpu_weight(integer) #Указывает долю влияния потребления ресурсов процессора на определение веса узла. Значение может быть задано в диапазоне от
0до10000. Значение по умолчанию —100. Параметр активен, когда для параметра proxima.load_balancer_algorithm задано значениеadaptive.proxima.load_balancer_io_weight(integer) #Указывает долю влияния загрузки ввода-вывода диска на определение веса узла. Значение может быть задано в диапазоне от
0до10000. Значение по умолчанию —100. Параметр активен, когда для параметра proxima.load_balancer_algorithm задано значениеadaptive. Можно также задать среднее время ожидания на выполнение одной операции при обращении к диску с помощью параметров proxima.load_balancer_io_max_latency_ms и proxima.load_balancer_io_min_latency_ms.proxima.load_balancer_io_max_latency_ms(integer) #Указывает максимальное время ожидания на выполнение одной операции при обращении к диску, в миллисекундах. Если текущее значение счётчика system.io_avg_latency_ms выше, чем значение
proxima.load_balancer_io_max_latency_ms, узел получает наименьшую возможную долю веса, которая зависит от загрузки ввода-вывода диска. Значение может быть задано в диапазоне от0до2^32-1. Значение по умолчанию —40. Параметр активен, когда для параметра proxima.load_balancer_algorithm задано значениеadaptiveилиadaptive-io.proxima.load_balancer_io_min_latency_ms(integer) #Указывает минимальное время ожидания для выполнения одной операции при обращении к диску, в миллисекундах. Если текущее значение счётчика system.io_avg_latency_ms меньше, чем значение
proxima.load_balancer_io_min_latency_ms, узел получает наибольшую возможную долю веса узла, которая зависит от загрузки ввода-вывода диска. Значение может быть задано в диапазоне от0до2^32-1. Значение по умолчанию —10. Параметр активен, когда для параметра proxima.load_balancer_algorithm задано значениеadaptiveилиadaptive-io.proxima.load_balancer_ram_weight(integer) #Указывает долю влияния потребления оперативной памяти на определение веса узла. Значение может быть задано в диапазоне от
0до10000. Значение по умолчанию —100. Параметр активен, когда для параметра proxima.load_balancer_algorithm задано значениеadaptive.proxima.port(integer) #Указывает порт Proxy-to-Leader (P2L) — TCP-порт, на котором proxima принимает входящие клиентские подключения и перенаправляет все запросы на ведущий узел (лидер).
Диапазон допустимых значений: от
0до65535. Значение по умолчанию —4545. Значение для параметраproxima.portдолжно быть одинаковым на всех узлах кластера.За подробной информацией о портах P2L и P2F обратитесь к Подразделу F.72.6.
proxima.p2f_port(integer) #Указывает порт Proxy-to-Follower (P2F) — TCP-порт, на котором proxima принимает входящие клиентские подключения и распределяет читающую нагрузку между репликами в кластере.
Диапазон допустимых значений: от
0до65535. Значение по умолчанию —4547.За подробной информацией о портах P2L и P2F обратитесь к Подразделу F.72.6.
proxima.p2p_auth_methods(text) #Указывает метод аутентификации для внутреннего взаимодействия между узлами кластера. Поддерживаются следующие методы:
Значение по умолчанию —
trust. Можно перечислить несколько методов через запятую, например:proxima.p2p_auth_methods = 'trust,ssl'
Если перечислить несколько методов, они будут применяться следующим образом в порядке убывания приоритета:
ssl,trust.proxima.p2p_ssl_enabled(boolean) #Включает или отключает SSL для внутреннего взаимодействия между узлами кластера. Значение по умолчанию —
off.proxima.ssl_enabled(boolean) #Включает или выключает SSL для входящих клиентских подключений к proxima.port. Значение по умолчанию —
off. Если включить SSL и не задать параметры proxima.ssl_key и proxima.ssl_cert, proxima будет использовать SSL-сертификат, настроенный для Postgres Pro.proxima.ssl_ca(text) #Указывает путь к файлу с публичными сертификатами центра сертификации для проверки клиентских сертификатов. Параметр обязателен при использовании метода аутентификации по сертификату.
proxima.ssl_cert(text) #Указывает путь к сертификату, который будет использоваться для SSL-соединения через proxima.port. Если значение не указано, proxima использует сертификат, указанный в ssl_cert_file. Если параметр задан, вам также нужно указать значение для proxima.ssl_key.
proxima.ssl_key(text) #Указывает путь к файлу закрытого ключа. Если параметр не задан, proxima использует ключ, указанный в ssl_key_file. Если параметр задан, вам также нужно указать значение для proxima.ssl_cert.
proxima.ssl_trusted_certs_dir(text) #Указывает путь к каталогу с доверенными сертификатами при настройке SSL-аутентификации с помощью proxima.p2p_auth_methods.
proxima.log_level(enum) #Указывает уровень детализации сообщений proxima. Возможные значения:
error,warning,info,verbose,debug. Значение по умолчанию —info.proxima.workers(integer) #Указывает число потоков, запускаемых для обработки запросов обслуживающим процессом proxima. Диапазон допустимых значений: от
1до65535. Чем выше значение, тем больше запросов может быть обработано. Значение по умолчанию —4.
F.72.11.1.2. Конфигурирование кластера #
proxima.cluster_mode(text) #Устанавливает режим работы кластера. Возможные режимы:
standalone— режим для одноузловой базы данных Postgres Pro.guc— режим для стандартного кластера Postgres Pro конструкции ведущий-ведомый. Конфигурация кластера определяется параметрами proxima.cluster_config и proxima.cluster_node_id.biha— режим для BiHA-кластера. В этом режиме конфигурация кластера передаётся расширением biha.
Значение по умолчанию —
standalone. Значение этого параметра должно быть одинаковым на всех узлах кластера.proxima.cluster_config(text) #Устанавливает конфигурацию кластера для режима работы кластера
guc. Значение этого параметра должно быть одинаковым на всех узлах кластера. Параметры подключения и идентификации необходимо указать для каждого узла следующим образом:'
id_узла,адрес_узла,порт_узла,роль_узла'где:
id_узла— это идентификатор узла, в качестве которого необходимо указать значение в диапазоне от0до255. Идентификатор узла должен быть уникальным для каждого узла в кластере.адрес_узла— это IP-адрес узла для внутреннего соединения между узлами кластера.порт_узла— это порт узла для внутреннего соединения между узлами кластера. Этот порт должен отличаться от proxima.port.роль_узла— это роль узла в кластере. Возможные значенияP(Primary, ведущий) иS(Standby, ведомый).
Пример значения proxima.cluster_config для кластера, состоящего из трёх узлов:
'0,127.0.0.1,4090,P;1,127.0.0.1,4091,S;2,127.0.0.1,4092,S;'
proxima.cluster_node_id(integer) #Указывает уникальный идентификатор узла для режима работы кластера
guc. Этот параметр не должен изменяться после запуска и до остановки кластера. Идентификатор узла должен быть уникальным для каждого узла кластера. Значение можно указать в диапазоне от0до255. Значение по умолчанию —0.Список идентификаторов узлов должен всегда начинаться с
0и заканчиватьсяn-1, гдеn— общее число узлов. Например, для кластера из трёх узлов идентификаторы узлов должны быть0, 1, 2.
F.72.11.1.3. Настройка аутентификации #
proxima.auth_policy(text) #Указывает, где должна выполняться аутентификация. Возможные значения:
local: аутентификация выполняется локально на узле с применением правил HBA и системного каталога узла. Это значение по умолчанию для всех узлов, кроме рефери.leader: аутентификация выполняется на главном узле (лидере) с применением правил HBA и системного каталога главного узла (лидера). В BiHA-кластере это значение автоматически задаётся для рефери.За подробной информацией обратитесь к разделу Проксирование аутентификации на главный узел (лидер).
F.72.11.1.4. Настройка хранилища подготовленных операторов #
Следующие параметры управляют хранилищем подготовленных операторов:
proxima.ps_enabled(boolean) #Включает хранилище подготовленных операторов proxima. При включении подготовленные операторы сохраняются в хранилище, что позволяет proxima не устанавливать выделенный сеанс для обслуживающего процесса.
Значение параметра можно изменить без перезапуска узла, отправив сигнал SIGHUP.
Возможные значения:
on,off. Значение по умолчанию —off.proxima.ps_shared(boolean) #Включает совместное использование подготовленных операторов для всех клиентов. При включении все клиенты используют единый идентификатор сеанса, что делает подготовленные операторы, созданные одним клиентов, доступными для всех клиентов. Использование этого параметра конфигурации имеет смысл, только если для параметра proxima.ps_enabled задано значение
on.Значение параметра можно изменить без перезапуска узла, отправив сигнал SIGHUP.
Возможные значения:
on,off. Значение по умолчанию —off.proxima.ps_cache_size(integer) #Определяет максимальное количество подготовленных операторов в обслуживающем процессе. Когда установленный предел достигается, подготовленные операторы вытесняются по стратегии LRU (Last Recently Used, удаление операторов, которые дольше всего не использовались). Если обслуживающий процесс попытается использовать вытесненный подготовленный оператор, ему придётся обратиться к хранилищу для повторного разбора запроса.
Этот параметр конфигурации влияет только на обслуживающие процессы. Его можно изменить в любое время с помощью команды
SET.Значение может быть задано в диапазоне от
8до2147483647. Значение по умолчанию —32.
F.72.11.1.5. Настройка локального пула обслуживающих процессов #
Следующие параметры устанавливают ограничения для пула локальных обслуживающих процессов — Postgres Pro, обрабатывающих клиентские запросы.
proxima.backend_pool_local_total_limit(integer) #Устанавливает максимальное число обслуживающих процессов, которые могут быть созданы на узле. Диапазон допустимых значений: от
1доmax_connections. Значение по умолчанию —100.proxima.backend_pool_local_bucket_limit(integer) #Устанавливает максимальное число обслуживающих процессов, которые могут быть созданы в рамках подключений, идентифицированных связкой
user + database. Диапазон допустимых значений: от1до значения, указанного в proxima.backend_pool_local_total_limit. Значение по умолчанию —100.proxima.backend_pool_local_overdue_interval(float) #Устанавливает время бездействия локального обслуживающего процесса в секундах. Если локальный обслуживающий процесс не используется клиентами дольше, чем установлено этим параметром, обслуживающий процесс будет остановлен. Диапазон допустимых значений: от
1.0до86400.0. Значение по умолчанию —10.0.
F.72.11.1.6. Настройка пула удалённых обслуживающих процессов #
Следующие параметры устанавливают ограничения для пула удалённых обслуживающих процессов. Удалённые обслуживающие процессы — это логические каналы, которые могут быть установлены через мультиплексированное соединение между узлами кластера для проксирования запросов от ведомого узла (последователя) к ведущему узлу (лидеру). Настройка этих параметров может быть необходима только для кластеров из нескольких узлов. Значения по умолчанию являются оптимальными и их не рекомендуется изменять.
proxima.backend_pool_remote_total_limit(integer) #Устанавливает максимальное число логических каналов между узлами кластера для проксирования запросов клиента. Диапазон допустимых значений: от
1до2^32-1. Значение по умолчанию —100000.proxima.backend_pool_remote_bucket_limit(integer) #Устанавливает максимальное число логических каналов между узлами кластера для проксирования клиентских запросов в рамках подключений, идентифицированных связкой
user + database. Диапазон допустимых значений: от1до значения, указанного в proxima.backend_pool_remote_total_limit. Значение по умолчанию —1000.proxima.backend_pool_remote_overdue_interval(float) #Устанавливает время бездействия удалённого обслуживающего процесса в секундах. Если удалённый обслуживающий процесс не используется клиентами дольше, чем установлено этим параметром, логическое соединение между узлами кластера будет разорвано. Диапазон допустимых значений от
1.0до86400.0. Значение по умолчанию —60.0.
F.72.11.2. Метрики мониторинга #
Все метрики мониторинга proxima разделены на несколько классов, чтобы их было удобно запрашивать через представления метрик.
Доступны следующие классы:
F.72.11.2.1. Представления метрик мониторинга #
При использовании в BiHA-кластере, proxima регистрирует схему proxima в базе данных biha_db, где создаёт представления для запроса метрик.
Доступны следующие представления:
proxima.proxima_metricsотображает все метрики кластера.proxima.proxima_metrics_thread_loadотображает метрики потоков.proxima.proxima_metrics_trafficотображает метрики трафика.proxima.proxima_metrics_backend_poolотображает метрики пула обслуживающих процессов.proxima.proxima_metrics_clientотображает метрики клиентских подключений.proxima.proxima_metrics_rpcотображает метрики RPC-сервера.proxima.proxima_metrics_systemотображает системные метрики.
F.72.11.2.2. Метрики потоков #
Метрики потоков отображают использование ресурсов процессора потоками proxima, а также метрики корутинового движка, на котором основана proxima. Количество счётчиков, которые используются в этом классе, зависит от количества запущенных потоков.
Имена метрик потоков имеют структуру thread.ID., где имя_счётчикаID — внутренний идентификатор корутинового движка.
Доступны следующие счётчики:
Таблица F.57. Счётчики потоков
| Имя | Тип | Описание |
|---|---|---|
thread.ID.active_time_ns | Интегральный | Количество наносекунд, в течение которого поток исполнял какую-либо полезную нагрузку. |
thread.ID.purged_coroutines | Интегральный | Количество контекстов корутин, которые были разрушены из-за длительной невостребованности. |
thread.ID.transferred_coroutines_accepted | Интегральный | Количество контекстов корутин, перенесённых для исполнения на этот поток. |
thread.ID.wakeup_requests_accepted | Интегральный | Количество принятых запросов на пробуждение корутины. |
thread.ID.futex_wakeup_requests_accepted | Интегральный | Количество принятых запросов на пробуждение корутины, заблокированной на фьютексе (futex). |
thread.ID.active_coroutines_called | Интегральный | Количество вызовов активных корутин. Если удвоить это значение, можно получить количество переключений контекстов корутин в текущем потоке. |
thread.ID.evrun_once | Интегральный | Количество вызовов библиотеки libev c блокировкой потока для ожидания событий, относящихся к вводу-выводу или активным таймерам. |
thread.ID.evrun_nowait | Интегральный | Количество вызовов библиотеки libev без блокировки потока для ожидания событий, относящихся к вводу-выводу или активным таймерам. |
thread.ID.scheduler.coroctx_in_use | Мгновенное значение | Количество контекстов корутин, которые используются в настоящий момент. |
thread.ID.scheduler.coroctx_cached | Мгновенное значение | Количество контекстов корутин, которые в текущий момент кешированны и не используются, но могут быть быстро предоставлены при создании новых корутин. |
thread.ID.scheduler.cs_active | Мгновенное значение | Количество активных корутин. |
thread.ID.scheduler.cs_inactive | Мгновенное значение | Количество корутин в неактивном состоянии. |
thread.ID.scheduler.cs_waiting_futex | Мгновенное значение | Количество корутин в ожидании фьютекса. |
thread.ID.scheduler.cs_wakeup_futex | Мгновенное значение | Количество корутин в очереди пробуждения при блокировке на фьютексе. |
thread.ID.scheduler.cs_waiting_io | Мгновенное значение | Количество корутин в ожидании доступности чтения или записи на устройстве ввода-вывода или активации таймера (например, при блокировке в операции sleep). |
Пример результата запроса метрик потоков выглядит следующим образом:
name | class | node_id | value ------------------------------------------+-------------+---------+------------ thread.1.active_time_ns | thread-load | 0 | 6319387757 thread.1.purged_coroutines | thread-load | 0 | 1 thread.1.transferred_coroutines_accepted | thread-load | 0 | 2 thread.1.wakeup_requests_accepted | thread-load | 0 | 0 thread.1.futex_wakeup_requests_accepted | thread-load | 0 | 10214 thread.1.active_coroutines_called | thread-load | 0 | 32385 thread.1.evrun_once | thread-load | 0 | 17162 thread.1.evrun_nowait | thread-load | 0 | 4567 thread.1.scheduler.coroctx_in_use | thread-load | 0 | 19 thread.1.scheduler.coroctx_cached | thread-load | 0 | 1 thread.1.scheduler.cs_active | thread-load | 0 | 1 thread.1.scheduler.cs_inactive | thread-load | 0 | 1 thread.1.scheduler.cs_waiting_futex | thread-load | 0 | 5 thread.1.scheduler.cs_wakeup_futex | thread-load | 0 | 0 thread.1.scheduler.cs_waiting_io | thread-load | 0 | 12 thread.2.active_time_ns | thread-load | 0 | 974064 thread.2.purged_coroutines | thread-load | 0 | 0 thread.2.transferred_coroutines_accepted | thread-load | 0 | 0 thread.2.wakeup_requests_accepted | thread-load | 0 | 0 thread.2.futex_wakeup_requests_accepted | thread-load | 0 | 6 thread.2.active_coroutines_called | thread-load | 0 | 7 thread.2.evrun_once | thread-load | 0 | 109 thread.2.evrun_nowait | thread-load | 0 | 0 thread.2.scheduler.coroctx_in_use | thread-load | 0 | 1 thread.2.scheduler.coroctx_cached | thread-load | 0 | 0 thread.2.scheduler.cs_active | thread-load | 0 | 0 thread.2.scheduler.cs_inactive | thread-load | 0 | 0 thread.2.scheduler.cs_waiting_futex | thread-load | 0 | 1 thread.2.scheduler.cs_wakeup_futex | thread-load | 0 | 0 thread.2.scheduler.cs_waiting_io | thread-load | 0 | 0 ...
F.72.11.2.3. Метрики трафика #
Метрики трафика отображают байты и/или сообщения, которые передаются через канал связи, а также количество сброшенных сообщений и повторных подключений, если они поддерживаются текущим каналом связи.
Имена метрик трафика имеют структуру traffic.CHANNEL.COUNTER, где:
CHANNEL— канал, данные которого отображаются в результате запроса. Поддерживаются следующие каналы:fe(frontend) — передача данных между всеми клиентами и proxima.be(backend) — данные, передаваемые между proxima и обслуживающими процессами proxima.rpc(RPC, Remote Procedure Call) — данные, передаваемые между proxima и другими процессами текущего экземпляра базы данных.nodeID.client— данные, передаваемые через клиентское подключение между текущим узлом и узлом с идентификаторомID.nodeID.server— данные, передаваемые через серверное подключение между текущим узлом и узлом с идентификаторомID.
COUNTER— имя счётчика.
Доступны следующие счётчики:
Таблица F.58. Счётчики трафика
| Имя | Тип | Описание |
|---|---|---|
traffic.CHANNEL.rx_bytes | Интегральный | Количество байтов, принятых по каналу связи. |
traffic.CHANNEL.tx_bytes | Интегральный | Количество байтов, отправленных по каналу связи. |
traffic.CHANNEL.rx_msgs | Интегральный | Количество принятых сообщений. Этот счётчик присутствует, только если канал поддерживает отслеживание отдельных сообщений. |
traffic.CHANNEL.tx_msgs | Интегральный | Количество отправленных сообщений. Этот счётчик присутствует, только если канал поддерживает отслеживание отдельных сообщений. |
traffic.CHANNEL.rx_msgs_dropped | Интегральный | Количество сброшенных сообщений. Этот счётчик присутствует, только если канал поддерживает сброс сообщений (dropping). |
traffic.CHANNEL.reconnects | Интегральный | Количество повторных подключений после сбоев. Этот счётчик присутствует, только если канал поддерживает повторные подключения. |
Пример результата запроса метрик трафика выглядит следующим образом:
name | class | node_id | value --------------------------------------+---------+---------+---------- traffic.fe.rx_bytes | traffic | 0 | 943 traffic.fe.tx_bytes | traffic | 0 | 10632 traffic.be.rx_bytes | traffic | 0 | 13233 traffic.be.tx_bytes | traffic | 0 | 2099 traffic.node1.client.rx_bytes | traffic | 0 | 32 traffic.node1.client.tx_bytes | traffic | 0 | 64641815 traffic.node1.client.rx_msgs | traffic | 0 | 124 traffic.node1.client.tx_msgs | traffic | 0 | 7868 traffic.node1.client.rx_msgs_dropped | traffic | 0 | 0 traffic.node1.client.reconnects | traffic | 0 | 1 traffic.node2.client.rx_bytes | traffic | 0 | 32 traffic.node2.client.tx_bytes | traffic | 0 | 64609591 traffic.node2.client.rx_msgs | traffic | 0 | 124 traffic.node2.client.tx_msgs | traffic | 0 | 7864 traffic.node2.client.rx_msgs_dropped | traffic | 0 | 0 traffic.node2.client.reconnects | traffic | 0 | 1 traffic.rpc.rx_bytes | traffic | 0 | 100 traffic.rpc.tx_bytes | traffic | 0 | 12416 traffic.rpc.rx_msgs | traffic | 0 | 3 traffic.rpc.tx_msgs | traffic | 0 | 2 traffic.node2.server.rx_bytes | traffic | 0 | 56532348 traffic.node2.server.tx_bytes | traffic | 0 | 32 traffic.node2.server.rx_msgs | traffic | 0 | 7868 traffic.node2.server.tx_msgs | traffic | 0 | 124 traffic.node2.server.rx_msgs_dropped | traffic | 0 | 0 traffic.node2.server.reconnects | traffic | 0 | 1 traffic.node1.server.rx_bytes | traffic | 0 | 56504900 traffic.node1.server.tx_bytes | traffic | 0 | 32 traffic.node1.server.rx_msgs | traffic | 0 | 7864 traffic.node1.server.tx_msgs | traffic | 0 | 124 traffic.node1.server.rx_msgs_dropped | traffic | 0 | 0 traffic.node1.server.reconnects | traffic | 0 | 1
F.72.11.2.4. Метрики пула обслуживающих процессов #
Метрики пула обслуживающих процессов отображают характеристики запросов клиентов к пулу на предоставление обслуживающих процессов.
Имена метрик пула обслуживающих процессов имеют структуру backend_pool.SCOPE.COUNTER, где:
SCOPEопределяет тип обслуживающего процесса: локальный или удалённый.COUNTER— имя счётчика.
Доступны следующие счётчики:
Таблица F.59. Счётчики пула обслуживающих процессов
| Имя | Тип | Описание |
|---|---|---|
backend_pool.SCOPE.requests | Интегральный | Количество запросов на предоставление обслуживающих процессов к пулу обслуживающих процессов. |
backend_pool.SCOPE.creations | Интегральный | Количество новых обслуживающих процессов, созданных при запросе у пула. |
backend_pool.SCOPE.destructions | Интегральный | Количество разрушений (закрытий) обслуживающих процессов. Может случиться, когда обслуживающий процесс вытесняется из бакета пула или не используется долгое время. |
backend_pool.SCOPE.unlinks | Интегральный | Количество обслуживающих процессов, отвязанных от пула. |
backend_pool.SCOPE.acquisitions | Интегральный | Количество обслуживающих процессов, предоставленных клиентам. |
backend_pool.SCOPE.releases | Интегральный | Количество обслуживающих процессов, возвращённых клиентами в пул. В случае ряда ошибок обслуживающий процесс может быть разрушен клиентом, а не возвращён в пул. Это вызовет рост значения backend_pool.SCOPE.unlinks, но не backend_pool.SCOPE.releases. |
backend_pool.SCOPE.steals | Интегральный | Количество «краж» обслуживающих процессов из других бакетов пула. Интенсивный рост этого значения означает, что система испытывает высокую нагрузку на множестве различных баз данных и/или от множества различных пользователей. Это указывает на недостаточный размер пула для текущей нагрузки, что приводит к деградации производительности системы. |
backend_pool.SCOPE.errors | Интегральный | Количество ошибок, возникших при запросе обслуживающих процессов из пула. Это обобщённый счётчик. В некоторых случаях ошибки могут вызвать разрыв клиентских подключений. В других случаях ошибка может привести к повторению запроса обслуживающего процесса и быть прозрачной для клиента. Например, если пул отказывает в предоставлении обслуживающего процесса, так как его невозможно создать по причине превышения лимита max_connections, клиент будет ожидать в очереди. |
backend_pool.SCOPE.request_duration.p* | Процентиль (окно: T = 60 секунд, C = 1000 событий) | Процентили времени между запросом обслуживающего процесса и фактическим предоставлением обслуживающего процесса клиенту. Это совокупный счётчик, значения которого могут сильно отличаться. Например, предоставление свободного обслуживающего процесса из пула может занимать микросекунды, создание нового — миллисекунды. Но если пул перегружен, и клиент должен ждать выполнения предыдущего запроса к базе данных, это может занять секунды, минуты, и даже часы. Другими словами, этот счётчик показывает распределение времени ожидания в очереди пула перед выполнением запроса. |
Пример результата запроса метрик пула обслуживающих процессов выглядит следующим образом:
name | class | node_id | value -------------------------------------------+--------------+---------+------------------------ backend_pool.local.requests | backend-pool | 0 | 13 backend_pool.local.creations | backend-pool | 0 | 5 backend_pool.local.destructions | backend-pool | 0 | 3 backend_pool.local.unlinks | backend-pool | 0 | 4 backend_pool.local.acquisitions | backend-pool | 0 | 12 backend_pool.local.releases | backend-pool | 0 | 10 backend_pool.local.steals | backend-pool | 0 | 0 backend_pool.local.errors | backend-pool | 0 | 1 backend_pool.local.request_duration.p0 | backend-pool | 0 | 8.74983775227453e-06 backend_pool.local.request_duration.p5 | backend-pool | 0 | 8.765000496725975e-06 backend_pool.local.request_duration.p25 | backend-pool | 0 | 9.654992595293691e-06 backend_pool.local.request_duration.p50 | backend-pool | 0 | 1.0727600464262677e-05 backend_pool.local.request_duration.p75 | backend-pool | 0 | 1.1514681787272259e-05 backend_pool.local.request_duration.p95 | backend-pool | 0 | 0.008438241305000952 backend_pool.local.request_duration.p100 | backend-pool | 0 | 0.008452788451603185 backend_pool.remote.requests | backend-pool | 0 | 0 backend_pool.remote.creations | backend-pool | 0 | 0 backend_pool.remote.destructions | backend-pool | 0 | 0 backend_pool.remote.unlinks | backend-pool | 0 | 0 backend_pool.remote.acquisitions | backend-pool | 0 | 0 backend_pool.remote.releases | backend-pool | 0 | 0 backend_pool.remote.steals | backend-pool | 0 | 0 backend_pool.remote.errors | backend-pool | 0 | 0 backend_pool.remote.request_duration.p0 | backend-pool | 0 | 0 backend_pool.remote.request_duration.p5 | backend-pool | 0 | 0 backend_pool.remote.request_duration.p25 | backend-pool | 0 | 0 backend_pool.remote.request_duration.p50 | backend-pool | 0 | 0 backend_pool.remote.request_duration.p75 | backend-pool | 0 | 0 backend_pool.remote.request_duration.p95 | backend-pool | 0 | 0 backend_pool.remote.request_duration.p100 | backend-pool | 0 | 0
F.72.11.2.5. Метрики клиентских подключений #
Метрики клиентских подключений включают счётчики подключений и их характеристики для различных каналов связи.
Имена метрик клиентских подключений имеют структуру client.CHANNEL.COUNTER, где:
CHANNEL— канал связи, данные которого отображаются в результате запроса. Поддерживаются следующие каналы:lfe(local frontend) — клиенты, которые подключаются к proxima через один из портов для выполнения SQL-запросов.lbe(local backend) — обслуживающие процессы Postgres Pro Enterprise, созданные proxima.rfe(remote frontend) — клиенты, перенаправленные на текущий узел с другого узла.rbe(remote backend) — внутренние каналы связи, созданные расширением proxima для перенаправления запросов на удалённый узел.rpc(RPC, Remote Procedure Call) — данные, передаваемые между proxima и другими процессами текущего экземпляра базы данных.
COUNTER— имя счётчика.
Доступны следующие счётчики:
Таблица F.60. Счётчики клиентских подключений
| Имя | Тип | Описание |
|---|---|---|
client.lfe.now_connected | Мгновенное значение | Количество клиентов, фактически подключённых к текущему узлу. |
client.lfe.accepted | Интегральный | Количество клиентов с успешно аутентифицированными подключениями. |
client.lfe.rejected | Интегральный | Количество клиентов с подключениями, которые были отклонены, так как не были аутентифицированы. |
client.lfe.failed | Интегральный | Количество клиентов с подключениями, отклонёнными по причине ошибок процесса аутентификации. |
client.lfe.disconnected | Интегральный | Количество клиентов с закрытыми подключениями. |
client.lfe.auth_password | Интегральный | Количество клиентов, аутентифицированных по паролю. |
client.lfe.auth_md5 | Интегральный | Количество клиентов, аутентифицированных по методу MD5. |
client.lfe.auth_scram_sha256 | Интегральный | Количество клиентов, аутентифицированных по методу SCRAM-SHA-256. |
client.lfe.auth_ldap | Интегральный | Количество клиентов, аутентифицированных по методу LDAP. |
client.lfe.auth_trust | Интегральный | Количество клиентов, подключение от которых попало под правила HBA в категории доверенных. |
client.lfe.auth_reject | Интегральный | Количество клиентов, подключение от которых попало под правила HBA в категории запрещённых (reject). |
client.lfe.auth_tls_accepted | Интегральный | Количество принятых TLS-подключений. |
client.lfe.auth_tls_rejected | Интегральный | Количество отклонённых TLS-подключений. |
client.lfe.auth_duration.p* | Процентиль (окно: T = 60 секунд, C = 1000 событий) | Распределение времени для процедуры аутентификации клиентов. |
client.lbe.enter_dedicated | Интегральный | Количество подключений обслуживающих процессов, перешедших в выделенный сеанс. |
client.lbe.leave_dedicated | Интегральный | Количество подключений обслуживающих процессов, покинувших выделенный сеанс. |
client.lbe.dedicated_duration.p* | Процентиль (окно: T = 60 секунд, C = 1000 событий) | Распределение времени для подключений, оставшихся в выделенном сеансе. |
client.rfe.now_connected | Мгновенное значение | Фактическое количество клиентов, перенаправленных на текущий узел для выполнения запроса. |
client.rfe.connected | Интегральный | Количество клиентов, перенаправленных на текущий узел для выполнения запроса. |
client.rfe.disconnected | Интегральный | Количество клиентов с закрытыми подключениями. |
client.rbe.enter_dedicated | Интегральный | Количество подключений обслуживающих процессов, перешедших в выделенный сеанс. |
client.rbe.leave_dedicated | Интегральный | Количество подключений обслуживающих процессов, покинувших выделенный сеанс. |
client.rbe.dedicated_duration.p* | Процентиль (окно: T = 60 секунд, C = 1000 событий) | Распределение времени для подключений, оставшихся в выделенном сеансе. |
client.rpc.now_connected | Мгновенное значение | Количество клиентов, подключённых в настоящий момент. |
client.rpc.accepted | Интегральный | Количество клиентов с успешно принятыми подключениями с учётом прохождения процедуры аутентификации. |
client.rpc.rejected | Интегральный | Количество клиентов с отклонёнными подключениями, в основном из-за ошибок аутентификации. |
client.rpc.disconnected | Интегральный | Количество клиентов с закрытыми подключениями. |
Пример результата запроса метрик клиентских подключений выглядит следующим образом:
name | class | node_id | value ------------------------------------+--------+---------+------- client.lfe.now_connected | client | 0 | 1 client.lfe.accepted | client | 0 | 1 client.lfe.rejected | client | 0 | 0 client.lfe.failed | client | 0 | 0 client.lfe.disconnected | client | 0 | 0 client.lfe.auth_password | client | 0 | 0 client.lfe.auth_md5 | client | 0 | 0 client.lfe.auth_scram_sha256 | client | 0 | 0 client.lfe.auth_ldap | client | 0 | 0 client.lfe.auth_trust | client | 0 | 1 client.lfe.auth_reject | client | 0 | 0 client.lfe.auth_tls_accepted | client | 0 | 0 client.lfe.auth_tls_rejected | client | 0 | 0 client.rfe.now_connected | client | 0 | 0 client.rfe.connected | client | 0 | 0 client.rfe.disconnected | client | 0 | 0 client.lbe.enter_dedicated | client | 0 | 0 client.lbe.leave_dedicated | client | 0 | 0 client.rbe.enter_dedicated | client | 0 | 0 client.rbe.leave_dedicated | client | 0 | 0 client.rpc.now_connected | client | 0 | 1 client.rpc.accepted | client | 0 | 4 client.rpc.rejected | client | 0 | 0 client.rpc.disconnected | client | 0 | 3 client.lfe.auth_duration.p0 | client | 0 | 0 client.lfe.auth_duration.p5 | client | 0 | 0 client.lfe.auth_duration.p25 | client | 0 | 0 client.lfe.auth_duration.p50 | client | 0 | 0 client.lfe.auth_duration.p75 | client | 0 | 0 client.lfe.auth_duration.p95 | client | 0 | 0 client.lfe.auth_duration.p100 | client | 0 | 0 client.lbe.dedicated_duration.p0 | client | 0 | 0 client.lbe.dedicated_duration.p5 | client | 0 | 0 client.lbe.dedicated_duration.p25 | client | 0 | 0 client.lbe.dedicated_duration.p50 | client | 0 | 0 client.lbe.dedicated_duration.p75 | client | 0 | 0 client.lbe.dedicated_duration.p95 | client | 0 | 0 client.lbe.dedicated_duration.p100 | client | 0 | 0 client.rbe.dedicated_duration.p0 | client | 0 | 0 client.rbe.dedicated_duration.p5 | client | 0 | 0 client.rbe.dedicated_duration.p25 | client | 0 | 0 client.rbe.dedicated_duration.p50 | client | 0 | 0 client.rbe.dedicated_duration.p75 | client | 0 | 0 client.rbe.dedicated_duration.p95 | client | 0 | 0 client.rbe.dedicated_duration.p100 | client | 0 | 0
F.72.11.2.6. Метрики RPC-сервера #
Доступны следующие счётчики:
Таблица F.61. Счётчики RPC-сервера
| Имя | Тип | Описание |
|---|---|---|
rpc.call_duration.p* | Процентиль (окно: T = 60 секунд, C = 1000 событий) | Время распределения выполнения команд. |
rpc.err_not_found | Интегральный | Количество вызовов несуществующих функций. |
Пример результата запроса метрик RPC-сервера выглядит следующим образом:
name | class | node_id | value ------------------------+-------+---------+------------------------ rpc.call_duration.p0 | rpc | 0 | 4.315190768277686e-05 rpc.call_duration.p5 | rpc | 0 | 4.331642078668621e-05 rpc.call_duration.p25 | rpc | 0 | 6.386338595749277e-05 rpc.call_duration.p50 | rpc | 0 | 7.37059571607683e-05 rpc.call_duration.p75 | rpc | 0 | 8.217731456416661e-05 rpc.call_duration.p95 | rpc | 0 | 0.00011075225182228674 rpc.call_duration.p100 | rpc | 0 | 0.00011117317272816024 rpc.err_not_found | rpc | 0 | 0
F.72.11.2.7. Системные метрики #
Доступны следующие счётчики:
Таблица F.62. Системные счётчики
| Имя | Тип | Описание |
|---|---|---|
system.cpu_load | Мгновенное значение | Процент загрузки ЦП на узле. |
system.avail_ram_b | Мгновенное значение | Объём свободной оперативной памяти на узле, в байтах. |
system.total_ram_b | Мгновенное значение | Общий объём оперативной памяти на узле, в байтах. |
system.io_avg_latency_ms | Мгновенное значение | Среднее время ожидания выполнения одной операции при обращении к диску, в миллисекундах. |
Пример результата запроса системных метрик выглядит следующим образом:
name | class | node_id | value --------------------------+--------+---------+-------------------- system.cpu_load | system | 0 | 6.779661016949152 system.avail_ram_b | system | 0 | 22180810752 system.total_ram_b | system | 0 | 32619315200 system.io_avg_latency_ms | system | 0 | 3.6666666666666665
F.72. proxima — a combination of a proxy, a load balancer, and a connection pooler #
proxima is a Postgres Pro Enterprise extension that combines functionality of a proxy server, a load balancer, and a connection pooler.
F.72.1. Overview #
The proxima extension can be used on a single-node Postgres Pro Enterprise server, in a standard Postgres Pro Enterprise primary-standby cluster or a BiHA cluster. The extension offers the following features:
Proxy server: proxima becomes a single connection point for client connections and redirects queries to the primary server or the BiHA cluster leader.
Connection pooler: proxima manages backend processes to lower consumption of system resources and prevent performance degradation.
Load balancer: built-in functionality for balancing read-only workloads across cluster replicas by the defined load balancing algorithm.
SSL support: you can configure proxima to operate with SSL connections.
Monitoring: when using proxima with BiHA, you can view a variety of metrics to track the proxima state.
Dynamic dedicated session: proxima maintains a session between the client and the backend for the entire lifetime of the client connection.
F.72.2. Considerations and Limitations #
This section provides a list of considerations and limitations that must be taken into account when using proxima.
F.72.2.1. General Considerations and Limitations #
The proxima extension does not manage replication between cluster nodes. To provide data consistency on all nodes, either use Built-in High Availability (BiHA), or configure replication manually.
Elbrus, ppc64le, and s390x CPU architectures are not supported.
When used in a standard primary-standby cluster or a BiHA cluster, right after the launch proxima may log error messages about connection or synchronization faults. This behavior is normal as nodes launch at different times. The error message logging stops shortly after the launch.
Currently, proxima has no mechanism to automatically establish dynamic dedicated session when you use extensions that keep their state within a session. For such cases, you must manually enable the forced dynamic dedicated session.
Dynamic dedicated session is not established when executing
CREATE STATISTICSin a temporary namespace.To enable the connection pooler to process a large number of client connections, you must set the limit of open files higher than the target number of connections:
sudo echo '* soft nofile
{value}' >> /etc/security/limits.conf sudo echo '* hard nofile{value}' >> /etc/security/limits.conf ulimit -n{value}For example, if the target number of client connections is
10000, set{value}to11000.
F.72.2.2. Considerations and Limitations when Operating in a BiHA Cluster #
The proxima extension offers a special operation mode for a BiHA cluster. When installed in the BiHA cluster, proxima automatically receives all required cluster configuration parameters from biha, such as:
number of cluster nodes
node IDs, addresses, and ports
node roles (leader, follower, or front follower)
You can either install proxima in the existing BiHA cluster, or enable it when setting up the cluster from scratch.
The proxima extension registers a set of callbacks to receive notifications about events in the BiHA cluster. For example, when the leader changes, proxima is notified about this event and automatically redirects traffic to the new leader. The callbacks are located in the
biha.callbackstable of thebiha_dbdatabase on BiHA cluster nodes. Do not delete these callbacks, as it would prevent proxima from reacting to the cluster events.When proxima is enabled in the BiHA cluster, cluster nodes connect to each other using the port P2L + 1. To ensure normal operation, the P2L port number must be identical on all nodes, and the port P2L + 1 must be free. For more information about P2L and P2F ports, refer to Section F.72.6.
If a node changes its state to
FRONT FOLLOWERorLEADER, on this node, proxima does not see other nodes until they exit theUNKNOWNstate. It means that this proxima instance terminates connections to other proxima instances, which also disconnects all active clients from this node.The proxima extension balances workloads across all cluster nodes according to the set balancing algorithm. If you use multiple segments, queries to the P2F port in the leader segment can be redirected to read-only nodes in the follower segment. If you do not want proxima to redirect queries to the follower segment nodes, you can set the
weighted_round_robinbalancing algorithm for proxima.load_balancer_algorithm and specify node weights using the proxima.load_balancer_node_weight configuration parameter. The nodes where you do not want proxima to redirect queries must get the lowest node weights, while the nodes where you want queries to be redirected must get the highest node weights. This solution does not fully exclude the possibility of redirecting queries to unwanted nodes, but helps to reduce it to a minimum.
F.72.3. Installation and Configuration #
The proxima extension is a built-in extension included into Postgres Pro Enterprise. To enable and configure proxima, perform the following steps:
Stop your Postgres Pro Enterprise server using pg_ctl:
pg_ctl stop -D
PGDATA_directoryAdd proxima to shared_preload_libraries in postgresql.conf:
shared_preload_libraries = 'proxima'
If you have a multi-node cluster, repeat this step on every node.
Depending on your Postgres Pro Enterprise configuration, specify the proxima configuration parameters in postgresql.conf:
For a single-node server, set the following configuration parameter:
proxima.cluster_mode = 'standalone'
For a standard primary-standby cluster, set the following configuration parameters:
proxima.cluster_mode = 'guc' proxima.cluster_config = '
node0_id,node0_address,node0_port,node0_role;node1_id,node1_address,node1_port,node1_role;' proxima.cluster_node_id =node_idFor example:
proxima.cluster_mode = 'guc' proxima.cluster_config = '0,192.168.0.57,4590,P;1,192.168.0.77,4590,S;' proxima.cluster_node_id = 0
Ensure that the proxima.cluster_config values are the same on all nodes and proxima.cluster_node_id is unique for each node.
For a BiHA cluster, set the following configuration parameter:
proxima.cluster_mode = 'biha'
When using proxima with biha, specifying cluster configuration parameters is not required as proxima receives this information directly from biha.
(Optional) If required, set other configuration parameters.
If you do not specify configuration parameters, proxima uses the default values. For more information about configuration parameters and their default values, refer to Section F.72.11.1.
Start the node using pg_ctl:
pg_ctl start -D
PGDATA_directory
F.72.4. Connecting to proxima #
This section provides connection string examples for connecting to proxima using different language interfaces.
In the examples below, the default 4545 P2L port number is used where all connections are redirected to the cluster primary (leader). However, if you want to use proxima as a load balancer and distribute read-only workloads across cluster replicas, you must also configure connection through the P2F port (4547 by default). For more information about load balancer configuration, refer to Section F.72.6.1.
In connection strings created specially for read-write or read-only connections, i.e. using either P2L or P2F port, specifying the target_session_attrs (psql/libpq, Python, Go) or targetServerType (JDBC) parameter is not required as connections are distributed by proxima.
F.72.4.1. psql/libpq #
Connection to proxima using the psql/libpq library looks as follows:
psql -d "dbname=postgres host=node3,node4,node2,node1 port=4545,4545,4545,4545 user=username password=password"
psql postgres://username:password@node1:4545,node2:4545,node3:4545,node4:4545/postgres
F.72.4.2. Python #
Connection to proxima using the psycopg2 library looks as follows:
import psycopg2
from psycopg2 import pool
pool = psycopg2.pool.SimpleConnectionPool(
min_size=1,
max_size=5,
user="pguser",
password="*****",
host="node1,node2,node3,node4",
port="4545,4545,4545,4545",
database="postgres")
connection = pool.getconn()
F.72.4.3. JDBC #
Connection to proxima using JDBC looks as follows:
String url = "jdbc:postgresql://node1:4545,node2:4545,node3:4545,node4:4545/postgres?loadBalanceHosts=true";
Properties props = new Properties();
props.setProperty("user","postgres");
props.setProperty("password","********");
Connection conn = DriverManager.getConnection(url, props);
url contains the connection string, where all the available nodes are listed. If no additional connection parameters of the JDBC driver are specified, connection to the cluster is performed through the first node available for connection. This is not always convenient. Therefore, connection string settings are added that allow using different nodes for different connections.
Setting the loadBalanceHosts parameter to true allows iterating through nodes connecting to one of them.
F.72.4.4. Go #
Ways to connect to proxima for Go are pretty much the same as those accepted in JDBC or Python. You need to specify lists of nodes, their TCP ports, as well as connection parameters and choose a suitable driver.
One of these drivers for Go is pgx version 4 or 5.
The following is an example of a connection string and creation of a pool for connecting to a cluster:
dbURL := "postgres://username:password@node1:4545,node2:4545,node3:4545,node4:4545/postgres" dbPool, err := pgxpool.New(context.Background(), dbURL)
F.72.5. Authentication #
The proxima extension uses the same authentication rules that are listed in the pg_hba.conf file. The following authentication methods are supported:
F.72.5.1. Proxying Authentication to the Primary (Leader) Node #
By default, user authentication is performed locally on nodes. However, in some cases, it is required to perform authentication on the primary (leader) node. The proxima extension provides the ability to proxy user authentication from any cluster node to the primary (leader).
You can specify where to perform user authentication by means of the proxima.auth_policy configuration parameter, which supports the local and leader modes.
The leader mode is automatically set for the BiHA referee node in a BiHA cluster meaning that authentication is performed on the leader. This is required, because the referee node has not enough information to authenticate users locally.
Note
The referee node can be deployed in the following operation modes: referee or referee_with_wal. If you use the referee mode, it is recommended to first start the leader with proxima enabled, and then add the referee. The reason is that proxima creates callbacks on the cluster leader which are replicated to other nodes, but not to the referee in the referee mode. However, if you add the referee after enabling proxima, all the required callbacks are copied by the bihactl utility.
For other cluster nodes, the value of proxima.auth_policy is set to local by default meaning that authentication is performed locally on nodes. However, if new databases or users are frequently created in your cluster, lagging asynchronous replicas may fail to authenticate a new user shortly after creation of the user or a database on the primary (leader) node, because those are still absent on the replica. To avoid this issue, you can set the leader value for the proxima.auth_policy configuration parameter on all cluster nodes.
F.72.6. Load Balancer #
The load balancing functionality allows distributing read-only workloads across cluster replicas using the defined load balancing algorithm.
The proxima extension provides the following ports to process client sessions:
The Proxy-to-Leader (P2L) port redirects all workloads to the primary (leader) node. The default is 4545, which can be changed using the proxima.port parameter. The P2L port number must be identical on all nodes of the cluster.
The Proxy-to-Follower (P2F) port distributes read-only workloads across cluster replicas. The default is 4547, which can be changed using the proxima.p2f_port parameter.
Note
In a BiHA cluster, queries are redirected to the leader in the LEADER_RW state. However, read-only workloads sent to the P2F port can also be redirected to the leader in the LEADER_RO state. For more information about BiHA cluster node states, refer to biha.status_v.
To distribute workloads across cluster nodes, configure your client application to send write workloads to the P2L port and read-only workloads to the P2F port. For more information, refer to Section F.72.6.1.
Important
proxima attaches a client session to a certain cluster node to ensure that all transactions within this particular session are executed on the same node. If this node fails during the session, the client connection is aborted.
F.72.6.1. Configuring Load Balancer #
You can configure proxima to distribute workloads across cluster nodes. In the example below, you will configure workload distribution for a three-node cluster with 192.168.0.1, 192.168.0.2, and 192.168.0.3 node addresses using the default 4545 (P2L) and 4547 (P2F) proxima ports.
Configure your client application to send write workloads to the P2L port and read-only workloads to the P2F port.
You can use the target_session_attrs parameter on the client side to specify the node type where the client must execute transactions and queries when connecting to the database.
For example, you can specify that queries must be executed on replicas only so within this connection the client will execute read-only queries sent to the P2F port.
(Optional) Specify the load balancing algorithm for read-only workloads using the proxima.load_balancer_algorithm parameter.
In the connection string, list the following node addresses in accordance with the format required by your library:
192.168.0.1:4545 192.168.0.1:4547 192.168.0.2:4545 192.168.0.2:4547 192.168.0.3:4545 192.168.0.3:4547
If you use libpq, refer to Section 36.1.1.3 for the requirements and syntax of specifying multiple addresses in a connection string.
As a result, when connected to port 4545 (P2L), write workloads are redirected to the primary (leader) node. When connected to port 4547 (P2F), read-only workloads are redirected to one of the replicas according to the selected algorithm.
F.72.7. Dynamic Dedicated Session #
When executing queries, a backend may keep temporary state within one session and create objects specific for this session, such as temporary tables, temporary views, etc. This information and these objects are not available for other backends. If a connection pooler redirects a client to another backend after such an object is created, the client has no more access to the object. To avoid this issue, proxima offers the dynamic dedicated session functionality that allows to retain sessions between clients and specific backends during the client connection lifetime.
Note
If you use extensions that keep their state within a session, you must manually enable the forced dynamic dedicated session. For more information, refer to Section F.72.7.2.
The proxima extension establishes the dynamic dedicated session automatically if a query contains any of the following objects or SQL functions:
prepared statements, which are also created within an extended query protocol parse message. To avoid establishing the dynamic dedicated session for prepared statements, you can use the prepared statement storage functionality.
SET SESSION,SET SESSION AUTHORIZATION, andSET SESSION CHARACTERISTICS AS TRANSACTIONNote
The dynamic dedicated session is not established if these commands modify any of the following configuration parameters: application_name, client_encoding, scram_iterations, DateStyle, default_transaction_read_only,
session-authorization, standard_conforming_strings, IntervalStyle, or TimeZone.Note
When using the
pg_backend_set_configfunction, the dynamic dedicated session is established for the target backend with the specified PID, rather than the one where the function is called from.CREATE STATISTICSin a temporary schema, for example:CREATE TABLE my_table (id1 int, id2 int); CREATE STATISTICS pg_temp.my_stats ON id1, id2 FROM my_table;
The session remains dedicated until the above mentioned objects are deleted.
The DISCARD function deletes session objects. After executing DISCARD ALL, a backend exits both the dynamic dedicated session and forced dynamic dedicated session.
F.72.7.1. Prepared Statement Storage #
Warning
The prepared statement storage functionality is currently experimental and is not recommended for using in production.
To avoid establishing dynamic dedicated sessions for queries with prepared statements, proxima provides the prepared statement storage functionality. When a client creates a prepared statement, its text and parameters are saved in the proxima storage. If proxima redirects the client to another backend, the new backend retrieves the prepared statement from the storage and prepares it locally. Therefore, establishing a dedicated session is not required when operating with prepared statements.
The prepared statement storage is located in the proxima process and cannot be managed directly. When a client creates or deletes a prepared statement, a backend informs proxima of a need to update the storage accordingly. The storage size depends on the number of connected clients and created prepared statements. Each client requires approximately 104 bytes of memory for system information. Each stored prepared statement requires approximately 58 bytes, and the total memory consumed depends on the query name, query text, parameter type specifications, etc. Consider this information when allocating RAM for your cluster.
You can manage the prepared statement storage functionality as follows:
To enable the prepared statement storage, use the proxima.ps_enabled configuration parameter. When
proxima.ps_enabledis set toon, proxima assigns a unique session ID to every client and provides this ID to a backend. Backends retrieve prepared statements from the storage considering the provided ID. This mechanism ensures that prepared statements of a specific client are not available for clients with other session IDs.To make prepared statements created by one of the clients available for all, use the proxima.ps_shared configuration parameter. When
proxima.ps_sharedis set toon, all clients use the same session ID, and prepared statements become visible for all backends within a node.Important
Prepared statements can only be shared within a single node. Since proxima distributes read-only workloads across cluster replicas according to the specified balancing algorithm, different clients may be redirected to different nodes. Consequently, a prepared statement created by
Client 1onNode 1is not accessible forClient 2connected toNode 2.When
proxima.ps_sharedis set toon, theDEALLOCATE ALLcommand does not clear the proxima storage. The reason is that prepared statements are shared and can be used by other clients.
To modify the maximum number of prepared statements in a backend, set the value of the proxima.ps_cache_size configuration parameter using the
SETcommand, for example:SET proxima.ps_cache_size = 64;
Note
Both proxima.ps_enabled and proxima.ps_shared configuration parameters only control how session IDs are provided by the proxima process, not the backend behavior. Changing these parameters, including via SIGHUP, does not affect the previously connected clients, as their session ID remains the same. The changes are only applied to new clients.
F.72.7.2. Managing Dynamic Dedicated Sessions Manually #
Some extensions keep their state within a session, which requires to retain the session between a client and a backend. If you use such extensions, you must manually enable the dynamic dedicated session at every connection by using the proxima.force_dedicated parameter.
You can manage forced dynamic dedicated sessions as follows:
To enable the forced dynamic dedicated session, execute the following command:
SET proxima.force_dedicated = true;
To disable the forced dynamic dedicated session, execute the following command:
SET proxima.force_dedicated = false;
To check whether the current session is dedicated, use proxima.is_dedicated:
SHOW proxima.is_dedicated;
The returned
tvalue means that the session is dedicated, whilefmeans that it is not dedicated.
F.72.8. Monitoring #
The proxima extension provides the monitoring functionality with a range of metrics to track the proxima state. Monitoring is currently available for BiHA clusters with proxima enabled.
proxima registers the proxima schema in the biha_db database and creates there special views that are used to query metrics. For more information on viewing metrics and an example of an SQL query, refer to Section F.72.8.3.
F.72.8.1. Metrics Transfer Across Cluster Nodes #
To make all cluster metrics available on all nodes, every node transmits its metrics to other nodes once per second. If metrics are not received from a node within ten seconds, for example, due to connection loss or node failure, a query will not return counter values from this node.
F.72.8.2. Considerations for Queries via P2L and P2F Ports #
Since metrics are queried using standard SQL, the metrics source is always the node that actually executes the query. When executing a query, consider the following:
When connecting via the P2L port, metrics are retrieved from the cluster leader.
When connecting via the P2F port, proxima may distribute consecutive metrics queries across different nodes. Due to metrics delivery latency, this may cause sequential queries showing decrease of values for integral counters.
For more information about P2L and P2F ports, refer to Section F.72.6.
To maintain integral counter monotonicity, always take the maximum value between the current and previously observed metrics values during result processing.
F.72.8.3. Viewing Monitoring Metrics #
You can view monitoring metrics in a BiHA cluster using standard SQL queries on metrics views:
To view all cluster metrics:
SELECT * FROM proxima.proxima_metrics;
To view all metrics of a particular node:
SELECT * FROM proxima.proxima_metrics WHERE node_id =
node_id;To view metrics of a particular class, execute a query on a corresponding class view. For example:
SELECT * FROM proxima.proxima_metrics_client;
For more information about the monitoring functionality, refer to Section F.72.8.
For more information about available metrics, refer to Section F.72.11.2.
See below for the example of a query to view all metrics of the node with the 0 node ID and its output (which was cut as there are too many metrics):
postgres=# SELECT * FROM proxima.proxima_metrics WHERE node_id = 0;
name | class | node_id | value
-------------------------------------------+--------------+---------+----------------------
thread.1.active_time_ns | thread-load | 0 | 12590006201
thread.1.purged_coroutines | thread-load | 0 | 6
thread.1.transferred_coroutines_accepted | thread-load | 0 | 2
thread.1.wakeup_requests_accepted | thread-load | 0 | 0
thread.1.futex_wakeup_requests_accepted | thread-load | 0 | 22752
thread.1.active_coroutines_called | thread-load | 0 | 72905
thread.1.evrun_once | thread-load | 0 | 38456
thread.1.evrun_nowait | thread-load | 0 | 8700
thread.1.scheduler.coroctx_in_use | thread-load | 0 | 19
thread.1.scheduler.coroctx_cached | thread-load | 0 | 6
thread.1.scheduler.cs_active | thread-load | 0 | 1
thread.1.scheduler.cs_inactive | thread-load | 0 | 1
thread.1.scheduler.cs_waiting_futex | thread-load | 0 | 5
thread.1.scheduler.cs_wakeup_futex | thread-load | 0 | 0
thread.1.scheduler.cs_waiting_io | thread-load | 0 | 12
memory.lgist-0 | memory | 0 | 0
memory.lgist-1 | memory | 0 | 8
memory.lgist-2 | memory | 0 | 15
memory.lgist-3 | memory | 0 | 162
memory.lgist-4 | memory | 0 | 737
memory.lgist-5 | memory | 0 | 1490
memory.lgist-6 | memory | 0 | 174
memory.lgist-7 | memory | 0 | 295
memory.lgist-8 | memory | 0 | 70
memory.lgist-9 | memory | 0 | 32
memory.lgist-10 | memory | 0 | 20
memory.lgist-11 | memory | 0 | 9
memory.lgist-12 | memory | 0 | 1
memory.lgist-13 | memory | 0 | 71
memory.lgist-14 | memory | 0 | 61
memory.lgist-15 | memory | 0 | 0
memory.lgist-16 | memory | 0 | 6
memory.lgist-17 | memory | 0 | 1
memory.lgist-18 | memory | 0 | 0
memory.lgist-19 | memory | 0 | 0
memory.lgist-20 | memory | 0 | 0
memory.lgist-21 | memory | 0 | 0
memory.lgist-22 | memory | 0 | 1
memory.lgist-23 | memory | 0 | 0
memory.lgist-24 | memory | 0 | 0
memory.usage | memory | 0 | 6581078
memory.traffic | memory | 0 | 7983836
client.lfe.now_connected | client | 0 | 1
client.lfe.accepted | client | 0 | 1
client.lfe.rejected | client | 0 | 0
client.lfe.disconnected | client | 0 | 0
client.lfe.auth_password | client | 0 | 0
client.lfe.auth_md5 | client | 0 | 0
client.lfe.auth_scram_sha256 | client | 0 | 0
client.lfe.auth_trust | client | 0 | 1
client.lfe.auth_tls_accepted | client | 0 | 0
client.lfe.auth_tls_rejected | client | 0 | 0
client.rfe.now_connected | client | 0 | 0
client.rfe.connected | client | 0 | 0
client.rfe.disconnected | client | 0 | 0
client.lbe.enter_dedicated | client | 0 | 0
F.72.9. General Administration #
This section describes how to administer proxima.
F.72.9.1. SSL Configuration #
You can enable SSL both for incoming client connections and for internal communication between cluster nodes.
F.72.9.1.1. Enabling SSL for Incoming Client Connections #
Enable SSL for incoming client connections:
Stop the cluster nodes using pg_ctl.
Obtain and install a certificate and a private key.
You can either obtain those from independent certificate authorities (CA), or generate your own certificates using a certificate management utility, such as OpenSSL.
In postgresql.conf, specify paths to the certificate and private key:
proxima.ssl_key = '
/path/to/key.pem' proxima.ssl_cert = '/path/to/cert.pem'If you do not specify the proxima.ssl_cert and proxima.ssl_key parameters, proxima uses a certificate and a key configured for Postgres Pro in
ssl_cert_fileandssl_key_file.Enable SSL for incoming connections using proxima.ssl_enabled:
proxima.ssl_enabled = on
(Optional) To verify client certificates, specify the path to the file containing public CA certificates using the proxima.ssl_ca configuration parameter.
This parameter is mandatory if you use the certificate authentication method.
Start the nodes using pg_ctl.
All client connections to the proxima port are now secured with SSL.
F.72.9.1.2. Enabling SSL Authentication for Internal Connections #
Configure SSL authentication for internal connections between cluster nodes. In this procedure, you will configure SSL authentication for a two-node cluster.
Stop the cluster nodes using pg_ctl.
For each node of your cluster, obtain and install a certificate and a private key.
You can either obtain those from independent certificate authorities (CA), or generate your own certificates using a certificate management utility, such as OpenSSL.
Enable SSL for communication between cluster nodes using proxima.p2p_ssl_enabled:
proxima.p2p_ssl_enabled = on
Set the proxima.p2p_auth_methods and proxima.ssl_trusted_certs_dir configuration parameters as follows:
proxima.p2p_auth_methods = 'ssl' proxima.ssl_trusted_certs_dir =
path_to_the_directory_with_certificatesStart the nodes using pg_ctl.
Check the log to ensure that SSL authentication is successful.
The following log entries indicate that the SSL authentication method is used and that authentication has passed successfully:
[auth]: using SSL authentication [auth]: authentication success
F.72.9.2. Disabling and Enabling proxima #
You can temporarily disable the proxima extension and then re-enable it using the proxima.enabled configuration parameter:
In the postgresql.conf file, set the
proxima.enabledparameter as required:To disable proxima, set
proxima.enabledtooff:proxima.enabled = off
To enable proxima, set
proxima.enabledtoon:proxima.enabled = on
Send the SIGHUP signal to the
proximaprocess:kill -SIGHUP
proxima_pidHere
proxima_pidis the process ID of the theproximaprocess.
F.72.9.3. Migration #
When migrating your Postgres Pro Enterprise cluster with proxima, always disable proxima before you start migrating your BiHA cluster. When the migration is finished, re-enable proxima. You can disable and enable proxima in a BiHA cluster using the biha.enable_proxima function.
F.72.9.4. Removing proxima #
To stop using proxima:
On all nodes of the cluster, remove the extension from the shared_preload_libraries in postgresql.conf.
Restart the nodes using
pg_ctl.
F.72.10. Troubleshooting #
This section contains information about typical issues that you might encounter when using proxima and the ways you can fix them.
F.72.10.1. Database or User Not Found #
The proxima extension performs authentication on a node locally and does not redirect access requests to the primary server or the leader. If a database or a user you are trying to connect to is not found, do the following:
Ensure that replication is configured between cluster nodes by means of the standard replication mechanism or using BiHA.
If replication is configured and turned on, wait for some time as the data may not have reached the replica yet.
F.72.10.2. Failed to Connect to proxima #
If you cannot connect to proxima, do the following:
Ensure that you use proxima.port for connection.
Ensure that the pg_hba.conf file is configured correctly.
F.72.10.3. Log Message: “connection cannot be established” #
If you see this message from proxima in the log, do the following:
Ensure that all nodes are on and there are no network issues.
If you use the
guccluster operation mode, ensure that the proxima.cluster_node_id values are set up correctly for each node and match the IDs specified in proxima.cluster_config.
F.72.10.4. Log Message: “failed to create cluster manager” #
If you use the guc cluster operation mode, ensure that proxima.cluster_config is configured correctly:
all required values are listed
a set of values for each node ends with a semicolon (
;)
F.72.10.5. Log Message: “postgres: cannot accept new connection, error: Too many open files” #
Increase the maximum number of open files by means of the ulimit -S -n command.
F.72.10.6. Log Message: “router: trying to route session, last error: error_message” #
This log message may occur when connecting to cluster nodes.
Do the following:
In case of a BiHA cluster, ensure that the value of the proxima.port configuration parameter (the P2L port) is the same on all nodes of your cluster. After setting identical P2L port numbers, try to reconnect.
If different P2L port numbers are not the case, check the
error_messagecontent:If the message contains “failed to find leader config”, wait for the node to receive information about the primary (leader). When information is received, the connection is established.
If the message contains “load balancer error: are there any RO nodes in the cluster? Aborting”, ensure there are nodes in the
ROstate and reconnect.
F.72.11. Reference #
F.72.11.1. Configuration Parameters #
F.72.11.1.1. Common Parameters #
proxima.address(text) #Specifies the IP addresses that proxima listens to. You can specify IPv4 or IPv6 addresses, as well as Unix socket directories. Values are comma-separated. You can specify addresses as follows:
Any number of IPv4 addresses, provided that each address corresponds to the address of one of the local network interfaces. The
0.0.0.0address represents all interfaces. If specified, all other provided IPv4 addresses are ignored.Any number of IPv6 addresses, provided that each address corresponds to the address of one of the local network interfaces. The
::0address represents all interfaces. If specified, all other provided IPv6 addresses are ignored.Any number of paths to Unix socket directories. The Unix socket name format is
.s.PGSQL., whereportportis the number corresponding to one of the P2L or P2F ports. Socket names imitate PostgreSQL sockets in order to use psql or pgbench for connections via proxima.The paths that you specify must be absolute and start with a slash. You can also specify the
/$[macros whereindex]indexis the number of the directory from the list specified in the unix_socket_directories configuration parameter. If theunix_socket_directoriesvalue is not specified orindexis higher than the number of directories, the/tmpdirectory is used. Directory names must not contain spaces, all spaces are ignored during parsing.
The default value is
0.0.0.0,::0,$/[0].proxima.enabled(boolean) #Temporarily enables and disables proxima. The available values are the following:
off: temporarily stops the proxima extension.on: starts the proxima extension after it was temporarily stopped.
proxima.force_dedicated(boolean) #Enables and disables forced dynamic dedicated sessions. The available values are the following:
true: enables the forced dynamic dedicated session.false: disables the forced dynamic dedicated session.
For more information, refer to Section F.72.7.2.
proxima.is_dedicated(boolean) #Allows to check whether the current session is dedicated. Returns one of the following values:
t: the session is dedicated.f: the session is not dedicated.
For more information, refer to Section F.72.7.2.
proxima.load_balancer_algorithm(text) #Specifies the load balancing algorithm for distributing read-only workloads between cluster replicas. The following values are supported:
round-robin: workloads are distributed across replicas sequentially.weighted-round-robin: workloads are distributed across replicas sequentially, proportionally to their configured weights. If you select this algorithm, set node weights using the proxima.load_balancer_node_weight configuration parameter.adaptive: workloads are distributed across replicas in a way similar to theweighted-round-robinalgorithm. However, for theadaptivealgorithm, values of replica weights depend on CPU, RAM, and disk I/O load at any specific time. The higher the load on a replica, the fewer queries are redirected to it. Theadaptivealgorithm determines how utilization of each resource impacts node selection during balancing. You can specify a share of each resource using proxima.load_balancer_cpu_weight, proxima.load_balancer_io_weight, and proxima.load_balancer_ram_weight.adaptive-cpu: workloads are distributed across replicas depending on utilization of CPU. The higher utilization on a replica, the fewer queries are redirected to it.adaptive-io: workloads are distributed across replicas depending on disk I/O load. The higher the load on a replica, the fewer queries are redirected to it. You can also set the average waiting time for execution of a single operation when accessing disk using proxima.load_balancer_io_max_latency_ms and proxima.load_balancer_io_min_latency_ms.adaptive-ram: workloads are distributed across replicas depending on utilization of RAM. The higher utilization on a replica, the fewer queries are redirected to it.least-connections: workloads are distributed to the replica with the lowest number of active connections.random: workloads are distributed across replicas in random order.
The default value is
round-robin.proxima.load_balancer_node_weight(integer) #Specifies the weight of the current node for the
weighted-round-robinalgorithm set in the proxima.load_balancer_node_weight configuration parameter. The percentage of redirected queries to theknode is calculated based on the following formula:Pk = (nodek.weight / Σi nodei.weight) × 100%Only replica nodes are considered in calculation.
You can modify the parameter value without node restart by sending the SIGHUP signal.
The value can be set in the range from
1to10000. The default value is100.proxima.load_balancer_cpu_weight(integer) #Specifies the share of the CPU utilization impact on the node weight calculation. The value can be set in the range from
0to10000. The default value is100. The parameter is active when you set theadaptivevalue for proxima.load_balancer_algorithm.proxima.load_balancer_io_weight(integer) #Specifies the share of the disk I/O load impact on the node weight calculation. The value can be set in the range from
0to10000. The default value is100. The parameter is active when you set theadaptivevalue for proxima.load_balancer_algorithm. You can also set the average waiting time for execution of a single operation when accessing disk using proxima.load_balancer_io_max_latency_ms and proxima.load_balancer_io_min_latency_ms.proxima.load_balancer_io_max_latency_ms(integer) #Specifies the maximum waiting time for execution of a single operation when accessing disk, in milliseconds. If the actual value of the system.io_avg_latency_ms counter is higher than the
proxima.load_balancer_io_max_latency_msvalue, the node receives the lowest possible weight share that depends on the disk I/O load. The value can be set in the range from0to2^32-1. The default value is40. The parameter is active when you set theadaptiveoradaptive-iovalue for proxima.load_balancer_algorithm.proxima.load_balancer_io_min_latency_ms(integer) #Specifies the minimum waiting time for execution of a single operation when accessing disk, in milliseconds. If the actual value of the system.io_avg_latency_ms counter is lower than the
proxima.load_balancer_io_min_latency_msvalue, the node receives the highest possible weight share that depends on the disk I/O load. The value can be set in the range from0to2^32-1. The default value is10. The parameter is active when you set theadaptiveoradaptive-iovalue for proxima.load_balancer_algorithm.proxima.load_balancer_ram_weight(integer) #Specifies the share of the RAM utilization impact on the node weight calculation. The value can be set in the range from
0to10000. The default value is100. The parameter is active when you set theadaptivevalue for proxima.load_balancer_algorithm.proxima.port(integer) #Specifies the Proxy-to-Leader (P2L) port — a TCP port where proxima accepts incoming client connections and transfers all queries to the primary (leader) node.
The value can be set in the range from
0to65535. The default value is4545. Theproxima.portnumber must be identical on all nodes of the cluster.For more information about P2L and P2F ports, refer to Section F.72.6.
proxima.p2f_port(integer) #Specifies the Proxy-to-Follower (P2F) port — a TCP port where proxima accepts incoming client connections and distribute read-only workloads between cluster replicas.
The value can be set in the range from
0to65535. The default value is4547.For more information about P2L and P2F ports, refer to Section F.72.6.
proxima.p2p_auth_methods(text) #Specifies authentication methods for internal communication of cluster nodes. The following methods are supported:
The default value is
trust. You can list multiple values separated by a comma, for example:proxima.p2p_auth_methods = 'trust,ssl'
If you list multiple methods, they are applied in descending order of priority, as follows:
ssl,trust.proxima.p2p_ssl_enabled(boolean) #Enables or disables SSL for internal connections between cluster nodes. The default value is
off.proxima.ssl_enabled(boolean) #Enables or disables SSL for incoming client connections on proxima.port. The default value is
off. If you enable SSL without specifying proxima.ssl_key and proxima.ssl_cert, proxima will use the SSL certificate configured for Postgres Pro.proxima.ssl_ca(text) #Specifies the path to the file containing public CA certificates for verifying client certificates. This parameter is mandatory if you use the certificate authentication method.
proxima.ssl_cert(text) #Specifies the path to the certificate that will be used for SSL connection via proxima.port. If not set, proxima uses the certificate specified in ssl_cert_file. If you set this parameter, you must also set proxima.ssl_key.
proxima.ssl_key(text) #Specifies the path to the private key file. If not set, proxima uses the key specified in ssl_key_file. If you set this parameter, you must also set proxima.ssl_cert.
proxima.ssl_trusted_certs_dir(text) #Specifies the path to a directory with trusted certificates when you configure SSL authentication with proxima.p2p_auth_methods.
proxima.log_level(enum) #Sets the log level for proxima messages. The following values are available:
error,warning,info,verbose,debug. The default value isinfo.proxima.workers(integer) #Sets the number of threads that are launched for processing queries by the proxima background process. The value can be set in the range from
1to65535. The higher the value, the more queries can be processed. The default value is4.
F.72.11.1.2. Cluster Configuration #
proxima.cluster_mode(text) #Sets the cluster operation mode. The following modes are available:
standalonemode for a single-node Postgres Pro database.gucmode for a standard Postgres Pro primary-standby cluster. The cluster configuration is set by the proxima.cluster_config and proxima.cluster_node_id parameters.bihamode for a BiHA cluster. In this mode, cluster configuration is received from biha.
The default value is
standalone. The value of this parameter must be the same on all nodes of the cluster.proxima.cluster_config(text) #Sets cluster node configuration for the
guccluster operation mode. The value of this parameter must be the same on all nodes of the cluster. The parameters for connection and identification are specified for each node as follows:'
node_id,node_address,node_port,node_role'where:
node_idis the ID of the node specified as a value from0to255. The node ID must be unique for each node of the cluster.node_addressis the IP address of the node for internal connection between cluster nodes.node_portis the node port for internal connection between cluster nodes. This port must be different from proxima.port.node_roleis the role of the node in the cluster. The available values areP(Primary) andS(Standby).
Here is an example of the proxima.cluster_config value for a three-node cluster:
'0,127.0.0.1,4090,P;1,127.0.0.1,4091,S;2,127.0.0.1,4092,S;'
proxima.cluster_node_id(integer) #Sets the unique node ID for the
guccluster operation mode. This parameter must not be changed once the cluster has started and until it is stopped. The node ID must be unique for each node of the cluster. The value can be set in the range from0to255. The default value is0.The list of node IDs must always start with
0and end withn-1, wherenis the total number of nodes. For example, for a three-node cluster, the node IDs must be0, 1, 2.
F.72.11.1.3. Authentication Configuration #
proxima.auth_policy(text) #Specifies where the user authentication is performed. Possible values:
local: Authentication is performed locally on a node using a set of HBA rules and a system catalog of a node. This is the default value for all nodes except the referee.leader: Authentication is performed on the primary (leader) node using a set of HBA rules and a system catalog of the primary (leader) node. In a BiHA cluster, this value is automatically set for the referee.For more information, refer to Proxying Authentication to the Primary (Leader) Node.
F.72.11.1.4. Configuration of the Prepared Statement Storage #
The following parameters manage the prepared statement storage.
proxima.ps_enabled(boolean) #Enables the prepared statement storage of proxima. When enabled, prepared statements are saved in the storage, which allows proxima to avoid establishing a dedicated session for a backend.
You can modify the parameter value without node restart by sending the SIGHUP signal.
Possible values:
on,off. The default value isoff.proxima.ps_shared(boolean) #Enables sharing of prepared statements for all clients. When enabled, all clients use the same session ID, which makes prepared statements created by a client available for all other clients. Using this configuration parameter only makes sense when proxima.ps_enabled is set to
on.You can modify the parameter value without node restart by sending the SIGHUP signal.
Possible values:
on,off. The default value isoff.proxima.ps_cache_size(integer) #Determines the maximum number of prepared statements in a backend. When the set limit is reached, prepared statements are evicted using the LRU (Last Recently Used) strategy. If a backend attempts to use an evicted prepared statement, the backend has to access the storage and re-parse the query.
This configuration parameter only affects backends. You can modify the value any time using the
SETcommand.The value can be set in the range from
8to2147483647. The default value is32.
F.72.11.1.5. Configuration of the Local Backend Pool #
The following parameters set limits for the pool of local backends — Postgres Pro processes responsible for processing client queries.
proxima.backend_pool_local_total_limit(integer) #Sets the maximum number of backends that can be created on the node. The value can be set in the range from
1tomax_connections. The default value is100.proxima.backend_pool_local_bucket_limit(integer) #Sets the maximum number of backends that can be created within connections identified by the
user + databasebinding. The value can be set in the range from1to the value set in proxima.backend_pool_local_total_limit. The default value is100.proxima.backend_pool_local_overdue_interval(float) #Sets the local backend idle time, in seconds. If a local backend is not used by clients longer than set in this parameter, the backend process will be stopped. The value can be set in the range from
1.0to86400.0. The default value is10.0.
F.72.11.1.6. Configuration of the Remote Backend Pool #
The following parameters set limits for the pool of remote backends — logical channels that can be established through a multiplexed connection between cluster nodes to proxy queries from a standby (follower) node to the primary (leader) node. Configuring these parameters is reasonable only for multi-node clusters. The default values are optimal, and it is not recommended to change them.
proxima.backend_pool_remote_total_limit(integer) #Sets the maximum number of logical connection channels between cluster nodes to proxy client queries. The value can be set in the range from
1to2^32-1. The default value is100000.proxima.backend_pool_remote_bucket_limit(integer) #Sets the maximum number of logical connection channels between cluster nodes to proxy client queries within connections identified by the
user + databasebinding. The value can be set in the range from1to the value set in proxima.backend_pool_remote_total_limit. The default value is1000.proxima.backend_pool_remote_overdue_interval(float) #Sets the remote backend idle time, in seconds. If a remote backend is not used by clients longer than set in this parameter, the logical connection channel between cluster nodes will be closed. The value can be set in the range from
1.0to86400.0. The default value is60.0.
F.72.11.2. Monitoring Metrics #
All proxima monitoring metrics are divided into several classes for convenient querying via metrics views.
The following classes are available:
F.72.11.2.1. Views for Monitoring Metrics #
When used in a BiHA cluster, proxima registers the proxima schema in the biha_db database and creates there views that are used to query metrics.
The following views are available:
proxima.proxima_metricsdisplays all cluster metrics.proxima.proxima_metrics_thread_loaddisplays thread load metrics.proxima.proxima_metrics_trafficdisplays traffic metrics.proxima.proxima_metrics_backend_pooldisplays backend pool metrics.proxima.proxima_metrics_clientdisplays client connection metrics.proxima.proxima_metrics_rpcdisplays RPC server metrics.proxima.proxima_metrics_systemdisplays system metrics.
F.72.11.2.2. Thread Load Metrics #
Thread load metrics display CPU utilization by proxima threads as well as metrics of the coroutine engine that proxima is based on. The number of counters that are used in this class depends on running threads.
Names of thread load metrics have the thread.ID., structure, where counter_nameID is the internal identifier of the coroutine engine.
The following counters are available:
Table F.57. Thread Load Counters
| Name | Type | Description |
|---|---|---|
thread.ID.active_time_ns | Integral | Number of nanoseconds during which the thread executed any useful workload. |
thread.ID.purged_coroutines | Integral | Number of coroutine contexts destructed due to prolonged inactivity. |
thread.ID.transferred_coroutines_accepted | Integral | Number of coroutine contexts transferred to this thread for execution. |
thread.ID.wakeup_requests_accepted | Integral | Number of requests for coroutine wakeup accepted. |
thread.ID.futex_wakeup_requests_accepted | Integral | Number of accepted wakeup requests for a coroutine blocked on futex. |
thread.ID.active_coroutines_called | Integral | Number of active coroutine calls. Doubling this value gives the number of coroutine context switches in the current thread. |
thread.ID.evrun_once | Integral | Number of calls to the libev library with thread locking to wait for events related to I/O or active timers. |
thread.ID.evrun_nowait | Integral | Number of calls to the libev library without thread locking to wait for events related to I/O or active timers. |
thread.ID.scheduler.coroctx_in_use | Actual value | Number of coroutine contexts currently in use. |
thread.ID.scheduler.coroctx_cached | Actual value | Number of coroutine contexts currently cached and unused, but available for quick allocation when creating new coroutines. |
thread.ID.scheduler.cs_active | Actual value | Number of active coroutines. |
thread.ID.scheduler.cs_inactive | Actual value | Number of inactive coroutines. |
thread.ID.scheduler.cs_waiting_futex | Actual value | Number of coroutines waiting for futex. |
thread.ID.scheduler.cs_wakeup_futex | Actual value | Number of coroutines in the wakeup queue when locked on futex. |
thread.ID.scheduler.cs_waiting_io | Actual value | Number of coroutines waiting for read or write availability on an I/O device or timer activation (for example, when locked in the sleep operation). |
The example of the thread load metrics query output looks as follows:
name | class | node_id | value
------------------------------------------+-------------+---------+------------
thread.1.active_time_ns | thread-load | 0 | 6319387757
thread.1.purged_coroutines | thread-load | 0 | 1
thread.1.transferred_coroutines_accepted | thread-load | 0 | 2
thread.1.wakeup_requests_accepted | thread-load | 0 | 0
thread.1.futex_wakeup_requests_accepted | thread-load | 0 | 10214
thread.1.active_coroutines_called | thread-load | 0 | 32385
thread.1.evrun_once | thread-load | 0 | 17162
thread.1.evrun_nowait | thread-load | 0 | 4567
thread.1.scheduler.coroctx_in_use | thread-load | 0 | 19
thread.1.scheduler.coroctx_cached | thread-load | 0 | 1
thread.1.scheduler.cs_active | thread-load | 0 | 1
thread.1.scheduler.cs_inactive | thread-load | 0 | 1
thread.1.scheduler.cs_waiting_futex | thread-load | 0 | 5
thread.1.scheduler.cs_wakeup_futex | thread-load | 0 | 0
thread.1.scheduler.cs_waiting_io | thread-load | 0 | 12
thread.2.active_time_ns | thread-load | 0 | 974064
thread.2.purged_coroutines | thread-load | 0 | 0
thread.2.transferred_coroutines_accepted | thread-load | 0 | 0
thread.2.wakeup_requests_accepted | thread-load | 0 | 0
thread.2.futex_wakeup_requests_accepted | thread-load | 0 | 6
thread.2.active_coroutines_called | thread-load | 0 | 7
thread.2.evrun_once | thread-load | 0 | 109
thread.2.evrun_nowait | thread-load | 0 | 0
thread.2.scheduler.coroctx_in_use | thread-load | 0 | 1
thread.2.scheduler.coroctx_cached | thread-load | 0 | 0
thread.2.scheduler.cs_active | thread-load | 0 | 0
thread.2.scheduler.cs_inactive | thread-load | 0 | 0
thread.2.scheduler.cs_waiting_futex | thread-load | 0 | 1
thread.2.scheduler.cs_wakeup_futex | thread-load | 0 | 0
thread.2.scheduler.cs_waiting_io | thread-load | 0 | 0
...
F.72.11.2.3. Traffic Metrics #
The traffic metrics display counters of bytes and/or messages that are transferred via the communication channel, as well as the number of dropped messages and reconnections if supported by this communication channel.
Names of traffic metrics have the traffic.CHANNEL.COUNTER structure, where:
CHANNELis the channel, which data is displayed in the query output. The following channels are supported:fe(frontend): data transfer between all clients and proxima.be(backend): data transfer between proxima and backends of proxima.rpc(RPC, Remote Procedure Call): data transfer between proxima and other processes of the current database instance.nodeID.client: data transfer via the client connection between the current node and the node with theIDidentifier.nodeID.server: data transfer via the server connection between the current node and the node with theIDidentifier.
COUNTERis the name of the counter.
The following counters are available:
Table F.58. Traffic Counters
| Name | Type | Description |
|---|---|---|
traffic.CHANNEL.rx_bytes | Integral | Number of bytes received via the communication channel. |
traffic.CHANNEL.tx_bytes | Integral | Number of bytes transmitted through the communication channel. |
traffic.CHANNEL.rx_msgs | Integral | Number of messages received. This counter is only present if a channel supports tracking of separate messages. |
traffic.CHANNEL.tx_msgs | Integral | Number of messages transmitted. This counter is only present if a channel supports tracking of separate messages. |
traffic.CHANNEL.rx_msgs_dropped | Integral | Number of dropped messages. This counter is only present if a channel supports message dropping. |
traffic.CHANNEL.reconnects | Integral | Number of reconnections after failures. This counter is only present if a channel supports reconnections. |
The example of the traffic metrics query output looks as follows:
name | class | node_id | value
--------------------------------------+---------+---------+----------
traffic.fe.rx_bytes | traffic | 0 | 943
traffic.fe.tx_bytes | traffic | 0 | 10632
traffic.be.rx_bytes | traffic | 0 | 13233
traffic.be.tx_bytes | traffic | 0 | 2099
traffic.node1.client.rx_bytes | traffic | 0 | 32
traffic.node1.client.tx_bytes | traffic | 0 | 64641815
traffic.node1.client.rx_msgs | traffic | 0 | 124
traffic.node1.client.tx_msgs | traffic | 0 | 7868
traffic.node1.client.rx_msgs_dropped | traffic | 0 | 0
traffic.node1.client.reconnects | traffic | 0 | 1
traffic.node2.client.rx_bytes | traffic | 0 | 32
traffic.node2.client.tx_bytes | traffic | 0 | 64609591
traffic.node2.client.rx_msgs | traffic | 0 | 124
traffic.node2.client.tx_msgs | traffic | 0 | 7864
traffic.node2.client.rx_msgs_dropped | traffic | 0 | 0
traffic.node2.client.reconnects | traffic | 0 | 1
traffic.rpc.rx_bytes | traffic | 0 | 100
traffic.rpc.tx_bytes | traffic | 0 | 12416
traffic.rpc.rx_msgs | traffic | 0 | 3
traffic.rpc.tx_msgs | traffic | 0 | 2
traffic.node2.server.rx_bytes | traffic | 0 | 56532348
traffic.node2.server.tx_bytes | traffic | 0 | 32
traffic.node2.server.rx_msgs | traffic | 0 | 7868
traffic.node2.server.tx_msgs | traffic | 0 | 124
traffic.node2.server.rx_msgs_dropped | traffic | 0 | 0
traffic.node2.server.reconnects | traffic | 0 | 1
traffic.node1.server.rx_bytes | traffic | 0 | 56504900
traffic.node1.server.tx_bytes | traffic | 0 | 32
traffic.node1.server.rx_msgs | traffic | 0 | 7864
traffic.node1.server.tx_msgs | traffic | 0 | 124
traffic.node1.server.rx_msgs_dropped | traffic | 0 | 0
traffic.node1.server.reconnects | traffic | 0 | 1
F.72.11.2.4. Backend Pool Metrics #
Backend pool metrics display characteristics of backend allocation requests from clients to the backend pool.
Names of backend pool metrics have the backend_pool.SCOPE.COUNTER structure, where:
SCOPEdefines the backend type: local or remote.COUNTERis the name of the counter.
The following counters are available:
Table F.59. Backend Pool Counters
| Name | Type | Description |
|---|---|---|
backend_pool.SCOPE.requests | Integral | Number of backend allocation requests to the backend pool. |
backend_pool.SCOPE.creations | Integral | Number or new backends created when requested from the pool. |
backend_pool.SCOPE.destructions | Integral | Number of backend destructions (closures). It may occur when a backend is evicted from the pool bucket or not in use for a long time. |
backend_pool.SCOPE.unlinks | Integral | Number of backends unbound from the pool. |
backend_pool.SCOPE.acquisitions | Integral | Number of backends allocated to clients. |
backend_pool.SCOPE.releases | Integral | Number of backends released by clients and returned to the pool. Due to some failures a backend may be destructed by the client instead of returning to the pool. This will cause increase of the backend_pool.SCOPE.unlinks value, but not backend_pool.SCOPE.releases. |
backend_pool.SCOPE.steals | Integral | Number of backends "stolen" from other pool buckets. Intense growth of this value means that the system experiences high load on many different databases and/or from many different users. This indicates that the pool size is not enough for the current workload, that leads to the system performance degradation. |
backend_pool.SCOPE.errors | Integral | Number of errors occurred when requesting backends from the pool. This is a generalized counter. In some cases, errors may cause termination of client connections. In other cases, an error may lead to a repeated backend request and be transparent for a client. For example, if the pool rejects to allocate a backend due to inability to create it caused by reaching the max_connections limit, the client will wait in a queue. |
backend_pool.SCOPE.request_duration.p* | Percentile (window: T = 60 seconds, C = 1000 events) | Percentiles of time between a backend request to actual backend allocation to a client. This is a cumulative counter and can have significantly different values. For example, allocation of a free backend from the pool may take microseconds, creation of a new backend — milliseconds. However, if the pool is overloaded and clients have to wait for execution of previous request to the database, this may take seconds, minutes, and even hours. In other words, this counter indicates distribution of waiting time in the pool queue before executing the request. |
The example of the backend pool metrics query output looks as follows:
name | class | node_id | value
-------------------------------------------+--------------+---------+------------------------
backend_pool.local.requests | backend-pool | 0 | 13
backend_pool.local.creations | backend-pool | 0 | 5
backend_pool.local.destructions | backend-pool | 0 | 3
backend_pool.local.unlinks | backend-pool | 0 | 4
backend_pool.local.acquisitions | backend-pool | 0 | 12
backend_pool.local.releases | backend-pool | 0 | 10
backend_pool.local.steals | backend-pool | 0 | 0
backend_pool.local.errors | backend-pool | 0 | 1
backend_pool.local.request_duration.p0 | backend-pool | 0 | 8.74983775227453e-06
backend_pool.local.request_duration.p5 | backend-pool | 0 | 8.765000496725975e-06
backend_pool.local.request_duration.p25 | backend-pool | 0 | 9.654992595293691e-06
backend_pool.local.request_duration.p50 | backend-pool | 0 | 1.0727600464262677e-05
backend_pool.local.request_duration.p75 | backend-pool | 0 | 1.1514681787272259e-05
backend_pool.local.request_duration.p95 | backend-pool | 0 | 0.008438241305000952
backend_pool.local.request_duration.p100 | backend-pool | 0 | 0.008452788451603185
backend_pool.remote.requests | backend-pool | 0 | 0
backend_pool.remote.creations | backend-pool | 0 | 0
backend_pool.remote.destructions | backend-pool | 0 | 0
backend_pool.remote.unlinks | backend-pool | 0 | 0
backend_pool.remote.acquisitions | backend-pool | 0 | 0
backend_pool.remote.releases | backend-pool | 0 | 0
backend_pool.remote.steals | backend-pool | 0 | 0
backend_pool.remote.errors | backend-pool | 0 | 0
backend_pool.remote.request_duration.p0 | backend-pool | 0 | 0
backend_pool.remote.request_duration.p5 | backend-pool | 0 | 0
backend_pool.remote.request_duration.p25 | backend-pool | 0 | 0
backend_pool.remote.request_duration.p50 | backend-pool | 0 | 0
backend_pool.remote.request_duration.p75 | backend-pool | 0 | 0
backend_pool.remote.request_duration.p95 | backend-pool | 0 | 0
backend_pool.remote.request_duration.p100 | backend-pool | 0 | 0
F.72.11.2.5. Client Connection Metrics #
Client connection metrics include counters of connections and their characteristics for different communication channels.
Names of client connection metrics have the client.CHANNEL.COUNTER structure, where:
CHANNELis the communication channel, whose data is displayed in the query output. The following channels are supported:lfe(local frontend): clients that connect to proxima via one of the ports to execute SQL queries.lbe(local backend): backend processes of Postgres Pro Enterprise created by proxima.rfe(remote frontend): clients redirected to the current node from another node.rbe(remote backend): internal communication channels created by proxima to redirect queries to a remote node.rpc(RPC, Remote Procedure Call): data transfer between proxima and other processes of the current database instance.
COUNTERis the name of the counter.
The following counters are available:
Table F.60. Client Connection Counters
| Name | Type | Description |
|---|---|---|
client.lfe.now_connected | Actual value | Number of clients actually connected to the current node. |
client.lfe.accepted | Integral | Number of clients with successfully authenticated connections. |
client.lfe.rejected | Integral | Number of clients with connections rejected because they were not authenticated. |
client.lfe.failed | Integral | Number of clients with connections rejected due to failures of authentication process. |
client.lfe.disconnected | Integral | Number of clients with closed connections. |
client.lfe.auth_password | Integral | Number of clients authenticated using the password method. |
client.lfe.auth_md5 | Integral | Number of clients authenticated using the MD5 method. |
client.lfe.auth_scram_sha256 | Integral | Number of clients with the SCRAM-SHA-256 authentication method applied. |
client.lfe.auth_ldap | Integral | Number of clients with the LDAP authentication method applied. |
client.lfe.auth_trust | Integral | Number of clients with trusted connections according to HBA rules. |
client.lfe.auth_reject | Integral | Number of clients with prohibited (reject) connections according to HBA rules. |
client.lfe.auth_tls_accepted | Integral | Number of accepted TLS connections. |
client.lfe.auth_tls_rejected | Integral | Number of rejected TLS connections. |
client.lfe.auth_duration.p* | Percentile (window: T = 60 seconds, C = 1000 events) | Time distribution for client authentication procedure. |
client.lbe.enter_dedicated | Integral | Number of backend connections that entered the dedicated session. |
client.lbe.leave_dedicated | Integral | Number of backend connections that left the dedicated session. |
client.lbe.dedicated_duration.p* | Percentile (window: T = 60 seconds, C = 1000 events) | Time distribution for connections that remained in the dedicated session. |
client.rfe.now_connected | Actual value | Actual number of clients redirected to the current node for query execution. |
client.rfe.connected | Integral | Number of clients redirected to the current node for query execution. |
client.rfe.disconnected | Integral | Number of clients with closed connections. |
client.rbe.enter_dedicated | Integral | Number of backend connections that entered the dedicated session. |
client.rbe.leave_dedicated | Integral | Number of backend connections that left the dedicated session. |
client.rbe.dedicated_duration.p* | Percentile (window: T = 60 seconds, C = 1000 events) | Time distribution for connections that remained in the dedicated session. |
client.rpc.now_connected | Actual value | Number of currently connected clients. |
client.rpc.accepted | Integral | Number of clients with successfully accepted connections including authentication passed. |
client.rpc.rejected | Integral | Number of clients with rejected connections, mainly due to authentication errors. |
client.rpc.disconnected | Integral | Number of clients with closed connections. |
The example of the client connection metrics query output looks as follows:
name | class | node_id | value
------------------------------------+--------+---------+-------
client.lfe.now_connected | client | 0 | 1
client.lfe.accepted | client | 0 | 1
client.lfe.rejected | client | 0 | 0
client.lfe.failed | client | 0 | 0
client.lfe.disconnected | client | 0 | 0
client.lfe.auth_password | client | 0 | 0
client.lfe.auth_md5 | client | 0 | 0
client.lfe.auth_scram_sha256 | client | 0 | 0
client.lfe.auth_ldap | client | 0 | 0
client.lfe.auth_trust | client | 0 | 1
client.lfe.auth_reject | client | 0 | 0
client.lfe.auth_tls_accepted | client | 0 | 0
client.lfe.auth_tls_rejected | client | 0 | 0
client.rfe.now_connected | client | 0 | 0
client.rfe.connected | client | 0 | 0
client.rfe.disconnected | client | 0 | 0
client.lbe.enter_dedicated | client | 0 | 0
client.lbe.leave_dedicated | client | 0 | 0
client.rbe.enter_dedicated | client | 0 | 0
client.rbe.leave_dedicated | client | 0 | 0
client.rpc.now_connected | client | 0 | 1
client.rpc.accepted | client | 0 | 4
client.rpc.rejected | client | 0 | 0
client.rpc.disconnected | client | 0 | 3
client.lfe.auth_duration.p0 | client | 0 | 0
client.lfe.auth_duration.p5 | client | 0 | 0
client.lfe.auth_duration.p25 | client | 0 | 0
client.lfe.auth_duration.p50 | client | 0 | 0
client.lfe.auth_duration.p75 | client | 0 | 0
client.lfe.auth_duration.p95 | client | 0 | 0
client.lfe.auth_duration.p100 | client | 0 | 0
client.lbe.dedicated_duration.p0 | client | 0 | 0
client.lbe.dedicated_duration.p5 | client | 0 | 0
client.lbe.dedicated_duration.p25 | client | 0 | 0
client.lbe.dedicated_duration.p50 | client | 0 | 0
client.lbe.dedicated_duration.p75 | client | 0 | 0
client.lbe.dedicated_duration.p95 | client | 0 | 0
client.lbe.dedicated_duration.p100 | client | 0 | 0
client.rbe.dedicated_duration.p0 | client | 0 | 0
client.rbe.dedicated_duration.p5 | client | 0 | 0
client.rbe.dedicated_duration.p25 | client | 0 | 0
client.rbe.dedicated_duration.p50 | client | 0 | 0
client.rbe.dedicated_duration.p75 | client | 0 | 0
client.rbe.dedicated_duration.p95 | client | 0 | 0
client.rbe.dedicated_duration.p100 | client | 0 | 0
F.72.11.2.6. RPC Server Metrics #
The following counters are available:
Table F.61. RPC Server Counters
| Name | Type | Description |
|---|---|---|
rpc.call_duration.p* | Percentile (window: T = 60 seconds, C = 1000 events) | Time distribution for command execution. |
rpc.err_not_found | Integral | Number of calls to non-existent functions. |
The example of the RPC server metrics query output looks as follows:
name | class | node_id | value
------------------------+-------+---------+------------------------
rpc.call_duration.p0 | rpc | 0 | 4.315190768277686e-05
rpc.call_duration.p5 | rpc | 0 | 4.331642078668621e-05
rpc.call_duration.p25 | rpc | 0 | 6.386338595749277e-05
rpc.call_duration.p50 | rpc | 0 | 7.37059571607683e-05
rpc.call_duration.p75 | rpc | 0 | 8.217731456416661e-05
rpc.call_duration.p95 | rpc | 0 | 0.00011075225182228674
rpc.call_duration.p100 | rpc | 0 | 0.00011117317272816024
rpc.err_not_found | rpc | 0 | 0
F.72.11.2.7. System Metrics #
The following counters are available:
Table F.62. System Counters
| Name | Type | Description |
|---|---|---|
system.cpu_load | Actual value | Percentage of CPU utilization on a node. |
system.avail_ram_b | Actual value | Amount of free RAM on a node, in bytes. |
system.total_ram_b | Actual value | Total amount of RAM on a node, in bytes. |
system.io_avg_latency_ms | Actual value | Average waiting time for execution of a single operation when accessing disk, in milliseconds. |
The example of the system metrics query output looks as follows:
name | class | node_id | value
--------------------------+--------+---------+--------------------
system.cpu_load | system | 0 | 6.779661016949152
system.avail_ram_b | system | 0 | 22180810752
system.total_ram_b | system | 0 | 32619315200
system.io_avg_latency_ms | system | 0 | 3.6666666666666665