52.7. Сбор статистики распределённых операторов расширением pgpro_stats #

Во время выполнения распределённых запросов Postgres Pro Shardman отправляет производные SQL-запросы на удалённые узлы, содержащие секции данных, задействованные в выполнении запроса. Назовём эти SQL-запросы фрагментами запроса. Узел, который запрашивает распределённую таблицу, называется координатор, а узлы, принимающие фрагменты запроса, называются сегменты. Для проверки, является ли текущий узел координатором, используйте функцию shardman.am_coordinator().

Когда расширение pgpro_stats включено на узле кластера Postgres Pro Shardman, оно собирает статистику по локальным и распределённым запросам. Информация о распределённых запросах, инициированных этим узлом, является неполной, поскольку в ней отсутствуют данные об удалённых фрагментах запроса. Статистика запросов, инициированных другими узлами, также неоднозначна, поскольку у пользователя нет простого способа определить распределённый запрос, которому соответствует фрагмент.

Для решения этих проблем расширение pgpro_stats для Postgres Pro Shardman предоставляет агрегирование статистики для распределённых запросов. Доступ к этой агрегированной статистике можно получить с помощью представления pgpro_stats_sdm_statements. Однако каждый узелPostgres Pro Shardman также собирает статистику для всех операторов, поэтому представление pgpro_stats_statements может работать так же, как раньше.

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

Расширение pgpro_stats запускает отдельный фоновый рабочий процесс. Этот рабочий процесс отвечает за отправку накопленной статистики узлам-координаторам либо каждые 5 секунд, либо при срабатывании защитного механизма. Функция сбора запускает этот механизм, когда хеш-таблица почти заполнена.

Для уменьшения сетевого трафика, инициированного отправителем статистики, к отправляемым статистическим данным применяется сжатие. Метод сжатия можно выбрать с помощью параметра конфигурации pgpro_stats.transport_compression.

Каждый узел хранит общее число записей статистики, полученных от узла сегмента, и метку времени их последнего приёма. Когда узел-координатор получает сообщение статистики, он изменяет соответствующие значения, которые доступны через интерфейс SQL.

52.7. Collecting Distributed Statement Statistics Using the pgpro_stats Extension #

During execution of distributed queries, Postgres Pro Shardman sends derived SQL queries to remote nodes that hold data partitions involved in the query execution. Let's call these SQL queries query fragments. The node that queries the sharded table is called the coordinator, while the nodes that accept query fragments are called shards. You can use the shardman.am_coordinator() function to check whether the current node is the query coordinator.

When the pgpro_stats extension is enabled on a Postgres Pro Shardman cluster node, it collects statistics about local and distributed queries. The information about distributed queries initiated by this node is incomplete because it misses data about remote query fragments. The statistics concerning queries initiated by other nodes is also ambiguous because there is no simple way for a user to determine the distributed query to which the fragment corresponds.

To address these issues, pgpro_stats for Postgres Pro Shardman introduces an aggregation of statistics for the distributed queries. These aggregated statistics can be accesses with the pgpro_stats_sdm_statements view. However, each Postgres Pro Shardman node collects statistics for all the statements, so that the pgpro_stats_statements view can work the way it did before.

When a node receives a query fragment, it saves its statistics to a separate shared hash table. Periodically and asynchronously, each node sends this information from a separate table to the coordinator corresponding to the query. The coordinator aggregates the statistical data obtained from the query fragments with the statistics of its parent query, which is the query initiated by the client.

The pgpro_stats extension starts a separate background worker. This worker is responsible for sending the accumulated statistics to the coordinator nodes either every 5 seconds or when triggered by the guard latch. The collecting function sets this latch when the hash table is almost full.

To reduce the network traffic initiated by a statistics sender, compression is applied to the statistics data sent. The compression method can be selected by the pgpro_stats.transport_compression configuration parameter.

Each node stores the total number of statistics entries received from the shard node and the timestamp of when they were last received. When a coordinator node receives a statistics message, it updates the appropriate values, which are accessible using the SQL interface.

FAQ