Monitoring
==========

..  Important::
   PrometheusとGrafanaのインストールは、このプロジェクトの範囲を超えています。これらはシステムに正しくインストールされていることを前提としています。ただし、実験のために、 :ref:`Part 4 of the Quickstart <Quickstart>`  で指示を提供します。

モニタリングインスタンス
------------------------

PostgreSQLインスタンスごとに、オペレーターは、HTTPまたはHTTPS、ポート9187で\ ``metrics``
という名前の `Prometheus <https://prometheus.io/>`_ のメトリックのエクスポーターを提供します。オペレーターには、
:ref:`事前定義されたメトリックセット <事前定義されたメトリックセット>`  に加えて、1つ以上の\ ``ConfigMap`` または\ ``Secret``
リソースを介して追加クエリを定義するための高度な構成およびカスタマイズ可能なシステムが付属しています詳細については、以下の :ref:`ユーザー定義メトリック <ユーザー定義メトリック>` を参照してください。

..  Important::
   KubernetesのEDB Postgresは、デフォルトで :ref:`メトリックのデフォルトセット <メトリックのデフォルトセット>` のセットをインストールします

``default-monitoring`` という名前の\ ``ConfigMap`` で。

..  Note::
   :ref:`エクスポートされたメトリックを検査する方法 <エクスポートされたメトリックを検査する方法>` の指示に従って、エクスポートされたメトリックを検査できます。

以下のセクション。

PostgreSQLで実行されるすべての監視クエリは次のとおりです。

- アトミック クエリごとに1つのトランザクション

- ``pg_monitor`` ロールで実行

- ``application_name`` を\ ``cnp_metrics_exporter`` に設定して実行

- ユーザー\ ``postgres`` として実行

PostgreSQLの「事前定義されたロール」セクションを参照してください
`documentation <https://www.postgresql.org/docs/current/predefined-roles.html>`_ 

``pg_monitor`` ロールの詳細は、

デフォルトでは、クエリーは、次のロジックに従って、 ``Cluster``
リソースの指定された\ ``bootstrap`` メソッドで定義された_main
Database_に対して実行されます。

- using ``initdb`` クエリーはデフォルトで\ ``initdb.database``
  または\ ``app``
  で指定されたデータベースに対して実行されます指定しない場合

- using ``recovery`` クエリーはデフォルトで\ ``recovery.database``
  または\ ``postgres``
  で指定されたデータベースに対して実行されます指定しない場合

- using ``pg_basebackup``
  クエリーはデフォルトで\ ``pg_basebackup.database``
  または\ ``postgres``
  で指定されたデータベースに対して実行されます指定しない場合

``target_databases``
オプションで1つ以上のデータベースのリストを指定することにより、特定のユーザー定義メトリックのデフォルトデータベースを常にオーバーライドできます。

..  Seealso::
   KubernetesのEDB PostgresとPrometheusおよびGrafanaの統合を評価することに興味がある場合は、 :ref:`Part 4 of the quickstart <Quickstart>` で簡単なセットアップガイドを見つけることができます。

Prometheus Operatorの例
^^^^^^^^^^^^^^^^^^^^^^^

特定のPostgreSQLクラスターは、 `Prometheus Operator's <https://github.com/prometheus-operator/prometheus-operator>`_ リソース
`PodMonitor <https://github.com/prometheus-operator/prometheus-operator/blob/v0.75.1/Documentation/api.md#podmonitor>`_ を使用してモニタできます。

クラスターリソース自分自身デフォルト\ ``false``
で\ ``.spec.monitoring.enablePodMonitor`` 〜\ ``true``
を設定することにより、クラスターを正しくポイントする\ ``PodMonitor``
をオペレーターが自動的に作成できます。

..  Important::
   自動的に作成される`PodMonitor` への変更は、次の調整サイクルでオペレーターによってオーバーライドされます。カスタマイズが必要な場合は、以下の説明に従って行うことができます。

特定のクラスターに\ ``PodMonitor``
を手動で展開するには、次のように定義し、必要に応じて調整します。

.. code:: yaml

   apiVersion: monitoring.coreos.com/v1
   kind: PodMonitor
   metadata:
     name: cluster-example
   spec:
     selector:
       matchLabels:
         "k8s.enterprisedb.io/cluster": cluster-example
     podMetricsEndpoints:
       - port: metrics

..  Important::
   一意の名前、および正しいクラスターの名前空間とラベルたとえば `cluster-example` などを使用して上記の例を変更していることを確認します。

..  Important::
   このドキュメントの以前のバージョンで使用されていた`postgresql` ラベルは非推奨であり、将来的に削除されます。代わりに`k8s.enterprisedb.io/cluster` ラベルを使用して、インスタンスを選択してください。

メトリックポートでTLSを有効にする
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

メトリックポートでTLS通信を有効にするには、
``.spec.monitoring.tls.enabled`` 設定を\ ``true``
に構成します。この設定により、メトリックエクスポーターは、PostgreSQLが使用するものと同じサーバー証明書を使用して、ポート5432での通信を安全にします。

..  Important::
   `.spec.monitoring.tls.enabled` 設定を変更すると、クラスターのローリング再起動がトリガーされます。

``PodMonitor`` がオペレーター\ ``.spec.monitoring.enablePodMonitor``
を\ ``true``
に設定して管理されている場合、TLSを介してメトリックにアクセスするために必要な構成が自動的に含まれます。

TLS経由でメトリックを読み取るのに適した\ ``PodMonitor``
を手動で展開するには、次のように定義し、必要に応じて調整します。

.. code:: yaml

   apiVersion: monitoring.coreos.com/v1
   kind: PodMonitor
   metadata:
     name: cluster-example
   spec:
     selector:
       matchLabels:
         "k8s.enterprisedb.io/cluster": cluster-example
     podMetricsEndpoints:
       - port: metrics
         scheme: https
         tlsConfig:
           ca:
             secret:
               name: cluster-example-ca
               key: ca.crt
           serverName: cluster-example-rw

..  Important::
   一意の名前、および正しいクラスターの名前空間とラベルたとえば `cluster-example` などを使用して上記の例を変更していることを確認します。

..  Important::
   メトリックエンドポイントの`serverName` フィールドは、サーバー証明書で定義された名前のいずれかと一致する必要があります。デフォルトの証明書が使用されている場合、`serverName` 値は`<cluster-name>-rw` 形式である必要があります。

事前定義されたメトリックセット
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

すべてのPostgreSQLインスタンスエクスポーターは、事前定義されたメトリックのセットを自動的に公開します。これらは2つの主要カテゴリに分類できます。

- ``cnp_collector_*``
  で始まるPostgreSQL関連メトリックインスタンスを収容する個別のノードの数s

- 最後に失敗したバックアップと最後に使用可能なバックアップを示すタイムスタンプ、およびcluster

- フラグ レプリカクラスターモードが有効または無効かを示します

- フラグ
  手動スイッチオーバーが必要かどうかを示すb_tran_12フェンシングが有効かどうかを示すb_tran_12フラグ有効または無効

- ``go_*`` で始まるGoランタイム関連のメトリック

以下は、インスタンスの\ ``localhost:9187/metrics``
エンドポイントによって返されるメトリックのサンプルです。ご覧のとおり、Prometheusフォーマットは自己文書です。

.. code:: text


   #  HELP cnp_collector_collection_duration_seconds Collection time duration in seconds

   #  TYPE cnp_collector_collection_duration_seconds gauge

   cnp_collector_collection_duration_seconds{collector="Collect.up"} 0.0031393

   #  HELP cnp_collector_collections_total Total number of times PostgreSQL was accessed for metrics.

   #  TYPE cnp_collector_collections_total counter

   cnp_collector_collections_total 2

   #  HELP cnp_collector_fencing_on 1 if the instance is fenced, 0 otherwise

   #  TYPE cnp_collector_fencing_on gauge

   cnp_collector_fencing_on 0

   #  HELP cnp_collector_nodes_used NodesUsed represents the count of distinct nodes accommodating the instances. A value of -1 suggests that the metric is not available. A value of 1 suggests that all instances are hosted on a single node, implying the absence of High Availability (HA). Ideally this value should match the number of instances in the cluster.

   #  TYPE cnp_collector_nodes_used gauge

   cnp_collector_nodes_used 3

   #  HELP cnp_collector_last_collection_error 1 if the last collection ended with error, 0 otherwise.

   #  TYPE cnp_collector_last_collection_error gauge

   cnp_collector_last_collection_error 0

   #  HELP cnp_collector_manual_switchover_required 1 if a manual switchover is required, 0 otherwise

   #  TYPE cnp_collector_manual_switchover_required gauge

   cnp_collector_manual_switchover_required 0

   #  HELP cnp_collector_pg_wal Total size in bytes of WAL segments in the /var/lib/postgresql/data/pgdata/pg_wal directory  computed as (wal_segment_size * count)

   #  TYPE cnp_collector_pg_wal gauge

   cnp_collector_pg_wal{value="count"} 9
   cnp_collector_pg_wal{value="slots_max"} NaN
   cnp_collector_pg_wal{value="keep"} 32
   cnp_collector_pg_wal{value="max"} 64
   cnp_collector_pg_wal{value="min"} 5
   cnp_collector_pg_wal{value="size"} 1.50994944e+08
   cnp_collector_pg_wal{value="volume_max"} 128
   cnp_collector_pg_wal{value="volume_size"} 2.147483648e+09

   #  HELP cnp_collector_pg_wal_archive_status Number of WAL segments in the /var/lib/postgresql/data/pgdata/pg_wal/archive_status directory (ready, done)

   #  TYPE cnp_collector_pg_wal_archive_status gauge

   cnp_collector_pg_wal_archive_status{value="done"} 6
   cnp_collector_pg_wal_archive_status{value="ready"} 0

   #  HELP cnp_collector_replica_mode 1 if the cluster is in replica mode, 0 otherwise

   #  TYPE cnp_collector_replica_mode gauge

   cnp_collector_replica_mode 0

   #  HELP cnp_collector_sync_replicas Number of requested synchronous replicas (synchronous_standby_names)

   #  TYPE cnp_collector_sync_replicas gauge

   cnp_collector_sync_replicas{value="expected"} 0
   cnp_collector_sync_replicas{value="max"} 0
   cnp_collector_sync_replicas{value="min"} 0
   cnp_collector_sync_replicas{value="observed"} 0

   #  HELP cnp_collector_up 1 if PostgreSQL is up, 0 otherwise.

   #  TYPE cnp_collector_up gauge

   cnp_collector_up{cluster="cluster-example"} 1

   #  HELP cnp_collector_postgres_version Postgres version

   #  TYPE cnp_collector_postgres_version gauge

   cnp_collector_postgres_version{cluster="cluster-example",full="17.4"} 17.4

   #  HELP cnp_collector_last_failed_backup_timestamp The last failed backup as a unix timestamp

   #  TYPE cnp_collector_last_failed_backup_timestamp gauge

   cnp_collector_last_failed_backup_timestamp 0

   #  HELP cnp_collector_last_available_backup_timestamp The last available backup as a unix timestamp

   #  TYPE cnp_collector_last_available_backup_timestamp gauge

   cnp_collector_last_available_backup_timestamp 1.63238406e+09

   #  HELP cnp_collector_first_recoverability_point The first point of recoverability for the cluster as a unix timestamp

   #  TYPE cnp_collector_first_recoverability_point gauge

   cnp_collector_first_recoverability_point 1.63238406e+09

   #  HELP cnp_collector_lo_pages Estimated number of pages in the pg_largeobject table

   #  TYPE cnp_collector_lo_pages gauge

   cnp_collector_lo_pages{datname="app"} 0
   cnp_collector_lo_pages{datname="postgres"} 78

   #  HELP cnp_collector_wal_buffers_full Number of times WAL data was written to disk because WAL buffers became full. Only available on PG 14+

   #  TYPE cnp_collector_wal_buffers_full gauge

   cnp_collector_wal_buffers_full{stats_reset="2023-06-19T10:51:27.473259Z"} 6472

   #  HELP cnp_collector_wal_bytes Total amount of WAL generated in bytes. Only available on PG 14+

   #  TYPE cnp_collector_wal_bytes gauge

   cnp_collector_wal_bytes{stats_reset="2023-06-19T10:51:27.473259Z"} 1.0035147e+07

   #  HELP cnp_collector_wal_fpi Total number of WAL full page images generated. Only available on PG 14+

   #  TYPE cnp_collector_wal_fpi gauge

   cnp_collector_wal_fpi{stats_reset="2023-06-19T10:51:27.473259Z"} 1474

   #  HELP cnp_collector_wal_records Total number of WAL records generated. Only available on PG 14+

   #  TYPE cnp_collector_wal_records gauge

   cnp_collector_wal_records{stats_reset="2023-06-19T10:51:27.473259Z"} 26178

   #  HELP cnp_collector_wal_sync Number of times WAL files were synced to disk via issue_xlog_fsync request (if fsync is on and wal_sync_method is either fdatasync, fsync or fsync_writethrough, otherwise zero). Only available on PG 14+

   #  TYPE cnp_collector_wal_sync gauge

   cnp_collector_wal_sync{stats_reset="2023-06-19T10:51:27.473259Z"} 37

   #  HELP cnp_collector_wal_sync_time Total amount of time spent syncing WAL files to disk via issue_xlog_fsync request, in milliseconds (if track_wal_io_timing is enabled, fsync is on, and wal_sync_method is either fdatasync, fsync or fsync_writethrough, otherwise zero). Only available on PG 14+

   #  TYPE cnp_collector_wal_sync_time gauge

   cnp_collector_wal_sync_time{stats_reset="2023-06-19T10:51:27.473259Z"} 0

   #  HELP cnp_collector_wal_write Number of times WAL buffers were written out to disk via XLogWrite request. Only available on PG 14+

   #  TYPE cnp_collector_wal_write gauge

   cnp_collector_wal_write{stats_reset="2023-06-19T10:51:27.473259Z"} 7243

   #  HELP cnp_collector_wal_write_time Total amount of time spent writing WAL buffers to disk via XLogWrite request, in milliseconds (if track_wal_io_timing is enabled, otherwise zero). This includes the sync time when wal_sync_method is either open_datasync or open_sync. Only available on PG 14+

   #  TYPE cnp_collector_wal_write_time gauge

   cnp_collector_wal_write_time{stats_reset="2023-06-19T10:51:27.473259Z"} 0

   #  HELP cnp_last_error 1 if the last collection ended with error, 0 otherwise.

   #  TYPE cnp_last_error gauge

   cnp_last_error 0

   #  HELP go_gc_duration_seconds A summary of the pause duration of garbage collection cycles.

   #  TYPE go_gc_duration_seconds summary

   go_gc_duration_seconds{quantile="0"} 5.01e-05
   go_gc_duration_seconds{quantile="0.25"} 7.27e-05
   go_gc_duration_seconds{quantile="0.5"} 0.0001748
   go_gc_duration_seconds{quantile="0.75"} 0.0002959
   go_gc_duration_seconds{quantile="1"} 0.0012776
   go_gc_duration_seconds_sum 0.0035741
   go_gc_duration_seconds_count 13

   #  HELP go_goroutines Number of goroutines that currently exist.

   #  TYPE go_goroutines gauge

   go_goroutines 25

   #  HELP go_info Information about the Go environment.

   #  TYPE go_info gauge

   go_info{version="go1.20.5"} 1

   #  HELP go_memstats_alloc_bytes Number of bytes allocated and still in use.

   #  TYPE go_memstats_alloc_bytes gauge

   go_memstats_alloc_bytes 4.493744e+06

   #  HELP go_memstats_alloc_bytes_total Total number of bytes allocated, even if freed.

   #  TYPE go_memstats_alloc_bytes_total counter

   go_memstats_alloc_bytes_total 2.1698216e+07

   #  HELP go_memstats_buck_hash_sys_bytes Number of bytes used by the profiling bucket hash table.

   #  TYPE go_memstats_buck_hash_sys_bytes gauge

   go_memstats_buck_hash_sys_bytes 1.456234e+06

   #  HELP go_memstats_frees_total Total number of frees.

   #  TYPE go_memstats_frees_total counter

   go_memstats_frees_total 172118

   #  HELP go_memstats_gc_cpu_fraction The fraction of this programs available CPU time used by the GC since the program started.

   #  TYPE go_memstats_gc_cpu_fraction gauge

   go_memstats_gc_cpu_fraction 1.0749468700447189e-05

   #  HELP go_memstats_gc_sys_bytes Number of bytes used for garbage collection system metadata.

   #  TYPE go_memstats_gc_sys_bytes gauge

   go_memstats_gc_sys_bytes 5.530048e+06

   #  HELP go_memstats_heap_alloc_bytes Number of heap bytes allocated and still in use.

   #  TYPE go_memstats_heap_alloc_bytes gauge

   go_memstats_heap_alloc_bytes 4.493744e+06

   #  HELP go_memstats_heap_idle_bytes Number of heap bytes waiting to be used.

   #  TYPE go_memstats_heap_idle_bytes gauge

   go_memstats_heap_idle_bytes 5.8236928e+07

   #  HELP go_memstats_heap_inuse_bytes Number of heap bytes that are in use.

   #  TYPE go_memstats_heap_inuse_bytes gauge

   go_memstats_heap_inuse_bytes 7.528448e+06

   #  HELP go_memstats_heap_objects Number of allocated objects.

   #  TYPE go_memstats_heap_objects gauge

   go_memstats_heap_objects 26306

   #  HELP go_memstats_heap_released_bytes Number of heap bytes released to OS.

   #  TYPE go_memstats_heap_released_bytes gauge

   go_memstats_heap_released_bytes 5.7401344e+07

   #  HELP go_memstats_heap_sys_bytes Number of heap bytes obtained from system.

   #  TYPE go_memstats_heap_sys_bytes gauge

   go_memstats_heap_sys_bytes 6.5765376e+07

   #  HELP go_memstats_last_gc_time_seconds Number of seconds since 1970 of last garbage collection.

   #  TYPE go_memstats_last_gc_time_seconds gauge

   go_memstats_last_gc_time_seconds 1.6311727586032727e+09

   #  HELP go_memstats_lookups_total Total number of pointer lookups.

   #  TYPE go_memstats_lookups_total counter

   go_memstats_lookups_total 0

   #  HELP go_memstats_mallocs_total Total number of mallocs.

   #  TYPE go_memstats_mallocs_total counter

   go_memstats_mallocs_total 198424

   #  HELP go_memstats_mcache_inuse_bytes Number of bytes in use by mcache structures.

   #  TYPE go_memstats_mcache_inuse_bytes gauge

   go_memstats_mcache_inuse_bytes 14400

   #  HELP go_memstats_mcache_sys_bytes Number of bytes used for mcache structures obtained from system.

   #  TYPE go_memstats_mcache_sys_bytes gauge

   go_memstats_mcache_sys_bytes 16384

   #  HELP go_memstats_mspan_inuse_bytes Number of bytes in use by mspan structures.

   #  TYPE go_memstats_mspan_inuse_bytes gauge

   go_memstats_mspan_inuse_bytes 191896

   #  HELP go_memstats_mspan_sys_bytes Number of bytes used for mspan structures obtained from system.

   #  TYPE go_memstats_mspan_sys_bytes gauge

   go_memstats_mspan_sys_bytes 212992

   #  HELP go_memstats_next_gc_bytes Number of heap bytes when next garbage collection will take place.

   #  TYPE go_memstats_next_gc_bytes gauge

   go_memstats_next_gc_bytes 8.689632e+06

   #  HELP go_memstats_other_sys_bytes Number of bytes used for other system allocations.

   #  TYPE go_memstats_other_sys_bytes gauge

   go_memstats_other_sys_bytes 2.566622e+06

   #  HELP go_memstats_stack_inuse_bytes Number of bytes in use by the stack allocator.

   #  TYPE go_memstats_stack_inuse_bytes gauge

   go_memstats_stack_inuse_bytes 1.343488e+06

   #  HELP go_memstats_stack_sys_bytes Number of bytes obtained from system for stack allocator.

   #  TYPE go_memstats_stack_sys_bytes gauge

   go_memstats_stack_sys_bytes 1.343488e+06

   #  HELP go_memstats_sys_bytes Number of bytes obtained from system.

   #  TYPE go_memstats_sys_bytes gauge

   go_memstats_sys_bytes 7.6891144e+07

   #  HELP go_threads Number of OS threads created.

   #  TYPE go_threads gauge

   go_threads 18

..  Note::
   `cnp_collector_postgres_version` は、 Postgres PostgreSQLまたはEPASの`Major.Minor` バージョンを含むGaugeVecメトリックです。フルセマンティックバージョン`Major.Minor.Patch` は、 `full` という名前のラベルフィールドの1つ内にあります。

..  Note::
   `cnp_collector_first_recoverability_point` および`cnp_collector_last_available_backup_timestamp` は、オブジェクトストアへの最初のバックアップまで0になります。これはWALアーカイブとは別です。

ユーザー定義メトリック
^^^^^^^^^^^^^^^^^^^^^^

この機能は現在_beta_状態にあり、フォーマットは `queries.yaml file (release 0.12) <https://github.com/prometheus-community/postgres_exporter/blob/v0.12.1/queries.yaml>`_ 

PostgreSQL Prometheus Exporterの。

カスタムメトリックは、次の例のように、\ ``.spec.monitoring.customQueriesConfigMap``
または\ ``customQueriesSecret`` セクションの下の\ ``Cluster``
定義で作成した\ ``Configmap`` /``Secret``
を参照することにより、ユーザーが定義できます。

.. code:: yaml

   apiVersion: postgresql.k8s.enterprisedb.io/v1
   kind: Cluster
   metadata:
     name: cluster-example
     namespace: test
   spec:
     instances: 3

     storage:
       size: 1Gi

     monitoring:
       customQueriesConfigMap:
         - name: example-monitoring
           key: custom-queries

``customQueriesConfigMap`` /``customQueriesSecret``
セクションには、カスタムクエリーが定義されているキーを指定する\ ``ConfigMap``
/``Secret`` 参照のリストが含まれています。参照されるリソースは、
**クラスター**
リソースと同じ名前空間に作成する必要があることに注意してください。

..  Note::
   ConfigMapとSecretsをインスタンスによって**自動的に**リロードしたい場合は、キー`k8s.enterprisedb.io/reload` を持つラベルをそれに追加できます。それ以外の場合、 `kubectl cnp reload` サブコマンドを使用してインスタンスをリロードする必要があります。

..  Important::
   ユーザー定義メトリックが既存のメトリックを上書きすると、インスタンスマネージャーはjson警告ログを出力します。これには、メッセージ`Query with the same name already found. Overwriting the existing one.` と上書きされたクエリー名を含むキー`queryName` が含まれます。

ユーザー定義メトリックの例
^^^^^^^^^^^^^^^^^^^^^^^^^^

ここでは、上記の\ ``Cluster``
の例で参照される、単一のカスタムクエリーを含む\ ``ConfigMap``
の例を示します。

.. code:: yaml

   apiVersion: v1
   kind: ConfigMap
   metadata:
     name: example-monitoring
     namespace: test
     labels:
       k8s.enterprisedb.io/reload: ""
   data:
     custom-queries: |
       pg_replication:
         query: "SELECT CASE WHEN NOT pg_is_in_recovery()
                 THEN 0
                 ELSE GREATEST (0,
                   EXTRACT(EPOCH FROM (now() - pg_last_xact_replay_timestamp())))
                 END AS lag,
                 pg_is_in_recovery() AS in_recovery,
                 EXISTS (TABLE pg_stat_wal_receiver) AS is_wal_receiver_up,
                 (SELECT count(*) FROM pg_stat_replication) AS streaming_replicas"

         metrics:
           - lag:
               usage: "GAUGE"
               description: "Replication lag behind primary in seconds"
           - in_recovery:
               usage: "GAUGE"
               description: "Whether the instance is in recovery"
           - is_wal_receiver_up:
               usage: "GAUGE"
               description: "Whether the instance wal_receiver is up"
           - streaming_replicas:
               usage: "GAUGE"
               description: "Number of streaming replicas connected to the instance"

基本的なモニタリングクエリのリストは以下にあります。

::

   apiVersion: v1
   kind: ConfigMap
   metadata:
     name: default-monitoring
     labels:
       k8s.enterprisedb.io/reload: ""
   data:
     queries: |
       backends:
         query: |
          SELECT sa.datname
              , sa.usename
              , sa.application_name
              , states.state
              , COALESCE(sa.count, 0) AS total
              , COALESCE(sa.max_tx_secs, 0) AS max_tx_duration_seconds
              FROM ( VALUES (active)
                  , (idle)
                  , (idle in transaction)
                  , (idle in transaction (aborted))
                  , (fastpath function call)
                  , (disabled)
                  ) AS states(state)
              LEFT JOIN (
                  SELECT datname
                      , state
                      , usename
                      , COALESCE(application_name, ) AS application_name
                      , COUNT(*)
                      , COALESCE(EXTRACT (EPOCH FROM (max(now() - xact_start))), 0) AS max_tx_secs
                  FROM pg_catalog.pg_stat_activity
                  GROUP BY datname, state, usename, application_name
              ) sa ON states.state = sa.state
              WHERE sa.usename IS NOT NULL
         metrics:
           - datname:
               usage: "LABEL"
               description: "Name of the database"
           - usename:
               usage: "LABEL"
               description: "Name of the user"
           - application_name:
               usage: "LABEL"
               description: "Name of the application"
           - state:
               usage: "LABEL"
               description: "State of the backend"
           - total:
               usage: "GAUGE"
               description: "Number of backends"
           - max_tx_duration_seconds:
               usage: "GAUGE"
               description: "Maximum duration of a transaction in seconds"

       backends_waiting:
         query: |
          SELECT count(*) AS total
          FROM pg_catalog.pg_locks blocked_locks
          JOIN pg_catalog.pg_locks blocking_locks
            ON blocking_locks.locktype = blocked_locks.locktype
            AND blocking_locks.database IS NOT DISTINCT FROM blocked_locks.database
            AND blocking_locks.relation IS NOT DISTINCT FROM blocked_locks.relation
            AND blocking_locks.page IS NOT DISTINCT FROM blocked_locks.page
            AND blocking_locks.tuple IS NOT DISTINCT FROM blocked_locks.tuple
            AND blocking_locks.virtualxid IS NOT DISTINCT FROM blocked_locks.virtualxid
            AND blocking_locks.transactionid IS NOT DISTINCT FROM blocked_locks.transactionid
            AND blocking_locks.classid IS NOT DISTINCT FROM blocked_locks.classid
            AND blocking_locks.objid IS NOT DISTINCT FROM blocked_locks.objid
            AND blocking_locks.objsubid IS NOT DISTINCT FROM blocked_locks.objsubid
            AND blocking_locks.pid != blocked_locks.pid
          JOIN pg_catalog.pg_stat_activity blocking_activity ON blocking_activity.pid = blocking_locks.pid
          WHERE NOT blocked_locks.granted
         metrics:
           - total:
               usage: "GAUGE"
               description: "Total number of backends that are currently waiting on other queries"

       pg_database:
         query: |
           SELECT datname
             , pg_catalog.pg_database_size(datname) AS size_bytes
             , pg_catalog.age(datfrozenxid) AS xid_age
             , pg_catalog.mxid_age(datminmxid) AS mxid_age
           FROM pg_catalog.pg_database
           WHERE datallowconn
         metrics:
           - datname:
               usage: "LABEL"
               description: "Name of the database"
           - size_bytes:
               usage: "GAUGE"
               description: "Disk space used by the database"
           - xid_age:
               usage: "GAUGE"
               description: "Number of transactions from the frozen XID to the current one"
           - mxid_age:
               usage: "GAUGE"
               description: "Number of multiple transactions (Multixact) from the frozen XID to the current one"

       pg_postmaster:
         query: |
           SELECT EXTRACT(EPOCH FROM pg_postmaster_start_time) AS start_time
           FROM pg_catalog.pg_postmaster_start_time()
         metrics:
           - start_time:
               usage: "GAUGE"
               description: "Time at which postgres started (based on epoch)"

       pg_replication:
         query: "SELECT CASE WHEN (
                   NOT pg_catalog.pg_is_in_recovery()
                   OR pg_catalog.pg_last_wal_receive_lsn() = pg_catalog.pg_last_wal_replay_lsn())
                 THEN 0
                 ELSE GREATEST (0,
                   EXTRACT(EPOCH FROM (now() - pg_catalog.pg_last_xact_replay_timestamp())))
                 END AS lag,
                 pg_catalog.pg_is_in_recovery() AS in_recovery,
                 EXISTS (TABLE pg_stat_wal_receiver) AS is_wal_receiver_up,
                 (SELECT count(*) FROM pg_catalog.pg_stat_replication) AS streaming_replicas"
         metrics:
           - lag:
               usage: "GAUGE"
               description: "Replication lag behind primary in seconds"
           - in_recovery:
               usage: "GAUGE"
               description: "Whether the instance is in recovery"
           - is_wal_receiver_up:
               usage: "GAUGE"
               description: "Whether the instance wal_receiver is up"
           - streaming_replicas:
               usage: "GAUGE"
               description: "Number of streaming replicas connected to the instance"

       pg_replication_slots:
         query: |
           SELECT slot_name,
             slot_type,
             database,
             active,
             (CASE pg_catalog.pg_is_in_recovery()
               WHEN TRUE THEN pg_catalog.pg_wal_lsn_diff(pg_catalog.pg_last_wal_receive_lsn(), restart_lsn)
               ELSE pg_catalog.pg_wal_lsn_diff(pg_catalog.pg_current_wal_lsn(), restart_lsn)
             END) as pg_wal_lsn_diff
           FROM pg_catalog.pg_replication_slots
           WHERE NOT temporary
         metrics:
           - slot_name:
               usage: "LABEL"
               description: "Name of the replication slot"
           - slot_type:
               usage: "LABEL"
               description: "Type of the replication slot"
           - database:
               usage: "LABEL"
               description: "Name of the database"
           - active:
               usage: "GAUGE"
               description: "Flag indicating whether the slot is active"
           - pg_wal_lsn_diff:
               usage: "GAUGE"
               description: "Replication lag in bytes"

       pg_stat_archiver:
         query: |
           SELECT archived_count
             , failed_count
             , COALESCE(EXTRACT(EPOCH FROM (now() - last_archived_time)), -1) AS seconds_since_last_archival
             , COALESCE(EXTRACT(EPOCH FROM (now() - last_failed_time)), -1) AS seconds_since_last_failure
             , COALESCE(EXTRACT(EPOCH FROM last_archived_time), -1) AS last_archived_time
             , COALESCE(EXTRACT(EPOCH FROM last_failed_time), -1) AS last_failed_time
             , COALESCE(CAST(CAST(x||pg_catalog.right(pg_catalog.split_part(last_archived_wal, ., 1), 16) AS pg_catalog.bit(64)) AS pg_catalog.int8), -1) AS last_archived_wal_start_lsn
             , COALESCE(CAST(CAST(x||pg_catalog.right(pg_catalog.split_part(last_failed_wal, ., 1), 16) AS pg_catalog.bit(64)) AS pg_catalog.int8), -1) AS last_failed_wal_start_lsn
             , EXTRACT(EPOCH FROM stats_reset) AS stats_reset_time
           FROM pg_catalog.pg_stat_archiver
         metrics:
           - archived_count:
               usage: "COUNTER"
               description: "Number of WAL files that have been successfully archived"
           - failed_count:
               usage: "COUNTER"
               description: "Number of failed attempts for archiving WAL files"
           - seconds_since_last_archival:
               usage: "GAUGE"
               description: "Seconds since the last successful archival operation"
           - seconds_since_last_failure:
               usage: "GAUGE"
               description: "Seconds since the last failed archival operation"
           - last_archived_time:
               usage: "GAUGE"
               description: "Epoch of the last time WAL archiving succeeded"
           - last_failed_time:
               usage: "GAUGE"
               description: "Epoch of the last time WAL archiving failed"
           - last_archived_wal_start_lsn:
               usage: "GAUGE"
               description: "Archived WAL start LSN"
           - last_failed_wal_start_lsn:
               usage: "GAUGE"
               description: "Last failed WAL LSN"
           - stats_reset_time:
               usage: "GAUGE"
               description: "Time at which these statistics were last reset"

       pg_stat_bgwriter:
         runonserver: "<17.0.0"
         query: |
           SELECT checkpoints_timed
             , checkpoints_req
             , checkpoint_write_time
             , checkpoint_sync_time
             , buffers_checkpoint
             , buffers_clean
             , maxwritten_clean
             , buffers_backend
             , buffers_backend_fsync
             , buffers_alloc
           FROM pg_catalog.pg_stat_bgwriter
         metrics:
           - checkpoints_timed:
               usage: "COUNTER"
               description: "Number of scheduled checkpoints that have been performed"
           - checkpoints_req:
               usage: "COUNTER"
               description: "Number of requested checkpoints that have been performed"
           - checkpoint_write_time:
               usage: "COUNTER"
               description: "Total amount of time that has been spent in the portion of checkpoint processing where files are written to disk, in milliseconds"
           - checkpoint_sync_time:
               usage: "COUNTER"
               description: "Total amount of time that has been spent in the portion of checkpoint processing where files are synchronized to disk, in milliseconds"
           - buffers_checkpoint:
               usage: "COUNTER"
               description: "Number of buffers written during checkpoints"
           - buffers_clean:
               usage: "COUNTER"
               description: "Number of buffers written by the background writer"
           - maxwritten_clean:
               usage: "COUNTER"
               description: "Number of times the background writer stopped a cleaning scan because it had written too many buffers"
           - buffers_backend:
               usage: "COUNTER"
               description: "Number of buffers written directly by a backend"
           - buffers_backend_fsync:
               usage: "COUNTER"
               description: "Number of times a backend had to execute its own fsync call (normally the background writer handles those even when the backend does its own write)"
           - buffers_alloc:
               usage: "COUNTER"
               description: "Number of buffers allocated"

       pg_stat_bgwriter_17:
         runonserver: ">=17.0.0"
         name: pg_stat_bgwriter
         query: |
           SELECT buffers_clean
             , maxwritten_clean
             , buffers_alloc
             , EXTRACT(EPOCH FROM stats_reset) AS stats_reset_time
           FROM pg_catalog.pg_stat_bgwriter
         metrics:
           - buffers_clean:
               usage: "COUNTER"
               description: "Number of buffers written by the background writer"
           - maxwritten_clean:
               usage: "COUNTER"
               description: "Number of times the background writer stopped a cleaning scan because it had written too many buffers"
           - buffers_alloc:
               usage: "COUNTER"
               description: "Number of buffers allocated"
           - stats_reset_time:
               usage: "GAUGE"
               description: "Time at which these statistics were last reset"

       pg_stat_checkpointer:
         runonserver: ">=17.0.0"
         query: |
           SELECT num_timed AS checkpoints_timed
             , num_requested AS checkpoints_req
             , restartpoints_timed
             , restartpoints_req
             , restartpoints_done
             , write_time
             , sync_time
             , buffers_written
             , EXTRACT(EPOCH FROM stats_reset) AS stats_reset_time
           FROM pg_catalog.pg_stat_checkpointer
         metrics:
           - checkpoints_timed:
               usage: "COUNTER"
               description: "Number of scheduled checkpoints that have been performed"
           - checkpoints_req:
               usage: "COUNTER"
               description: "Number of requested checkpoints that have been performed"
           - restartpoints_timed:
               usage: "COUNTER"
               description: "Number of scheduled restartpoints due to timeout or after a failed attempt to perform it"
           - restartpoints_req:
               usage: "COUNTER"
               description: "Number of requested restartpoints that have been performed"
           - restartpoints_done:
               usage: "COUNTER"
               description: "Number of restartpoints that have been performed"
           - write_time:
               usage: "COUNTER"
               description: "Total amount of time that has been spent in the portion of processing checkpoints and restartpoints where files are written to disk, in milliseconds"
           - sync_time:
               usage: "COUNTER"
               description: "Total amount of time that has been spent in the portion of processing checkpoints and restartpoints where files are synchronized to disk, in milliseconds"
           - buffers_written:
               usage: "COUNTER"
               description: "Number of buffers written during checkpoints and restartpoints"
           - stats_reset_time:
               usage: "GAUGE"
               description: "Time at which these statistics were last reset"

       pg_stat_database:
         query: |
           SELECT datname
             , xact_commit
             , xact_rollback
             , blks_read
             , blks_hit
             , tup_returned
             , tup_fetched
             , tup_inserted
             , tup_updated
             , tup_deleted
             , conflicts
             , temp_files
             , temp_bytes
             , deadlocks
             , blk_read_time
             , blk_write_time
           FROM pg_catalog.pg_stat_database
         metrics:
           - datname:
               usage: "LABEL"
               description: "Name of this database"
           - xact_commit:
               usage: "COUNTER"
               description: "Number of transactions in this database that have been committed"
           - xact_rollback:
               usage: "COUNTER"
               description: "Number of transactions in this database that have been rolled back"
           - blks_read:
               usage: "COUNTER"
               description: "Number of disk blocks read in this database"
           - blks_hit:
               usage: "COUNTER"
               description: "Number of times disk blocks were found already in the buffer cache, so that a read was not necessary (this only includes hits in the PostgreSQL buffer cache, not the operating systems file system cache)"
           - tup_returned:
               usage: "COUNTER"
               description: "Number of rows returned by queries in this database"
           - tup_fetched:
               usage: "COUNTER"
               description: "Number of rows fetched by queries in this database"
           - tup_inserted:
               usage: "COUNTER"
               description: "Number of rows inserted by queries in this database"
           - tup_updated:
               usage: "COUNTER"
               description: "Number of rows updated by queries in this database"
           - tup_deleted:
               usage: "COUNTER"
               description: "Number of rows deleted by queries in this database"
           - conflicts:
               usage: "COUNTER"
               description: "Number of queries canceled due to conflicts with recovery in this database"
           - temp_files:
               usage: "COUNTER"
               description: "Number of temporary files created by queries in this database"
           - temp_bytes:
               usage: "COUNTER"
               description: "Total amount of data written to temporary files by queries in this database"
           - deadlocks:
               usage: "COUNTER"
               description: "Number of deadlocks detected in this database"
           - blk_read_time:
               usage: "COUNTER"
               description: "Time spent reading data file blocks by backends in this database, in milliseconds"
           - blk_write_time:
               usage: "COUNTER"
               description: "Time spent writing data file blocks by backends in this database, in milliseconds"

       pg_stat_replication:
         primary: true
         query: |
          SELECT usename
            , COALESCE(application_name, ) AS application_name
            , COALESCE(client_addr::text, ) AS client_addr
            , COALESCE(client_port::text, ) AS client_port
            , EXTRACT(EPOCH FROM backend_start) AS backend_start
            , COALESCE(pg_catalog.age(backend_xmin), 0) AS backend_xmin_age
            , pg_catalog.pg_wal_lsn_diff(pg_catalog.pg_current_wal_lsn(), sent_lsn) AS sent_diff_bytes
            , pg_catalog.pg_wal_lsn_diff(pg_catalog.pg_current_wal_lsn(), write_lsn) AS write_diff_bytes
            , pg_catalog.pg_wal_lsn_diff(pg_catalog.pg_current_wal_lsn(), flush_lsn) AS flush_diff_bytes
            , COALESCE(pg_catalog.pg_wal_lsn_diff(pg_catalog.pg_current_wal_lsn(), replay_lsn),0) AS replay_diff_bytes
            , COALESCE((EXTRACT(EPOCH FROM write_lag)),0)::float AS write_lag_seconds
            , COALESCE((EXTRACT(EPOCH FROM flush_lag)),0)::float AS flush_lag_seconds
            , COALESCE((EXTRACT(EPOCH FROM replay_lag)),0)::float AS replay_lag_seconds
          FROM pg_catalog.pg_stat_replication
         metrics:
           - usename:
               usage: "LABEL"
               description: "Name of the replication user"
           - application_name:
               usage: "LABEL"
               description: "Name of the application"
           - client_addr:
               usage: "LABEL"
               description: "Client IP address"
           - client_port:
               usage: "LABEL"
               description: "Client TCP port"
           - backend_start:
               usage: "COUNTER"
               description: "Time when this process was started"
           - backend_xmin_age:
               usage: "COUNTER"
               description: "The age of this standbys xmin horizon"
           - sent_diff_bytes:
               usage: "GAUGE"
               description: "Difference in bytes from the last write-ahead log location sent on this connection"
           - write_diff_bytes:
               usage: "GAUGE"
               description: "Difference in bytes from the last write-ahead log location written to disk by this standby server"
           - flush_diff_bytes:
               usage: "GAUGE"
               description: "Difference in bytes from the last write-ahead log location flushed to disk by this standby server"
           - replay_diff_bytes:
               usage: "GAUGE"
               description: "Difference in bytes from the last write-ahead log location replayed into the database on this standby server"
           - write_lag_seconds:
               usage: "GAUGE"
               description: "Time elapsed between flushing recent WAL locally and receiving notification that this standby server has written it"
           - flush_lag_seconds:
               usage: "GAUGE"
               description: "Time elapsed between flushing recent WAL locally and receiving notification that this standby server has written and flushed it"
           - replay_lag_seconds:
               usage: "GAUGE"
               description: "Time elapsed between flushing recent WAL locally and receiving notification that this standby server has written, flushed and applied it"

       pg_settings:
         query: |
           SELECT name,
           CASE setting WHEN on THEN 1 WHEN off THEN 0 ELSE setting END AS setting
           FROM pg_catalog.pg_settings
           WHERE vartype IN (integer, real, bool)
           ORDER BY 1
         metrics:
           - name:
               usage: "LABEL"
               description: "Name of the setting"
           - setting:
               usage: "GAUGE"
               description: "Setting value"

述語クエリーを使用したユーザー定義メトリックの例
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

``predicate_query`` オプションを使用すると、ユーザーは\ ``query``
を実行して、指定された条件でのみメトリックを収集できます。これを行うには、ユーザーは単一の\ ``boolean``
列で最大1つの行を返す述語照会を提供する必要があります。

述語クエリーは、メインクエリーと同じトランザクションで、同じデータベースに対して実行されます。

.. code:: yaml

   some_query: |
     predicate_query: |
       SELECT 
         some_bool as predicate 
       FROM some_table
     query: |
       SELECT
        count(*) as rows
       FROM some_table
     metrics:
       - rows:
           usage: "GAUGE"
           description: "number of rows"

複数のデータベースで実行されているユーザー定義メトリックの例
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

``target_databases``
オプションが複数のデータベースをリストする場合、メトリックは各データベースから収集されます。

``target_databases`` のリストで_shell-like pattern_つまり、\ ``*``
、\ ``?`` または\ ``[]``
を含むを指定することにより、特定のクエリーに対してデータベース自動検出を有効にできます。提供されている場合、オペレーターは、
``SELECT datname FROM pg_database WHERE datallowconn AND NOT datistemplate``
の実行によって返されたすべてのデータベースを追加し、 `path.Match() <https://pkg.go.dev/path#Match>`_ ルールに従ってパターンと一致することにより、ターゲットデータベースのリストを展開します。

..  Note::
   `*` 文字は、yamlに `special meaning <https://yaml.org/spec/1.2/spec.html#id2786448>`_ があるため、このようなパターンが含まれる場合、`target_databases` 値を引用符で`"*"` する必要があります。

返されるラベルには、常にデータベースの名前を含めることをお勧めします。たとえば、次の例のように\ ``current_database()``
ファンクションを使用します。

.. code:: yaml

   some_query: |
     query: |
       SELECT
        current_database() as datname,
        count(*) as rows
       FROM some_table
     metrics:
       - datname:
           usage: "LABEL"
           description: "Name of current database"
       - rows:
           usage: "GAUGE"
           description: "number of rows"
     target_databases:
       - albert
       - bb
       - freddie

これにより、次のメトリックが公開されます。

.. code:: text

   cnp_some_query_rows{datname="albert"} 2
   cnp_some_query_rows{datname="bb"} 5
   cnp_some_query_rows{datname="freddie"} 10

次に、自動検出を有効にしたクエリーの例を示します。これは、 ``template1``
データベースでも実行されますそれ以外の場合、前述のクエリーによって返されません。

.. code:: yaml

   some_query: |
     query: |
       SELECT
        current_database() as datname,
        count(*) as rows
       FROM some_table
     metrics:
       - datname:
           usage: "LABEL"
           description: "Name of current database"
       - rows:
           usage: "GAUGE"
           description: "number of rows"
     target_databases:
       - "*"
       - "template1"

上記の例では、次のメトリックを生成しますデータベースが存在する場合。

.. code:: text

   cnp_some_query_rows{datname="albert"} 2
   cnp_some_query_rows{datname="bb"} 5
   cnp_some_query_rows{datname="freddie"} 10
   cnp_some_query_rows{datname="template1"} 7
   cnp_some_query_rows{datname="postgres"} 42

ユーザー定義メトリックの構造
^^^^^^^^^^^^^^^^^^^^^^^^^^^^

すべてのカスタムクエリーには、次の基本構造があります。

.. code:: yaml

   <MetricName>:
     query: "<SQLQuery>"
     metrics:
       - <ColumnName>:
           usage: "<MetricType>"
           description: "<MetricDescription>"

次に、使用可能なすべてのフィールドの簡単な説明を示します。

- ``<MetricName>`` プロメテウスの名前 metric
- ``name`` オーバーライド\ ``<MetricName>`` 、定義されている場合
- ``query``
  メトリックを生成するためにターゲットデータベースで実行するSQLクエリー
- ``primary`` プライマリインスタンスでのみクエリーを実行するかどうか
- edb_fortran_20 Prometheus PostgreSQLエクスポータの互換性-非推奨)
- ``runonserver``
  クエリを実行するPostgreSQLのバージョンを制限するセマンティックバージョンレンジたとえば
  ``">=11.0.0"`` または\ ``">=12.0.0 <=15.0.0"``
- ``target_databases`` ``query``
  を実行するデータベースのリスト、またはedb_asis edb_5lk_15

自動検出を有効にします。デフォルトのデータベースが提供されている場合は上書きします。
- ``predicate_query``
ターゲットデータベースで実行する最大1つの行と1つの\ ``boolean``
列を返すSQLクエリー。システムは述語を評価し、\ ``true`` が\ ``query`` .
- ``metrics``
エクスポートされたすべての列のリストを含むセクション。次のように定義します。
- ``<ColumnName>`` クエリーによって返された列の名前 - ``name``
列の\ ``ColumnName``
をオーバーライドしますメトリック、定義されている場合b_tran_17 ``usage``
以下で説明する値のいずれか - ``description`` メトリックの説明 -
``metrics_mapping`` ``usage`` が\ ``MAPPEDMETRIC``
に設定されている場合のオプションの列マッピング

``usage`` の可能な値は次のとおりです。

.. csv-table::
  :header: Column Usage Label,Description
  :widths: 10,30
  :align: left
  :class: longtable

  `DISCARD`,この列は無視する必要があります
  `LABEL`,この列をラベルとして使用します
  `COUNTER`,この列をカウンターとして使用する
  `GAUGE`,この列をゲージとして使用します
  `MAPPEDMETRIC`,指定されたテキスト値のマッピングでこの列を使用します
  `DURATION`,この列をテキストの長さミリ秒単位として使用します
  `HISTOGRAM`,この列をヒストグラムとして使用します

`Metric Types <https://prometheus.io/docs/concepts/metric_types/>`_ にアクセスしてください。

詳細については、Prometheusのドキュメントから 。

ユーザー定義メトリックの出力
^^^^^^^^^^^^^^^^^^^^^^^^^^^^

カスタム定義メトリックは、次の形式でPrometheusエクスポータエンドポイント\ ``:9187/metrics``
によって返されます。

.. code:: text

   cnp_<MetricName>_<ColumnName>{<LabelColumnName>=<LabelColumnValue> ... } <ColumnValue>

..  Note::
   `LabelColumnName` は、 `usage` が`LABEL` に設定されたメトリックとその`Value` 

上記の\ ``pg_replication``
の例を考慮すると、エクスポーターのエンドポイントは、呼び出されると次の出力を結果ます。

.. code:: text


   #  HELP cnp_pg_replication_in_recovery Whether the instance is in recovery

   #  TYPE cnp_pg_replication_in_recovery gauge

   cnp_pg_replication_in_recovery 0

   #  HELP cnp_pg_replication_lag Replication lag behind primary in seconds

   #  TYPE cnp_pg_replication_lag gauge

   cnp_pg_replication_lag 0

   #  HELP cnp_pg_replication_streaming_replicas Number of streaming replicas connected to the instance

   #  TYPE cnp_pg_replication_streaming_replicas gauge

   cnp_pg_replication_streaming_replicas 2

   #  HELP cnp_pg_replication_is_wal_receiver_up Whether the instance wal_receiver is up

   #  TYPE cnp_pg_replication_is_wal_receiver_up gauge

   cnp_pg_replication_is_wal_receiver_up 0

メトリックのデフォルトセット
^^^^^^^^^^^^^^^^^^^^^^^^^^^^

オペレーターは、オペレーターの名前空間内のConfigMapまたはSecretで定義された一連のモニタリングクエリーをクラスターに自動的に注入するように構成できます。
:ref:`Operator configuration <Operator configuration>` の\ ``MONITORING_QUERIES_CONFIGMAP``
または\ ``MONITORING_QUERIES_SECRET``
キーを、それぞれConfigMapまたはSecretの名前に設定する必要があります。オペレーターは\ ``queries``
キーの内容を使用します。

``queries``
コンテンツを変更すると、それを使用するデプロイされたすべてのクラスターにすぐに反映されます。

オペレーターインストールマニフェストには、すべてのクラスターが使用する\ ``postgresql-operator-default-monitoring``
と呼ばれる事前定義されたConfigMapが付属しています。
``MONITORING_QUERIES_CONFIGMAP``
は、オペレーター構成でデフォルトで\ ``postgresql-operator-default-monitoring``
に設定されます。

デフォルトのメトリックセットを無効にする場合は、次のことができます。

- オペレーターレベルで無効にする オペレーターConfigMapで
  ``MONITORING_QUERIES_CONFIGMAP`` / ``MONITORING_QUERIES_SECRET``
  キーを\ ``""``
  空の文字列に設定します。オペレーターのConfigMapを変更するには、オペレーターの再起動が必要です。

- 特定のクラスターで無効にします。クラスターで\ ``.spec.monitoring.disableDefaultQueries``
  を\ ``true`` に設定します。

..  Important::
   `MONITORING_QUERIES_CONFIGMAP`  / `MONITORING_QUERIES_SECRET` を介して指定されたConfigMapまたはSecretは、常に固定名`postgresql-operator-default-monitoring` でクラスターの名前空間にコピーされます。そのため、デフォルトのメトリックを使用する場合は、クラスターの名前空間にこの名前でConfigMapを作成しないでください。

Prometheus Postgresエクスポーターとの違い
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

EDB Postgres for Kubernetesは、PostgreSQL Prometheus
Exporterからインスピレーションを得ていますが、いくつかの違いがあります。特に、
``cache_seconds`` フィールドは、KubernetesのエクスポーターのEDB
Postgresに実装されていません。

オペレーターのモニタリング
--------------------------

オペレーターは、\ ``metrics``
という名前のポート8080でHTTPを介して `Prometheus <https://prometheus.io/>`_ メトリックを内部公開します。

..  Note::
   :ref:`エクスポートされたメトリックを検査する方法 <エクスポートされたメトリックを検査する方法>` の指示に従って、エクスポートされたメトリックを検査できます。

以下のセクション。

現在、オペレーターはデフォルトの\ ``kubebuilder``
メトリックを公開しています。詳細については、
`kubebuilder documentation <https://book.kubebuilder.io/reference/metrics.html>`_ を参照してください。

.. _prometheus-operatorの例-1:

Prometheus Operatorの例
^^^^^^^^^^^^^^^^^^^^^^^

オペレーターの展開は、次の `PodMonitor <https://github.com/prometheus-operator/prometheus-operator/blob/v0.47.1/Documentation/api.md#podmonitor>`_ を定義することにより、 `Prometheus Operator <https://github.com/prometheus-operator/prometheus-operator>`_ を使用して監視できます。

リソース

.. code:: yaml

   apiVersion: monitoring.coreos.com/v1
   kind: PodMonitor
   metadata:
     name: postgresql-operator-controller-manager
   spec:
     selector:
       matchLabels:
         app.kubernetes.io/name: cloud-native-postgresql
     podMetricsEndpoints:
       - port: metrics

エクスポートされたメトリックを検査する方法
------------------------------------------

このセクションでは、同じ名前空間で\ ``curl``
を実行する一時ポッドを使用して、特定のPostgreSQLインスタンスマネージャープライマリまたはレプリカまたはオペレーターによってエクスポートされたメトリックを検査する方法に関する基本的な手順を提供します。

..  Note::
   次の例では、PostgreSQLクラスターと並んで、デフォルトの名前空間で作業していることを前提としています。 Kubernetesの基本的な知識を適用して、この例をユースケースに自由に調整してください。

次の内容で\ ``curl.yaml`` ファイルを作成します。

.. code:: yaml

   apiVersion: v1
   kind: Pod
   metadata:
     name: curl
   spec:
     containers:
       - name: curl
         image: curlimages/curl:8.2.1
         command: ["sleep", "3600"]

次に、ポッドを作成します。

.. code:: shell

   kubectl apply -f curl.yaml

インスタンスによってエクスポートされたメトリックを検査する場合、ターゲットポッドのポート9187に接続する必要があります。これは、実行する汎用コマンドです。ポッドの正しいIPを使用していることを確認します。

.. code:: shell

   kubectl exec -ti curl -- curl -s <pod_ip>:9187/metrics

たとえば、PostgreSQLクラスターが\ ``cluster-example``
と呼ばれ、クラスター内の最初のポッドのエクスポートされたメトリックを取得する場合、次のコマンドを実行してそのポッドのIPをプログラム的に取得できます。

.. code:: shell

   POD_IP=$(kubectl get pod cluster-example-1 --template {{.status.podIP}})

そして、実行します。

.. code:: shell

   kubectl exec -ti curl -- curl -s ${POD_IP}:9187/metrics

TLSメトリックを有効にした場合、代わりに実行します。

.. code:: shell

   kubectl exec -ti curl -- curl -sk https://${POD_IP}:9187/metrics

オペレーターのメトリックにアクセスする場合は、オペレーターが実行されているポッドをポイントし、ターゲットとしてTCPポート8080を使用する必要があります。

インスペクションの最後に、\ ``curl``
ポッドを削除していることを確認してください。

.. code:: shell

   kubectl delete -f curl.yaml

補助リソース
------------

..  Important::
   これらのリソースは、説明と実験のために提供されており、実稼働システムへのいかなる種類の推奨を表すものではありません

:ref:`doc/src/samples/monitoring/ <Examples>` 

ディレクトリには、可観測性のための一連のサンプルファイルがあります。
:ref:`Part 4 of the quickstart <Quickstart>` を参照してください。

コンテキストのセクション

- ``kube-stack-config.yaml`` kube-stack Helm
  chartインストールの構成ファイル。これにより、PrometheusがすべてのPodMonitorリソースをリッスンすることが保証されます。

- ``prometheusrule.yaml`` KubernetesのEDB
  Postgresのアラートを含む\ ``PrometheusRule``
  。注これには、通知サービスとの相互運用は含まれません。
  `Prometheus documentation <https://prometheus.io/docs/alerting/latest/alertmanager/>`_ を参照してください。

- ``podmonitor.yaml`` Kubernetes Operator展開のEDB
  Postgresの\ ``PodMonitor`` 。

さらに、Prometheusアラートルールの「生」ソースを\ ``alerts.yaml``
ファイルで提供します。

`Grafana dashboard <https://github.com/cloudnative-pg/grafana-dashboards/blob/main/charts/cluster/grafana-dashboard.json>`_ には、専用のリポジトリがあります。

``kube-prometheus-stack`` の構成では、\ ``kube-stack-config.yaml``
で提供するものより他のフィールドと設定が利用できることに注意してください。

``helm show values prometheus-community/kube-prometheus-stack``
を実行して表示できます。詳細については、
`kube-prometheus-stack <https://github.com/prometheus-community/helm-charts/tree/main/charts/kube-prometheus-stack>`_ を参照してください。

ページ。

OpenShiftでのモニタリング
-------------------------

Openshift
4.6以降、 :ref:`Monitoring for user-defined projects <Red Hat OpenShift>` と呼ばれる完全なモニタリングスタックがあります

これは、クラスター管理者が有効にできます。 ``Cluster``
定義のオプション\ ``spec.monitoring.enablePodMonitor`` が\ ``true``
に設定されている場合、クラウドネイティブPostgreSQLは\ ``PodMonitor``
オブジェクトを自動的に作成します。

クラスター全体の\ ``user-defined``
モニタリングを有効にするには、最初に次の内容を使用して\ ``openshift-monitoring``
名前空間/プロジェクトに\ ``cluster-monitoring-config``
という名前で\ ``ConfigMap`` を作成する必要があります。

.. code:: yaml

   apiVersion: v1
   kind: ConfigMap
   metadata:
     name: cluster-monitoring-config
     namespace: openshift-monitoring
   data:
     config.yaml: |
       enableUserWorkload: true

``ConfigMap`` が既に存在する場合、変数\ ``enableUserWorkload: true``
を追加するだけです。

..  Important::
   これにより、クラスター全体のモニタリングが有効になります。1つの名前空間/プロジェクトでのみ必要な場合は、Red Hatの公式ドキュメントを参照するか、クラスター管理者に相談してください。

その後、これに似たものを使用して名前空間/プロジェクトに適切なPodMonitorを作成するだけです。

.. code:: yaml

   apiVersion: monitoring.coreos.com/v1
   kind: PodMonitor
   metadata:
     name: cluster-sample
   spec:
     selector:
       matchLabels:
         postgresql: cluster-sample
     podMetricsEndpoints:
       - port: metrics

..  Note::
   私たちのサービスはメトリックを指すポートを定義していないため、現在`ServiceMonitor` は使用しません。メトリックポートを追加すると、機密データが公開される可能性があります。
