セルフホストの Postgres のデータベースモニタリングの設定

データベースモニタリングはこのサイトでサポートされていません。

データベースモニタリングは、クエリメトリクス、クエリサンプル、実行計画、データベースの状態、フェイルオーバー、イベントを公開することで、Postgres データベースを詳細に視覚化します。

Agent は、読み取り専用のユーザーとしてログインすることでデータベースから直接テレメトリを収集します。Postgres データベースでデータベースモニタリングを有効にするには、以下の設定を行ってください。

  1. データベースのパラメーターを構成する
  2. Agent にデータベースへのアクセスを付与する
  3. Agent をインストールする

はじめに

サポート対象の PostgreSQL バージョン
9.6, 10, 11, 12, 13, 14, 15
前提条件
Postgres の追加供給モジュールがインストールされている必要があります。ほとんどのインストールでは、これはデフォルトで含まれていますが、一般的でない設定でインストールされている場合、お使いのバージョンの postgresql-contrib パッケージの追加インストールが必要になる場合があります。
サポート対象の Agent バージョン
7.36.1+
パフォーマンスへの影響
データベースモニタリングのデフォルトの Agent 構成は保守的ですが、収集間隔やクエリのサンプリングレートなどの設定を調整することで、よりニーズに合ったものにすることができます。ワークロードの大半において、Agent はデータベース上のクエリ実行時間の 1 % 未満、CPU の 1 % 未満を占めています。

データベースモニタリングは、ベースとなる Agent 上のインテグレーションとして動作します (ベンチマークを参照してください)。
プロキシ、ロードバランサー、コネクションプーラー
Agent は、監視対象のホストに直接接続する必要があります。セルフホスト型のデータベースでは、127.0.0.1 またはソケットを使用することをお勧めします。Agent をプロキシ、ロードバランサー、または pgbouncer などのコネクションプーラーを経由させないようご注意ください。クライアントアプリケーションのアンチパターンとなる可能性があります。また、各 Agent は基礎となるホスト名を把握し、フェイルオーバーの場合でも常に 1 つのホストのみを使用する必要があります。Datadog Agent が実行中に異なるホストに接続すると、メトリクス値の正確性が失われます。
データセキュリティへの配慮
Agent がデータベースから収集するデータとその安全性については、機密情報を参照してください。

Postgres 設定を構成する

postgresql.conf ファイルに以下のパラメーターを構成し、サーバーを再起動すると設定が有効になります。これらのパラメーターの詳細については、Postgres ドキュメントを参照してください。

パラメーター説明
shared_preload_librariespg_stat_statementspostgresql.queries.* メトリクスに対して必要です。pg_stat_statements 拡張機能を使用して、クエリメトリクスの収集を可能にします。
track_activity_query_size4096より大きなクエリを収集するために必要です。pg_stat_activity の SQL テキストのサイズを拡大します。 デフォルト値のままだと、1024 文字よりも長いクエリは収集されません。
pg_stat_statements.trackALLオプション。ストアドプロシージャや関数内のステートメントを追跡することができます。
pg_stat_statements.max10000オプション。pg_stat_statements で追跡する正規化されたクエリの数を増やします。この設定は、多くの異なるクライアントからさまざまな種類のクエリが送信される大容量のデータベースに推奨されます。
pg_stat_statements.track_utilityoffオプション。PREPARE や EXPLAIN のようなユーティリティコマンドを無効にします。この値を off にすると、SELECT、UPDATE、DELETE などのクエリのみが追跡されます。
track_io_timingonオプション。クエリのブロックの読み取りおよび書き込み時間の収集を有効にします。

Agent にアクセスを付与する

Datadog Agent は、統計やクエリを収集するためにデータベース サーバーへの読み取り専用のアクセスを必要とします。

Postgres がレプリケートされている場合、以下の SQL コマンドはクラスタ内のプライマリデータベースサーバー(ライター)で実行する必要があります。Agent が接続するデータベースサーバー上の PostgreSQL データベースを選択します。Agent は、どのデータベースに接続してもデータベースサーバー上のすべてのデータベースからテレメトリーを収集することができるため、デフォルトの postgres データベースを使用することをお勧めします。特定のデータに対するカスタムクエリを Agent で実行する必要がある場合のみ、別のデータベースを選択してください。

選択したデータベースに、スーパーユーザー (または十分な権限を持つ他のユーザー) として接続します。例えば、選択したデータベースが postgres である場合は、次のように実行して psql を使用する postgres ユーザーとして接続します。

psql -h mydb.example.com -d postgres -U postgres

datadog ユーザーを作成します。

CREATE USER datadog WITH password '<PASSWORD>';

datadog ユーザーに関連テーブルに対する権限を与えます。

ALTER ROLE datadog INHERIT;

すべてのデータベースに以下のスキーマを作成します。

CREATE SCHEMA datadog;
GRANT USAGE ON SCHEMA datadog TO datadog;
GRANT USAGE ON SCHEMA public TO datadog;
GRANT pg_monitor TO datadog;
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;

すべてのデータベースに以下のスキーマを作成します。

CREATE SCHEMA datadog;
GRANT USAGE ON SCHEMA datadog TO datadog;
GRANT USAGE ON SCHEMA public TO datadog;
GRANT pg_monitor TO datadog;
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;

すべてのデータベースに以下のスキーマを作成します。

CREATE SCHEMA datadog;
GRANT USAGE ON SCHEMA datadog TO datadog;
GRANT USAGE ON SCHEMA public TO datadog;
GRANT SELECT ON pg_stat_database TO datadog;
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;

すべてのデータベースに関数を作成して、Agent が pg_stat_activity および pg_stat_statements の全コンテンツを読み込めるようにします。

CREATE OR REPLACE FUNCTION datadog.pg_stat_activity() RETURNS SETOF pg_stat_activity AS
  $$ SELECT * FROM pg_catalog.pg_stat_activity; $$
LANGUAGE sql
SECURITY DEFINER;
CREATE OR REPLACE FUNCTION datadog.pg_stat_statements() RETURNS SETOF pg_stat_statements AS
    $$ SELECT * FROM pg_stat_statements; $$
LANGUAGE sql
SECURITY DEFINER;
追加のテーブルをクエリする必要があるデータ収集またはカスタムメトリクスでは、それらのテーブルの SELECT 権限を datadog ユーザーに付与する必要がある場合があります。例: grant SELECT on <TABLE_NAME> to datadog;。詳細は、PostgreSQL カスタムメトリクス収集を参照してください。

Agent が実行計画を収集できるように、すべてのデータベースに関数を作成します。

CREATE OR REPLACE FUNCTION datadog.explain_statement(
   l_query TEXT,
   OUT explain JSON
)
RETURNS SETOF JSON AS
$$
DECLARE
curs REFCURSOR;
plan JSON;

BEGIN
   OPEN curs FOR EXECUTE pg_catalog.concat('EXPLAIN (FORMAT JSON) ', l_query);
   FETCH curs INTO plan;
   CLOSE curs;
   RETURN QUERY SELECT plan;
END;
$$
LANGUAGE 'plpgsql'
RETURNS NULL ON NULL INPUT
SECURITY DEFINER;

検証する

権限が正しいことを確認するために、以下のコマンドを実行して、Agent ユーザーがデータベースに接続してコアテーブルを読み取ることができることを確認します。

psql -h localhost -U datadog postgres -A \
  -c "select * from pg_stat_database limit 1;" \
  && echo -e "\e[0;32mPostgres connection - OK\e[0m" \
  || echo -e "\e[0;31mCannot connect to Postgres\e[0m"
psql -h localhost -U datadog postgres -A \
  -c "select * from pg_stat_activity limit 1;" \
  && echo -e "\e[0;32mPostgres pg_stat_activity read OK\e[0m" \
  || echo -e "\e[0;31mCannot read from pg_stat_activity\e[0m"
psql -h localhost -U datadog postgres -A \
  -c "select * from pg_stat_statements limit 1;" \
  && echo -e "\e[0;32mPostgres pg_stat_statements read OK\e[0m" \
  || echo -e "\e[0;31mCannot read from pg_stat_statements\e[0m"
psql -h localhost -U datadog postgres -A \
  -c "select * from pg_stat_database limit 1;" \
  && echo -e "\e[0;32mPostgres connection - OK\e[0m" \
  || echo -e "\e[0;31mCannot connect to Postgres\e[0m"
psql -h localhost -U datadog postgres -A \
  -c "select * from pg_stat_activity limit 1;" \
  && echo -e "\e[0;32mPostgres pg_stat_activity read OK\e[0m" \
  || echo -e "\e[0;31mCannot read from pg_stat_activity\e[0m"
psql -h localhost -U datadog postgres -A \
  -c "select * from pg_stat_statements limit 1;" \
  && echo -e "\e[0;32mPostgres pg_stat_statements read OK\e[0m" \
  || echo -e "\e[0;31mCannot read from pg_stat_statements\e[0m"

パスワードの入力を求められた場合は、datadog ユーザーを作成したときに入力したパスワードを使用してください。

Agent のインストール

Datadog Agent をインストールすると、Postgres でのデータベースモニタリングに必要な Postgres チェックもインストールされます。Postgres データベースホストの Agent をまだインストールしていない場合は、Agent のインストール手順を参照してください。

  1. Agent の conf.d/postgres.d/conf.yaml ファイルを編集して、host / port を指定し、監視するホストを設定します。使用可能なすべてのコンフィギュレーションオプションについては、サンプル postgres.d/conf.yaml を参照してください。
init_config:
instances:
  - dbm: true
    host: localhost
    port: 5432
    username: datadog
    password: '<PASSWORD>'
    ## オプション: `custom_queries` に必要な場合は、別のデータベースに接続します
    # dbname: '<DB_NAME>'
init_config:
instances:
  - dbm: true
    host: localhost
    port: 5432
    username: datadog
    password: '<PASSWORD>'
    pg_stat_statements_view: datadog.pg_stat_statements()
    pg_stat_activity_view: datadog.pg_stat_activity()
    ## オプション: `custom_queries` に必要な場合は、別のデータベースに接続します
    # dbname: '<DB_NAME>'
  1. Agent を再起動します

ログの収集 (オプション)

PostgreSQL のデフォルトのログは stderr に記録され、ログに詳細な情報は含まれません。ログ行のプレフィックスに指定された詳細を追加してファイルに記録することをお勧めします。詳細については、このトピックに関する PostgreSQL ドキュメントを参照してください。

  1. ロギングはファイル /etc/postgresql/<バージョン>/main/postgresql.conf 内で構成されます。ステートメント出力を含む通常のログ結果の場合、ログセクションの次のパラメーターのコメントを外します。

      logging_collector = on
      log_directory = 'pg_log'  # directory where log files are written,
                                # can be absolute or relative to PGDATA
      log_filename = 'pg.log'   # log file name, can include pattern
      log_statement = 'all'     # log all queries
      #log_duration = on
      log_line_prefix= '%m [%p] %d %a %u %h %c '
      log_file_mode = 0644
      ## For Windows
      #log_destination = 'eventlog'
    
  2. 詳細な期間メトリクスを収集し、Datadog インターフェースで検索可能にするには、ステートメント自体を使用してインラインで構成する必要があります。上記の例と推奨コンフィギュレーションとの違いについては、以下を参照してください。また、log_statement オプションと log_duration オプションの両方がコメントアウトされているので注意してください。このトピックに関する議論はこちらをご覧ください。

    この構成はすべてのステートメントをログしますが、出力を特定の期間を持つものに減らすには、log_min_duration_statement の値を目的の最小期間(ミリ秒単位)に設定します(完全な SQL ステートメントのログ記録が組織のプライバシー要件に準拠していることを確認してください)。

      log_min_duration_statement = 0    # -1 is disabled, 0 logs all statements
                                        # and their durations, > 0 logs only
                                        # statements running at least this number
                                        # of milliseconds
      #log_statement = 'all'
      #log_duration = on
    
  3. Datadog Agent で、ログの収集はデフォルトで無効になっています。以下のように、datadog.yaml ファイルでこれを有効にします。

    logs_enabled: true
    
  4. PostgreSQL のログの収集を開始するには、次の構成ブロックを conf.d/postgres.d/conf.yaml ファイルに追加し、編集します。

    logs:
      - type: file
        path: "<LOG_FILE_PATH>"
        source: postgresql
        service: "<SERVICE_NAME>"
        #To handle multi line that starts with yyyy-mm-dd use the following pattern
        #log_processing_rules:
        #  - type: multi_line
        #    pattern: \d{4}\-(0?[1-9]|1[012])\-(0?[1-9]|[12][0-9]|3[01])
        #    name: new_log_start_with_date
    

    service パラメーターと path パラメーターの値を変更し、環境に合わせて構成してください。使用可能なすべての構成オプションの詳細については、サンプル postgres.d/conf.yaml を参照してください。

  5. Agent を再起動します

検証

Agent の status サブコマンドを実行し、Checks セクションで postgres を探します。または、データベースのページを参照してください。

Agent の構成例

One agent connecting to multiple hosts

It is common to configure a single Agent host to connect to multiple remote database instances (see Agent installation architectures for DBM). To connect to multiple hosts, create an entry for each host in the Postgres integration config. In these cases, Datadog recommends limiting the number of instances per Agent to a maximum of 10 database instances to guarantee reliable performance.

init_config:
instances:
  - dbm: true
    host: example-service-primary.example-host.com
    port: 5432
    username: datadog
    password: '<PASSWORD>'
    tags:
      - 'env:prod'
      - 'team:team-discovery'
      - 'service:example-service'
  - dbm: true
    host: example-service–replica-1.example-host.com
    port: 5432
    username: datadog
    password: '<PASSWORD>'
    tags:
      - 'env:prod'
      - 'team:team-discovery'
      - 'service:example-service'
  - dbm: true
    host: example-service–replica-2.example-host.com
    port: 5432
    username: datadog
    password: '<PASSWORD>'
    tags:
      - 'env:prod'
      - 'team:team-discovery'
      - 'service:example-service'
    [...]

Monitoring multiple databases on a database host

Use the database_autodiscovery option to permit the Agent to discover all databases on your host to monitor. You can specify include or exclude fields to narrow the scope of databases discovered. See the sample postgres.d/conf.yaml for more details.

init_config:
instances:
  - dbm: true
    host: example-service-primary.example-host.com
    port: 5432
    username: datadog
    password: '<PASSWORD>'
    database_autodiscovery:
      enabled: true
      # Optionally, set the include field to specify
      # a set of databases you are interested in discovering
      include:
        - mydb.*
        - example.*
    tags:
      - 'env:prod'
      - 'team:team-discovery'
      - 'service:example-service'

Storing passwords securely

While it is possible to declare passwords directly in the Agent configuration files, it is a more secure practice to encrypt and store database credentials elsewhere using secret management software such as Vault. The Agent is able to read these credentials using the ENC[] syntax. Review the secrets management documentation for the required setup to store these credentials. The following example shows how to declare and use those credentials:

init_config:
instances:
  - dbm: true
    host: localhost
    port: 5432
    username: datadog
    password: 'ENC[datadog_user_database_password]'

Running custom queries

To collect custom metrics, use the custom_queries option. See the sample postgres.d/conf.yaml for more details.

init_config:
instances:
  - dbm: true
    host: localhost
    port: 5432
    username: datadog
    password: '<PASSWORD>'
    custom_queries:
    - metric_prefix: employee
      query: SELECT age, salary, hours_worked, name FROM hr.employees;
      columns:
        - name: custom.employee_age
          type: gauge
        - name: custom.employee_salary
           type: gauge
        - name: custom.employee_hours
           type: count
        - name: name
           type: tag
      tags:
        - 'table:employees'

Monitoring relation metrics for multiple databases

In order to collect relation metrics (such as postgresql.seq_scans, postgresql.dead_rows, postgresql.index_rows_read, and postgresql.table_size), the Agent must be configured to connect to each database (by default, the Agent only connects to the postgres database).

Specify a single “DBM” instance to collect DBM telemetry from all databases. Use the database_autodiscovery option to avoid specifying each database name.

init_config:
instances:
  # This instance is the "DBM" instance. It will connect to the
  # all logical databases, and send DBM telemetry from all databases
  - dbm: true
    host: example-service-primary.example-host.com
    port: 5432
    username: datadog
    password: '<PASSWORD>'
    database_autodiscovery:
      enabled: true
      exclude:
        - ^users$
        - ^inventory$
    relations:
      - relation_regex: .*
  # This instance only collects data from the `users` database
  # and collects relation metrics from tables prefixed by "2022_"
  - host: example-service-primary.example-host.com
    port: 5432
    username: datadog
    password: '<PASSWORD>'
    dbname: users
    dbstrict: true
    relations:
      - relation_regex: 2022_.*
        relkind:
          - r
          - i
  # This instance only collects data from the `inventory` database
  # and collects relation metrics only from the specified tables
  - host: example-service-primary.example-host.com
    port: 5432
    username: datadog
    password: '<PASSWORD>'
    dbname: inventory
    dbstrict: true
    relations:
      - relation_name: products
      - relation_name: external_seller_products

Collecting schemas

To enable this feature, use the collect_schemas option. You must also configure the Agent to connect to each logical database.

Use the database_autodiscovery option to avoid specifying each logical database. See the sample postgres.d/conf.yaml for more details.

init_config:
# This instance only collects data from the `users` database
# and collects relation metrics only from the specified tables
instances:
  - dbm: true
    host: example-service-primary.example-host.com
    port: 5432
    username: datadog
    password: '<PASSWORD>'
    dbname: users
    dbstrict: true
    collect_schemas:
      enabled: true
    relations:
      - products
      - external_seller_products
  # This instance detects every logical database automatically
  # and collects relation metrics from every table
  - dbm: true
    host: example-service–replica-1.example-host.com
    port: 5432
    username: datadog
    password: '<PASSWORD>'
    database_autodiscovery:
      enabled: true
    collect_schemas:
      enabled: true
    relations:
      - relation_regex: .*

Working with hosts through a proxy

If the Agent must connect through a proxy such as the Cloud SQL Auth proxy, all telemetry is tagged with the hostname of the proxy rather than the database instance. Use the reported_hostname option to set a custom override of the hostname detected by the Agent.

init_config:
instances:
  - dbm: true
    host: localhost
    port: 5000
    username: datadog
    password: '<PASSWORD>'
    reported_hostname: example-service-primary
  - dbm: true
    host: localhost
    port: 5001
    username: datadog
    password: '<PASSWORD>'
    reported_hostname: example-service-replica-1

トラブルシューティング

インテグレーションと Agent を手順通りにインストール・設定しても期待通りに動作しない場合は、トラブルシューティングを参照してください。

その他の参考資料

お役に立つドキュメント、リンクや記事: