diff --git a/CHANGELOG.md b/CHANGELOG.md index c195e585b..fd8a71ac8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,9 @@ ### 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). +### Behavioral Changes +- **Gateway liveness probe**: The `documentdb-gateway` container now has a TCP liveness probe on the gateway port (10260 by default). If the gateway stops accepting connections for about a minute, the kubelet restarts the gateway container only: PostgreSQL keeps running and no failover occurs. During the restart, usually a few seconds, the pod is not Ready, so the CloudNativePG Services briefly drop it and standbys streaming from it reconnect, as already happens when the gateway process exits. The first check runs 10 minutes after the container starts, which covers the gateway's wait for PostgreSQL. The gateway has no readiness or startup probe, so a gateway that isn't listening doesn't mark the pod unready. The probe can't detect a gateway that hangs with its port open, and the gateway logs each probe connection as two `ERROR` lines (a failed TLS handshake and a closed connection). Pods get the probe when they are next created, for example during a rolling restart. See [Gateway Container Restarts](docs/operator-public-documentation/v1/high-availability/local-ha.md#gateway-container-restarts). + ## [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 720e8d065..a4882c085 100644 --- a/docs/designs/product-neutral-core.md +++ b/docs/designs/product-neutral-core.md @@ -149,7 +149,8 @@ them, so existing clusters see no parameter change and no rolling restart. `SyncCnpgCluster` adds, updates, and removes these parameters on existing clusters and requests a rolling restart when they change. When the gateway port changes, the client Service's ports follow it; the Service keeps its -assigned cluster IPs and node ports. Its selector also converges, disabling +assigned cluster IPs and node ports. The injector's TCP liveness probe checks +the same port, so a product gateway must listen on `gatewayPort`. Its selector also converges, disabling traffic while promotion is pending and restoring it when promotion completes. See [the plugin configuration guide](../developer-guides/sidecar-injector-plugin-configuration.md). diff --git a/docs/developer-guides/sidecar-injector-plugin-configuration.md b/docs/developer-guides/sidecar-injector-plugin-configuration.md index 0407b8f8e..20eb8974e 100644 --- a/docs/developer-guides/sidecar-injector-plugin-configuration.md +++ b/docs/developer-guides/sidecar-injector-plugin-configuration.md @@ -84,7 +84,7 @@ defaults below apply. | Parameter | Default | Description | | --- | --- | --- | | `gatewayContainerName` | `documentdb-gateway` | Name of the injected gateway container | -| `gatewayPort` | `10260` | Gateway container port | +| `gatewayPort` | `10260` | Gateway container port, also checked by the gateway's TCP liveness probe | | `gatewayArgs` | DocumentDB gateway args | JSON array that replaces `--create-user --start-pg false --pg-port 5432` and the TLS `--cert-path`/`--key-file` flags verbatim | | `gatewayUsernameEnv` | `USERNAME` | Env var that receives the credential secret's `username` key | | `gatewayPasswordEnv` | `PASSWORD` | Env var that receives the credential secret's `password` key | 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 0dd126830..83cc10644 100644 --- a/docs/operator-public-documentation/v1/high-availability/local-ha.md +++ b/docs/operator-public-documentation/v1/high-availability/local-ha.md @@ -206,6 +206,20 @@ The failover process occurs in two phases: !!! tip "Tuning for RTO vs RPO" Lower `stopDelay` values favor faster recovery (RTO) but may increase data loss risk (RPO). Higher values prioritize data safety but may delay recovery. +### Gateway Container Restarts + +The `documentdb-gateway` container in each pod has a TCP liveness probe on the gateway port (10260): + +| Probe | Settings | Effect | +|-------|----------|--------| +| Liveness | First check 10 minutes after the container starts, then every 10 seconds, 5 second timeout, 6 failures | Restarts the gateway container after about one minute without accepting connections. The initial delay covers the gateway's wait for PostgreSQL at startup. | + +A liveness restart restarts only the gateway container: PostgreSQL keeps running and no failover occurs. Client connections to that pod fail until the gateway is back. While the gateway container restarts, usually a few seconds, the pod is not Ready, because pod readiness covers every container. The CloudNativePG Services drop the pod for that time, so standbys streaming from it reconnect. The same happens today when the gateway process exits on its own; the probe adds restarts only for a gateway that stops accepting connections. Because the first check waits 10 minutes, a gateway that never starts listening, or stops within 10 minutes of starting, is restarted about 11 minutes after it started. + +The gateway has no readiness or startup probe. Pod readiness covers every container, and a container with a startup probe is not ready until that probe succeeds, so either probe would remove PostgreSQL from the CloudNativePG Services while the gateway is not listening and break replication. + +The probe only checks that the port accepts TCP connections; it doesn't perform a TLS handshake or send a request. A gateway that hangs with its port still open passes the probe. Each probe opens a connection and closes it without sending data, about six times per minute per pod. The gateway logs each probe as two `ERROR` lines: `Failed to create TLS connection` and `Gateway runtime connection failed … Connection closed`. Exclude these from error-based alerts. A request-level health check in the gateway is tracked in [documentdb/documentdb#834](https://github.com/documentdb/documentdb/issues/834). + ## Monitoring and Failover Detection Understanding when a failover has occurred is essential for operations. diff --git a/operator/cnpg-plugins/sidecar-injector/internal/lifecycle/lifecycle.go b/operator/cnpg-plugins/sidecar-injector/internal/lifecycle/lifecycle.go index b1c30a668..d2fc1c7ab 100644 --- a/operator/cnpg-plugins/sidecar-injector/internal/lifecycle/lifecycle.go +++ b/operator/cnpg-plugins/sidecar-injector/internal/lifecycle/lifecycle.go @@ -172,6 +172,7 @@ func (impl Implementation) reconcileMetadata( }, Env: envVars, SecurityContext: gatewaySecurityContext(), + LivenessProbe: gatewayLivenessProbe(configuration.GatewayPort), } if resources := buildResources( configuration.GatewayCPURequest, @@ -527,6 +528,7 @@ func injectGatewayOTelEnv(pod *corev1.Pod, containerName string) { // otelCollectorContainerName is the name of the injected OpenTelemetry // Collector sidecar. const otelCollectorContainerName = "otel-collector" + const otelMonitorRoleName = "otel_monitor" // dataVolumeName is the CloudNativePG volume that holds PGDATA. CNPG mounts @@ -554,6 +556,27 @@ func podHasVolume(pod *corev1.Pod, name string) bool { return false } +// gatewayLivenessProbe restarts only the gateway container after it stops +// accepting TCP connections on port for about a minute; PostgreSQL keeps +// running. The first check waits 600 s because the gateway entrypoint waits up +// to that long for PostgreSQL before it opens its port. +// +// The gateway deliberately has no readiness or startup probe. Pod readiness +// covers every container, and a container with a startup probe is not ready +// until that probe succeeds, so either probe would remove PostgreSQL from the +// CNPG Services while the gateway is not listening and break replication. +func gatewayLivenessProbe(port int32) *corev1.Probe { + return &corev1.Probe{ + ProbeHandler: corev1.ProbeHandler{ + TCPSocket: &corev1.TCPSocketAction{Port: intstr.FromInt32(port)}, + }, + InitialDelaySeconds: 600, + PeriodSeconds: 10, + TimeoutSeconds: 5, + FailureThreshold: 6, + } +} + // 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. 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 fc5131046..d35fb925f 100644 --- a/operator/cnpg-plugins/sidecar-injector/internal/lifecycle/lifecycle_test.go +++ b/operator/cnpg-plugins/sidecar-injector/internal/lifecycle/lifecycle_test.go @@ -16,6 +16,7 @@ import ( corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/util/intstr" pluginconfig "github.com/documentdb/cnpg-i-sidecar-injector/internal/config" pluginmetadata "github.com/documentdb/cnpg-i-sidecar-injector/pkg/metadata" @@ -708,6 +709,7 @@ func TestLifecycleHookCustomGatewayContract(t *testing.T) { if gateway.Ports[0].ContainerPort != 8081 { t.Errorf("port = %d, want 8081", gateway.Ports[0].ContainerPort) } + assertTCPProbe(t, "liveness", gateway.LivenessProbe, 8081) if !reflect.DeepEqual(gateway.Args, []string{"--port", "8081"}) { t.Errorf("args = %v", gateway.Args) } @@ -730,3 +732,46 @@ func TestLifecycleHookCustomGatewayContract(t *testing.T) { assertEnvValue(t, gateway.Env, "KEY_FILE", "/tls/tls.key") assertEnvValue(t, gateway.Env, "OTEL_METRICS_ENABLED", "true") } + +// TestLifecycleHookAddsGatewayLivenessProbe checks the gateway liveness probe, +// and that the gateway has no readiness or startup probe: either would keep the +// pod unready, and so take PostgreSQL out of the CNPG Services, while the +// gateway is not listening. +func TestLifecycleHookAddsGatewayLivenessProbe(t *testing.T) { + containers := runCreateHook(t, map[string]string{}) + + gateway, ok := containers[gatewayContainerName] + if !ok { + t.Fatalf("gateway container missing from patch") + } + if gateway.ReadinessProbe != nil { + t.Errorf("gateway ReadinessProbe = %+v, want nil", gateway.ReadinessProbe) + } + if gateway.StartupProbe != nil { + t.Errorf("gateway StartupProbe = %+v, want nil", gateway.StartupProbe) + } + + liveness := gateway.LivenessProbe + assertTCPProbe(t, "liveness", liveness, 10260) + if liveness != nil { + if liveness.PeriodSeconds != 10 || liveness.TimeoutSeconds != 5 || liveness.FailureThreshold != 6 { + t.Errorf("liveness period/timeout/failureThreshold = %d/%d/%d, want 10/5/6", + liveness.PeriodSeconds, liveness.TimeoutSeconds, liveness.FailureThreshold) + } + // The gateway entrypoint waits up to 600 s for PostgreSQL before it listens. + if liveness.InitialDelaySeconds < 600 { + t.Errorf("liveness initialDelaySeconds = %d, want at least 600", liveness.InitialDelaySeconds) + } + } +} + +func assertTCPProbe(t *testing.T, name string, probe *corev1.Probe, port int32) { + t.Helper() + if probe == nil { + t.Errorf("gateway %s probe is nil", name) + return + } + if probe.TCPSocket == nil || probe.TCPSocket.Port != intstr.FromInt32(port) { + t.Errorf("gateway %s probe handler = %+v, want tcpSocket on %d", name, probe.ProbeHandler, port) + } +} diff --git a/test/e2e/tests/resources/sidecar_resources_test.go b/test/e2e/tests/resources/sidecar_resources_test.go index 95c13690a..f5031c390 100644 --- a/test/e2e/tests/resources/sidecar_resources_test.go +++ b/test/e2e/tests/resources/sidecar_resources_test.go @@ -29,6 +29,8 @@ import ( // 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. +// The specs also check that the gateway has a TCP liveness probe and no +// startup or readiness probe. const ( podEnvelope = "1Gi" wantGatewayMem = "192Mi" @@ -42,6 +44,12 @@ const ( dataVolumeName = "pgdata" wantOTelDataMountPath = "/var/lib/otel/pgdata" wantOTelDataSubPath = "otel-statfs" + + gatewayPort = 10260 + // gatewayEntrypointWaitSeconds is how long the gateway entrypoint waits + // for PostgreSQL before it listens; the liveness probe's initial delay + // must cover it. + gatewayEntrypointWaitSeconds = 600 ) var _ = Describe("Sidecar memory carve-out", @@ -68,6 +76,9 @@ var _ = Describe("Sidecar memory carve-out", Expect(gw).ToNot(BeNil(), "gateway container present") assertGuaranteedMemory(gw, wantGatewayMem) + By("checking the gateway's TCP liveness probe") + assertGatewayProbes(gw) + pg := containerByName(pod, postgresContainerName) Expect(pg).ToNot(BeNil(), "postgres container present") assertGuaranteedMemory(pg, wantPostgresNoMon) @@ -176,3 +187,18 @@ func assertOTelDataVolumeMount(otel *corev1.Container) { Expect(mount.SubPath).To(Equal(wantOTelDataSubPath)) Expect(mount.ReadOnly).To(BeTrue(), "otel collector data volume mount is read-only") } + +// assertGatewayProbes asserts the gateway has a TCP liveness probe on its +// listener port that waits out the entrypoint, and no startup or readiness +// probe. +func assertGatewayProbes(gw *corev1.Container) { + GinkgoHelper() + probe := gw.LivenessProbe + Expect(probe).ToNot(BeNil(), "gateway liveness probe present") + Expect(probe.TCPSocket).ToNot(BeNil(), "gateway liveness probe uses tcpSocket") + Expect(probe.TCPSocket.Port.IntValue()).To(Equal(gatewayPort), "gateway liveness probe port") + Expect(probe.InitialDelaySeconds).To(BeNumerically(">=", gatewayEntrypointWaitSeconds), + "gateway liveness probe must wait out the entrypoint's wait for PostgreSQL") + Expect(gw.StartupProbe).To(BeNil(), "gateway must not have a startup probe") + Expect(gw.ReadinessProbe).To(BeNil(), "gateway must not have a readiness probe") +}