Google Cloud SQL マネージド Postgres のデータベースモニタリングの設定

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

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

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

  1. データベースのパラメーターを構成する
  2. Agent にデータベースへのアクセスを付与する
  3. Agent をインストールする
  4. Cloud SQL インテグレーションをインストールする

はじめに

サポート対象の PostgreSQL バージョン
10、11、12、13、14、15
サポート対象の Agent バージョン
7.36.1+
パフォーマンスへの影響
データベースモニタリングのデフォルトの Agent 構成は保守的ですが、収集間隔やクエリのサンプリングレートなどの設定を調整してニーズに合わせることができます。ほとんどのワークロードで、Agent はデータベース上のクエリ実行時間とCPU使用率のそれぞれ 1 % 未満を占めています。

データベースモニタリングは、ベースとなる Agent 上のインテグレーションとして動作します (ベンチマークを参照してください)。
プロキシ、ロードバランサー、コネクションプーラー
Datadog Agent は、監視対象のホストに直接接続する必要があります。セルフホスト型のデータベースでは、127.0.0.1 またはソケットを使用することをお勧めします。Agent をプロキシ、ロードバランサー、または pgbouncer などのコネクションプーラーを経由してデータベースに接続しないようご注意ください。Agent が実行中に異なるホストに接続すると (フェイルオーバーやロードバランシングなどの場合)、Agent は 2 つのホスト間の統計の差を計算し、不正確なメトリクスを生成します。
データセキュリティへの配慮
Agent がデータベースから収集するデータとそのデータの安全性の確保方法については、機密情報をご覧ください。

Postgres 設定を構成する

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

パラメーター説明
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>';

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

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;
追加のテーブルをクエリする必要があるデータ収集またはカスタムメトリクスでは、それらのテーブルの 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"

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

Agent のインストール

Cloud SQL ホストを監視するには、インフラストラクチャーに Datadog Agent をインストールし、各インスタンスにリモートで接続するよう構成します。Agent はデータベース上で動作する必要はなく、データベースに接続するだけで問題ありません。ここに記載されていないその他の Agent のインストール方法については、Agent のインストール手順を参照してください。

ホストで実行されている Agent に対してデータベースモニタリングメトリクスのコレクションを構成するには、次の手順に従ってください。 (Agent が Google Cloud SQL データベースから収集するように小さな GCE インスタンスをプロビジョニングする場合など)

  1. postgres.d/conf.yaml ファイルを編集して host / port を指定し、マスターを監視するように設定します。利用可能なすべての構成オプションについては、サンプル postgres.d/conf.yaml を参照してください。postgres.d ディレクトリの場所は、オペレーティングシステムに依存します。詳しくは、Agent 構成ディレクトリを参照してください。
    init_config:
    instances:
      - dbm: true
        host: '<INSTANCE_ADDRESS>'
        port: 5432
        username: datadog
        password: '<PASSWORD>'
        ## Optional: Connect to a different database if needed for `custom_queries`
        # dbname: '<DB_NAME>'
    
        # After adding your project and instance, configure the Datadog Google Cloud (GCP) integration to pull additional cloud data such as CPU, Memory, etc.
        gcp:
         project_id: '<PROJECT_ID>'
         instance_id: '<INSTANCE_ID>'
    
  2. Agent を再起動します

project_idinstance_id フィールドの設定に関する追加情報は、Postgres インテグレーション仕様を参照してください。

Google Cloud Run などの Docker コンテナで動作するデータベースモニタリング Agent を設定するには、Agent コンテナの Docker ラベルとしてオートディスカバリーのインテグレーションテンプレートを設定します。

: ラベルのオートディスカバリーを機能させるためには、Agent にDocker ソケットに対する読み取り権限が与えられている必要があります。

コマンドライン

次のコマンドを実行して、コマンドラインから Agent を実行することですぐに稼動させることができます。お使いのアカウントや環境に合わせて値を変更してください。

export DD_API_KEY=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
export DD_AGENT_VERSION=7.36.1

docker run -e "DD_API_KEY=${DD_API_KEY}" \
  -v /var/run/docker.sock:/var/run/docker.sock:ro \
  -l com.datadoghq.ad.check_names='["postgres"]' \
  -l com.datadoghq.ad.init_configs='[{}]' \
  -l com.datadoghq.ad.instances='[{
    "dbm": true,
    "host": "<INSTANCE_ADDRESS>",
    "port": 5432,
    "username": "datadog",
    "password": "<UNIQUEPASSWORD>",
    "gcp": {
      "project_id": "<PROJECT_ID>",
      "instance_id": "<INSTANCE_ID>"
    }
  }]' \
  gcr.io/datadoghq/agent:${DD_AGENT_VERSION}

Dockerfile

Dockerfile ではラベルの指定も可能であるため、インフラストラクチャーのコンフィギュレーションを変更することなく、カスタム Agent を構築・デプロイすることができます。

FROM gcr.io/datadoghq/agent:7.36.1

LABEL "com.datadoghq.ad.check_names"='["postgres"]'
LABEL "com.datadoghq.ad.init_configs"='[{}]'
LABEL "com.datadoghq.ad.instances"='[{"dbm": true, "host": "<INSTANCE_ADDRESS>", "port": 5432,"username": "datadog","password": "<UNIQUEPASSWORD>", "gcp": {"project_id": "<PROJECT_ID>", "instance_id": "<INSTANCE_ID>"}}]'

project_idinstance_id フィールドの設定に関する追加情報は、Postgres インテグレーション仕様を参照してください。

datadog ユーザーのパスワードをプレーンテキストで公開しないようにするには、Agent のシークレット管理パッケージを使用し、ENC[] 構文を使ってパスワードを宣言するか、オートディスカバリーテンプレート変数に関するドキュメントでパスワードを環境変数として渡す方法をご確認ください。

Kubernetes クラスターをお使いの場合は、データベースモニタリング用の Datadog Cluster Agent をご利用ください。

Kubernetes クラスターでまだチェックが有効になっていない場合は、手順に従ってクラスターチェックを有効にしてください。Postgres のコンフィギュレーションは、Cluster Agent コンテナにマウントされた静的ファイル、またはサービスアノテーションのいずれかを使用して宣言できます。

Helm のコマンドライン

以下の Helm コマンドを実行して、Kubernetes クラスターに Datadog Cluster Agent をインストールします。お使いのアカウントや環境に合わせて値を変更してください。

helm repo add datadog https://helm.datadoghq.com
helm repo update

helm install <RELEASE_NAME> \
  --set 'datadog.apiKey=<DATADOG_API_KEY>' \
  --set 'clusterAgent.enabled=true' \
  --set 'clusterChecksRunner.enabled=true' \
  --set 'clusterAgent.confd.postgres\.yaml=cluster_check: true
init_config:
instances:
  - dbm: true
    host: <INSTANCE_ADDRESS>
    port: 5432
    username: datadog
    password: "<UNIQUEPASSWORD>"
    gcp:
      project_id: "<PROJECT_ID>"
      instance_id: "<INSTANCE_ID>"' \
  datadog/datadog

マウントされたファイルで構成する

マウントされたコンフィギュレーションファイルを使ってクラスターチェックを構成するには、コンフィギュレーションファイルを Cluster Agent コンテナのパス /conf.d/postgres.yaml にマウントします。

cluster_check: true  # このフラグを必ず入れてください
init_config:
instances:
  - dbm: true
    host: '<INSTANCE_ADDRESS>'
    port: 5432
    username: datadog
    password: '<PASSWORD>'
    # プロジェクトとインスタンスを追加した後、CPU、メモリなどの追加のクラウドデータをプルするために Datadog GCP インテグレーションを構成します。
    gcp:
      project_id: '<PROJECT_ID>'
      instance_id: '<INSTANCE_ID>'

Kubernetes サービスアノテーションで構成する

ファイルをマウントせずに、インスタンスのコンフィギュレーションを Kubernetes サービスとして宣言することができます。Kubernetes 上で動作する Agent にこのチェックを設定するには、Datadog Cluster Agent と同じネームスペースにサービスを作成します。

apiVersion: v1
kind: Service
metadata:
  name: postgres
  labels:
    tags.datadoghq.com/env: '<ENV>'
    tags.datadoghq.com/service: '<SERVICE>'
  annotations:
    ad.datadoghq.com/service.check_names: '["postgres"]'
    ad.datadoghq.com/service.init_configs: '[{}]'
    ad.datadoghq.com/service.instances: |
      [
        {
          "dbm": true,
          "host": "<INSTANCE_ADDRESS>",
          "port": 5432,
          "username": "datadog",
          "password": "<UNIQUEPASSWORD>",
          "gcp": {
            "project_id": "<PROJECT_ID>",
            "instance_id": "<INSTANCE_ID>"
          }
        }
      ]      
spec:
  ports:
  - port: 5432
    protocol: TCP
    targetPort: 5432
    name: postgres

project_idinstance_id フィールドの設定に関する追加情報は、Postgres インテグレーション仕様を参照してください。

Cluster Agent は自動的にこのコンフィギュレーションを登録し、Postgres チェックを開始します。

datadog ユーザーのパスワードをプレーンテキストで公開しないよう、Agent のシークレット管理パッケージを使用し、ENC[] 構文を使ってパスワードを宣言します。

検証

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

Cloud SQL インテグレーションをインストールする

Google Cloud からより包括的なデータベースメトリクスを収集するには、Cloud SQL インテグレーションをインストールします (オプション)。

トラブルシューティング

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

その他の参考資料

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