pgbouncer_exporter

pgbouncer_exporter — экспорт метрик Prometheus для pgbouncer

Синтаксис

pgbouncer_exporter [параметры]

Описание #

pgbouncer_exporter — это экспортёр Prometheus для pgbouncer. По умолчанию экспортирует метрики в 9127/metrics.

Установка и настройка #

Расширение pgbouncer_exporter поставляется вместе с Postgres Pro Standard в виде отдельного пакета pgbouncer_exporter (подробные инструкции по установке приведены в Главе 16). После установки pgbouncer_exporter поменяйте конфигурацию pgbouncer, чтобы параметр подключения драйвера PostgreSQL игнорировался. В файл pgbouncer.ini добавьте:

ignore_startup_parameters = extra_float_digits

Метрики #

В таблице ниже перечислены экспортируемые метрики:

Таблица I.3. Метрики

Столбец pgbouncerМетрика PrometheusОписание
stats.total_query_countpgbouncer_stats_queries_pooled_totalОбщее количество SQL-запросов, прошедших через pgbouncer
stats.total_query_timepgbouncer_stats_queries_duration_seconds_totalОбщее время в секундах, в течение которого pgbouncer использовал подключения к Postgres Pro, выполняя запросы
stats.total_receivedpgbouncer_stats_received_bytes_totalОбщий объём сетевого трафика, который получил pgbouncer; отображается как bytes (байты)
stats.total_requestspgbouncer_stats_queries_totalОбщее количество SQL-запросов, прошедших через pgbouncer; отображается как requests (запросы)
stats.total_sentpgbouncer_stats_sent_bytes_totalОбщий объём сетевого трафика, который передал pgbouncer; отображается как bytes (байты)
stats.total_wait_timepgbouncer_stats_client_wait_seconds_totalВремя ожидания клиентами ответов сервера в секундах
stats.total_xact_countpgbouncer_stats_sql_transactions_pooled_totalОбщее количество SQL-транзакций, прошедших через pgbouncer
stats.total_xact_timepgbouncer_stats_server_in_transaction_seconds_totalОбщее время в секундах, в течение которого pgbouncer использовал подключения к Postgres Pro, выполняя запросы или простаивая
pools.cl_activepgbouncer_pools_client_active_connectionsЧисло клиентских подключений, которые связаны с подключением к серверу и могут обрабатывать запросы; отображается как connection (подключение)
pools.cl_waitingpgbouncer_pools_client_waiting_connectionsЧисло клиентских подключений, которые ожидают подключения к серверу; отображается как connection (подключение)
pools.sv_activepgbouncer_pools_server_active_connectionsЧисло серверных подключений, которые связаны с клиентским подключением; отображается как connection (подключение)
pools.sv_idlepgbouncer_pools_server_idle_connectionsЧисло серверных подключений, которые простаивают и готовы к запросу от клиента; отображается как connection (подключение)
pools.sv_usedpgbouncer_pools_server_used_connectionsЧисло серверных подключений, простаивающие дольше server_check_delay, для которых необходимо выполнить запрос server_check_query; отображается как connection (подключение)
pools.sv_testedpgbouncer_pools_server_testing_connectionsЧисло серверных подключений, для которых в данный момент выполняются запросы server_reset_query или server_check_query; отображается как connection (подключение)
pools.sv_loginpgbouncer_pools_server_login_connectionsЧисло серверных подключений, через которые в данный момент выполняется вход на сервер; отображается как connection (подключение)
pools.maxwaitpgbouncer_pools_client_maxwait_secondsВозраст самого старого клиентского подключения в очереди; отображается в секундах
config.max_client_connpgbouncer_config_max_client_connectionsМаксимальное количество клиентских подключений
config.max_user_connectionspgbouncer_config_max_user_connectionsМаксимальное количество серверных подключений для пользователя

Справка #

Синтаксис:

pgbouncer_exporter [--[no-]help] [--help-long] [--log-level=info]
[--log-format=logfmt]
[--pgBouncer.connectionString="postgres://postgres:@localhost:6543/pgbouncer?sslmode=disable"]
[--web.telemetry-path="/metrics"] [--pgBouncer.pid-file=""] [--[no-]web.systemd-socket]
[--web.listen-address=:9127...] [--web.config.file=""] [--[no-]version]
-h
--[no-]help

Вывести или не выводить справку, зависящую от контекста.

--help-long

Вывести справку по приложению.

--log-level

Писать в журнал только сообщения с заданным уровнем важности или выше. Возможные значения — debug, info, warn, error. Значение по умолчанию — info.

--log.format

Формат вывода сообщений журнала. Возможные значения — logfmt или json. Значение по умолчанию — logfmt.

--pgBouncer.connectionString

Строка подключения для доступа к pgbouncer. Значение по умолчанию — "postgres://postgres:@localhost:6543/pgbouncer?sslmode=disable". Значение также можно задать через переменную окружения PGBOUNCER_EXPORTER_CONNECTION_STRING.

--web.telemetry-path

Путь для экспорта метрик. Значение по умолчанию — "/metrics".

--pgBouncer.pid-file

Путь к PID-файлу pgbouncer. Если он указан, метрики стандартного процесса экспортируются для процесса pgbouncer с префиксом «pgbouncer_process_». У экспортёра pgbouncer_process должны быть права на чтение файлов, которыми владеет процесс pgbouncer. Зависит от доступности /proc. За подробной информацией обратитесь к https://prometheus.io/docs/instrumenting/writing_clientlibs/#process-metrics.

--[no-]web.systemd-socket

Использовать или не использовать приёмники для активации systemd-сокетов вместо приёмников с портов (только для Linux).

--web.listen-address

Адреса для доступа к метрикам и веб-интерфейсу. Можно использовать несколько раз для разных адресов. Например: ':9100' или '[::1]:9100' для HTTP, 'vsock://:9100' для VSOCK (Virtual Machine Sockets, сокеты виртуальной машины). Значение по умолчанию — ':9127'.

--web.config.file

Путь к файлу конфигурации, позволяющему включать TLS или аутентификацию. За подробной информацией обратитесь к Разделу «TLS и базовая аутентификация».

--[no-]version

Вывести или не выводить версию приложения.

TLS и базовая аутентификация #

pgbouncer_exporter поддерживает TLS и базовую аутентификацию. Чтобы использовать TLS и/или базовую аутентификацию, необходимо передать YAML-файл конфигурации, используя параметр --web.config.file. Формат файла следующий:

tls_server_config:
  # Сертификат, используемый сервером для аутентификации клиента.
  # Предполагается передача в виде строки с закодированной последовательностью байтов в формате PEM.
  #
  # ПРИМЕЧАНИЕ: При передаче сертификата напрямую, cert_file указывать ниже не нужно.
  [ cert: <string> ]

  # Ключ, используемый сервером для аутентификации клиента.
  # Предполагается передача в виде строки с закодированной последовательностью байтов в формате PEM.
  #
  # ПРИМЕЧАНИЕ: При передаче ключа напрямую, key_file указывать ниже не нужно.
  [ key: <secret> ]

  # Сертификат ЦС для аутентификации клиента по сертификату на стороне сервера.
  # Предполагается передача в виде строки с закодированной последовательностью байтов в формате PEM.
  #
  # ПРИМЕЧАНИЕ: При передаче сертификата ЦС напрямую, client_ca_file указывать ниже не нужно.
  [ client_ca: <string> ]

  # Файлы сертификата и ключа, используемых сервером для аутентификации клиента.
  cert_file: <filename>
  key_file: <filename>

  # Политика сервера для аутентификации клиента. Сопоставляется с политиками ClientAuth.
  # За подробной информацией о параметрах ClientAuth обратитесь к
  # https://golang.org/pkg/crypto/tls/#ClientAuthType
  #
  # ПРИМЕЧАНИЕ: Чтобы включить аутентификацию для клиента, используйте
  # RequireAndVerifyClientCert. Другие значения небезопасны.
  [ client_auth_type: <string> | default = "NoClientCert" ]

  # Сертификат ЦС для аутентификации клиента по сертификату на стороне сервера.
  [ client_ca_file: <filename> ]

  # Проверить, что у клиентского сертификата есть дополнительное имя субъекта (SAN),
  # которое полностью соответствует записи в этом списке, и в случае несоответствия прервать
  # соединение. SAN может иметь один или несколько из следующих форматов: DNS,
  # IP, e-mail или URI-адрес из https://pkg.go.dev/crypto/x509#Certificate.
  [ client_allowed_sans:
    [ - <string> ] ]

  # Минимальная допустимая версия TLS.
  [ min_version: <string> | default = "TLS12" ]

  # Максимальная допустимая версия TLS.
  [ max_version: <string> | default = "TLS13" ]

  # Список поддерживаемых наборов шифров для версий TLS до TLS 1.2. Если значение не задано,
  # используется набор шифров Go по умолчанию. Доступные наборы шифров описаны
  # в документации go:
  # https://golang.org/pkg/crypto/tls/#pkg-constants
  #
  # Обратите внимание, что поддерживаются только шифры, возвращаемые следующей функцией:
  # https://pkg.go.dev/crypto/tls#CipherSuites
  [ cipher_suites:
    [ - <string> ] ]

  # prefer_server_cipher_suites определяет, выбирает ли сервер
  # набор шифров, предпочтительный для клиента, или набор шифров, предпочтительный
  # для сервера. При значении true учитывается приоритетность шифров для сервера,
  # которая определяется порядком элементов в cipher_suites.
  [ prefer_server_cipher_suites: <boo> | default = true ]

  # Эллиптические кривые, которые будут использоваться для согласования по ECDHE в порядке
  # предпочтения. Доступные кривые описаны в документации go:
  # https://golang.org/pkg/crypto/tls/#CurveID
  [ curve_preferences:
    [ - <string> ] ]

http_server_config:
  # Включить поддержку HTTP/2. Обратите внимание, что HTTP/2 поддерживается только с TLS.
  # Этот параметр нельзя изменить на лету.
  [ http2: <boolean> | default = true ]
  # Список заголовков, которые можно добавить к HTTP-ответам.
  [ headers:
    # Установить заголовок Content-Security-Policy для HTTP-ответов.
    # Заголовок не установлен, если значение не задано.
    [ Content-Security-Policy: <string> ]
    # Установить заголовок X-Frame-Options для HTTP-ответов.
    # Заголовок не установлен, если значение не задано. Допустимые значения — deny и sameorigin.
    # https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options
    [ X-Frame-Options: <string> ]
    # Установить заголовок X-Content-Type-Options для HTTP-ответов.
    # Заголовок не установлен, если значение не задано. Допустимое значение — nosniff.
    # https://developer.mozilla.org/ru/docs/Web/HTTP/Headers/X-Content-Type-Options
    [ X-Content-Type-Options: <string> ]
    # Установить заголовок X-XSS-Protection для всех ответов.
    # Заголовок не установлен, если значение не задано.
    # https://developer.mozilla.org/ru/docs/Web/HTTP/Headers/X-XSS-Protection
    [ X-XSS-Protection: <string> ]
    # Установить заголовок Strict-Transport-Security для HTTP-ответов.
    # Заголовок не установлен, если значение не задано.
    # Используйте этот заголовок с осторожностью, так как он может заставить
    # браузеры загрузить Prometheus и другие приложения, размещённые на одном
    # домене и  поддоменах через HTTPS.
    # https://developer.mozilla.org/ru/docs/Web/HTTP/Headers/Strict-Transport-Security
    [ Strict-Transport-Security: <string> ] ]

# Имена пользователей и хешированные пароли для полного доступа к веб-
# серверу, используя механизм базовой аутентификации. Если значение не установлено, базовая аутентификация не
# требуется. Пароли хешируются с помощью bcrypt.
basic_auth_users:
  [ <string>: <secret> ... ]


# Ограничение запросов в конечной точке, используя набор токенов
rate_limit:
  interval: <duration> # время между двумя запросами; установите значение 0, чтобы отключить ограничитель
  burst: <int> # и разрешение на пакетную передачу <int> запросов.

Где общие местозаполнители определяются следующим образом:

  • <boolean>: логическое значение true или false

  • <filename>: путь в текущем рабочем каталоге

  • <secret>: обычная строка, которая является секретом, таким как пароль

  • <string>: обычная строка

  • <int>: целое число

  • <duration>: временной интервал

Например:

# Пример конфигурации TLS и базовой аутентификации.
#
# Кроме того, требуются сертификат и файл ключа.
tls_server_config:
  cert_file: server.crt
  key_file: server.key

# Имена пользователей и пароли необходимы для подключения.
# Пароли хешируются с помощью bcrypt: https://github.com/prometheus/exporter-toolkit/blob/master/docs/web-configuration.md#about-bcrypt.
basic_auth_users:
  alice: $2y$10$mDwo.lAisC94iLAyP81MCesa29IzH37oigHC/42V2pdJlUprsJPze
  bob: $2y$10$hLqFl9jSjoAAy95Z/zw8Ye8wkdMBM8c5Bn1ptYqP/AXyV0.oy0S8m

# Ограничение запросов в конечной точке с использованием набора токенов
rate_limit:
  interval: "1s" # время между двумя запросами; установите значение 0, чтобы отключить ограничитель
  burst: 20 # и разрешение на пакетную передачу до 20 запросов.

Автор

Prometheus Monitoring Community: https://prometheus.io/community/

pgbouncer_exporter

pgbouncer_exporter — export Prometheus metrics for pgbouncer

Synopsis

pgbouncer_exporter [options]

Description #

pgbouncer_exporter is a Prometheus exporter for pgbouncer. By default, it exports metrics at 9127/metrics.

Installation and Setup #

pgbouncer_exporter is provided with Postgres Pro Standard as a separate pre-built package pgbouncer_exporter (for the detailed installation instructions, see Chapter 16). Once you have installed pgbouncer_exporter, make a configuration change to pgbouncer to ignore a PostgreSQL driver connection parameter. In the pgbouncer.ini file, include:

ignore_startup_parameters = extra_float_digits

Metrics #

The following table lists the exported metrics:

Table I.3. Metrics

pgbouncer ColumnPrometheus MetricDescription
stats.total_query_countpgbouncer_stats_queries_pooled_totalTotal number of SQL queries pooled
stats.total_query_timepgbouncer_stats_queries_duration_seconds_totalTotal number of seconds spent by pgbouncer when actively connected to Postgres Pro, executing queries
stats.total_receivedpgbouncer_stats_received_bytes_totalTotal volume of network traffic received by pgbouncer, shown as bytes
stats.total_requestspgbouncer_stats_queries_totalTotal number of SQL requests pooled by pgbouncer, shown as requests
stats.total_sentpgbouncer_stats_sent_bytes_totalTotal volume of network traffic sent by pgbouncer, shown as bytes
stats.total_wait_timepgbouncer_stats_client_wait_seconds_totalTime spent by clients waiting for a server in seconds
stats.total_xact_countpgbouncer_stats_sql_transactions_pooled_totalTotal number of SQL transactions pooled
stats.total_xact_timepgbouncer_stats_server_in_transaction_seconds_totalTotal number of seconds spent by pgbouncer when connected to Postgres Pro in a transaction, either idle in transaction or executing queries
pools.cl_activepgbouncer_pools_client_active_connectionsClient connections linked to server connection and able to process queries, shown as connection
pools.cl_waitingpgbouncer_pools_client_waiting_connectionsClient connections waiting for a server connection, shown as connection
pools.sv_activepgbouncer_pools_server_active_connectionsServer connections linked to a client connection, shown as connection
pools.sv_idlepgbouncer_pools_server_idle_connectionsServer connections idle and ready for a client query, shown as connection
pools.sv_usedpgbouncer_pools_server_used_connectionsServer connections idle more than server_check_delay, needing server_check_query, shown as connection
pools.sv_testedpgbouncer_pools_server_testing_connectionsServer connections currently running either server_reset_query or server_check_query, shown as connection
pools.sv_loginpgbouncer_pools_server_login_connectionsServer connections currently in the process of logging in, shown as connection
pools.maxwaitpgbouncer_pools_client_maxwait_secondsAge of oldest unserved client connection, shown as second
config.max_client_connpgbouncer_config_max_client_connectionsConfigured maximum number of client connections
config.max_user_connectionspgbouncer_config_max_user_connectionsConfigured maximum number of server connections per user

Reference #

Syntax:

pgbouncer_exporter [--[no-]help] [--help-long] [--log-level=info]
[--log-format=logfmt]
[--pgBouncer.connectionString="postgres://postgres:@localhost:6543/pgbouncer?sslmode=disable"]
[--web.telemetry-path="/metrics"] [--pgBouncer.pid-file=""] [--[no-]web.systemd-socket]
[--web.listen-address=:9127...] [--web.config.file=""] [--[no-]version]
-h
--[no-]help

Show or not show context-sensitive help.

--help-long

Show the application help.

--log-level

Only log messages with the given severity or above. One of: debug, info, warn, error. The default is info.

--log.format

Output format of log messages. One of: logfmt or json. The default is logfmt.

--pgBouncer.connectionString

Connection string for accessing pgbouncer. The default is "postgres://postgres:@localhost:6543/pgbouncer?sslmode=disable". Can alternatively be set through the PGBOUNCER_EXPORTER_CONNECTION_STRING environment variable.

--web.telemetry-path

Path under which to expose metrics. The default is "/metrics".

--pgBouncer.pid-file

Path to pgbouncer PID file. If provided, the standard process metrics get exported for the pgbouncer process, prefixed with “pgbouncer_process_”. The pgbouncer_process exporter needs to have read access to files owned by the pgbouncer process. Depends on the availability of /proc. See https://prometheus.io/docs/instrumenting/writing_clientlibs/#process-metrics for details.

--[no-]web.systemd-socket

Use or not use systemd socket activation listeners instead of port listeners (Linux only).

--web.listen-address

Addresses on which to expose metrics and web interface. Repeatable for multiple addresses. Examples: ':9100' or '[::1]:9100' for HTTP, 'vsock://:9100' for VSOCK (Virtual Machine Sockets). The default is ':9127'.

--web.config.file

Path to configuration file that can enable TLS or authentication. See the section called “TLS and Basic Authentication” for details.

--[no-]version

Show or not show the application version.

TLS and Basic Authentication #

pgbouncer_exporter supports TLS and basic authentication. To use TLS and/or basic authentication, you need to pass a yaml configuration file using the --web.config.file option. The format of the file is as follows:

tls_server_config:
  # Certificate for server to use to authenticate to client.
  # Expected to be passed as a PEM encoded sequence of bytes as a string.
  #
  # NOTE: If passing the cert inline, cert_file should not be specified below.
  [ cert: <string> ]

  # Key for server to use to authenticate to client.
  # Expected to be passed as a PEM encoded sequence of bytes as a string.
  #
  # NOTE: If passing the key inline, key_file should not be specified below.
  [ key: <secret> ]

  # CA certificate for client certificate authentication to the server.
  # Expected to be passed as a PEM encoded sequence of bytes as a string.
  #
  # NOTE: If passing the client_ca inline, client_ca_file should not be specified below.
  [ client_ca: <string> ]

  # Certificate and key files for server to use to authenticate to client.
  cert_file: <filename>
  key_file: <filename>

  # Server policy for client authentication. Maps to ClientAuth Policies.
  # For more detail on clientAuth options:
  # https://golang.org/pkg/crypto/tls/#ClientAuthType
  #
  # NOTE: If you want to enable client authentication, you need to use
  # RequireAndVerifyClientCert. Other values are insecure.
  [ client_auth_type: <string> | default = "NoClientCert" ]

  # CA certificate for client certificate authentication to the server.
  [ client_ca_file: <filename> ]

  # Verify that the client certificate has a Subject Alternate Name (SAN)
  # which is an exact match to an entry in this list, else terminate the
  # connection. SAN match can be one or multiple of the following: DNS,
  # IP, e-mail, or URI address from https://pkg.go.dev/crypto/x509#Certificate.
  [ client_allowed_sans:
    [ - <string> ] ]

  # Minimum TLS version that is acceptable.
  [ min_version: <string> | default = "TLS12" ]

  # Maximum TLS version that is acceptable.
  [ max_version: <string> | default = "TLS13" ]

  # List of supported cipher suites for TLS versions up to TLS 1.2. If empty,
  # Go default cipher suites are used. Available cipher suites are documented
  # in the go documentation:
  # https://golang.org/pkg/crypto/tls/#pkg-constants
  #
  # Note that only the cipher returned by the following function are supported:
  # https://pkg.go.dev/crypto/tls#CipherSuites
  [ cipher_suites:
    [ - <string> ] ]

  # prefer_server_cipher_suites controls whether the server selects the
  # client's most preferred ciphersuite, or the server's most preferred
  # ciphersuite. If true then the server's preference, as expressed in
  # the order of elements in cipher_suites, is used.
  [ prefer_server_cipher_suites: <boo> | default = true ]

  # Elliptic curves that will be used in an ECDHE handshake, in preference
  # order. Available curves are documented in the go documentation:
  # https://golang.org/pkg/crypto/tls/#CurveID
  [ curve_preferences:
    [ - <string> ] ]

http_server_config:
  # Enable HTTP/2 support. Note that HTTP/2 is only supported with TLS.
  # This can not be changed on the fly.
  [ http2: <boolean> | default = true ]
  # List of headers that can be added to HTTP responses.
  [ headers:
    # Set the Content-Security-Policy header to HTTP responses.
    # Unset if blank.
    [ Content-Security-Policy: <string> ]
    # Set the X-Frame-Options header to HTTP responses.
    # Unset if blank. Accepted values are deny and sameorigin.
    # https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options
    [ X-Frame-Options: <string> ]
    # Set the X-Content-Type-Options header to HTTP responses.
    # Unset if blank. Accepted value is nosniff.
    # https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Content-Type-Options
    [ X-Content-Type-Options: <string> ]
    # Set the X-XSS-Protection header to all responses.
    # Unset if blank.
    # https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-XSS-Protection
    [ X-XSS-Protection: <string> ]
    # Set the Strict-Transport-Security header to HTTP responses.
    # Unset if blank.
    # Please make sure that you use this with care as this header might force
    # browsers to load Prometheus and the other applications hosted on the same
    # domain and subdomains over HTTPS.
    # https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security
    [ Strict-Transport-Security: <string> ] ]

# Usernames and hashed passwords that have full access to the web
# server via basic authentication. If empty, no basic authentication is
# required. Passwords are hashed with bcrypt.
basic_auth_users:
  [ <string>: <secret> ... ]


# Rate limiting requests on the endpoint using a token bucket
rate_limit:
  interval: <duration> # time interval between two requests, set to 0 to disable rate limiter
  burst: <int> # and permits a burst of <int> requests.

Where generic placeholders are defined as follows:

  • <boolean>: a boolean that can take the values true or false

  • <filename>: a valid path in the current working directory

  • <secret>: a regular string that is a secret, such as a password

  • <string>: a regular string

  • <int>: a regular integer

  • <duration>: a time interval

For example:

# TLS and basic authentication configuration example.
#
# Additionally, a certificate and a key file are needed.
tls_server_config:
  cert_file: server.crt
  key_file: server.key

# Usernames and passwords required to connect.
# Passwords are hashed with bcrypt: https://github.com/prometheus/exporter-toolkit/blob/master/docs/web-configuration.md#about-bcrypt.
basic_auth_users:
  alice: $2y$10$mDwo.lAisC94iLAyP81MCesa29IzH37oigHC/42V2pdJlUprsJPze
  bob: $2y$10$hLqFl9jSjoAAy95Z/zw8Ye8wkdMBM8c5Bn1ptYqP/AXyV0.oy0S8m

# Rate limiting requests on the endpoint using a token bucket
rate_limit:
  interval: "1s" # time interval between two requests, set to 0 to disable rate limiter
  burst: 20 # and permits a burst of up to 20 requests.

Author

Prometheus Monitoring Community: https://prometheus.io/community/

FAQ