> For the complete documentation index, see [llms.txt](https://docs.cennso.com/cennso/cennso-db/latest/llms.txt) (all documentation: [llms.txt](https://docs.cennso.com/llms.txt)). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.cennso.com/cennso/cennso-db/latest/deployment-guides/cennso-postgresql-observability.md).

# Enable metrics collector

You can use [Prometheus PostgreSQL exporter](https://github.com/percona/postgres_exporter) to gather metrics from the deployed PostgreSQL database instances. The Cennso PostgreSQL extension provides the postgres-exporter deployment per PostgreSQL instance.

> [!NOTE]
> Do not mix the PostgreSQL instance with `PostgreSQLInstance`. The PostgreSQL instance refers to a single PostgreSQL database server deployed within the PostgreSQL cluster described by the `PostgreSQLInstance`.

You can enable postgres-exporter using the following configuration option:

```yaml
apiVersion: db.contrib.cennso.com/v1alpha1
kind: PostgreSQLInstance
metadata:
  name: postgresql-cluster
spec:
  metricsExporter:
    enabled: true
```

If **spec.metricsExporter.enabled** is set to `true`, a postgres-exporter instance is deployed for each PostgreSQL instance as a separate pod. The exporter pod is pinned to the node of its PostgreSQL instance with a node selector, and gets the tolerations of its instance set, so the taints on that node do not block it.

The following example shows how you can deploy a postgres-exporter instance for your PostgreSQL cluster:

```yaml
apiVersion: db.contrib.cennso.com/v1alpha1
kind: PostgreSQLInstance
metadata:
  name: {POSTGRESQL-INSTANCE-NAME}
  namespace: cennso-infra
spec:
  namespace: {NAMESPACE-WITH-DATABASE-INSTANCES}
  instances:
    - name: instance1
      replicas: 2
      storage:
        capacity: 20Gi
        className: postgresql-data-storage
  proxy:
    pgBouncer:
      replicas: 2
  metricsExporter:
    enabled: true
    chart:
      name: prometheus-postgres-exporter
      version: "8.2.0"
      registry: oci://registry.cennso.com/cennso/charts
      pullSecretRef: cennso-pull-secret
    image:
      registry: registry.cennso.com
      repository: cennso/percona-postgres-exporter
      tag: v3.10.0-cennso-0.0.1
    imagePullSecretRef:
      name: cennso-pull-secret
    scrapeInterval: "30s"
    scrapeTimeout: "10s"
    additionalRelabelings:
      - action: replace
        replacement: custom-instance-metric
        targetLabel: custom_metric_label
    logLevel: "info"
    collectors:
      postmaster: true
      database: true
      replication: true
    prometheusRules:
      enabled: false
      rules:
        - alert: PostgreSQLDown
          expr: pg_up == 0
          for: 1m
          labels:
            severity: critical
          annotations:
            summary: PostgreSQL down (instance {{ $labels.instance }})
            description: "PostgreSQL instance is down on {{ $labels.instance }}\n  VALUE = {{ $value }}\n  LABELS = {{ $labels }}"
```

> [!NOTE]
> For more information about all the configuration options except the **spec.metricsExporter**, see the [Deploy Cennso PostgreSQL Instance](https://docs.cennso.com/cennso/cennso-db/latest/deployment-guides/cennso-postgresql.md#deploy-cennso-postgresql-instance) document.

Using the example above, you can deploy the PostgreSQL cluster, which consists of two PostgreSQL instances. Together with the PostgreSQL instances, two postgres-exporter instances are deployed on the same nodes to collect metrics from the PostgreSQL servers.

## Relabeling rules

By default, each postgres-exporter instance provides the following [relabeling](https://grafana.com/docs/alloy/latest/reference/components/prometheus/prometheus.relabel/) rules:

```yaml
- sourceLabels: [__meta_kubernetes_pod_annotation_cennso_com_monitor_db_instance]
  action: replace
  targetLabel: pod
- targetLabel: postgresql_instance
  replacement: "{{ POSTGRESQL_INSTANCE_POD_NAME }}"
- targetLabel: instance
  replacement: "{{ POSTGRESQL_INSTANCE_POD_NAME }}"
```

The `{{ POSTGRESQL_INSTANCE_POD_NAME }}` has the `{POSTGRESQL-INSTANCE-NAME}-{INSTANCE-SET-NAME}-{SUFFIX}-0` format, where `{SUFFIX}` is a random string generated for each PostgreSQL instance.

Using the relabeling rules described above, you can use the `postgresql_instance` or `instance` label to refer to a PostgreSQL instance pod name. In addition, you can specify your relabeling rules using the **spec.metricsExporter.additionalRelabelings** configuration option.

## Metric collectors

In addition to the collectors that the postgres-exporter enables by default, the `postmaster` collector is enabled, because the PostgreSQL Grafana dashboard requires it to show the uptime of the PostgreSQL instances.

To enable a different set of collectors, use the **spec.metricsExporter.collectors** configuration option. Setting this option replaces the default, so keep `postmaster: true` in it. For more information about the available collectors, see the [official documentation](https://github.com/percona/postgres_exporter/blob/pmm-3.10.0/README.md#flags).

> [!NOTE]
> The postgres-exporter connects to the `postgres` database, so the `stat_user_tables` and `statio_user_tables` collectors report only the tables of the `postgres` database.
>
> The `stat_statements` collector requires the `pg_stat_statements` extension, which you can enable using the **spec.postgresql.extensions.pgStatStatements.enabled** configuration option. The collector creates metrics for every distinct statement, so the number of metrics grows with the number of statements of your applications.

If the **spec.postgresql.extensions.pgStatStatements.enabled** configuration option is set to `true`, the postgres-exporter also exposes the following measurements grouped by statement type:

- the number of executed statements
- the number of rows
- the execution time

Unlike the `stat_statements` collector, these metrics do not grow with the number of statements. The metrics are described in the [Statements by type](https://docs.cennso.com/cennso/cennso-db/latest/observability/cennso-postgresql-metrics.md#statements-by-type) section, and the extension in the [PostgreSQL extensions](https://docs.cennso.com/cennso/cennso-db/latest/concepts/cennso-postgresql-instance.md#postgresql-extensions) section.

## Prometheus rules

To configure additional [Prometheus rules](https://prometheus.io/docs/prometheus/latest/configuration/alerting_rules/), use the **spec.metricsExporter.prometheusRules** configuration option. To do that, set the **spec.metricsExporter.prometheusRules.enabled** to `true` and fill the **spec.metricsExporter.prometheusRules.rules** with your custom Prometheus rules. The rules are created as one PrometheusRule named `{POSTGRESQL-INSTANCE-NAME}-exporter` in the namespace set by **spec.namespace**. For examples, see the [Custom alert rules](https://docs.cennso.com/cennso/cennso-db/latest/observability/alerting.md#custom-alert-rules) section.

## Metrics based on custom queries

> [!NOTE]
> Each postgres-exporter instance runs custom queries against its own PostgreSQL instance and exposes the results as metrics that Prometheus can scrape. The results are reported per PostgreSQL instance and are not aggregated across the cluster.

In addition to the built-in [collectors](https://github.com/percona/postgres_exporter/blob/pmm-3.10.0/README.md#flags), you can expose Prometheus metrics for arbitrary SQL statements using the **spec.metricsExporter.customQueries** configuration option.

By default, custom queries are disabled (the **spec.metricsExporter.customQueries** configuration option is set to the empty string - `""`). When the value of this configuration option is set, the postgres-exporter is launched with the `--collect.custom_query.hr` flag and reads the YAML definitions from a Kubernetes ConfigMap mounted at `/etc/postgres-exporter/custom-queries/hr`. The ConfigMap is created and reconciled automatically for each PostgreSQL instance.

The custom queries are executed in the `postgres` database. PostgreSQL does not support queries across databases, so only the views that cover the whole server, such as `pg_stat_database`, `pg_stat_activity`, or `pg_database`, return data about other databases. Tables and per-table statistics views, such as `pg_stat_user_tables`, return the data of the `postgres` database only. The example below uses such views and the `datname` label to report metrics per database.

The value is an inline YAML document. Each top-level key defines a metric namespace used as the metric name prefix. Each namespace must contain a `query` and a `metrics` key. The `query` key specifies an SQL query that is executed to build data points for the metrics. The `metrics` key is a YAML array which contains the column name from the SQL query result and specifies how the value of this column is used. The usage of the value should be under the `usage` key. The possible values of the `usage` key are:

| Usage | Description |
| --- | --- |
| `LABEL` | The column value becomes a Prometheus label dimension on every emitted sample |
| `GAUGE` | The column value is emitted as a gauge sample |
| `COUNTER` | The column value is emitted as a counter sample |
| `DURATION` | The column value is a text duration, for example `1h2m3s` or `250ms`, emitted as a gauge in milliseconds |
| `DISCARD` | The column is ignored |

The following example exposes four custom metrics:

```yaml
spec:
  metricsExporter:
    enabled: true
    customQueries: |
      pg_custom_database_size:
        query: |
          SELECT datname, pg_database_size(datname) AS bytes
          FROM pg_database
          WHERE NOT datistemplate
        metrics:
          - datname:
              usage: "LABEL"
          - bytes:
              usage: "GAUGE"
              description: "Database size in bytes"

      pg_custom_connections:
        query: |
          SELECT datname, usename, state, COUNT(*) AS connections
          FROM pg_stat_activity
          WHERE datname IS NOT NULL
          GROUP BY datname, usename, state
        metrics:
          - datname:
              usage: "LABEL"
          - usename:
              usage: "LABEL"
          - state:
              usage: "LABEL"
          - connections:
              usage: "GAUGE"
              description: "Number of connections per database, user, and state"

      pg_custom_transactions:
        query: |
          SELECT datname, xact_commit, xact_rollback
          FROM pg_stat_database
          WHERE datname IS NOT NULL
        metrics:
          - datname:
              usage: "LABEL"
          - xact_commit:
              usage: "COUNTER"
              description: "Number of committed transactions"
          - xact_rollback:
              usage: "COUNTER"
              description: "Number of rolled back transactions"
```

The example above produces the following metrics:

- `pg_custom_database_size_bytes{datname="..."} value`
- `pg_custom_connections_connections{datname="...", usename="...", state="..."} value`
- `pg_custom_transactions_xact_commit{datname="..."} value`
- `pg_custom_transactions_xact_rollback{datname="..."} value`

The emitted metric name follows the pattern `{namespace}_{column}` for every non-`LABEL` and non-`DISCARD` value column, and `{namespace}_{column}_milliseconds` for `DURATION` columns.

> [!NOTE]
> Every custom query is executed on every Prometheus scrape, so avoid statements that are expensive to run or that lock tables. Use **spec.metricsExporter.scrapeInterval** to reduce the load if needed.

For more examples of the YAML schema, see the [`queries-hr.yml`](https://github.com/percona/postgres_exporter/blob/pmm-3.10.0/queries-hr.yml).
