From 571a45f481f4ddd89d0eb642b358b0a2c068e594 Mon Sep 17 00:00:00 2001 From: urismiley Date: Mon, 30 Nov 2026 14:49:57 -0500 Subject: [PATCH] feat: add PostgreSQL, catalog, data volume, and network metrics to the OTel sidecar Signed-off-by: urismiley --- CHANGELOG.md | 3 + docs/designs/product-neutral-core.md | 2 + .../v1/high-availability/local-ha.md | 2 + .../v1/monitoring/metrics.md | 129 +++++++++- .../v1/monitoring/overview.md | 10 +- .../internal/lifecycle/lifecycle.go | 45 +++- .../internal/lifecycle/lifecycle_test.go | 150 ++++++++--- operator/src/internal/cnpg/cnpg_cluster.go | 59 ++++- .../cnpg/testdata/golden/env-overrides.json | 2 +- .../golden/explicit-component-resources.json | 2 +- .../internal/cnpg/testdata/golden/full.json | 2 +- .../controller/documentdb_controller_test.go | 233 ++++++++++++++++++ .../src/internal/engine/cluster_reconciler.go | 32 ++- operator/src/internal/engine/otel_monitor.go | 122 +++++++++ .../src/internal/engine/otel_monitor_test.go | 79 ++++++ operator/src/internal/engine/predicates.go | 16 +- .../internal/engine/predicates_sql_test.go | 18 ++ operator/src/internal/otel/base_config.yaml | 154 ++++++++++++ operator/src/internal/otel/config.go | 55 +++-- operator/src/internal/otel/config_test.go | 221 ++++++++++++++++- operator/src/internal/product/documentdb.go | 6 + operator/src/internal/product/profile.go | 13 + .../tests/resources/sidecar_resources_test.go | 27 ++ 23 files changed, 1304 insertions(+), 78 deletions(-) create mode 100644 operator/src/internal/engine/otel_monitor.go create mode 100644 operator/src/internal/engine/otel_monitor_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 9b2d6d878..c195e585b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,9 @@ ## [Unreleased] +### Major Features +- **Expanded OpenTelemetry sidecar metrics**: With `spec.monitoring.enabled: true`, every instance's sidecar now reports PostgreSQL uptime and shared-buffer block counters, plus replication lag and WAL receiver state on standbys (`documentdb.postgres.*`). The primary reports per-database collection, view, and index counts and storage size every 5 minutes (`documentdb.database.*`), with the database name in the `db.namespace` attribute. Every instance also reports its data volume usage and pod network I/O through the collector's `hostmetrics` receiver. The collector mounts the data volume read-only on an empty subdirectory, so it sees the volume's capacity and usage but none of its data files. Once the primary is healthy, the operator grants the `otel_monitor` role `USAGE` on the `documentdb_core`, `documentdb_api_internal`, and `documentdb_api_catalog` schemas so the metric queries can run, and it revokes the grants before removing the role when monitoring is disabled. The DocumentDB product profile enables these metrics and grants through `PostgresProfile.DocumentDBMetrics` and `PostgresProfile.MonitoringSchemas`; other products get neither unless they set them. The Prometheus exporter now keeps serving a series for 6 minutes after its last update. Because the collector configuration changes, monitored clusters perform one rolling restart after the operator upgrade. See the [Metrics Reference](docs/operator-public-documentation/v1/monitoring/metrics.md). + ## [1.2.2] - 2026-11-24 Operator security-hardening release. The default DocumentDB engine stays at `1.0.1` (extension schema `1.0-0`). The operator image now uses Azure Linux distroless instead of the Alpine dev container base; the operator, sidecar and Helm chart are released together. The CRDs are unchanged from `1.2.0`; when upgrading from `1.1.x` or earlier, apply the `1.2.2` CRDs before `helm upgrade`. diff --git a/docs/designs/product-neutral-core.md b/docs/designs/product-neutral-core.md index 8617efa0a..720e8d065 100644 --- a/docs/designs/product-neutral-core.md +++ b/docs/designs/product-neutral-core.md @@ -132,6 +132,8 @@ DocumentDB wrappers. | Service name prefix, finalizer, labels | `NamingProfile` | `documentdb-service-`, `documentdb.io/...` | | OTel metric attribute | `NamingProfile` | `documentdb.cluster` | | OTel SQL health metric | `NamingProfile.HealthMetricName` | `documentdb.postgres.up` | +| OTel SQL instance and catalog metrics | `PostgresProfile.DocumentDBMetrics` (off when false) | enabled (`documentdb.postgres.*`, `documentdb.database.*`) | +| Monitoring role schema grants | `PostgresProfile.MonitoringSchemas` (skipped when empty) | `documentdb_core`, `documentdb_api_internal`, `documentdb_api_catalog` | | Admission error wording | `validation.Terms` | `documentDBVersion`, `spec.documentDBImage`, ... | ## Sidecar-injector gateway contract diff --git a/docs/operator-public-documentation/v1/high-availability/local-ha.md b/docs/operator-public-documentation/v1/high-availability/local-ha.md index 46eada24b..0dd126830 100644 --- a/docs/operator-public-documentation/v1/high-availability/local-ha.md +++ b/docs/operator-public-documentation/v1/high-availability/local-ha.md @@ -244,6 +244,8 @@ Track replication health using PostgreSQL system views: kubectl exec -n documentdb my-documentdb-1 -- psql -U postgres -c "SELECT client_addr, state, sent_lsn, write_lsn, flush_lsn, replay_lsn FROM pg_stat_replication;" ``` +With `spec.monitoring.enabled: true`, each standby's OTel Collector sidecar also reports replication lag and WAL receiver state. See [PostgreSQL instance metrics](../monitoring/metrics.md#postgresql-instance). + !!! tip "Alerting and Observability" For production monitoring, see the [CloudNative-PG Monitoring documentation](https://cloudnative-pg.io/documentation/current/monitoring/) which covers Prometheus metrics, Grafana dashboards, and alerting rules for failover detection. diff --git a/docs/operator-public-documentation/v1/monitoring/metrics.md b/docs/operator-public-documentation/v1/monitoring/metrics.md index 228a0b214..4830de3f6 100644 --- a/docs/operator-public-documentation/v1/monitoring/metrics.md +++ b/docs/operator-public-documentation/v1/monitoring/metrics.md @@ -13,15 +13,15 @@ This page documents metrics that are part of the DocumentDB operator monitoring ## Available metrics -### PostgreSQL health +The sidecar in each DocumentDB pod collects three groups of metrics: -The sidecar runs a lightweight SQL health query against the local PostgreSQL container in each DocumentDB pod. +| Group | Source | Interval | Reported by | +|-------|--------|----------|-------------| +| [PostgreSQL instance](#postgresql-instance) | SQL queries against the local PostgreSQL server | 30 seconds | Every instance | +| [DocumentDB catalog](#documentdb-catalog) | SQL queries against the DocumentDB catalog | 5 minutes | Primary only | +| [Pod filesystem and network](#pod-filesystem-and-network) | OpenTelemetry Collector `hostmetrics` receiver | 30 seconds | Every instance | -| OpenTelemetry metric | Type | Description | -|----------------------|------|-------------| -| `documentdb.postgres.up` | Gauge | `1` when the local PostgreSQL container responds to the sidecar health query. | - -Common resource attributes include: +Every metric carries these resource attributes: | Attribute | Description | |-----------|-------------| @@ -29,25 +29,128 @@ Common resource attributes include: | `k8s.namespace.name` | Kubernetes namespace | | `k8s.pod.name` | Kubernetes pod name | -When exported through the Prometheus exporter, this metric is commonly queried as: +The Prometheus exporter turns attributes into labels, replaces dots with underscores, and adds unit and type suffixes to metric names. The tables below list both forms. For example: ```promql documentdb_postgres_up{documentdb_cluster="my-cluster"} ``` -## Planned DocumentDB metric groups +### PostgreSQL instance + +Each instance reports these metrics for its local PostgreSQL server. Use `k8s.pod.name` to tell instances apart. + +| OpenTelemetry metric | Prometheus name | Type | Unit | Description | +|----------------------|-----------------|------|------|-------------| +| `documentdb.postgres.up` | `documentdb_postgres_up` | Gauge | | `1` each time the sidecar's health query to the local PostgreSQL server succeeds. The sidecar never reports `0`. | +| `documentdb.postgres.uptime` | `documentdb_postgres_uptime_seconds` | Gauge | `s` | Time since the local PostgreSQL server started. Resets whenever PostgreSQL restarts, including restarts inside a running pod. | +| `documentdb.postgres.replication.lag` | `documentdb_postgres_replication_lag_seconds` | Gauge | `s` | Standbys only. Time since the last replayed transaction, or `0` when the standby has replayed all the WAL it received. | +| `documentdb.postgres.replication.receiver.up` | `documentdb_postgres_replication_receiver_up` | Gauge | | Standbys only. `1` while the WAL receiver process runs, otherwise `0`. | +| `documentdb.postgres.blocks.hit` | `documentdb_postgres_blocks_hit_total` | Counter | `{block}` | Blocks found in PostgreSQL shared buffers. | +| `documentdb.postgres.blocks.read` | `documentdb_postgres_blocks_read_total` | Counter | `{block}` | Blocks read from outside shared buffers, including reads that the OS page cache serves. | + +- When the local PostgreSQL server does not answer, the sidecar records no PostgreSQL instance metrics. The Prometheus exporter keeps serving their last values, including `1` for `documentdb_postgres_up`, for up to 6 minutes, and then the series disappear. Detect an unresponsive server from an uptime that stops increasing or a missing `documentdb_postgres_up` series, not from `documentdb_postgres_up == 0`. +- A standby that loses its connection to the primary also reports a lag of `0` once it has replayed everything it received. Read the lag together with `documentdb.postgres.replication.receiver.up`. +- The primary does not report the replication metrics. After a standby is promoted, the Prometheus exporter keeps serving its last replication values for up to 6 minutes. +- The block counters cover the PostgreSQL database that stores DocumentDB data. Compute the shared-buffer hit ratio from their rates. + +```promql +# Shared-buffer hit ratio per instance +rate(documentdb_postgres_blocks_hit_total[5m]) + / (rate(documentdb_postgres_blocks_hit_total[5m]) + rate(documentdb_postgres_blocks_read_total[5m])) + +# Standbys whose WAL receiver is not running +documentdb_postgres_replication_receiver_up == 0 + +# Instances whose PostgreSQL has not answered the sidecar for 2 minutes, before their series expire +changes(documentdb_postgres_uptime_seconds[2m]) == 0 + +# Pods whose PostgreSQL series have expired or never appeared +count by (k8s_namespace_name, documentdb_cluster, k8s_pod_name) (system_network_io_bytes_total) + unless on (k8s_namespace_name, documentdb_cluster, k8s_pod_name) documentdb_postgres_up +``` + +### DocumentDB catalog + +The primary reports these metrics; standbys report none. They describe user data only: the `admin`, `config`, and `local` databases and collections whose names start with `system.` are excluded. + +| OpenTelemetry metric | Prometheus name | Type | Unit | Description | +|----------------------|-----------------|------|------|-------------| +| `documentdb.database.count` | `documentdb_database_count` | Gauge | `{database}` | Number of user databases. | +| `documentdb.database.collection.count` | `documentdb_database_collection_count` | Gauge | `{collection}` | Number of collections in the database, not counting views. | +| `documentdb.database.view.count` | `documentdb_database_view_count` | Gauge | `{view}` | Number of views in the database. | +| `documentdb.database.index.count` | `documentdb_database_index_count` | Gauge | `{index}` | Number of indexes in the database whose build has completed, including `_id` indexes. | +| `documentdb.database.storage.size` | `documentdb_database_storage_size_bytes` | Gauge | `By` | On-disk size of the database's collections, excluding indexes. Matches `storageSize` from the `dbStats` command. | + +- Every catalog metric except `documentdb.database.count` has a `db.namespace` attribute (`db_namespace` in Prometheus) that holds the database name. Database names leave the cluster with your metrics, and each database adds four series. +- After a switchover or failover, the new primary reports catalog metrics at its next collection, within 5 minutes. The Prometheus exporter on the former primary keeps serving its last values for up to 6 minutes, so aggregate across pods with `max` rather than `sum`. +- With OTLP push, the backend receives one data point per series every 5 minutes. In backends with a 5 minute lookback window, such as Prometheus, query over a longer range. + +```promql +# Storage size per database +max by (k8s_namespace_name, documentdb_cluster, db_namespace) (documentdb_database_storage_size_bytes) + +# The same query for series ingested over OTLP +max by (k8s_namespace_name, documentdb_cluster, db_namespace) (last_over_time(documentdb_database_storage_size_bytes[10m])) +``` + +### Pod filesystem and network + +The sidecar reads these metrics from inside its own pod with the OpenTelemetry Collector `hostmetrics` receiver. It needs no node-level collector or kubelet access. A node-level collector that runs the same receiver reports the same `system.*` names; the sidecar's series are the ones with the `documentdb.cluster` attribute. + +The `system.*` names and attributes come from OpenTelemetry Collector Contrib 0.149.0, the operator's default collector version. Upstream marks these metrics as Development stability, so other collector versions can rename them or change their attributes. + +#### Data volume + +The operator mounts the PostgreSQL data volume into the sidecar read-only, on an empty subdirectory, at `/var/lib/otel/pgdata`. The sidecar sees the capacity and usage of the whole volume but none of its data files. + +| OpenTelemetry metric | Prometheus name | Type | Unit | Description | +|----------------------|-----------------|------|------|-------------| +| `system.filesystem.usage` | `system_filesystem_usage_bytes` | UpDownCounter | `By` | Data volume space by `state`: `used`, `free`, or `reserved`. `free` is the space available to PostgreSQL, as in the `Avail` column of `df`. | +| `system.filesystem.inodes.usage` | `system_filesystem_inodes_usage` | UpDownCounter | `{inodes}` | Data volume inodes by `state`: `used` or `free`. | +| `system.filesystem.utilization` | `system_filesystem_utilization_ratio` | Gauge | `1` | Fraction of the data volume in use, from `0` to `1`, as in the `Use%` column of `df`. | + +These series also carry `device`, `mode`, `mountpoint`, and `type` attributes. `mountpoint` is always `/var/lib/otel/pgdata`, and `mode` is `ro` because the sidecar's mount is read-only; PostgreSQL's own mount stays writable. + +#### Network + +The sidecar shares the pod's network namespace, so these metrics count all pod traffic on each non-loopback interface (the `device` attribute, such as `eth0`): client traffic to the gateway, replication between instances, and metric export. Loopback traffic between the gateway, PostgreSQL, and the sidecar is excluded. + +| OpenTelemetry metric | Prometheus name | Type | Unit | Description | +|----------------------|-----------------|------|------|-------------| +| `system.network.io` | `system_network_io_bytes_total` | Counter | `By` | Bytes by `direction`: `receive` or `transmit`. | +| `system.network.packets` | `system_network_packets_total` | Counter | `{packets}` | Packets by `direction`. | +| `system.network.errors` | `system_network_errors_total` | Counter | `{errors}` | Errors by `direction`. | +| `system.network.dropped` | `system_network_dropped_total` | Counter | `{packets}` | Dropped packets by `direction`. | + +Each pod reports 6 filesystem series, plus 8 network series per non-loopback interface. + +```promql +# Free space on the data volume +system_filesystem_usage_bytes{documentdb_cluster="my-cluster", state="free"} + +# Pod network throughput in bytes per second +rate(system_network_io_bytes_total{documentdb_cluster="my-cluster"}[5m]) +``` + +### Monitoring role permissions + +The sidecar connects to PostgreSQL as the `otel_monitor` role. Once the primary is healthy, the operator grants this role `USAGE` on the `documentdb_core`, `documentdb_api_internal`, and `documentdb_api_catalog` schemas. DocumentDB checks the first two for any query that calls a function or operator, and the catalog metrics read the third. The role has no access to the `documentdb_data` schema that stores documents. + +Until the grants apply, the sidecar reports only `documentdb.postgres.up` and the filesystem and network metrics. When you disable monitoring, the operator revokes the grants before it removes the role. + +## Other metric groups -The preview monitoring API is intentionally small while instrumentation lands. These areas are planned or out of scope for the current preview docs: +The inventory above covers the sidecar's SQL and hostmetrics receivers. Other telemetry sources have a separate scope: | Area | Status | |------|--------| -| Gateway application metrics | Planned. The sidecar can receive local OTLP from the gateway, but user-facing gateway metrics will be documented after a public gateway image emits them. | -| CNPG/PostgreSQL internals | Out of preview scope. A future revision may expose a curated subset such as replication freshness, PostgreSQL availability, WAL health, and database size. | +| Gateway application metrics | The public gateway includes [Nacelle](https://github.com/microsoft/nacelle) `server.connection.*` instrumentation. The sidecar can receive gateway OTLP, but gateway-emitted metrics are outside the inventory on this page. | +| CNPG/PostgreSQL internals | The sidecar reports the curated PostgreSQL metrics listed above. Other CloudNativePG and PostgreSQL internals, such as WAL health, are out of preview scope. | | Operator controller metrics | Not yet exposed end-to-end through the operator Helm chart. | ## Pod and container resource metrics -Pod CPU, container memory, network I/O, filesystem usage, and node metrics are Kubernetes platform metrics. The DocumentDB operator does not install a node-level collector or grant kubelet permissions to DocumentDB pods. +The sidecar reports the data volume usage and pod network I/O listed under [Pod filesystem and network](#pod-filesystem-and-network). CPU, memory, ephemeral storage, and node metrics are Kubernetes platform metrics. The DocumentDB operator does not install a node-level collector or grant kubelet permissions to DocumentDB pods. Use your existing platform collector, managed cloud agent, kube-prometheus-stack, or OTel Collector DaemonSet for these metrics. Filter that data to DocumentDB workloads using pod or container attributes such as: diff --git a/docs/operator-public-documentation/v1/monitoring/overview.md b/docs/operator-public-documentation/v1/monitoring/overview.md index 41208f4f7..50ef153b6 100644 --- a/docs/operator-public-documentation/v1/monitoring/overview.md +++ b/docs/operator-public-documentation/v1/monitoring/overview.md @@ -12,7 +12,7 @@ tags: DocumentDB monitoring is built around an opt-in OpenTelemetry Collector sidecar that the operator injects into each DocumentDB pod. The sidecar collects DocumentDB-owned, pod-local metrics and can export them to an OTLP backend, expose them for Prometheus scraping, or do both. -Pod, container, and node resource metrics are Kubernetes platform metrics, not DocumentDB-specific metrics. Use your platform collector for those signals. If your cluster does not already collect them, the telemetry playground includes a reference kubeletstats DaemonSet you can deploy as an example. +The sidecar also reports data volume usage and network I/O for its own pod. CPU, memory, and ephemeral storage metrics for pods and containers, and node metrics, are Kubernetes platform metrics, not DocumentDB-specific metrics. Use your platform collector for those signals. If your cluster does not already collect them, the telemetry playground includes a reference kubeletstats DaemonSet you can deploy as an example. ## What the operator owns @@ -22,7 +22,8 @@ The operator-owned monitoring surface is intentionally narrow: |------|----------------| | Sidecar injection | `spec.monitoring.enabled: true` adds one OTel Collector sidecar to each DocumentDB pod. | | Exporter routing | `spec.monitoring.exporter` chooses OTLP push, Prometheus pull, or both. | -| DocumentDB-specific metrics | The sidecar emits pod-local metrics such as PostgreSQL health. Gateway application metrics will be documented when a public gateway image emits them. | +| DocumentDB-specific metrics | The sidecar emits pod-local metrics: PostgreSQL instance health and replication, per-database collection, index, and storage metrics, and data volume and pod network usage. See [Available metrics](metrics.md#available-metrics) and [Other metric groups](metrics.md#other-metric-groups) for the scope of gateway application metrics. | +| Monitoring role grants | The operator grants the sidecar's `otel_monitor` PostgreSQL role `USAGE` on the DocumentDB schemas that the metric queries need, and revokes the grants when you disable monitoring. The role has no access to document data. See [Monitoring role permissions](metrics.md#monitoring-role-permissions). | The operator chart does not install a node-level collector, a Prometheus stack, Grafana, or vendor dashboards. Those are downstream platform choices. @@ -129,7 +130,9 @@ spec: ## Pod and container resource metrics -CPU, memory, network, filesystem, and node metrics are collected from the Kubernetes platform, usually from kubelet, cAdvisor, a managed cloud agent, kube-prometheus-stack, or an OTel Collector DaemonSet. They are useful for operating DocumentDB, but they are not produced by the DocumentDB operator. +The sidecar reports two pod-level resource signals itself: data volume usage and pod network I/O. See [Pod filesystem and network](metrics.md#pod-filesystem-and-network). + +CPU, memory, ephemeral storage, and node metrics are collected from the Kubernetes platform, usually from kubelet, cAdvisor, a managed cloud agent, kube-prometheus-stack, or an OTel Collector DaemonSet. They are useful for operating DocumentDB, but they are not produced by the DocumentDB operator. If your platform already collects these metrics, filter to DocumentDB pods or containers in that backend. For example, Prometheus metrics produced by an OTel kubeletstats collector commonly use filters like: @@ -165,6 +168,7 @@ If metrics are missing, check: - At least one exporter is configured under `spec.monitoring.exporter`. - The pods include an `otel-collector` container. - The sidecar logs do not show exporter connection errors: `kubectl logs -c otel-collector -n "$NS"`. +- If the sidecar reports only `documentdb.postgres.up` and the `system.*` metrics, the monitoring role does not have its schema grants yet. The operator applies them once the primary is healthy. Check the operator logs for `Failed to grant schema usage to the OTel monitoring role`. ## Telemetry playground diff --git a/operator/cnpg-plugins/sidecar-injector/internal/lifecycle/lifecycle.go b/operator/cnpg-plugins/sidecar-injector/internal/lifecycle/lifecycle.go index ac0fe2ba6..b1c30a668 100644 --- a/operator/cnpg-plugins/sidecar-injector/internal/lifecycle/lifecycle.go +++ b/operator/cnpg-plugins/sidecar-injector/internal/lifecycle/lifecycle.go @@ -271,7 +271,11 @@ func (impl Implementation) reconcileMetadata( }) } - otelSidecar := newOtelCollectorSidecar(configuration.OtelCollectorImage, configuration.OtelPasswordSecret) + otelSidecar := newOtelCollectorSidecar( + configuration.OtelCollectorImage, + configuration.OtelPasswordSecret, + podHasVolume(mutatedPod, dataVolumeName), + ) if resources := buildResources( configuration.OTelCPURequest, configuration.OTelCPULimit, @@ -525,6 +529,31 @@ func injectGatewayOTelEnv(pod *corev1.Pod, containerName string) { const otelCollectorContainerName = "otel-collector" const otelMonitorRoleName = "otel_monitor" +// dataVolumeName is the CloudNativePG volume that holds PGDATA. CNPG mounts +// it at /var/lib/postgresql/data and keeps PGDATA in its pgdata subdirectory. +const dataVolumeName = "pgdata" + +// otelDataVolumeMountPath is where the collector mounts the data volume. The +// hostmetrics filesystem scraper in the operator's collector config +// (operator/src/internal/otel/base_config.yaml) reports this mount point; keep +// the two paths equal. +const otelDataVolumeMountPath = "/var/lib/otel/pgdata" + +// otelDataVolumeSubPath is the directory the collector mounts from the data +// volume. Kubelet creates it empty next to PGDATA, so statfs reports the +// volume's capacity and usage while no data files are visible. +const otelDataVolumeSubPath = "otel-statfs" + +// podHasVolume reports whether the pod declares a volume with the given name. +func podHasVolume(pod *corev1.Pod, name string) bool { + for _, v := range pod.Spec.Volumes { + if v.Name == name { + return true + } + } + return false +} + // gatewaySecurityContext returns the SecurityContext for the documentdb-gateway // sidecar: the shared PSA-restricted hardening plus an explicit UID/GID of // 1000, the non-root user the gateway image is built to run as. @@ -541,7 +570,11 @@ func gatewaySecurityContext() *corev1.SecurityContext { // explicit UID so the upstream collector image keeps its own baked-in non-root // user (UID 10001); PSA "restricted" only requires runAsNonRoot, not a fixed // UID. -func newOtelCollectorSidecar(image, passwordSecret string) *corev1.Container { +// +// When mountDataVolume is true, the container also mounts the data volume +// read-only on an empty subPath so the hostmetrics filesystem scraper can +// report the volume's usage. +func newOtelCollectorSidecar(image, passwordSecret string, mountDataVolume bool) *corev1.Container { container := &corev1.Container{ Name: otelCollectorContainerName, Image: image, @@ -583,5 +616,13 @@ func newOtelCollectorSidecar(image, passwordSecret string) *corev1.Container { }, }) } + if mountDataVolume { + container.VolumeMounts = append(container.VolumeMounts, corev1.VolumeMount{ + Name: dataVolumeName, + MountPath: otelDataVolumeMountPath, + SubPath: otelDataVolumeSubPath, + ReadOnly: true, + }) + } return container } diff --git a/operator/cnpg-plugins/sidecar-injector/internal/lifecycle/lifecycle_test.go b/operator/cnpg-plugins/sidecar-injector/internal/lifecycle/lifecycle_test.go index 93ed2ef67..fc5131046 100644 --- a/operator/cnpg-plugins/sidecar-injector/internal/lifecycle/lifecycle_test.go +++ b/operator/cnpg-plugins/sidecar-injector/internal/lifecycle/lifecycle_test.go @@ -260,6 +260,122 @@ func TestLifecycleHookInjectsContainerResourcesAndGoMemLimit(t *testing.T) { assertEnvValue(t, otel.Env, "GOMEMLIMIT", "107374182") } +// TestLifecycleHookMountsDataVolumeOnCollector checks that the collector +// mounts the data volume read-only on an empty subPath, and only when the pod +// has the CNPG pgdata volume. The mount path must stay equal to the hostmetrics +// filesystem mount point in operator/src/internal/otel/base_config.yaml. +func TestLifecycleHookMountsDataVolumeOnCollector(t *testing.T) { + wantMount := corev1.VolumeMount{ + Name: "pgdata", + MountPath: "/var/lib/otel/pgdata", + SubPath: "otel-statfs", + ReadOnly: true, + } + tests := []struct { + name string + volumes []corev1.Volume + wantMount bool + }{ + { + name: "pod with pgdata volume", + volumes: []corev1.Volume{{Name: "pgdata"}, {Name: "scratch-data"}}, + wantMount: true, + }, + { + name: "pod without pgdata volume", + volumes: []corev1.Volume{{Name: "scratch-data"}}, + wantMount: false, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + containers := runCreateHookForPod(t, map[string]string{ + "otelCollectorImage": "otel:latest", + "otelConfigMapName": "otel-config", + }, primaryPod(tt.volumes...)) + + otel, ok := containers[otelCollectorContainerName] + if !ok { + t.Fatalf("otel container missing from patch") + } + var dataMounts []corev1.VolumeMount + for _, mount := range otel.VolumeMounts { + if mount.Name == "pgdata" { + dataMounts = append(dataMounts, mount) + } + } + switch { + case !tt.wantMount && len(dataMounts) != 0: + t.Fatalf("collector mounts pgdata without a pgdata volume: %+v", dataMounts) + case tt.wantMount && (len(dataMounts) != 1 || dataMounts[0] != wantMount): + t.Fatalf("collector pgdata mounts = %+v, want [%+v]", dataMounts, wantMount) + } + }) + } +} + +// primaryPod returns the CNPG pod for the cluster's target primary with the +// given volumes. +func primaryPod(volumes ...corev1.Volume) *corev1.Pod { + return &corev1.Pod{ + TypeMeta: metav1.TypeMeta{ + APIVersion: "v1", + Kind: "Pod", + }, + ObjectMeta: metav1.ObjectMeta{ + Name: "cluster-1", + Namespace: "default", + Labels: map[string]string{"cnpg.io/cluster": "cluster"}, + Annotations: map[string]string{"cnpg.io/operatorVersion": "test"}, + }, + Spec: corev1.PodSpec{ + Containers: []corev1.Container{{Name: "postgres"}}, + Volumes: volumes, + }, + } +} + +// runCreateHookForPod runs the CREATE lifecycle hook for pod on a cluster whose +// plugin has the given parameters and returns the containers the patch adds. +func runCreateHookForPod(t *testing.T, parameters map[string]string, pod *corev1.Pod) map[string]corev1.Container { + t.Helper() + enabled := true + cluster := &apiv1.Cluster{ + TypeMeta: metav1.TypeMeta{ + APIVersion: apiv1.SchemeGroupVersion.String(), + Kind: apiv1.ClusterKind, + }, + ObjectMeta: metav1.ObjectMeta{ + Name: "cluster", + Namespace: "default", + }, + Spec: apiv1.ClusterSpec{ + Plugins: []apiv1.PluginConfiguration{ + { + Name: pluginmetadata.PluginName, + Enabled: &enabled, + Parameters: parameters, + }, + }, + }, + Status: apiv1.ClusterStatus{ + TargetPrimary: pod.Name, + }, + } + + response, err := Implementation{}.LifecycleHook(context.Background(), &cnpglifecycle.OperatorLifecycleRequest{ + OperationType: &cnpglifecycle.OperatorOperationType{ + Type: cnpglifecycle.OperatorOperationType_TYPE_CREATE, + }, + ClusterDefinition: mustMarshal(t, cluster), + ObjectDefinition: mustMarshal(t, pod), + }) + if err != nil { + t.Fatalf("LifecycleHook() error: %v", err) + } + return addedContainersFromPatch(t, response.JsonPatch) +} + func mustMarshal(t *testing.T, value any) []byte { t.Helper() data, err := json.Marshal(value) @@ -405,7 +521,7 @@ func TestGatewaySecurityContext_PSARestrictedAsUID1000(t *testing.T) { // restricted and, unlike the gateway, does not force a UID so the collector // image keeps its own non-root user (UID 10001). func TestNewOtelCollectorSidecar_Hardened(t *testing.T) { - c := newOtelCollectorSidecar("otel/opentelemetry-collector-contrib:test", "") + c := newOtelCollectorSidecar("otel/opentelemetry-collector-contrib:test", "", false) if c.Name != otelCollectorContainerName { t.Fatalf("container name = %q, want %q", c.Name, otelCollectorContainerName) @@ -422,7 +538,7 @@ func TestNewOtelCollectorSidecar_Hardened(t *testing.T) { // TestNewOtelCollectorSidecar_MonitorUser asserts the sidecar connects using // the dedicated monitoring identity without injecting an unused password. func TestNewOtelCollectorSidecar_MonitorUser(t *testing.T) { - c := newOtelCollectorSidecar("otel/opentelemetry-collector-contrib:test", "") + c := newOtelCollectorSidecar("otel/opentelemetry-collector-contrib:test", "", false) for _, env := range c.Env { if env.Name == "PGPASSWORD" { @@ -545,35 +661,11 @@ func TestLifecycleHookMonitoringPasswordSecret(t *testing.T) { } } +// runCreateHook runs the CREATE lifecycle hook for the target primary pod +// without volumes. func runCreateHook(t *testing.T, params map[string]string) map[string]corev1.Container { t.Helper() - enabled := true - cluster := &apiv1.Cluster{ - TypeMeta: metav1.TypeMeta{APIVersion: apiv1.SchemeGroupVersion.String(), Kind: apiv1.ClusterKind}, - ObjectMeta: metav1.ObjectMeta{Name: "cluster", Namespace: "default"}, - Spec: apiv1.ClusterSpec{Plugins: []apiv1.PluginConfiguration{ - {Name: pluginmetadata.PluginName, Enabled: &enabled, Parameters: params}, - }}, - Status: apiv1.ClusterStatus{TargetPrimary: "cluster-1"}, - } - pod := &corev1.Pod{ - TypeMeta: metav1.TypeMeta{APIVersion: "v1", Kind: "Pod"}, - ObjectMeta: metav1.ObjectMeta{ - Name: "cluster-1", Namespace: "default", - Labels: map[string]string{"cnpg.io/cluster": "cluster"}, - Annotations: map[string]string{"cnpg.io/operatorVersion": "test"}, - }, - Spec: corev1.PodSpec{Containers: []corev1.Container{{Name: "postgres"}}}, - } - response, err := Implementation{}.LifecycleHook(context.Background(), &cnpglifecycle.OperatorLifecycleRequest{ - OperationType: &cnpglifecycle.OperatorOperationType{Type: cnpglifecycle.OperatorOperationType_TYPE_CREATE}, - ClusterDefinition: mustMarshal(t, cluster), - ObjectDefinition: mustMarshal(t, pod), - }) - if err != nil { - t.Fatalf("LifecycleHook() error: %v", err) - } - return addedContainersFromPatch(t, response.JsonPatch) + return runCreateHookForPod(t, params, primaryPod()) } func TestLifecycleHookDefaultGatewayContract(t *testing.T) { diff --git a/operator/src/internal/cnpg/cnpg_cluster.go b/operator/src/internal/cnpg/cnpg_cluster.go index a0cfee393..d3c78e8ad 100644 --- a/operator/src/internal/cnpg/cnpg_cluster.go +++ b/operator/src/internal/cnpg/cnpg_cluster.go @@ -367,6 +367,9 @@ func applyIOUringSeccomp(spec *cnpgv1.ClusterSpec, intent product.ClusterIntent) // applyOtelMonitorRole declares the PostgreSQL identity used by the OTel // Collector sidecar. When monitoring is disabled, the role remains declared // with ensure=absent so CNPG removes any role left by an earlier configuration. +// The cluster reconciler grants the role USAGE on the product's +// PostgresProfile.MonitoringSchemas and revokes it before the role becomes +// absent, because the grants block DROP ROLE (see RetainOtelMonitorRole). // // Password authentication is an explicit product choice backed by an existing // Secret. Without one, retain the password-disabled DocumentDB default. @@ -376,8 +379,8 @@ func applyOtelMonitorRole(spec *cnpgv1.ClusterSpec, monitoring *dbv1.MonitoringS } role := absentOtelMonitorRole() if monitoringEnabled(monitoring) { - // The current health query is SELECT 1, so the role needs LOGIN only - // and is not granted broad monitoring memberships. + // The role needs LOGIN plus the schema grants the cluster reconciler + // applies. It gets no broad monitoring memberships such as pg_monitor. role = cnpgv1.RoleConfiguration{ Name: otelcfg.MonitorRoleName, Comment: "Dedicated role for the OTel Collector monitoring sidecar", @@ -407,6 +410,49 @@ func absentOtelMonitorRole() cnpgv1.RoleConfiguration { } } +// OtelMonitorRoleMayExist reports whether the OTel monitoring role may still +// exist in PostgreSQL: the cluster declares it present, or CNPG reports that +// it could not reconcile the role, for example because a grant blocked +// DROP ROLE. +func OtelMonitorRoleMayExist(cluster *cnpgv1.Cluster) bool { + if cluster == nil { + return false + } + for _, role := range managedRoles(cluster) { + if role.Name == otelcfg.MonitorRoleName && role.Ensure != cnpgv1.EnsureAbsent { + return true + } + } + return len(cluster.Status.ManagedRolesStatus.CannotReconcile[otelcfg.MonitorRoleName]) > 0 +} + +// RetainOtelMonitorRole replaces the OTel monitoring role in desired with the +// entry declared on current, so syncing desired leaves the role unchanged. +// The cluster reconciler uses it while it cannot revoke the role's schema +// grants, which would make CNPG's DROP ROLE fail. +func RetainOtelMonitorRole(desired, current *cnpgv1.Cluster) { + var currentRole *cnpgv1.RoleConfiguration + for _, role := range managedRoles(current) { + if role.Name == otelcfg.MonitorRoleName { + currentRole = role.DeepCopy() + break + } + } + if desired == nil || currentRole == nil { + return + } + if desired.Spec.Managed == nil { + desired.Spec.Managed = &cnpgv1.ManagedConfiguration{} + } + for i := range desired.Spec.Managed.Roles { + if desired.Spec.Managed.Roles[i].Name == otelcfg.MonitorRoleName { + desired.Spec.Managed.Roles[i] = *currentRole + return + } + } + desired.Spec.Managed.Roles = append(desired.Spec.Managed.Roles, *currentRole) +} + // buildPostgresConfiguration renders the PostgreSQL configuration for the // cluster from the product profile: the product extension is declared via CNPG's // Extensions stanza (mounted from the extension image as an ImageVolumeSource), @@ -455,11 +501,12 @@ func addGatewayContractParams(params map[string]string, gw product.GatewayProfil } } -// OTelOptions maps the product naming onto the OTel collector config options. +// OTelOptions maps the product naming and metrics onto the OTel collector config options. func OTelOptions(p product.ProductProfile) otelcfg.Options { return otelcfg.Options{ - ClusterAttribute: p.Naming.MetricClusterAttribute, - Generator: p.Naming.OperatorName, - HealthMetricName: p.Naming.HealthMetricName, + ClusterAttribute: p.Naming.MetricClusterAttribute, + Generator: p.Naming.OperatorName, + HealthMetricName: p.Naming.HealthMetricName, + DocumentDBMetrics: p.Postgres.DocumentDBMetrics, } } diff --git a/operator/src/internal/cnpg/testdata/golden/env-overrides.json b/operator/src/internal/cnpg/testdata/golden/env-overrides.json index e80e617e3..99d13cdcc 100644 --- a/operator/src/internal/cnpg/testdata/golden/env-overrides.json +++ b/operator/src/internal/cnpg/testdata/golden/env-overrides.json @@ -138,7 +138,7 @@ "gatewayMemoryLimit": "1536Mi", "gatewayMemoryRequest": "1536Mi", "otelCollectorImage": "env/otel:1", - "otelConfigHash": "fbb647d6c740ff44", + "otelConfigHash": "41623ecfc00ea82d", "otelConfigMapName": "golden-otel-config", "otelCpuLimit": "200m", "otelCpuRequest": "50m", diff --git a/operator/src/internal/cnpg/testdata/golden/explicit-component-resources.json b/operator/src/internal/cnpg/testdata/golden/explicit-component-resources.json index b42f86b40..e18c9165e 100644 --- a/operator/src/internal/cnpg/testdata/golden/explicit-component-resources.json +++ b/operator/src/internal/cnpg/testdata/golden/explicit-component-resources.json @@ -132,7 +132,7 @@ "gatewayMemoryLimit": "1Gi", "gatewayMemoryRequest": "1Gi", "otelCollectorImage": "otel/opentelemetry-collector-contrib:0.149.0", - "otelConfigHash": "fbb647d6c740ff44", + "otelConfigHash": "41623ecfc00ea82d", "otelConfigMapName": "golden-otel-config", "otelCpuLimit": "100m", "otelCpuRequest": "100m", diff --git a/operator/src/internal/cnpg/testdata/golden/full.json b/operator/src/internal/cnpg/testdata/golden/full.json index 362179495..def0d9692 100644 --- a/operator/src/internal/cnpg/testdata/golden/full.json +++ b/operator/src/internal/cnpg/testdata/golden/full.json @@ -154,7 +154,7 @@ "gatewayMemoryRequest": "3Gi", "gatewayTLSSecret": "gw-tls", "otelCollectorImage": "otel/opentelemetry-collector-contrib:0.149.0", - "otelConfigHash": "d60e2ff6f9bb55d4", + "otelConfigHash": "8c1e4abb88b35fc7", "otelConfigMapName": "golden-otel-config", "otelCpuLimit": "200m", "otelCpuRequest": "50m", diff --git a/operator/src/internal/controller/documentdb_controller_test.go b/operator/src/internal/controller/documentdb_controller_test.go index b108128fe..787143efc 100644 --- a/operator/src/internal/controller/documentdb_controller_test.go +++ b/operator/src/internal/controller/documentdb_controller_test.go @@ -6,6 +6,7 @@ package controller import ( "context" "fmt" + "slices" "strings" cnpgv1 "github.com/cloudnative-pg/cloudnative-pg/api/v1" @@ -2907,6 +2908,9 @@ var _ = Describe("DocumentDB Controller", func() { // Mock SQLExecutor: permissions already granted, extension versions match sqlExecutor := func(_ context.Context, _ *cnpgv1.Cluster, cmd string) (string, error) { + if strings.Contains(cmd, "has_schema_privilege") { + return " otel_monitor_grants\n---------------------\n granted\n(1 row)", nil + } if strings.Contains(cmd, "pg_roles") { return "(1 row)", nil } @@ -3122,6 +3126,232 @@ var _ = Describe("DocumentDB Controller", func() { Expect(updatedCluster.Spec.Plugins[0].Parameters["gatewayTLSSecret"]).To(Equal("new-tls-secret")) Expect(updatedCluster.Annotations).To(HaveKey("kubectl.kubernetes.io/restartedAt")) }) + + Context("OTel monitoring role schema grants", func() { + const ( + grantSQL = `GRANT USAGE ON SCHEMA "documentdb_core", "documentdb_api_internal", "documentdb_api_catalog" TO otel_monitor;` + revokeSQL = `REVOKE USAGE ON SCHEMA "documentdb_core", "documentdb_api_internal", "documentdb_api_catalog" FROM otel_monitor;` + clusterPatched = "patch CNPG Cluster" + ) + + var ( + // events records SQL commands and CNPG Cluster patches in order. + events []string + grantState string + grantStateErr error + grantErr error + revokeErr error + ) + + BeforeEach(func() { + Expect(rbacv1.AddToScheme(scheme)).To(Succeed()) + events = nil + grantState = "granted" + grantStateErr = nil + grantErr = nil + revokeErr = nil + }) + + otelRole := func(ensure cnpgv1.EnsureOption) cnpgv1.RoleConfiguration { + return cnpgv1.RoleConfiguration{ + Name: "otel_monitor", + Ensure: ensure, + Login: ensure == cnpgv1.EnsurePresent, + DisablePassword: ensure == cnpgv1.EnsurePresent, + ConnectionLimit: -1, + Inherit: ptr.To(true), + } + } + + newCluster := func(primaryHealthy bool, roles ...cnpgv1.RoleConfiguration) *cnpgv1.Cluster { + cluster := &cnpgv1.Cluster{ + ObjectMeta: metav1.ObjectMeta{Name: documentDBName, Namespace: documentDBNamespace}, + Spec: cnpgv1.ClusterSpec{ + Instances: 1, + PostgresConfiguration: cnpgv1.PostgresConfiguration{ + Extensions: []cnpgv1.ExtensionConfiguration{{ + Name: "documentdb", + ImageVolumeSource: corev1.ImageVolumeSource{Reference: util.DEFAULT_DOCUMENTDB_IMAGE}, + }}, + }, + Plugins: []cnpgv1.PluginConfiguration{{ + Name: util.DEFAULT_SIDECAR_INJECTOR_PLUGIN, + Enabled: ptr.To(true), + Parameters: map[string]string{ + "gatewayImage": util.DEFAULT_GATEWAY_IMAGE, + "documentDbCredentialSecret": util.DEFAULT_DOCUMENTDB_CREDENTIALS_SECRET, + "otelCollectorImage": util.DEFAULT_OTEL_COLLECTOR_IMAGE, + "otelConfigMapName": documentDBName + "-otel-config", + }, + }}, + Managed: &cnpgv1.ManagedConfiguration{Roles: roles}, + }, + Status: cnpgv1.ClusterStatus{ + CurrentPrimary: documentDBName + "-1", + TargetPrimary: documentDBName + "-1", + }, + } + if primaryHealthy { + cluster.Status.InstancesStatus = map[cnpgv1.PodStatus][]string{ + cnpgv1.PodHealthy: {documentDBName + "-1"}, + } + } + return cluster + } + + reconcile := func(monitoringEnabled bool, cluster *cnpgv1.Cluster) (ctrl.Result, *cnpgv1.Cluster) { + documentdb := &dbv1.DocumentDB{ + ObjectMeta: metav1.ObjectMeta{ + Name: documentDBName, + Namespace: documentDBNamespace, + Finalizers: []string{documentDBFinalizer}, + }, + Spec: dbv1.DocumentDBSpec{ + InstancesPerNode: 1, + Resource: dbv1.Resource{ + Storage: dbv1.StorageConfiguration{PvcSize: "1Gi"}, + }, + Monitoring: &dbv1.MonitoringSpec{Enabled: monitoringEnabled}, + }, + } + fakeClient := fake.NewClientBuilder(). + WithScheme(scheme). + WithObjects(documentdb, cluster). + WithStatusSubresource(&dbv1.DocumentDB{}). + WithInterceptorFuncs(interceptor.Funcs{ + Patch: func(ctx context.Context, c client.WithWatch, obj client.Object, patch client.Patch, opts ...client.PatchOption) error { + if _, ok := obj.(*cnpgv1.Cluster); ok { + events = append(events, clusterPatched) + } + return c.Patch(ctx, obj, patch, opts...) + }, + }). + Build() + reconciler := &DocumentDBReconciler{ + Client: fakeClient, + Scheme: scheme, + Recorder: recorder, + SQLExecutor: func(_ context.Context, _ *cnpgv1.Cluster, cmd string) (string, error) { + events = append(events, cmd) + switch { + case strings.Contains(cmd, "has_schema_privilege"): + return " otel_monitor_grants\n---------------------\n " + grantState + "\n(1 row)", grantStateErr + case cmd == grantSQL: + return "", grantErr + case strings.Contains(cmd, "REVOKE"): + return "DO", revokeErr + case strings.Contains(cmd, "pg_roles"): + return "(1 row)", nil + case strings.Contains(cmd, "pg_available_extensions"): + return " default_version | installed_version\n" + + "-----------------+-------------------\n" + + " 0.110-0 | 0.110-0\n(1 row)", nil + } + return "", nil + }, + } + + result, err := reconciler.Reconcile(ctx, ctrl.Request{ + NamespacedName: types.NamespacedName{Name: documentDBName, Namespace: documentDBNamespace}, + }) + Expect(err).NotTo(HaveOccurred()) + + updated := &cnpgv1.Cluster{} + Expect(fakeClient.Get(ctx, types.NamespacedName{Name: documentDBName, Namespace: documentDBNamespace}, updated)).To(Succeed()) + return result, updated + } + + otelRoleEnsure := func(cluster *cnpgv1.Cluster) cnpgv1.EnsureOption { + Expect(cluster.Spec.Managed).NotTo(BeNil()) + for _, role := range cluster.Spec.Managed.Roles { + if role.Name == "otel_monitor" { + return role.Ensure + } + } + Fail("the CNPG Cluster does not declare the otel_monitor role") + return "" + } + + revokeIndex := func() int { + return slices.IndexFunc(events, func(event string) bool { return strings.Contains(event, revokeSQL) }) + } + + DescribeTable("on a healthy primary with monitoring enabled", + func(state string, stateErr, execErr error, wantGrants int, wantRequeue bool) { + grantState = state + grantStateErr = stateErr + grantErr = execErr + result, _ := reconcile(true, newCluster(true, otelRole(cnpgv1.EnsurePresent))) + + grants := 0 + for _, event := range events { + if event == grantSQL { + grants++ + } + } + Expect(grants).To(Equal(wantGrants)) + Expect(events).To(ContainElement(ContainSubstring("pg_available_extensions"))) + if wantRequeue { + Expect(result.RequeueAfter).To(Equal(RequeueAfterShort)) + } else { + Expect(result.RequeueAfter).To(BeZero()) + } + }, + Entry("grants schema usage once when the role lacks it", "pending", nil, nil, 1, false), + Entry("skips the grant when the role already holds it", "granted", nil, nil, 0, false), + Entry("requeues until CNPG creates the role", "missing", nil, nil, 0, true), + Entry("requeues when the grant state is empty", "", nil, nil, 0, true), + Entry("requeues when the grant state is unexpected", "unexpected", nil, nil, 0, true), + Entry("requeues without granting when the grant-state query fails", "pending", fmt.Errorf("simulated grant-state query failure"), nil, 0, true), + Entry("requeues when granting schema usage fails", "pending", nil, fmt.Errorf("simulated grant failure"), 1, true), + ) + + It("does not query or grant schema usage until the primary is healthy", func() { + grantState = "pending" + result, _ := reconcile(true, newCluster(false, otelRole(cnpgv1.EnsurePresent))) + + Expect(events).NotTo(ContainElement(ContainSubstring("otel_monitor"))) + Expect(result.RequeueAfter).To(BeZero()) + }) + + It("revokes the grants before declaring the role absent when monitoring is disabled", func() { + result, updated := reconcile(false, newCluster(true, otelRole(cnpgv1.EnsurePresent))) + + Expect(revokeIndex()).To(BeNumerically(">=", 0)) + Expect(revokeIndex()).To(BeNumerically("<", slices.Index(events, clusterPatched))) + Expect(otelRoleEnsure(updated)).To(Equal(cnpgv1.EnsureAbsent)) + Expect(result.RequeueAfter).To(BeZero()) + }) + + It("revokes the grants while CNPG cannot drop the role, for example after a restore", func() { + cluster := newCluster(true, otelRole(cnpgv1.EnsureAbsent)) + cluster.Status.ManagedRolesStatus.CannotReconcile = map[string][]string{ + "otel_monitor": {"role cannot be dropped because some objects depend on it"}, + } + reconcile(false, cluster) + + Expect(revokeIndex()).To(BeNumerically(">=", 0)) + }) + + It("does not revoke anything once CNPG has dropped the role", func() { + reconcile(false, newCluster(true, otelRole(cnpgv1.EnsureAbsent))) + + Expect(revokeIndex()).To(Equal(-1)) + }) + + DescribeTable("keeps the role declared and removes the sidecar until its grants are revoked", + func(primaryHealthy bool, err error) { + revokeErr = err + result, updated := reconcile(false, newCluster(primaryHealthy, otelRole(cnpgv1.EnsurePresent))) + + Expect(otelRoleEnsure(updated)).To(Equal(cnpgv1.EnsurePresent)) + Expect(updated.Spec.Plugins[0].Parameters).NotTo(HaveKey("otelCollectorImage")) + Expect(result.RequeueAfter).To(Equal(RequeueAfterShort)) + }, + Entry("when the revoke fails", true, fmt.Errorf("simulated revoke failure")), + Entry("when the primary is not healthy", false, nil), + ) + }) }) Describe("reconcileOtelConfigMap", func() { @@ -3166,6 +3396,9 @@ var _ = Describe("DocumentDB Controller", func() { Expect(cm.Data).To(HaveKey("dynamic.yaml")) Expect(cm.Data["dynamic.yaml"]).To(ContainSubstring("otel-collector:4317")) Expect(cm.Data["dynamic.yaml"]).To(ContainSubstring(documentDBName)) + // The DocumentDB profile enables the DocumentDB SQL metrics. + Expect(cm.Data["static.yaml"]).To(ContainSubstring("sqlquery/catalog:")) + Expect(cm.Data["dynamic.yaml"]).To(ContainSubstring("sqlquery/catalog")) }) It("updates an existing OTel ConfigMap when monitoring spec changes", func() { diff --git a/operator/src/internal/engine/cluster_reconciler.go b/operator/src/internal/engine/cluster_reconciler.go index b53bdc654..e96ef8c6c 100644 --- a/operator/src/internal/engine/cluster_reconciler.go +++ b/operator/src/internal/engine/cluster_reconciler.go @@ -12,7 +12,6 @@ package engine import ( "context" "fmt" - "slices" "strings" "sync" "time" @@ -327,6 +326,22 @@ func (r *ClusterReconciler[T]) Reconcile(ctx context.Context, req ctrl.Request) } } + // otelMonitorPending requeues the reconcile while the OTel monitoring + // role's schema grants are not settled, without blocking the steps below. + otelMonitorPending := false + monitoringSchemas := intent.Product.Postgres.MonitoringSchemas + + // Schema grants block CNPG's DROP ROLE, so revoke them before the role is + // declared absent. Until they are revoked, keep the role as declared. + // Replica clusters skip this: CNPG manages roles only on the primary + // cluster, which revokes the grants and replicates the change. + if !monitoringEnabled && len(monitoringSchemas) > 0 && replicationContext.IsPrimary() && cnpg.OtelMonitorRoleMayExist(currentCnpgCluster) { + if !r.revokeOtelMonitorGrants(ctx, currentCnpgCluster, monitoringSchemas) { + cnpg.RetainOtelMonitorRole(desiredCnpgCluster, currentCnpgCluster) + otelMonitorPending = true + } + } + // Sync all CNPG Cluster changes in one atomic patch (images + plugins + replication) if err := cnpg.SyncCnpgCluster(ctx, r.Client, currentCnpgCluster, desiredCnpgCluster, replicationOps); err != nil { logger.Error(err, "Failed to sync CNPG Cluster spec") @@ -343,7 +358,7 @@ func (r *ClusterReconciler[T]) Reconcile(ctx context.Context, req ctrl.Request) } } - if slices.Contains(currentCnpgCluster.Status.InstancesStatus[cnpgv1.PodHealthy], currentCnpgCluster.Status.CurrentPrimary) && replicationContext.IsPrimary() { + if isPrimaryHealthy(currentCnpgCluster) && replicationContext.IsPrimary() { if role := intent.Product.Postgres.ReplicationAdminRole; role != "" { // Check if permissions have already been granted output, err := r.SQLExecutor(ctx, currentCnpgCluster, cnpg.ReplicationRoleCheckSQL(role)) @@ -359,6 +374,15 @@ func (r *ClusterReconciler[T]) Reconcile(ctx context.Context, req ctrl.Request) } } } + + // The grants replicate to standbys and replica clusters. + if monitoringEnabled && len(monitoringSchemas) > 0 { + roleMissing, err := r.grantOtelMonitorSchemas(ctx, currentCnpgCluster, monitoringSchemas) + if err != nil { + logger.Error(err, "Failed to grant schema usage to the OTel monitoring role") + } + otelMonitorPending = otelMonitorPending || roleMissing || err != nil + } } if r.Replication != nil { @@ -408,6 +432,10 @@ func (r *ClusterReconciler[T]) Reconcile(ctx context.Context, req ctrl.Request) return ctrl.Result{RequeueAfter: RequeueAfterShort}, nil } + if otelMonitorPending { + return ctrl.Result{RequeueAfter: RequeueAfterShort}, nil + } + // Don't requeue again unless there is a change return ctrl.Result{}, nil } diff --git a/operator/src/internal/engine/otel_monitor.go b/operator/src/internal/engine/otel_monitor.go new file mode 100644 index 000000000..bdb032293 --- /dev/null +++ b/operator/src/internal/engine/otel_monitor.go @@ -0,0 +1,122 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +package engine + +import ( + "context" + "fmt" + "slices" + "strings" + + cnpgv1 "github.com/cloudnative-pg/cloudnative-pg/api/v1" + "github.com/lib/pq" + "sigs.k8s.io/controller-runtime/pkg/log" + + otelcfg "github.com/documentdb/documentdb-operator/internal/otel" +) + +// isPrimaryHealthy reports whether CNPG lists the cluster's current primary +// among its healthy instances. +func isPrimaryHealthy(cluster *cnpgv1.Cluster) bool { + return slices.Contains(cluster.Status.InstancesStatus[cnpgv1.PodHealthy], cluster.Status.CurrentPrimary) +} + +// grantOtelMonitorSchemas grants the OTel monitoring role USAGE on schemas +// when it does not hold it yet. It returns true when the role does not exist +// yet: CNPG creates managed roles asynchronously, so the caller retries later. +func (r *ClusterReconciler[T]) grantOtelMonitorSchemas(ctx context.Context, cluster *cnpgv1.Cluster, schemas []string) (bool, error) { + output, err := r.SQLExecutor(ctx, cluster, otelMonitorGrantStateSQL(schemas)) + if err != nil { + return false, fmt.Errorf("failed to check the OTel monitoring role's schema grants: %w", err) + } + switch state := parseOtelMonitorGrantState(output); state { + case otelMonitorGranted: + return false, nil + case otelMonitorRoleMissing: + return true, nil + case otelMonitorNotGranted: + if _, err := r.SQLExecutor(ctx, cluster, otelMonitorGrantSQL(schemas)); err != nil { + return false, err + } + log.FromContext(ctx).Info("Granted schema usage to the OTel monitoring role", + "role", otelcfg.MonitorRoleName, "schemas", schemas) + return false, nil + default: + return false, fmt.Errorf("unexpected OTel monitoring role grant state: %q", output) + } +} + +// revokeOtelMonitorGrants revokes the OTel monitoring role's USAGE on schemas +// on the healthy primary so that CNPG can drop the role. It returns false when +// the grants could not be revoked. +func (r *ClusterReconciler[T]) revokeOtelMonitorGrants(ctx context.Context, cluster *cnpgv1.Cluster, schemas []string) bool { + logger := log.FromContext(ctx) + if !isPrimaryHealthy(cluster) { + logger.Info("Keeping the OTel monitoring role until a healthy primary can revoke its schema grants") + return false + } + if _, err := r.SQLExecutor(ctx, cluster, otelMonitorRevokeSQL(schemas)); err != nil { + logger.Error(err, "Failed to revoke schema usage from the OTel monitoring role") + return false + } + return true +} + +// States reported by otelMonitorGrantStateSQL. +const ( + otelMonitorGranted = "granted" + otelMonitorNotGranted = "pending" + otelMonitorRoleMissing = "missing" +) + +// otelMonitorGrantStateSQL reports whether the OTel monitoring role is +// missing, lacks USAGE on any of schemas, or holds all of it. +func otelMonitorGrantStateSQL(schemas []string) string { + checks := make([]string, 0, len(schemas)) + for _, schema := range schemas { + checks = append(checks, fmt.Sprintf("has_schema_privilege(r.oid, %s, 'USAGE')", pq.QuoteLiteral(schema))) + } + return fmt.Sprintf( + "SELECT CASE WHEN r.oid IS NULL THEN '%s' WHEN %s THEN '%s' ELSE '%s' END AS otel_monitor_grants "+ + "FROM (SELECT 1) AS one LEFT JOIN pg_roles r ON r.rolname = %s;", + otelMonitorRoleMissing, strings.Join(checks, " AND "), otelMonitorGranted, otelMonitorNotGranted, + pq.QuoteLiteral(otelcfg.MonitorRoleName), + ) +} + +// parseOtelMonitorGrantState extracts the state from the psql output of +// otelMonitorGrantStateSQL, or returns "" when no state is found. +func parseOtelMonitorGrantState(output string) string { + for _, line := range strings.Split(output, "\n") { + switch state := strings.TrimSpace(line); state { + case otelMonitorGranted, otelMonitorNotGranted, otelMonitorRoleMissing: + return state + } + } + return "" +} + +func otelMonitorGrantSQL(schemas []string) string { + return fmt.Sprintf("GRANT USAGE ON SCHEMA %s TO %s;", quoteIdentifiers(schemas), otelcfg.MonitorRoleName) +} + +// otelMonitorRevokeSQL revokes the schema grants and does nothing when the +// role does not exist. +func otelMonitorRevokeSQL(schemas []string) string { + return fmt.Sprintf( + "DO $$ BEGIN IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = %s) THEN "+ + "REVOKE USAGE ON SCHEMA %s FROM %s; END IF; END $$;", + pq.QuoteLiteral(otelcfg.MonitorRoleName), quoteIdentifiers(schemas), otelcfg.MonitorRoleName, + ) +} + +// quoteIdentifiers quotes each name as an SQL identifier and joins them with +// commas. +func quoteIdentifiers(names []string) string { + quoted := make([]string, len(names)) + for i, name := range names { + quoted[i] = pq.QuoteIdentifier(name) + } + return strings.Join(quoted, ", ") +} diff --git a/operator/src/internal/engine/otel_monitor_test.go b/operator/src/internal/engine/otel_monitor_test.go new file mode 100644 index 000000000..02689072f --- /dev/null +++ b/operator/src/internal/engine/otel_monitor_test.go @@ -0,0 +1,79 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +package engine + +import ( + "context" + "fmt" + "testing" + + cnpgv1 "github.com/cloudnative-pg/cloudnative-pg/api/v1" + ctrl "sigs.k8s.io/controller-runtime" + + dbv1 "github.com/documentdb/documentdb-operator/api/v1" + otelcfg "github.com/documentdb/documentdb-operator/internal/otel" + "github.com/documentdb/documentdb-operator/internal/product" +) + +// noMonitoringSchemasAdapter is DocumentDB with a profile that declares no +// monitoring schemas. +type noMonitoringSchemasAdapter struct{ product.DocumentDBAdapter } + +func (a noMonitoringSchemasAdapter) Profile() product.ProductProfile { + p := product.DocumentDBProfile() + p.Postgres.MonitoringSchemas = nil + return p +} + +func (a noMonitoringSchemasAdapter) Intent(db *dbv1.DocumentDB) product.ClusterIntent { + intent := a.DocumentDBAdapter.Intent(db) + intent.Product = a.Profile() + return intent +} + +// TestClusterReconcileSkipsMonitoringGrantsWithoutSchemas checks that a product +// without MonitoringSchemas runs no monitoring-role SQL, and that disabling +// monitoring declares the role absent instead of retaining it. +func TestClusterReconcileSkipsMonitoringGrantsWithoutSchemas(t *testing.T) { + for _, monitoring := range []bool{true, false} { + t.Run(fmt.Sprintf("monitoring=%t", monitoring), func(t *testing.T) { + s := newTestScheme(t) + db := reconcilableCluster() + db.Spec.ExposeViaService.ServiceType = "" + seed := db.DeepCopy() + seed.Spec.Monitoring = &dbv1.MonitoringSpec{Enabled: true} + cluster := healthyCNPGCluster(t, s, seed) + db.Spec.Monitoring = &dbv1.MonitoringSpec{Enabled: monitoring} + c := newFakeClient(t, s, nil, db, cluster) + sql := &sqlRecorder{roleOut: "(1 row)"} + r, _ := newClusterReconciler(c, s, sql) + r.Adapter = noMonitoringSchemasAdapter{} + + if res, err := r.Reconcile(context.Background(), clusterKey); err != nil || res != (ctrl.Result{}) { + t.Fatalf("expected converged reconcile, got %v, %v", res, err) + } + if sql.ran(otelcfg.MonitorRoleName) { + t.Fatalf("monitoring-role SQL ran without monitoring schemas: %q", sql.commands) + } + + updated := &cnpgv1.Cluster{} + if err := c.Get(context.Background(), clusterKey.NamespacedName, updated); err != nil { + t.Fatal(err) + } + want := cnpgv1.EnsurePresent + if !monitoring { + want = cnpgv1.EnsureAbsent + } + for _, role := range updated.Spec.Managed.Roles { + if role.Name == otelcfg.MonitorRoleName { + if role.Ensure != want { + t.Fatalf("monitoring role ensure = %q, want %q", role.Ensure, want) + } + return + } + } + t.Fatal("the CNPG Cluster does not declare the OTel monitoring role") + }) + } +} diff --git a/operator/src/internal/engine/predicates.go b/operator/src/internal/engine/predicates.go index fdf8ab1d2..3377cb292 100644 --- a/operator/src/internal/engine/predicates.go +++ b/operator/src/internal/engine/predicates.go @@ -10,11 +10,14 @@ import ( cnpgv1 "github.com/cloudnative-pg/cloudnative-pg/api/v1" "sigs.k8s.io/controller-runtime/pkg/event" "sigs.k8s.io/controller-runtime/pkg/predicate" + + cnpg "github.com/documentdb/documentdb-operator/internal/cnpg" ) // ClusterInstanceStatusChangedPredicate triggers on CNPG cluster healthy-instance -// or phase changes. If you ever have another state from the cluster that you -// want to trigger on, add it here. +// or phase changes, and when the OTel monitoring role may start or stop +// existing. If you ever have another state from the cluster that you want to +// trigger on, add it here. func ClusterInstanceStatusChangedPredicate() predicate.Predicate { return predicate.Funcs{ UpdateFunc: func(e event.UpdateEvent) bool { @@ -26,9 +29,14 @@ func ClusterInstanceStatusChangedPredicate() predicate.Predicate { if !ok { return true } - // Trigger on healthy instances change OR phase change + // Trigger on healthy instances change OR phase change, and when the + // OTel monitoring role may start or stop existing: CNPG reports a role + // it cannot drop only in its status, for example after restoring a + // backup taken with monitoring enabled, and the reconciler must then + // revoke the role's schema grants. return !slices.Equal(oldCluster.Status.InstancesStatus[cnpgv1.PodHealthy], newCluster.Status.InstancesStatus[cnpgv1.PodHealthy]) || - oldCluster.Status.Phase != newCluster.Status.Phase + oldCluster.Status.Phase != newCluster.Status.Phase || + cnpg.OtelMonitorRoleMayExist(oldCluster) != cnpg.OtelMonitorRoleMayExist(newCluster) }, } } diff --git a/operator/src/internal/engine/predicates_sql_test.go b/operator/src/internal/engine/predicates_sql_test.go index c194b62cf..1eda21876 100644 --- a/operator/src/internal/engine/predicates_sql_test.go +++ b/operator/src/internal/engine/predicates_sql_test.go @@ -27,6 +27,22 @@ func TestClusterInstanceStatusChangedPredicate(t *testing.T) { InstancesStatus: map[cnpgv1.PodStatus][]string{cnpgv1.PodHealthy: healthy}, }} } + // absentOtelRole declares the OTel monitoring role absent, as a cluster + // restored with monitoring disabled does, and reports when CNPG cannot drop + // the cannotDrop role. + absentOtelRole := func(cannotDrop string) *cnpgv1.Cluster { + c := cluster("ok", "a") + c.Spec.Managed = &cnpgv1.ManagedConfiguration{Roles: []cnpgv1.RoleConfiguration{{ + Name: "otel_monitor", + Ensure: cnpgv1.EnsureAbsent, + }}} + if cannotDrop != "" { + c.Status.ManagedRolesStatus.CannotReconcile = map[string][]string{ + cannotDrop: {"role cannot be dropped because some objects depend on it"}, + } + } + return c + } tests := []struct { name string old, new client.Object @@ -35,6 +51,8 @@ func TestClusterInstanceStatusChangedPredicate(t *testing.T) { {name: "unchanged", old: cluster("ok", "a"), new: cluster("ok", "a"), want: false}, {name: "healthy instances changed", old: cluster("ok", "a"), new: cluster("ok", "a", "b"), want: true}, {name: "phase changed", old: cluster("ok", "a"), new: cluster("failover", "a"), want: true}, + {name: "CNPG cannot drop the OTel monitoring role", old: absentOtelRole(""), new: absentOtelRole("otel_monitor"), want: true}, + {name: "CNPG cannot drop another role", old: absentOtelRole(""), new: absentOtelRole("app_user"), want: false}, {name: "old is not a CNPG cluster", old: &corev1.Pod{}, new: cluster("ok"), want: true}, {name: "new is not a CNPG cluster", old: cluster("ok"), new: &corev1.Pod{}, want: true}, } diff --git a/operator/src/internal/otel/base_config.yaml b/operator/src/internal/otel/base_config.yaml index 546791256..339776a26 100644 --- a/operator/src/internal/otel/base_config.yaml +++ b/operator/src/internal/otel/base_config.yaml @@ -5,6 +5,9 @@ receivers: # SQL-driven Postgres health metrics. Add new SQL metric queries here — # no Go code changes needed. + # Every instance runs these queries; the k8s.pod.name resource attribute + # tells instances apart. Queries other than the health check rely on the + # DocumentDB schema USAGE that the operator grants to the monitoring role. sqlquery: driver: postgres datasource: "host=localhost port=5432 user=${env:PGUSER} dbname=postgres sslmode=disable" @@ -15,6 +18,157 @@ receivers: - metric_name: {{ .HealthMetricName }} value_column: up data_type: gauge +{{- /* The DocumentDB SQL metrics from here through the sqlquery/catalog + receiver are rendered only with Options.DocumentDBMetrics. */}} +{{- if .DocumentDBMetrics }} + # Resets when the postmaster restarts, including in-place restarts. + - sql: "SELECT EXTRACT(EPOCH FROM now() - pg_postmaster_start_time())::float8 AS uptime_seconds" + metrics: + - metric_name: documentdb.postgres.uptime + value_column: uptime_seconds + value_type: double + data_type: gauge + unit: s + description: Time since the local PostgreSQL server started. + # Standbys only; the primary returns no rows. Lag reads 0 once every + # received WAL record has been replayed, so an idle primary does not + # look like growing lag. A disconnected standby also reads 0, which is + # why the query pairs lag with the WAL receiver state. + - sql: | + SELECT CASE WHEN pg_last_wal_receive_lsn() = pg_last_wal_replay_lsn() THEN 0 + ELSE GREATEST(COALESCE(EXTRACT(EPOCH FROM now() - pg_last_xact_replay_timestamp()), 0), 0) + END::float8 AS lag_seconds, + (SELECT count(*) FROM pg_stat_wal_receiver) AS wal_receiver_up + WHERE pg_is_in_recovery() + metrics: + - metric_name: documentdb.postgres.replication.lag + value_column: lag_seconds + value_type: double + data_type: gauge + unit: s + description: Time since the last replayed transaction on a standby, or 0 when replay has caught up with received WAL. + - metric_name: documentdb.postgres.replication.receiver.up + value_column: wal_receiver_up + data_type: gauge + description: 1 when the standby's WAL receiver process is running, otherwise 0. + # Shared-buffer cache counters for the DocumentDB database. Compute the + # hit ratio in the backend as rate(hit) / (rate(hit) + rate(read)). + - sql: "SELECT blks_hit, blks_read FROM pg_stat_database WHERE datname = current_database()" + metrics: + - metric_name: documentdb.postgres.blocks.hit + value_column: blks_hit + data_type: sum + monotonic: true + aggregation: cumulative + unit: "{block}" + description: Disk blocks found in PostgreSQL shared buffers. + - metric_name: documentdb.postgres.blocks.read + value_column: blks_read + data_type: sum + monotonic: true + aggregation: cumulative + unit: "{block}" + description: Disk blocks read outside PostgreSQL shared buffers, including reads served by the OS page cache. + + # DocumentDB catalog metrics. Runs less often than the health queries + # because it reads the collection catalog and relation sizes. Standbys + # return no rows, so only the primary reports. Internal databases (admin, + # config, local) and system.* collections are excluded. + sqlquery/catalog: + driver: postgres + datasource: "host=localhost port=5432 user=${env:PGUSER} dbname=postgres sslmode=disable" + collection_interval: "5m" + queries: + # One row per database. Sizes are looked up by pg_class OID so the + # monitoring role needs no access to the documentdb_data schema. + - sql: | + SELECT c.database_name AS "db.namespace", + count(*) FILTER (WHERE c.view_definition IS NULL) AS collections, + count(*) FILTER (WHERE c.view_definition IS NOT NULL) AS views, + COALESCE(sum(ix.n), 0)::bigint AS indexes, + COALESCE(sum(pg_table_size(r.oid)), 0)::bigint AS storage_bytes + FROM documentdb_api_catalog.collections c + LEFT JOIN LATERAL ( + SELECT count(*) AS n + FROM documentdb_api_catalog.collection_indexes i + WHERE i.collection_id = c.collection_id AND i.index_is_valid) ix ON true + LEFT JOIN pg_class r + ON r.relname = 'documents_' || c.collection_id + AND r.relnamespace = (SELECT oid FROM pg_namespace WHERE nspname = 'documentdb_data') + WHERE NOT pg_is_in_recovery() + AND c.database_name NOT IN ('admin', 'config', 'local') + AND c.collection_name NOT LIKE 'system.%' + GROUP BY c.database_name + metrics: + - metric_name: documentdb.database.storage.size + value_column: storage_bytes + attribute_columns: ["db.namespace"] + data_type: gauge + unit: By + description: On-disk size of the database's collections, excluding indexes. Matches dbStats storageSize. + - metric_name: documentdb.database.collection.count + value_column: collections + attribute_columns: ["db.namespace"] + data_type: gauge + unit: "{collection}" + description: Number of collections in the database, excluding views and system collections. + - metric_name: documentdb.database.view.count + value_column: views + attribute_columns: ["db.namespace"] + data_type: gauge + unit: "{view}" + description: Number of views in the database. + - metric_name: documentdb.database.index.count + value_column: indexes + attribute_columns: ["db.namespace"] + data_type: gauge + unit: "{index}" + description: Number of ready indexes in the database, including _id indexes. + # HAVING keeps standbys silent: an aggregate without GROUP BY would + # otherwise return a row even when no collection qualifies. + - sql: | + SELECT count(DISTINCT database_name) AS databases + FROM documentdb_api_catalog.collections + WHERE database_name NOT IN ('admin', 'config', 'local') + AND collection_name NOT LIKE 'system.%' + HAVING NOT pg_is_in_recovery() + metrics: + - metric_name: documentdb.database.count + value_column: databases + data_type: gauge + unit: "{database}" + description: Number of user databases. +{{- end }} + + # Pod-local filesystem and network metrics. The sidecar mounts the data + # volume read-only on an empty subPath at /var/lib/otel/pgdata, so statfs + # reports the volume's capacity without exposing data files. The network + # scraper reads the pod's network namespace; loopback carries + # gateway-to-PostgreSQL and OTLP traffic and is excluded. + hostmetrics: + collection_interval: "30s" + scrapers: + filesystem: + # A subPath volume mount is a bind mount, which the scraper skips + # unless virtual filesystems are included. include_mount_points + # still limits the output to the data volume. + include_virtual_filesystems: true + include_mount_points: + # Keep equal to otelDataVolumeMountPath in the sidecar-injector plugin. + mount_points: ["/var/lib/otel/pgdata"] + match_type: strict + metrics: + system.filesystem.utilization: + enabled: true + network: + exclude: + interfaces: ["lo"] + match_type: strict + metrics: + # Would count the gateway's client connections; not part of the + # monitoring contract. + system.network.connections: + enabled: false # OTLP receiver for telemetry pushed by co-located pod containers # (e.g. the documentdb-gateway pushes metrics to localhost:4317). diff --git a/operator/src/internal/otel/config.go b/operator/src/internal/otel/config.go index 15954d706..45c97fec8 100644 --- a/operator/src/internal/otel/config.go +++ b/operator/src/internal/otel/config.go @@ -24,10 +24,13 @@ var baseConfigYAML []byte // over staticConfigData, so product-specific metric names stay structured. var baseConfigTemplate = template.Must(template.New("base_config.yaml").Option("missingkey=error").Parse(string(baseConfigYAML))) -// staticConfigData holds the product-specific names base_config.yaml uses. +// staticConfigData holds the product-specific names and metrics +// base_config.yaml uses. type staticConfigData struct { // HealthMetricName is the PostgreSQL liveness gauge. HealthMetricName string + // DocumentDBMetrics adds the DocumentDB SQL metrics; see Options. + DocumentDBMetrics bool } // renderStaticConfig renders static.yaml from base_config.yaml. @@ -46,8 +49,15 @@ func renderStaticConfig(data staticConfigData) (string, error) { const defaultPrometheusPort = 8888 +// prometheusMetricExpiration is how long the Prometheus exporter keeps serving +// a series after its last update. It must exceed the longest receiver +// collection_interval in base_config.yaml (sqlquery/catalog, 5m). With the +// exporter's 5m default, a catalog update that arrives a moment late would +// let the series expire, and scrapes in that window would miss it. +const prometheusMetricExpiration = "6m" + // MonitorRoleName is the dedicated PostgreSQL identity the OTel Collector -// sidecar uses for its health-check query. +// sidecar uses for its SQL metric queries. const MonitorRoleName = "otel_monitor" // collectorConfig represents the OTel Collector configuration structure. @@ -83,7 +93,8 @@ func ConfigMapName(clusterName string) string { return fmt.Sprintf("%s-otel-config", clusterName) } -// GenerateConfigMapData returns the ConfigMap data entries for the OTel Collector. +// GenerateConfigMapData returns the ConfigMap data entries for the OTel Collector +// with the default Options. // The config is split into two files that the collector merges at startup: // - static.yaml: receivers and static processors rendered from the embedded // base_config.yaml template. Add new SQL metric queries to base_config.yaml — @@ -98,8 +109,8 @@ func GenerateConfigMapData(clusterName, namespace string, spec *dbv1.MonitoringS return GenerateConfigMapDataWithOptions(Options{}, clusterName, namespace, spec) } -// Options carries the product naming used in the generated collector config. -// Empty fields fall back to the DocumentDB defaults. +// Options carries the product naming and metrics used in the generated +// collector config. Empty naming fields fall back to the DocumentDB defaults. type Options struct { // ClusterAttribute is the resource attribute key holding the cluster name. ClusterAttribute string @@ -108,6 +119,12 @@ type Options struct { // HealthMetricName is the gauge the sqlquery receiver reports PostgreSQL // liveness as. HealthMetricName string + // DocumentDBMetrics adds the DocumentDB PostgreSQL instance and catalog + // SQL metrics (documentdb.postgres.* and documentdb.database.*) and the + // sqlquery/catalog receiver. The queries need the monitoring role's USAGE + // on the DocumentDB schemas, so products enable it together with + // product.PostgresProfile.MonitoringSchemas. + DocumentDBMetrics bool } const ( @@ -128,11 +145,14 @@ func GenerateConfigMapDataWithOptions(opts Options, clusterName, namespace strin if opts.HealthMetricName == "" { opts.HealthMetricName = defaultHealthMetricName } - staticYAML, err := renderStaticConfig(staticConfigData{HealthMetricName: opts.HealthMetricName}) + staticYAML, err := renderStaticConfig(staticConfigData{ + HealthMetricName: opts.HealthMetricName, + DocumentDBMetrics: opts.DocumentDBMetrics, + }) if err != nil { return nil, err } - dynamicYAML, err := generateDynamicConfig(opts.ClusterAttribute, clusterName, namespace, spec) + dynamicYAML, err := generateDynamicConfig(opts, clusterName, namespace, spec) if err != nil { return nil, err } @@ -146,7 +166,7 @@ func GenerateConfigMapDataWithOptions(opts Options, clusterName, namespace strin // generateDynamicConfig builds the per-cluster dynamic config (resource // processor, exporters, pipeline wiring) that the collector deep-merges // with the embedded base_config.yaml. -func generateDynamicConfig(clusterAttribute, clusterName, namespace string, spec *dbv1.MonitoringSpec) (string, error) { +func generateDynamicConfig(opts Options, clusterName, namespace string, spec *dbv1.MonitoringSpec) (string, error) { cfg := collectorConfig{ Processors: map[string]any{ // `insert` (not `upsert`) so receivers that already emit their @@ -154,7 +174,7 @@ func generateDynamicConfig(clusterAttribute, clusterName, namespace string, spec // gap for receivers that don't (e.g. sqlquery). "resource": map[string]any{ "attributes": []map[string]any{ - {"key": clusterAttribute, "value": clusterName, "action": "insert"}, + {"key": opts.ClusterAttribute, "value": clusterName, "action": "insert"}, {"key": "k8s.namespace.name", "value": namespace, "action": "insert"}, {"key": "k8s.pod.name", "value": "${POD_NAME}", "action": "insert"}, }, @@ -162,11 +182,17 @@ func generateDynamicConfig(clusterAttribute, clusterName, namespace string, spec }, } - // sqlquery (Postgres health) + otlp (gateway-pushed metrics) come from - // base_config.yaml. Container/node resource metrics are served by a - // node-level collector such as the playground reference DaemonSet, not - // this sidecar. - receiverNames := []string{"sqlquery", "otlp"} + // sqlquery (Postgres health), sqlquery/catalog (DocumentDB catalog, only + // with DocumentDBMetrics), hostmetrics (data volume usage and pod network + // I/O), and otlp (gateway-pushed metrics) come from base_config.yaml. The + // sidecar reads only its own pod: it has no kubelet access, so container + // CPU/memory and node metrics come from a platform collector such as the + // playground reference DaemonSet. + receiverNames := []string{"sqlquery"} + if opts.DocumentDBMetrics { + receiverNames = append(receiverNames, "sqlquery/catalog") + } + receiverNames = append(receiverNames, "hostmetrics", "otlp") exporterNames := []string{} @@ -203,6 +229,7 @@ func generateDynamicConfig(clusterAttribute, clusterName, namespace string, spec "resource_to_telemetry_conversion": map[string]any{ "enabled": true, }, + "metric_expiration": prometheusMetricExpiration, } exporterNames = append(exporterNames, "prometheus") } diff --git a/operator/src/internal/otel/config_test.go b/operator/src/internal/otel/config_test.go index 5a1a8e56b..c7a35dcbf 100644 --- a/operator/src/internal/otel/config_test.go +++ b/operator/src/internal/otel/config_test.go @@ -4,8 +4,10 @@ package otel import ( + "fmt" "strings" "testing" + "time" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -45,6 +47,18 @@ func defaultStaticYAML() []byte { return []byte(out) } +// documentDBOptions enable the DocumentDB SQL metrics, as the DocumentDB +// product profile does. +var documentDBOptions = Options{DocumentDBMetrics: true} + +// documentDBStaticYAML is base_config.yaml rendered for DocumentDB: the +// DocumentDB names plus the DocumentDB SQL metrics. +func documentDBStaticYAML() []byte { + out, err := renderStaticConfig(staticConfigData{HealthMetricName: defaultHealthMetricName, DocumentDBMetrics: true}) + ExpectWithOffset(1, err).NotTo(HaveOccurred()) + return []byte(out) +} + var _ = Describe("base_config.yaml embed", func() { It("can be parsed as valid YAML with expected static components", func() { var cfg collectorConfig @@ -85,8 +99,181 @@ var _ = Describe("base_config.yaml embed", func() { Expect(ok).To(BeTrue(), "otlp.protocols.grpc must be a map") Expect(grpc["endpoint"]).To(Equal("127.0.0.1:4317")) }) + + DescribeTable("wires every static receiver into the metrics pipeline", + func(opts Options) { + spec := &dbv1.MonitoringSpec{ + Enabled: true, + Exporter: &dbv1.ExporterSpec{ + Prometheus: &dbv1.PrometheusExporterSpec{}, + }, + } + data, err := GenerateConfigMapDataWithOptions(opts, "cluster", "ns", spec) + Expect(err).NotTo(HaveOccurred()) + staticCfg := parseCfg(data["static.yaml"]) + dynCfg := parseCfg(data["dynamic.yaml"]) + + receivers := make([]string, 0, len(staticCfg.Receivers)) + for name := range staticCfg.Receivers { + receivers = append(receivers, name) + } + Expect(dynCfg.Service.Pipelines["metrics"].Receivers).To(ConsistOf(receivers)) + }, + Entry("with the DocumentDB SQL metrics", documentDBOptions), + Entry("without the DocumentDB SQL metrics", Options{}), + ) + + It("renders the DocumentDB SQL metrics only when enabled", func() { + spec := &dbv1.MonitoringSpec{Enabled: true} + without, err := GenerateConfigMapData("cluster", "ns", spec) + Expect(err).NotTo(HaveOccurred()) + staticCfg := parseCfg(without["static.yaml"]) + Expect(staticCfg.Receivers).To(HaveKey("hostmetrics")) + Expect(staticCfg.Receivers).NotTo(HaveKey("sqlquery/catalog")) + sqlquery, ok := staticCfg.Receivers["sqlquery"].(map[string]any) + Expect(ok).To(BeTrue(), "sqlquery receiver must be a map") + Expect(sqlquery["queries"]).To(HaveLen(1), "only the health query") + + with, err := GenerateConfigMapDataWithOptions(documentDBOptions, "cluster", "ns", spec) + Expect(err).NotTo(HaveOccurred()) + Expect(parseCfg(with["static.yaml"]).Receivers).To(HaveKey("sqlquery/catalog")) + Expect(with["static.yaml"]).To(ContainSubstring("metric_name: documentdb.postgres.uptime\n")) + }) + + It("declares the per-instance PostgreSQL metrics with parseable value types", func() { + queries := receiverQueries("sqlquery") + metrics := metricsByName(queries) + Expect(metrics).To(HaveKey("documentdb.postgres.up")) + + // Float columns must be parsed as doubles; the default int type would + // fail every scrape. + for _, name := range []string{"documentdb.postgres.uptime", "documentdb.postgres.replication.lag"} { + Expect(metrics).To(HaveKey(name)) + Expect(metrics[name]["value_type"]).To(Equal("double"), name) + Expect(metrics[name]["data_type"]).To(Equal("gauge"), name) + Expect(metrics[name]["unit"]).To(Equal("s"), name) + } + Expect(metrics).To(HaveKey("documentdb.postgres.replication.receiver.up")) + + // Block counters are cumulative monotonic sums so backends can compute rates. + for _, name := range []string{"documentdb.postgres.blocks.hit", "documentdb.postgres.blocks.read"} { + Expect(metrics).To(HaveKey(name)) + Expect(metrics[name]["data_type"]).To(Equal("sum"), name) + Expect(metrics[name]["monotonic"]).To(BeTrue(), name) + Expect(metrics[name]["aggregation"]).To(Equal("cumulative"), name) + } + + // Replication metrics come only from standbys. + Expect(querySQLFor(queries, "documentdb.postgres.replication.lag")).To(ContainSubstring("WHERE pg_is_in_recovery()")) + }) + + It("declares primary-only catalog metrics on a 5 minute interval", func() { + var cfg collectorConfig + Expect(yaml.Unmarshal(documentDBStaticYAML(), &cfg)).To(Succeed()) + catalog, ok := cfg.Receivers["sqlquery/catalog"].(map[string]any) + Expect(ok).To(BeTrue(), "sqlquery/catalog receiver must be a map") + Expect(catalog["collection_interval"]).To(Equal("5m")) + + queries := receiverQueries("sqlquery/catalog") + for _, q := range queries { + Expect(q["sql"]).To(ContainSubstring("NOT pg_is_in_recovery()"), "catalog queries must return no rows on standbys") + Expect(q["sql"]).To(ContainSubstring("NOT IN ('admin', 'config', 'local')")) + Expect(q["sql"]).To(ContainSubstring("NOT LIKE 'system.%'")) + } + + metrics := metricsByName(queries) + for _, name := range []string{ + "documentdb.database.storage.size", + "documentdb.database.collection.count", + "documentdb.database.view.count", + "documentdb.database.index.count", + } { + Expect(metrics).To(HaveKey(name)) + Expect(metrics[name]["attribute_columns"]).To(ConsistOf("db.namespace"), name) + } + Expect(metrics).To(HaveKey("documentdb.database.count")) + Expect(metrics["documentdb.database.count"]).NotTo(HaveKey("attribute_columns")) + }) + + It("scrapes only the data volume mount and non-loopback interfaces", func() { + var cfg collectorConfig + Expect(yaml.Unmarshal(defaultStaticYAML(), &cfg)).To(Succeed()) + hostmetrics, ok := cfg.Receivers["hostmetrics"].(map[string]any) + Expect(ok).To(BeTrue(), "hostmetrics receiver must be a map") + scrapers, ok := hostmetrics["scrapers"].(map[string]any) + Expect(ok).To(BeTrue(), "hostmetrics.scrapers must be a map") + Expect(scrapers).To(HaveLen(2)) + + filesystem, ok := scrapers["filesystem"].(map[string]any) + Expect(ok).To(BeTrue(), "filesystem scraper must be a map") + // The subPath mount is a bind mount; without this the scraper drops it. + Expect(filesystem["include_virtual_filesystems"]).To(BeTrue()) + Expect(filesystem["include_mount_points"]).To(Equal(map[string]any{ + "mount_points": []any{"/var/lib/otel/pgdata"}, + "match_type": "strict", + })) + + network, ok := scrapers["network"].(map[string]any) + Expect(ok).To(BeTrue(), "network scraper must be a map") + Expect(network["exclude"]).To(Equal(map[string]any{ + "interfaces": []any{"lo"}, + "match_type": "strict", + })) + Expect(network["metrics"]).To(Equal(map[string]any{ + "system.network.connections": map[string]any{"enabled": false}, + })) + }) }) +// receiverQueries returns the queries declared by a sqlquery receiver in the +// DocumentDB static config. +func receiverQueries(receiver string) []map[string]any { + var cfg collectorConfig + ExpectWithOffset(1, yaml.Unmarshal(documentDBStaticYAML(), &cfg)).To(Succeed()) + r, ok := cfg.Receivers[receiver].(map[string]any) + ExpectWithOffset(1, ok).To(BeTrue(), "%s receiver must be a map", receiver) + raw, ok := r["queries"].([]any) + ExpectWithOffset(1, ok).To(BeTrue(), "%s.queries must be a list", receiver) + queries := make([]map[string]any, 0, len(raw)) + for _, q := range raw { + query, ok := q.(map[string]any) + ExpectWithOffset(1, ok).To(BeTrue(), "%s query must be a map", receiver) + queries = append(queries, query) + } + return queries +} + +// metricsByName indexes the metric definitions of the given queries by metric_name. +func metricsByName(queries []map[string]any) map[string]map[string]any { + out := map[string]map[string]any{} + for _, q := range queries { + metrics, ok := q["metrics"].([]any) + ExpectWithOffset(1, ok).To(BeTrue(), "query metrics must be a list") + for _, m := range metrics { + metric, ok := m.(map[string]any) + ExpectWithOffset(1, ok).To(BeTrue(), "metric must be a map") + name, _ := metric["metric_name"].(string) + ExpectWithOffset(1, out).NotTo(HaveKey(name), "duplicate metric %s", name) + out[name] = metric + } + } + return out +} + +// querySQLFor returns the SQL of the query that emits the named metric. +func querySQLFor(queries []map[string]any, metricName string) string { + for _, q := range queries { + metrics, _ := q["metrics"].([]any) + for _, m := range metrics { + if metric, ok := m.(map[string]any); ok && metric["metric_name"] == metricName { + sql, _ := q["sql"].(string) + return sql + } + } + } + return "" +} + var _ = Describe("GenerateConfigMapData", func() { It("returns static.yaml from embedded base_config.yaml", func() { spec := &dbv1.MonitoringSpec{ @@ -112,7 +299,7 @@ var _ = Describe("GenerateConfigMapData", func() { Prometheus: &dbv1.PrometheusExporterSpec{Port: 9090}, }, } - data, err := GenerateConfigMapData("test-cluster", "test-ns", spec) + data, err := GenerateConfigMapDataWithOptions(documentDBOptions, "test-cluster", "test-ns", spec) Expect(err).NotTo(HaveOccurred()) dynCfg := parseCfg(data["dynamic.yaml"]) @@ -129,7 +316,7 @@ var _ = Describe("GenerateConfigMapData", func() { Expect(dynCfg.Exporters).To(HaveKey("prometheus")) // Pipeline wiring references receivers from static config - Expect(dynCfg.Service.Pipelines["metrics"].Receivers).To(ConsistOf("sqlquery", "otlp")) + Expect(dynCfg.Service.Pipelines["metrics"].Receivers).To(ConsistOf("sqlquery", "sqlquery/catalog", "hostmetrics", "otlp")) Expect(dynCfg.Service.Pipelines["metrics"].Processors).To(Equal([]string{"memory_limiter", "resource", "batch"})) Expect(dynCfg.Service.Pipelines["metrics"].Exporters).To(ConsistOf("prometheus")) }) @@ -259,6 +446,36 @@ var _ = Describe("GenerateConfigMapData", func() { Expect(data["dynamic.yaml"]).To(ContainSubstring("resource_to_telemetry_conversion")) Expect(data["dynamic.yaml"]).To(MatchRegexp(`resource_to_telemetry_conversion:\s*\n\s+enabled:\s*true`)) }) + + It("keeps prometheus series longer than the slowest receiver collection interval", func() { + spec := &dbv1.MonitoringSpec{ + Enabled: true, + Exporter: &dbv1.ExporterSpec{ + Prometheus: &dbv1.PrometheusExporterSpec{}, + }, + } + data, err := GenerateConfigMapData("cluster", "ns", spec) + Expect(err).NotTo(HaveOccurred()) + + promCfg, ok := parseCfg(data["dynamic.yaml"]).Exporters["prometheus"].(map[string]any) + Expect(ok).To(BeTrue()) + expiration, err := time.ParseDuration(fmt.Sprint(promCfg["metric_expiration"])) + Expect(err).NotTo(HaveOccurred()) + + var slowest time.Duration + for name, receiver := range parseCfg(string(documentDBStaticYAML())).Receivers { + cfg, _ := receiver.(map[string]any) + raw, ok := cfg["collection_interval"] + if !ok { + continue + } + interval, err := time.ParseDuration(fmt.Sprint(raw)) + Expect(err).NotTo(HaveOccurred(), "receiver %s", name) + slowest = max(slowest, interval) + } + Expect(slowest).To(BeNumerically(">", 0)) + Expect(expiration).To(BeNumerically(">", slowest)) + }) }) var _ = Describe("HashConfigMapData", func() { diff --git a/operator/src/internal/product/documentdb.go b/operator/src/internal/product/documentdb.go index 021997039..5a1ec75f4 100644 --- a/operator/src/internal/product/documentdb.go +++ b/operator/src/internal/product/documentdb.go @@ -43,6 +43,12 @@ func DocumentDBProfile() ProductProfile { "cron.database_name": "postgres", }, ReplicationAdminRole: "documentdb_admin_role", + // The DocumentDB planner hook resolves objects in documentdb_core + // and documentdb_api_internal for any query that calls a function + // or operator, and the catalog metrics read documentdb_api_catalog. + // Document data lives in documentdb_data, which is not granted. + MonitoringSchemas: []string{"documentdb_core", "documentdb_api_internal", "documentdb_api_catalog"}, + DocumentDBMetrics: true, }, Naming: NamingProfile{ Domain: "documentdb.io", diff --git a/operator/src/internal/product/profile.go b/operator/src/internal/product/profile.go index 5704b3384..b62bf226e 100644 --- a/operator/src/internal/product/profile.go +++ b/operator/src/internal/product/profile.go @@ -111,6 +111,19 @@ type PostgresProfile struct { // authentication must configure it explicitly; the core never adds trust // rules to PgHBA. Empty preserves the password-disabled default. MonitoringPasswordSecret string + // MonitoringSchemas are the schemas on which the operator grants the + // monitoring role USAGE once the primary is healthy, so the collector's SQL + // metric queries can resolve product objects. The grants would block CNPG's + // DROP ROLE, so the operator revokes them before the role is removed. + // Empty skips both. + MonitoringSchemas []string + // DocumentDBMetrics adds the DocumentDB PostgreSQL instance + // (documentdb.postgres.*) and catalog (documentdb.database.*) SQL metrics + // to the monitoring sidecar. The catalog queries read + // documentdb_api_catalog, so only products built on the DocumentDB + // extension can enable them, with MonitoringSchemas granting the DocumentDB + // schemas the queries need. + DocumentDBMetrics bool // ProtectedParameters are product GUCs the operator always forces, on top // of the core protected set. ProtectedParameters map[string]string diff --git a/test/e2e/tests/resources/sidecar_resources_test.go b/test/e2e/tests/resources/sidecar_resources_test.go index ec65e612f..95c13690a 100644 --- a/test/e2e/tests/resources/sidecar_resources_test.go +++ b/test/e2e/tests/resources/sidecar_resources_test.go @@ -25,6 +25,10 @@ import ( // otel = 48Mi request / 128Mi limit; cpu 50m req / 200m limit (monitoring on) // postgres = 1024 − 192 = 832Mi (monitoring off) // postgres = 1024 − 192 − 128 = 704Mi (monitoring on) +// +// The specs also check that the OTel collector mounts the data volume +// read-only through an empty subPath, so its hostmetrics filesystem scraper +// reports the volume's usage without seeing data files. const ( podEnvelope = "1Gi" wantGatewayMem = "192Mi" @@ -34,6 +38,10 @@ const ( wantOTelMemLimit = "128Mi" wantOTelCPURequest = "50m" wantOTelCPULimit = "200m" + + dataVolumeName = "pgdata" + wantOTelDataMountPath = "/var/lib/otel/pgdata" + wantOTelDataSubPath = "otel-statfs" ) var _ = Describe("Sidecar memory carve-out", @@ -100,6 +108,9 @@ var _ = Describe("Sidecar memory carve-out", Expect(hasEnv(otel, "GOMEMLIMIT")).To(BeTrue(), "otel collector should have a GOMEMLIMIT env var") + By("checking the collector's read-only data volume mount") + assertOTelDataVolumeMount(otel) + pg := containerByName(pod, postgresContainerName) Expect(pg).ToNot(BeNil(), "postgres container present") assertGuaranteedMemory(pg, wantPostgresWithMon) @@ -149,3 +160,19 @@ func hasEnv(ctr *corev1.Container, name string) bool { } return false } + +// assertOTelDataVolumeMount asserts the collector mounts the PostgreSQL data +// volume read-only through its own subPath. +func assertOTelDataVolumeMount(otel *corev1.Container) { + GinkgoHelper() + var mount *corev1.VolumeMount + for i := range otel.VolumeMounts { + if otel.VolumeMounts[i].Name == dataVolumeName { + mount = &otel.VolumeMounts[i] + } + } + Expect(mount).ToNot(BeNil(), "otel collector mounts the %s volume", dataVolumeName) + Expect(mount.MountPath).To(Equal(wantOTelDataMountPath)) + Expect(mount.SubPath).To(Equal(wantOTelDataSubPath)) + Expect(mount.ReadOnly).To(BeTrue(), "otel collector data volume mount is read-only") +}