Skip to content

feat: add PostgreSQL, catalog, data volume, and network metrics to the OTel sidecar - #475

Merged
hossain-rayhan merged 1 commit into
documentdb:mainfrom
udsmicrosoft:developer/sidecar-metrics-expansion
Dec 1, 2026
Merged

hossain-rayhan merged 1 commit into
documentdb:mainfrom
udsmicrosoft:developer/sidecar-metrics-expansion

Conversation

@udsmicrosoft

@udsmicrosoft udsmicrosoft commented Oct 14, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Adds PostgreSQL instance, DocumentDB catalog, and pod filesystem and network metrics to the OpenTelemetry Collector sidecar, grants the sidecar's monitoring role the schema access its queries need Each monitored cluster restarts once after the operator upgrade. There are no new services, components, CRD fields, or Helm values: everything runs in the existing otel-collector sidecar.

Area Change
PostgreSQL instance metrics Three queries in the existing sqlquery receiver: documentdb.postgres.uptime; documentdb.postgres.replication.lag and documentdb.postgres.replication.receiver.up (standbys only); documentdb.postgres.blocks.hit and documentdb.postgres.blocks.read (monotonic cumulative sums).
DocumentDB catalog metrics New sqlquery/catalog receiver, 5 minute interval, primary only: documentdb.database.count, plus per-database (db.namespace) documentdb.database.collection.count, .view.count, .index.count, and .storage.size.
Pod filesystem and network New hostmetrics receiver. The filesystem scraper reports only the data volume; the network scraper skips lo and keeps system.network.connections off. The plugin mounts pgdata into the collector read-only at /var/lib/otel/pgdata on the empty subPath otel-statfs, only when the pod has a pgdata volume.
Monitoring role grants The controller grants otel_monitor schema USAGE on the healthy primary and revokes it before the role is declared absent. The CNPG Cluster watch also reconciles when CNPG reports it cannot drop the role.

Docs: monitoring/metrics.md (inventory, scope text, role permissions, alerting on an unresponsive PostgreSQL server), monitoring/overview.md, high-availability/local-ha.md (link to the standby replication metrics), and CHANGELOG [Unreleased].

Design decisions

Topic Choice
Metric names documentdb.postgres.* for instance stats and documentdb.database.* for the catalog. documentdb.postgres.up is unchanged.
Storage size On-disk size via pg_table_size, the same as dbStats storageSize. Logical size would need per-table statistics that otel_monitor cannot read.
Catalog filter Exclude the admin, config, and local databases and system.* collections. Collections and views are counted separately; dashboards can add them for a namespace total.
Grant lifecycle Direct grants to otel_monitor, revoked when monitoring is turned off, rather than a NOLOGIN group role joined through CNPG inRoles. Details below.
Database names Exported in db.namespace, one set of series per database, so size and counts are available per database.
PostgreSQL health alerts documentdb.postgres.up is never 0: when PostgreSQL does not answer, the sidecar records nothing and the exporter serves the last values for 6 minutes. The docs alert on uptime that stops increasing and on a missing per-pod up series instead.
Catalog interval 5 minutes, with no cap on the number of databases.

Grant lifecycle

  • Grant. On the healthy primary of the primary cluster, one query reports the role as missing, pending, or granted. Only pending runs the GRANT. missing (CNPG has not created the role yet) and errors requeue after the short interval without blocking the rest of the reconcile. The grants replicate to standbys and replica clusters.
  • Revoke. When monitoring is off and the role may still exist, the controller revokes the grants before SyncCnpgCluster declares the role Ensure: absent, so CNPG's DROP ROLE never meets dependent privileges. This does not rely on CNPG retrying a failed drop. If the revoke cannot run (no healthy primary, or a SQL error), the desired spec keeps the role declared, the sidecar is still removed, and the reconcile requeues. Replica clusters skip the revoke because CNPG manages roles only on the primary cluster.
  • Restored backups. A cluster restored with monitoring disabled from a backup taken with it enabled declares the role absent from the start, so CNPG's DROP ROLE fails on the restored grants and CNPG reports the role in status.managedRolesStatus.cannotReconcile. The CNPG Cluster watch reconciles on that status change, and the controller then revokes the grants.

Upgrade behavior

  • Monitored clusters perform one rolling restart after the operator upgrade, because the collector config hash changes. The new pods get the collector's data volume mount.
  • Unmonitored clusters do not restart.

The gateway liveness probe moved to #526.

@udsmicrosoft
udsmicrosoft marked this pull request as ready for review October 15, 2026 16:16
Copilot AI balanced review requested due to automatic review settings October 15, 2026 16:16

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Gateway startup gates PostgreSQL endpoint readiness, and restored monitoring-role grants can remain without a cleanup trigger.

2 open findings
What changed in this PR

Expands monitoring through the existing OpenTelemetry sidecar and adds gateway health probes without new API fields or Helm values.

Changes:

  • Adds PostgreSQL, catalog, data-volume, and network metrics.
  • Manages monitoring-role schema grants and cleanup.
  • Adds gateway probes, tests, and operational documentation.
File Description
test/​e2e/​tests/​resources/​sidecar_resources_test.go Checks gateway probes and collector mounts.
operator/​src/​internal/​otel/​config.go Wires receivers and extends metric expiration.
operator/​src/​internal/​otel/​config_test.go Tests receiver configuration and metric definitions.
operator/​src/​internal/​otel/​base_config.yaml Defines SQL and filesystem/network metrics.
operator/​src/​internal/​controller/​documentdb_controller.go Grants and revokes monitoring permissions.
operator/​src/​internal/​controller/​documentdb_controller_test.go Tests grant and revoke reconciliation.
operator/​src/​internal/​cnpg/​cnpg_cluster.go Preserves monitoring roles during cleanup.
operator/​cnpg-plugins/​sidecar-injector/​internal/​lifecycle/​lifecycle.go Injects gateway probes and read-only data mounts.
operator/​cnpg-plugins/​sidecar-injector/​internal/​lifecycle/​lifecycle_test.go Tests probe and mount injection.
docs/​operator-public-documentation/​preview/​monitoring/​overview.md Updates monitoring scope and troubleshooting.
docs/​operator-public-documentation/​preview/​monitoring/​metrics.md Documents metrics, permissions, and probe traffic.
docs/​operator-public-documentation/​preview/​high-availability/​local-ha.md Describes gateway restarts and replication monitoring.
CHANGELOG.md Records monitoring and probe changes.

🧠 Review effort: Balanced


💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

@xgerman xgerman left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tested final head 1a57eea. I did not find a new correctness defect.

Validation performed:

  • go test ./internal/otel ./internal/cnpg ./internal/controller
  • go test ./internal/config ./internal/lifecycle
  • Validated the merged static/dynamic configuration with the exact otel/opentelemetry-collector-contrib:0.149.0 image
  • Ran that collector and confirmed the filtered filesystem/network metrics are emitted
  • Ran the SQL receiver against PostgreSQL 16 and confirmed documentdb.postgres.up, uptime, blocks.hit, and blocks.read are emitted
  • The full E2E matrix is green

The PR is still blocked by Check Unit Test Coverage: patch coverage is 88% (66/75 statements), below the required 90%.

Maintainability note: this combines gateway liveness, four metrics domains, sidecar volume injection, and a custom managed-role grant/revoke state machine. Most of the diff is tests/docs, but the runtime change could still be easier to review and roll back if gateway health were separate and the role permission lifecycle used a smaller idempotent SQL path.

@udsmicrosoft

udsmicrosoft commented Oct 22, 2026 •

Copy link
Copy Markdown
Collaborator Author

@xgerman Addressed the coverage blocker in 6c87680.

Added four cases to the existing OTel monitoring-role reconciliation table: empty grant-state output, unexpected grant-state output, a failing grant-state query, and a failing GRANT. The tests check the expected GRANT attempts and short retry, and verify that reconciliation still reaches the extension-version check.

Using the coverage workflow flags and its pinned go-patch-cover@v0.2.0, patch coverage now measures 94.67% (71/75 changed statements) locally, up from 88% (66/75). The operator tests passed with the race detector, and go vet ./... passed. This commit changes tests only; gateway health and the role permission lifecycle are unchanged.

@udsmicrosoft
udsmicrosoft requested a review from xgerman October 22, 2026 14:59
@udsmicrosoft
udsmicrosoft force-pushed the developer/sidecar-metrics-expansion branch from 5b21daf to 05439e0 Compare October 22, 2026 19:40
@udsmicrosoft
udsmicrosoft requested a review from alaye-ms October 23, 2026 14:26
@documentdb-triage-tool documentdb-triage-tool Bot added documentation Improvements or additions to documentation enhancement New feature or request go Pull requests that update go code test labels Nov 2, 2026
@documentdb-triage-tool

Copy link
Copy Markdown

🤖 Auto-triaged by documentdb-triage-tool.

Applied: go, documentation, test, enhancement
Project fields suggested: Component controllers · Priority P2 · Effort XL · Status Needs Review
Confidence: 0.80 (mixed)

Reasoning

component from path globs (controllers, docs, test); effort from diff stats (1424+80 LOC, 24 files); LLM: Cross-component PR adding new OTel metrics (PostgreSQL, catalog, filesystem, network), gateway liveness probes, monitoring role grants, and accompanying docs — touches controllers, manifests, and docs across multiple files with schema/config changes.

If a label is wrong, remove it manually and ping @patty-chow so the rules can be tuned. The bot will not re-label items that already have component labels.

@hossain-rayhan

Copy link
Copy Markdown
Collaborator

I think the gateway probe should be separate and comes with a separate design. I'm working towards it.

@hossain-rayhan

Copy link
Copy Markdown
Collaborator

The gateway liveness probe is split out into #526 so it can ship separately. Once that merges, could you drop the probe changes (the lifecycle.go probe, its tests, the E2E assertion and the local-ha docs) from this PR and rebase? That should also clear the current conflict with main.

@udsmicrosoft
udsmicrosoft force-pushed the developer/sidecar-metrics-expansion branch from 6bcffd4 to 04053ce Compare November 30, 2026 19:50
@udsmicrosoft udsmicrosoft changed the title feat: add PostgreSQL, catalog, data volume, and network metrics to the OTel sidecar, plus gateway liveness probes feat: add PostgreSQL, catalog, data volume, and network metrics to the OTel sidecar Nov 30, 2026

@xgerman xgerman left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed head 04053ce. The expansion adds PostgreSQL health/replication/block counters, primary-only catalog metrics, and pod filesystem/network metrics through the existing collector.

P1 operational requirement requested in this review: expose supported collection-interval overrides, especially for the catalog receiver; see the inline comment. The fixed cadence and API gap are verified, but production-scale query latency has not been measured. Targeted operator tests (otel, engine, cnpg, product) and sidecar lifecycle tests pass.

Security: the read-only empty subPath and restricted non-root collector avoid exposing data files or adding node access. Database names are now exported. Existing localhost trust authentication and plaintext remote OTLP remain separate hardening concerns; this PR does not introduce those settings.

Network metrics are meaningful at pod scope, not per container: shared interfaces include client, replication, backup and exporter traffic; excluded loopback omits local gateway-to-database and local OTLP traffic. Avoid double-counting these with platform network metrics.

CNPG alignment: the native OTLP push announced for 1.31 RC1 is log export (https://cloudnative-pg.io/releases/cloudnative-pg-1-31.0-rc1-released/). This PR's metrics pipeline is complementary, not an implementation of that log-export capability; receiving those logs would require a logs pipeline.

…e OTel sidecar

Signed-off-by: urismiley <urismiley@microsoft.com>
@hossain-rayhan
hossain-rayhan merged commit 7fde74b into documentdb:main Dec 1, 2026
54 checks passed
hossain-rayhan added a commit to hossain-rayhan/documentdb-kubernetes-operator that referenced this pull request Dec 1, 2026
…iner

Split from documentdb#475 so the gateway probe can ship on its own. The injected
documentdb-gateway container had no probes, so a gateway that stopped
accepting connections was never restarted (documentdb#522).

- tcpSocket liveness probe on gatewayPort: initial delay 600 s (the
  entrypoint waits up to 600 s for PostgreSQL), period 10 s, timeout 5 s,
  failure threshold 6. A failure restarts only the gateway container.
- No readiness or startup probe: either would make the pod unready and
  remove PostgreSQL from the CNPG Services while the gateway isn't
  listening.
- Unit tests (default and custom port, no readiness/startup probe) and
  an E2E assertion in the sidecar resources spec.
- Docs: Gateway Container Restarts in the local HA guide, including the
  limits of a TCP probe and its ERROR log lines; gatewayPort notes in the
  plugin guide and product-neutral-core design; CHANGELOG.

A request-level health check needs the gateway itself:
documentdb/documentdb#834.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 9f1a71b4-9969-4456-9f65-8d19dd550d8e
Signed-off-by: Rayhan Hossain <hossain.rayhan@outlook.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation enhancement New feature or request go Pull requests that update go code test

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants