From e777835ed4a85a753d891c2feeeb83bdf9797d17 Mon Sep 17 00:00:00 2001 From: Andrey Kolkov Date: Tue, 1 Dec 2026 10:40:07 +0700 Subject: [PATCH 1/7] fix(postgres): bring the standard-trixie image move back to release-1.7 #5461 took #5405 out of release-1.7 because the collation repair it shipped missed C.UTF-8, overran the Job budget on a rollout and could not update PostGIS (#5459). Those are fixed on main now, so the image move comes back to the line together with the fixes, which follow this commit. Without it, tenant PostgreSQL on 1.7 stays on bare bullseye tags that get no further minors, and CVE-2026-116331 stays open there. This reverts commit fad3e6e21 (#5461). Refs: #5459 Assisted-By: LLM Signed-off-by: Andrey Kolkov --- hack/e2e-chainsaw/postgres/chainsaw-test.yaml | 117 ++++++++ .../apps/postgres/files/postgis-versions.yaml | 10 +- packages/apps/postgres/files/versions.yaml | 10 +- .../apps/postgres/hack/update-versions.sh | 5 +- .../apps/postgres/templates/_versions.tpl | 32 ++- packages/apps/postgres/templates/db.yaml | 8 +- .../apps/postgres/templates/init-job.yaml | 5 +- .../apps/postgres/templates/init-script.yaml | 249 ++++++++++++++++++ packages/apps/postgres/tests/flavor_test.yaml | 8 +- 9 files changed, 410 insertions(+), 34 deletions(-) diff --git a/hack/e2e-chainsaw/postgres/chainsaw-test.yaml b/hack/e2e-chainsaw/postgres/chainsaw-test.yaml index bc0bc1c98..90d1552d3 100644 --- a/hack/e2e-chainsaw/postgres/chainsaw-test.yaml +++ b/hack/e2e-chainsaw/postgres/chainsaw-test.yaml @@ -249,6 +249,123 @@ spec: fi check: ($error == null): true + + # The init Job rebuilds an index whose collation changed library version. + # The pass is SQL run by a Helm hook, so only a real server can say whether + # it works. A collation created with an explicit version reads as stale + # without swapping the operand image, which makes one more upgrade of the + # release enough to run the pass over it. + - name: rebuild-index-after-collation-version-change + try: + - script: + timeout: 2m + content: | + set -eu + pod=$(kubectl -n "$NAMESPACE" get pod \ + -l cnpg.io/cluster=postgres-test,cnpg.io/instanceRole=primary \ + -o name | head -n1) + kubectl -n "$NAMESPACE" exec -i "$pod" -c postgres -- \ + psql -U postgres -d testdb -v ON_ERROR_STOP=1 <<'EOF' + CREATE COLLATION stale_icu (provider = icu, locale = 'en', version = '0'); + CREATE TABLE collation_probe (s text COLLATE stale_icu); + INSERT INTO collation_probe SELECT 'v' || g FROM generate_series(1, 1000) g; + CREATE UNIQUE INDEX collation_probe_s ON collation_probe (s); + CREATE EXTENSION IF NOT EXISTS btree_gist; + CREATE TABLE collation_probe_excl (s text COLLATE stale_icu, EXCLUDE USING gist (s WITH =)); + INSERT INTO collation_probe_excl SELECT 'k' || g FROM generate_series(1, 200) g; + CREATE TABLE collation_probe_before AS + SELECT 'collation_probe_s'::regclass::oid AS index, + (SELECT relfilenode FROM pg_class WHERE oid = 'collation_probe_excl_s_excl'::regclass) AS in_place_file; + EOF + check: + ($error == null): true + # A declared user is the smallest change that makes Helm upgrade the + # release, and so run the hook, without restarting PostgreSQL. + - patch: + resource: + apiVersion: apps.cozystack.io/v1alpha1 + kind: Postgres + metadata: + name: test + spec: + users: + collationprobe: {} + # 11m: above the 600s upgrade timeout cozystack-api gives this release. + # The step above that waited for this Job deleted it, so the Job found + # here is the one the upgrade created. + - assert: + timeout: 11m + resource: + apiVersion: batch/v1 + kind: Job + metadata: + name: postgres-test-init-job + status: + (conditions[?type == 'Complete']): + - status: "True" + - script: + timeout: 2m + content: | + set -eu + pod=$(kubectl -n "$NAMESPACE" get pod \ + -l cnpg.io/cluster=postgres-test,cnpg.io/instanceRole=primary \ + -o name | head -n1) + q() { + kubectl -n "$NAMESPACE" exec "$pod" -c postgres -- \ + psql -U postgres -d testdb -v ON_ERROR_STOP=1 -tAc "$1" + } + refreshed=$(q "SELECT collversion = pg_collation_actual_version(oid) FROM pg_collation WHERE collname = 'stale_icu'") + if [ "$refreshed" != t ]; then + echo "the init Job left the collation version stale" >&2 + exit 1 + fi + # REINDEX CONCURRENTLY gives the index a new OID, so an unchanged + # one means the version was refreshed over an index nobody rebuilt. + rebuilt=$(q "SELECT 'collation_probe_s'::regclass::oid <> index FROM collation_probe_before") + if [ "$rebuilt" != t ]; then + echo "the init Job refreshed the collation version without rebuilding the index" >&2 + exit 1 + fi + q "CREATE EXTENSION IF NOT EXISTS amcheck" + q "SELECT bt_index_check('collation_probe_s', true)" + # An exclusion constraint's index is rebuilt in place: it keeps its + # OID and gets a new storage file. + rebuilt_in_place=$(q "SELECT c.relfilenode <> b.in_place_file FROM pg_class c, collation_probe_before b WHERE c.oid = 'collation_probe_excl_s_excl'::regclass") + if [ "$rebuilt_in_place" != t ]; then + echo "the init Job did not rebuild the exclusion constraint's index" >&2 + exit 1 + fi + # The pass keeps its progress in a setting of the database and + # removes it once nothing is left to repair. + progress=$(q "SELECT count(*) FROM pg_db_role_setting s JOIN pg_database d ON d.oid = s.setdatabase, unnest(s.setconfig) AS c WHERE d.datname = current_database() AND c LIKE 'cozystack.collation_repair=%'") + if [ "$progress" != 0 ]; then + echo "the init Job left its repair setting on a database it finished repairing" >&2 + exit 1 + fi + leftovers=$(q "SELECT count(*) FROM pg_index WHERE NOT indisvalid") + if [ "$leftovers" != 0 ]; then + echo "the rebuild left $leftovers invalid index(es) behind" >&2 + exit 1 + fi + # The Job above also completes on a retry, so a hook that failed + # first would pass unseen without this. + cd ../../.. + . hack/e2e-chainsaw/_lib/remediation-guard.sh + statuses=$(kubectl -n "$NAMESPACE" get helmrelease postgres-test \ + -o jsonpath="$HELMRELEASE_HISTORY_JSONPATH") + printf 'HelmRelease postgres-test history statuses:\n%s\n' "${statuses:-}" + if helmrelease_has_remediation_cycle "$statuses"; then + echo "HelmRelease postgres-test failed an action while the index was rebuilt" >&2 + exit 1 + fi + check: + ($error == null): true + finally: + - delete: + ref: + apiVersion: batch/v1 + kind: Job + name: postgres-test-init-job # The Postgres CR itself was applied by chainsaw and is deleted (and waited # on) automatically during cleanup — no explicit teardown step needed. --- diff --git a/packages/apps/postgres/files/postgis-versions.yaml b/packages/apps/postgres/files/postgis-versions.yaml index 4b1ad284c..12d800143 100644 --- a/packages/apps/postgres/files/postgis-versions.yaml +++ b/packages/apps/postgres/files/postgis-versions.yaml @@ -1,6 +1,6 @@ -"v18": "18.1-3.6.1-standard-trixie" -"v17": "17.7-3.6.1-standard-trixie" -"v16": "16.11-3.6.1-standard-trixie" -"v15": "15.15-3.6.1-standard-trixie" -"v14": "14.20-3.6.1-standard-trixie" +"v18": "18.7-3.7.0-standard-trixie" +"v17": "17.12-3.7.0-standard-trixie" +"v16": "16.16-3.7.0-standard-trixie" +"v15": "15.20-3.7.0-standard-trixie" +"v14": "14.25-3.7.0-standard-trixie" "v13": "13.22-3.6.0-standard-trixie" diff --git a/packages/apps/postgres/files/versions.yaml b/packages/apps/postgres/files/versions.yaml index e4fe13ead..2624066e3 100644 --- a/packages/apps/postgres/files/versions.yaml +++ b/packages/apps/postgres/files/versions.yaml @@ -1,6 +1,6 @@ -"v18": "v18.1" -"v17": "v17.7" -"v16": "v16.11" -"v15": "v15.15" -"v14": "v14.20" +"v18": "v18.7" +"v17": "v17.12" +"v16": "v16.16" +"v15": "v15.20" +"v14": "v14.25" "v13": "v13.22" diff --git a/packages/apps/postgres/hack/update-versions.sh b/packages/apps/postgres/hack/update-versions.sh index 3a4f0a745..0afc55afa 100755 --- a/packages/apps/postgres/hack/update-versions.sh +++ b/packages/apps/postgres/hack/update-versions.sh @@ -33,9 +33,10 @@ if ! command -v jq &> /dev/null; then exit 1 fi -# Get available image tags +# Get available image tags. Only standard-trixie builds count: the chart +# appends that suffix to the minor it reads from versions.yaml. echo "Fetching available image tags from registry..." -AVAILABLE_TAGS=$(skopeo list-tags docker://ghcr.io/cloudnative-pg/postgresql | jq -r '.Tags[] | select(test("^[0-9]+\\.[0-9]+$"))' | sort -V) +AVAILABLE_TAGS=$(skopeo list-tags docker://ghcr.io/cloudnative-pg/postgresql | jq -r '.Tags[] | select(test("^[0-9]+\\.[0-9]+-standard-trixie$")) | sub("-standard-trixie$"; "")' | sort -V) if [ -z "$AVAILABLE_TAGS" ]; then echo "Error: Could not fetch available image tags" >&2 diff --git a/packages/apps/postgres/templates/_versions.tpl b/packages/apps/postgres/templates/_versions.tpl index b7cdb8c13..688c16b49 100644 --- a/packages/apps/postgres/templates/_versions.tpl +++ b/packages/apps/postgres/templates/_versions.tpl @@ -16,25 +16,33 @@ {{/* Single source for the operand image: the init Job runs psql against the - Cluster, so both must resolve the same image. + Cluster, so both must resolve the same image, and the Job compares its own + PostgreSQL build with the server's to tell when a new image has rolled out. + + standard-trixie, not the bare tag: a bare tag is the system variant on + Debian bullseye, which upstream stopped building. The standard variant, + because backups go through the barman-cloud plugin and need none of the + barman binaries the system variant adds. trixie, because the postgis + flavor is on it already, so both image families share one Debian release. */}} {{- define "postgres.imageName" -}} {{- if eq (default "postgresql" .Values.flavor) "postgis" -}} ghcr.io/cloudnative-pg/postgis:{{ include "postgres.postgisVersionMap" . | trim }} {{- else -}} -ghcr.io/cloudnative-pg/postgresql:{{ include "postgres.versionMap" . | trim | trimPrefix "v" }} +ghcr.io/cloudnative-pg/postgresql:{{ include "postgres.versionMap" . | trim | trimPrefix "v" }}-standard-trixie {{- end -}} {{- end -}} {{/* - The flavor is fixed at bootstrap. The two image families are built on - different Debian releases, so moving a live cluster from one to the other - swaps glibc under an initialised data directory and silently invalidates - every index on collatable text; the postgis-to-postgresql direction also - drops the shared libraries behind every PostGIS object. CNPG would roll - either change out as an ordinary image update, so refuse it here, before - the Cluster is patched. Only the image name is compared: a minor bump or - a registry mirror rewriting the host must keep passing. + The flavor is fixed at bootstrap. Only the postgis image carries the shared + libraries behind PostGIS objects, so the postgis-to-postgresql direction + leaves every one of them without its code. The two families are also built + and released separately, and nothing keeps their Debian release in step, so + either direction can swap glibc and ICU under an initialised data directory + together with the flavor. CNPG would roll either change out as an ordinary + image update, so refuse it here, before the Cluster is patched. Only the + image name is compared: a minor bump, a move to another variant of the same + family, or a registry mirror rewriting the host must keep passing. A physical recovery carries the same data directory across, so it is held to the same rule. With no live Cluster of its own yet, the release is @@ -49,14 +57,14 @@ ghcr.io/cloudnative-pg/postgresql:{{ include "postgres.versionMap" . | trim | tr {{- if and $live $live.spec $live.spec.imageName -}} {{- $liveName := regexReplaceAll "[:@].*$" (last (splitList "/" $live.spec.imageName)) "" -}} {{- if ne $liveName $wantName -}} -{{- fail (printf "postgres: flavor cannot change on an existing cluster (running %s, requested %s). The image families use different glibc versions, which would corrupt text indexes. Create a new Postgres with the wanted flavor and move the data with a logical dump (pg_dump / pg_restore); restoring a backup keeps the flavor it was taken from." $liveName $wantName) -}} +{{- fail (printf "postgres: flavor cannot change on an existing cluster (running %s, requested %s). Only the postgis image carries the PostGIS libraries, and the two image families can differ in glibc and ICU, which corrupts text indexes. Create a new Postgres with the wanted flavor and move the data with a logical dump (pg_dump / pg_restore); restoring a backup keeps the flavor it was taken from." $liveName $wantName) -}} {{- end -}} {{- else if and .Values.bootstrap.enabled .Values.bootstrap.oldName -}} {{- $source := lookup "postgresql.cnpg.io/v1" "Cluster" .Release.Namespace .Values.bootstrap.oldName -}} {{- if and $source $source.spec $source.spec.imageName -}} {{- $sourceName := regexReplaceAll "[:@].*$" (last (splitList "/" $source.spec.imageName)) "" -}} {{- if ne $sourceName $wantName -}} -{{- fail (printf "postgres: cannot recover a %s backup of %s into the %s flavor. A physical restore keeps the source's glibc and libraries, which would corrupt text indexes. Set flavor to match the source, or create the new Postgres empty and move the data with a logical dump (pg_dump / pg_restore)." $sourceName .Values.bootstrap.oldName $wantName) -}} +{{- fail (printf "postgres: cannot recover a %s backup of %s into the %s flavor. A physical restore carries over a data directory built with the source's libraries: PostGIS objects need the postgis image, and a glibc or ICU difference corrupts text indexes. Set flavor to match the source, or create the new Postgres empty and move the data with a logical dump (pg_dump / pg_restore)." $sourceName .Values.bootstrap.oldName $wantName) -}} {{- end -}} {{- end -}} {{- end -}} diff --git a/packages/apps/postgres/templates/db.yaml b/packages/apps/postgres/templates/db.yaml index 80f141187..7afeb0f16 100644 --- a/packages/apps/postgres/templates/db.yaml +++ b/packages/apps/postgres/templates/db.yaml @@ -176,11 +176,9 @@ spec: The S3/barman settings live in the barmancloud.cnpg.io/ObjectStore CR rendered at the bottom of this file (named after the release); the Cluster only references it by name. Native spec.backup.barmanObjectStore - is deprecated in CNPG 1.27 and removed in 1.29. The bare (system-flavor) - image tags this chart pins still ship the barman-cloud-* binaries the - native path needs (unlike the `standard` variant keycloak-db pins), but - the system flavor is deprecated upstream, so this chart moves to the - plugin as well. + is deprecated in CNPG 1.27 and removed in 1.29, and the standard image + variant this chart pins does not ship the barman-cloud-* binaries the + native path needs; the plugin runs them in a sidecar. */}} {{- $hasInlineCreds := and (ne (default "" .Values.backup.s3AccessKey) "") (ne (default "" .Values.backup.s3SecretKey) "") }} {{- $hasLegacyCreds := or $hasInlineCreds (ne (default "" $credCfg.name) "") }} diff --git a/packages/apps/postgres/templates/init-job.yaml b/packages/apps/postgres/templates/init-job.yaml index 31eb67ff3..26120839c 100644 --- a/packages/apps/postgres/templates/init-job.yaml +++ b/packages/apps/postgres/templates/init-job.yaml @@ -44,7 +44,8 @@ spec: is idempotent and the purged pod stays Pending on the missing mount, so a retry buys nothing. */}} - activeDeadlineSeconds: {{ if .Release.IsInstall }}570{{ else }}540{{ end }} + {{- $deadline := ternary 570 540 .Release.IsInstall }} + activeDeadlineSeconds: {{ $deadline }} backoffLimit: 0 ttlSecondsAfterFinished: 3600 template: @@ -77,6 +78,8 @@ spec: value: "5432" - name: PGDATABASE value: postgres + - name: JOB_DEADLINE + value: {{ $deadline | quote }} securityContext: allowPrivilegeEscalation: false capabilities: diff --git a/packages/apps/postgres/templates/init-script.yaml b/packages/apps/postgres/templates/init-script.yaml index 8787f1961..35b4d3043 100644 --- a/packages/apps/postgres/templates/init-script.yaml +++ b/packages/apps/postgres/templates/init-script.yaml @@ -591,6 +591,255 @@ stringData: EOT {{- end }} {{- end }} + {{- /* + An operand image built on another Debian release ships another glibc and + ICU, and an index ordered by a collation of either library is then + ordered by rules the server no longer applies: lookups miss rows and a + unique index stops seeing duplicates. PostgreSQL records the library + version each collation was created with, so a collation whose recorded + version differs from the one the server reports marks the indexes to + rebuild. The C and POSIX collations carry no version and never qualify, + which is every index of a database this chart created with its defaults. + + PostgreSQL records a collation for an index only where it orders a key. + A collation can also decide what an index holds without ordering it, in + a predicate or inside an expression, and for those the catalog names + the columns the index reads and nothing else. The collations of those + columns therefore count as well. That rebuilds an index or two that did + not need it, and still misses a collation that an expression applies to + a column of another one. + + This pass comes after the ones that manage roles and databases, so + that a rebuild that fails, or does not finish before the Job deadline, + costs none of them. Only the record of an adopted restore follows it: + that record must not be written by a run that failed. + + Helm runs this hook as soon as the Cluster is patched, while CNPG is + still rolling the instances, so the primary may answer from the previous + image for minutes. The Job runs the image the Cluster is moving to, so + the server is on it once both report the same PostgreSQL version and + the same Debian release. The rebuild counter that follows them is left + out: a tag is rebuilt in place, so the Job and an instance can run + different rebuilds of one release for good. Waiting is only worth its + time when an index depends on a versioned collation. The wait ends 120 + seconds before the Job's deadline, which is what a first run keeps for + rebuilding. + + Rebuilds survive a retry: REINDEX CONCURRENTLY gives the index a new + OID, so the highest OID seen when the repair began separates the + indexes still to rebuild from the ones already done. That mark is kept + as a setting of the database, next to a fingerprint of the stale + collations and their new versions, so another library change starts a + new repair. An exclusion constraint's index cannot be rebuilt + concurrently: its table is neither read nor written while it is rebuilt + in place, and it keeps its OID. The same setting therefore records each + attempt at one together with the index's storage file: a file that has + changed since means the index was rebuilt, by a run or by hand, and two + attempts on the same file mean two runs did not finish, after which the + index is left to an operator. The rebuild is given what is left of the + Job and no more, so that the table is not kept locked by a backend the + Job no longer waits for. + + A transaction that stays open on the table makes a rebuild wait for a + lock. That wait is bounded by what is left of the Job as well, so that + no backend is left waiting for a lock after the Job is gone. A + concurrent rebuild that is already running is not cut short: it blocks + nobody, and the index it finishes counts as done. Both bounds keep a + minute in reserve: the deadline counts from the start of the Job, + $SECONDS from the start of this script. + + One index must be rebuilt within one run of the Job, and a retry would + otherwise start a rebuild that cannot finish over and over. An + interrupted or failed REINDEX CONCURRENTLY leaves an invalid index with + a _ccnew suffix on the table, so two of those mean two runs already + failed there: the pass then leaves the table's stale indexes alone + until an operator has dropped the leftovers. A rebuild that succeeds + drops them itself. A failed or + skipped rebuild does not stop the others: the pass reports them and + exits non-zero at the end, with the recorded versions of that database + left as they are. + + A collation that a range partition key depends on is never refreshed: + rebuilding an index does not move a row to the partition the new + ordering assigns it, and the version mismatch PostgreSQL keeps logging + is the only lasting sign of that. Its indexes are still rebuilt, and + again only when another collation of the database goes stale. + Before PostgreSQL 15 the server records no version for a database's + default collation. The version recorded for the libc collation of the + same locale stands in for it there, and is refreshed in its place; the + two are matched as glibc matches them, without regard to the case of + the codeset or a hyphen in it. A locale with no such collation cannot + be checked, which a run that saw the image change says in a warning. + + Every session of the pass pins search_path to pg_catalog: the Job + connects as the superuser, and a function or operator a tenant defined + in public would otherwise be picked wherever its argument types match + a call more exactly than the built-in does. + */}} + + echo "== refresh collation versions" + collation_sql() { + cat <<\EOT + SET client_min_messages = error; + SET search_path = pg_catalog, pg_temp; + SELECT current_setting('server_version_num')::int >= 150000 AS tracks_database \gset + \if :tracks_database + SELECT datcollversion IS NOT NULL AS db_versioned, coalesce(pg_database_collation_actual_version(oid), '') AS db_actual, datcollversion IS NOT NULL AND datcollversion IS DISTINCT FROM pg_database_collation_actual_version(oid) AS db_stale, false AS db_unmatched FROM pg_database WHERE datname = current_database() \gset + \else + SELECT d.datcollate NOT IN ('C', 'POSIX') AS db_versioned, + coalesce(max(pg_collation_actual_version(c.oid)), '') AS db_actual, + coalesce(bool_or(c.collversion IS DISTINCT FROM pg_collation_actual_version(c.oid)), false) AS db_stale, + d.datcollate NOT IN ('C', 'POSIX') AND count(c.oid) = 0 AS db_unmatched + FROM pg_database d + LEFT JOIN pg_collation c ON c.collprovider = 'c' AND lower(replace(c.collcollate, '-', '')) = lower(replace(d.datcollate, '-', '')) AND c.collversion IS NOT NULL AND c.collencoding IN (-1, d.encoding) + WHERE d.datname = current_database() + GROUP BY d.datcollate \gset + \endif + CREATE TEMP TABLE cozystack_collation AS + SELECT v.oid, v.actual, v.stale, + EXISTS (SELECT FROM pg_partitioned_table p WHERE p.partstrat = 'r' AND v.oid = ANY (p.partcollation::oid[])) AS held + FROM ( + SELECT c.oid, coalesce(pg_collation_actual_version(c.oid), '') AS actual, c.collversion IS DISTINCT FROM pg_collation_actual_version(c.oid) AS stale + FROM pg_collation c + WHERE c.collversion IS NOT NULL + AND c.collencoding IN (-1, (SELECT encoding FROM pg_database WHERE datname = current_database())) + UNION ALL + SELECT 100, :'db_actual', :'db_stale'::boolean WHERE :'db_versioned'::boolean + ) v; + CREATE TEMP TABLE cozystack_collation_index AS + SELECT i.indexrelid AS index, bool_or(c.stale) AS stale + FROM ( + SELECT x.indexrelid, k.used FROM pg_index x, unnest(x.indcollation::oid[]) AS k(used) + UNION + SELECT d.objid, d.refobjid FROM pg_depend d WHERE d.classid = 'pg_class'::regclass AND d.refclassid = 'pg_collation'::regclass + UNION + SELECT d.objid, a.attcollation FROM pg_depend d JOIN pg_attribute a ON a.attrelid = d.refobjid AND a.attnum = d.refobjsubid + WHERE d.classid = 'pg_class'::regclass AND d.refclassid = 'pg_class'::regclass AND d.refobjsubid > 0 AND a.attcollation <> 0 + ) u + JOIN cozystack_collation c ON c.oid = u.used + JOIN pg_index i ON i.indexrelid = u.indexrelid + JOIN pg_class r ON r.oid = i.indexrelid + WHERE r.relkind = 'i' AND r.relpersistence <> 't' AND i.indisvalid + GROUP BY 1; + EOT + } + collation_run() { + { collation_sql; cat; } | psql -v ON_ERROR_STOP=1 -q -t -A --dbname "$1" -v moved="$IMAGE_MOVED" + } + IMAGE_MOVED=false + pg_release() { + sed -E 's/^([0-9.]+) \(Debian [^)]*(pgdg[0-9]+)\+[0-9]+\)$/\1 \2/' + } + server_release() { + psql -t -A -c 'SHOW server_version' 2>/dev/null | pg_release + } + JOB_RELEASE=$(psql -V | sed 's/^psql (PostgreSQL) //' | pg_release) + COLLATION_DBS=$(psql -v ON_ERROR_STOP=1 -t -A -c "SELECT datname FROM pg_database WHERE datallowconn AND NOT datistemplate") + if [ "$(server_release)" != "$JOB_RELEASE" ]; then + IMAGE_MOVED=true + DEPENDENT="" + for db in $COLLATION_DBS; do + DEPENDENT="$DEPENDENT$(collation_run "$db" <<\EOT + SELECT index FROM cozystack_collation_index; + EOT + )" + done + if [ -n "$DEPENDENT" ]; then + echo "indexes depend on a versioned collation; waiting for the server to run PostgreSQL $JOB_RELEASE" + until [ "$(server_release)" = "$JOB_RELEASE" ]; do + if [ "$SECONDS" -ge $((JOB_DEADLINE - 120)) ]; then + echo "the server did not move to PostgreSQL $JOB_RELEASE in time (check the rollout of the cnpg.io/Cluster); indexes that depend on a versioned collation are not rebuilt yet - failing the init-job, the next run of it rebuilds them" >&2 + exit 1 + fi + sleep 5 + done + fi + fi + COLLATION_FAILED="" + for db in $COLLATION_DBS; do + PLAN=$(collation_run "$db" <<\EOT + SELECT coalesce(md5(string_agg(oid || '=' || actual, ',' ORDER BY oid)), '') AS fingerprint FROM cozystack_collation WHERE stale \gset + SELECT coalesce(current_setting('cozystack.collation_repair', true), '') AS recorded \gset + SELECT :'fingerprint' <> '' AND split_part(:'recorded', ':', 1) = :'fingerprint' AS resumed \gset + \if :resumed + SELECT split_part(:'recorded', ':', 2) AS mark, split_part(:'recorded', ':', 3) AS inplace \gset + \else + SELECT max(oid)::bigint AS mark, '' AS inplace FROM pg_class \gset + SELECT format('ALTER DATABASE %I SET cozystack.collation_repair = %L', current_database(), :'fingerprint' || ':' || :'mark') WHERE :'fingerprint' <> '' \gexec + \endif + SELECT index::bigint FROM cozystack_collation_index WHERE stale AND index::bigint <= :'mark'::bigint AND NOT EXISTS (SELECT FROM unnest(string_to_array(:'inplace', ',')) AS e JOIN pg_class r ON r.oid = index WHERE split_part(e, '/', 1) = index::text AND split_part(e, '/', 2) <> r.relfilenode::text) ORDER BY pg_relation_size(index); + EOT + ) + DB_FAILED="" + for index in $PLAN; do + LEFT=$((JOB_DEADLINE - SECONDS - 60)) + if [ "$LEFT" -lt 10 ]; then + echo "index $index in database $db was not rebuilt: the init-job is out of time, the next run of it carries on" >&2 + DB_FAILED=yes + continue + fi + if ! psql -v ON_ERROR_STOP=1 -q -t -A --dbname "$db" -v index="$index" -v lock_wait="${LEFT}s" <<\EOT + SET client_min_messages = error; + SET search_path = pg_catalog, pg_temp; + SET lock_timeout = :'lock_wait'; + SELECT count(*) = 1 AS present FROM pg_index WHERE indexrelid = :'index'::oid \gset + \if :present + SELECT coalesce(current_setting('cozystack.collation_repair', true), '') AS recorded \gset + SELECT i.indrelid AS relation, i.indisexclusion AS exclusion, i.indexrelid::regclass AS name, :'index' || '/' || r.relfilenode AS attempt, + (SELECT count(*) FROM pg_index l JOIN pg_class n ON n.oid = l.indexrelid WHERE l.indrelid = i.indrelid AND NOT l.indisvalid AND n.relname ~ '_ccnew[0-9]*$') >= 2 AS abandoned, + (SELECT count(*) FROM unnest(string_to_array(split_part(:'recorded', ':', 3), ',')) AS e WHERE e = :'index' || '/' || r.relfilenode) >= 2 AS abandoned_in_place + FROM pg_index i JOIN pg_class r ON r.oid = i.indexrelid WHERE i.indexrelid = :'index'::oid \gset + \if :abandoned + SELECT format('DO %L', format('BEGIN RAISE EXCEPTION %L, %L; END', '%', format('index %s in database %s was left alone: two earlier runs failed to rebuild an index of its table, and each left an invalid _ccnew index there. Fix what made them fail, then drop those _ccnew indexes; the next run of the init-job rebuilds this one', :'name', current_database()))) \gexec + \endif + \if :exclusion + \if :abandoned_in_place + SELECT format('DO %L', format('BEGIN RAISE EXCEPTION %L, %L; END', '%', format('index %s in database %s was left alone: two earlier runs began rebuilding it in place and did not finish. Rebuild it by hand with REINDEX INDEX, which blocks its table meanwhile; the next run of the init-job sees that it was rebuilt', :'name', current_database()))) \gexec + \endif + SELECT format('rebuilding index %s in database %s in place: its collation changed version', :'name', current_database()); + SELECT format('ALTER DATABASE %I SET cozystack.collation_repair = %L', current_database(), split_part(:'recorded', ':', 1) || ':' || split_part(:'recorded', ':', 2) || ':' || concat_ws(',', nullif(split_part(:'recorded', ':', 3), ''), :'attempt')) WHERE :'recorded' <> '' \gexec + SET statement_timeout = :'lock_wait'; + SELECT format('REINDEX INDEX %s', :'name') \gexec + RESET statement_timeout; + \else + SELECT format('rebuilding index %s in database %s: its collation changed version', :'name', current_database()); + SELECT format('REINDEX INDEX CONCURRENTLY %s', :'name') \gexec + \endif + SELECT format('DROP INDEX CONCURRENTLY IF EXISTS %s', l.indexrelid::regclass) FROM pg_index l JOIN pg_class n ON n.oid = l.indexrelid WHERE l.indrelid = :'relation'::oid AND NOT l.indisvalid AND n.relname ~ '_ccnew[0-9]*$' \gexec + \endif + EOT + then + DB_FAILED=yes + fi + done + if [ -n "$DB_FAILED" ]; then + COLLATION_FAILED="$COLLATION_FAILED $db" + else + collation_run "$db" <<\EOT + SELECT format('WARNING: database %s uses the locale %s, for which this PostgreSQL major records no collation version and the catalog has no collation to stand in; the indexes on its default collation were not checked. If this upgrade moved the image to another Debian release, rebuild them with REINDEX DATABASE', datname, datcollate) FROM pg_database WHERE datname = current_database() AND :'db_unmatched'::boolean AND :'moved'::boolean; + SELECT format('WARNING: %s in database %s is range-partitioned on a key whose collation changed version; rows stored before the change may now belong to another partition, and the collation version is left as recorded until that is checked', p.partrelid::regclass, current_database()) FROM pg_partitioned_table p WHERE p.partstrat = 'r' AND EXISTS (SELECT FROM cozystack_collation c WHERE c.stale AND c.oid = ANY (p.partcollation::oid[])); + DO $$ + DECLARE + entry record; + BEGIN + FOR entry IN SELECT c.oid::regcollation AS name FROM cozystack_collation c WHERE c.stale AND NOT c.held AND c.oid <> 100 + AND NOT (current_setting('server_version_num')::int < 150000 + AND EXISTS (SELECT FROM cozystack_collation d WHERE d.oid = 100 AND d.held) + AND c.oid IN (SELECT n.oid FROM pg_collation n JOIN pg_database d ON d.datname = current_database() WHERE n.collprovider = 'c' AND lower(replace(n.collcollate, '-', '')) = lower(replace(d.datcollate, '-', '')))) LOOP + EXECUTE format('ALTER COLLATION %s REFRESH VERSION', entry.name); + END LOOP; + END$$; + SELECT format('ALTER DATABASE %I REFRESH COLLATION VERSION', current_database()) FROM cozystack_collation WHERE oid = 100 AND stale AND NOT held AND current_setting('server_version_num')::int >= 150000 \gexec + SELECT coalesce(md5(string_agg(oid || '=' || actual, ',' ORDER BY oid)), '') AS remaining FROM cozystack_collation WHERE stale AND held \gset + SELECT CASE WHEN :'remaining' = '' THEN '' ELSE :'remaining' || ':0' END AS settled \gset + SELECT CASE WHEN :'settled' = '' THEN format('ALTER DATABASE %I RESET cozystack.collation_repair', current_database()) ELSE format('ALTER DATABASE %I SET cozystack.collation_repair = %L', current_database(), :'settled') END WHERE coalesce(current_setting('cozystack.collation_repair', true), '') <> :'settled' \gexec + EOT + fi + done + if [ -n "$COLLATION_FAILED" ]; then + echo "index rebuilds failed in:$COLLATION_FAILED (the errors are above); the other indexes were rebuilt. A unique index cannot be rebuilt over rows that the previous ordering kept apart and the new one treats as equal, so remove such duplicates. The next run of the init-job tries again, except for an index an error above reports as left alone" >&2 + exit 1 + fi {{- if .Values.bootstrap.newServerName }} echo "== record the adopted restore" diff --git a/packages/apps/postgres/tests/flavor_test.yaml b/packages/apps/postgres/tests/flavor_test.yaml index a5f740da4..80461d143 100644 --- a/packages/apps/postgres/tests/flavor_test.yaml +++ b/packages/apps/postgres/tests/flavor_test.yaml @@ -1,8 +1,8 @@ suite: postgres image flavor # The Cluster and the init Job must resolve the same image, and a live -# cluster must never be moved to the other flavor: the two image families -# ship different glibc versions, so CNPG would roll an image swap that -# corrupts collatable indexes. Tags are matched by pattern so that +# cluster must never be moved to the other flavor: only one image family +# carries the PostGIS libraries, and CNPG would roll the swap out as an +# ordinary image update. Tags are matched by pattern so that # hack/update-versions.sh can bump minors without touching this suite. release: name: pg-test @@ -20,7 +20,7 @@ tests: asserts: - matchRegex: path: spec.imageName - pattern: ^ghcr\.io/cloudnative-pg/postgresql:18\.[0-9]+$ + pattern: ^ghcr\.io/cloudnative-pg/postgresql:18\.[0-9]+-standard-trixie$ - it: postgis flavor switches the Cluster to the standard-trixie PostGIS image set: From 8208a096165ab998445ea96674f6b66ff2252b9f Mon Sep 17 00:00:00 2001 From: Aleksei Sviridkin Date: Fri, 27 Nov 2026 18:21:49 +0300 Subject: [PATCH 2/7] fix(postgres): skip a stale index while another session builds on its table (#5485) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## What this PR does Refs #5459 (item 4) The collation repair pass in the postgres init Job rebuilds each stale index in its own psql session: it picks the index by OID, takes its name and runs `REINDEX INDEX CONCURRENTLY `. A rebuild started by a run that hit its Job deadline keeps going, because its backend only notices the lost client when the rebuild ends. The next run then lines up behind that orphaned rebuild on the table lock. Once the orphan swaps in the new index, the name resolves to the new, already rebuilt index and the run rebuilds it a second time, holding its table until the new run's own deadline. On PostgreSQL 17 the waiting run can also deadlock with the orphan in its final phase, and the deadlock detector then throws away the orphan's finished build. This PR skips an index while `pg_stat_progress_create_index` shows another backend building an index of its table (same database, other pid). The skip is reported the same way as a failed rebuild, so the run exits non-zero and the next run carries on. That next run finds the new index above the resume mark and treats it as done. The check is the first statement of the session. It runs before the index is looked up by OID and its name taken, with the table taken from `pg_index` by that OID. A rebuild that ended before the check has already removed the index the session looks for, so `present` skips it. An orphaned backend never starts another statement after the check, so it cannot swap the index in between. As a result the check also runs before: - the `_ccnew` leftover count, which a build in progress would otherwise inflate (it owns one invalid `_ccnew` index); - the in-place attempt record of an exclusion constraint's index, so a skip never counts towards leaving that index to an operator. The resume mark, the fingerprint, the `_ccnew` leftover rule and the `lock_timeout`/`statement_timeout` bounds are unchanged. A build that a live session starts after the check, in the moment before REINDEX takes its lock, is not covered: SQL has no way to REINDEX by OID. Only an operator or a tenant racing the Job could hit that window, because an orphaned rebuild cannot start a new statement. ### Screenshots Not a UI change. ### Testing - `helm unittest packages/apps/postgres`: 31 suites, 247 tests passed. - `helm template` renders. The only change in the rendered `init.sh` compared with `main` is the new check. - Ran the repair section of the rendered `init.sh` from `main` and from this branch in Docker (`postgres:17-trixie`). Each init-job run was a separate container on the same network as the database, the way the Job pod and the Cluster are. A run "hit its deadline" by having its container removed while its `REINDEX INDEX CONCURRENTLY` was in the `building index` phase. The index was made stale by setting `collversion = '0'` for `en-x-icu`. The build was slowed deterministically with an expression index over an ICU column through an immutable function that sleeps 1 ms per row (about 2.5 minutes per build). - `main`: run 2 logged `rebuilding index public.t_k` and waited behind the orphaned build. The deadlock detector then cancelled the orphan after its full build (`Process 135 waits for ShareLock on virtual transaction ...; blocked by process 175`), and run 2 rebuilt the index from scratch, so the index was built twice. In the field report on PostgreSQL 18 the orphan finished instead, and the waiting run rebuilt the fresh index a second time. - this branch (check first in the session): run 2 failed at once with `index public.t_k in database postgres was skipped: another session is building an index of its table ...` and exit 1. The orphan finished alone and the index got a new OID. Run 3 rebuilt nothing, refreshed the collation version, reset the repair setting and exited 0, with no invalid indexes left. - Exclusion constraint index (in-place path) on this branch: while another session ran `CREATE INDEX CONCURRENTLY` on the same table, the run skipped the index without recording an in-place attempt. The next run rebuilt it in place (same OID, new relfilenode) and exited 0. - Dev cluster (cozystack v1.7.0): this branch's chart with `17.12-standard-trixie` and 2 instances. A table of 300k rows with the slow expression index over `en-x-icu`, so a `REINDEX INDEX CONCURRENTLY` took about 12 minutes. `en-x-icu` was marked stale with `collversion = '0'`. - Upgrade 1 started the rebuild (`rebuilding index public.t_k ...`). Its init Job was deleted mid-build, and the backend kept building after the Job was gone. - Upgrade 2 while that build ran: the init Job failed at once with `index public.t_k in database postgres was skipped: another session is building an index of its table ...`, without queueing behind the lock. - The orphaned build finished alone (index OID 16453 → 16464). - Upgrade 3: the init Job completed in 10 s with no `rebuilding` line. The OID stayed 16464, the collation version was refreshed, `cozystack.collation_repair` was reset, and no invalid indexes were left. ### Downstream repositories Walked the trigger map against the diff. The PR changes only `packages/apps/postgres/templates/init-script.yaml` (SQL inside the init Job script). It touches no values, schema, README, ApplicationDefinition, package layout, `hack/`, platform keys or names that any listed repository mirrors. - [x] No downstream repository is affected by this change - [ ] [cozystack/website](https://github.com/cozystack/website) - follow-up: - [ ] [cozystack/terraform-provider-cozystack](https://github.com/cozystack/terraform-provider-cozystack) - follow-up: - [ ] [cozystack/ansible-cozystack](https://github.com/cozystack/ansible-cozystack) - follow-up: - [ ] [cozystack/ccp](https://github.com/cozystack/ccp) - follow-up: - [ ] [cozystack/talm](https://github.com/cozystack/talm) - follow-up: - [ ] [cozystack/cozyhr](https://github.com/cozystack/cozyhr) - follow-up: - [ ] [cozystack/cozy-proxy](https://github.com/cozystack/cozy-proxy) - follow-up: - [ ] [cozystack/cozystack-telemetry-server](https://github.com/cozystack/cozystack-telemetry-server) - follow-up: - [ ] [cozystack/external-apps-example](https://github.com/cozystack/external-apps-example) - follow-up: - [ ] [cozystack/examples](https://github.com/cozystack/examples) - follow-up: - [ ] [cozystack/community](https://github.com/cozystack/community) - follow-up: ### Release note ```release-note [postgres] The init Job's collation repair no longer rebuilds an index a second time, or deadlocks with a rebuild left running by an earlier run that hit its deadline; it skips an index while another session builds an index of its table, and the next run of the Job carries on. ``` ## Summary by CodeRabbit * **Bug Fixes** * Collation repair now detects when another session is building a planned index and reports an error identifying the index and database. The database’s repair failure is recorded, rather than proceeding to inspect or rebuild the index during the concurrent operation. This makes the conflict visible in the repair results. (cherry picked from commit 36af0b01104f0ce4c5e08364f309c9d0acac6fa0) Signed-off-by: Andrey Kolkov --- packages/apps/postgres/templates/init-script.yaml | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/packages/apps/postgres/templates/init-script.yaml b/packages/apps/postgres/templates/init-script.yaml index 35b4d3043..efbbfd6eb 100644 --- a/packages/apps/postgres/templates/init-script.yaml +++ b/packages/apps/postgres/templates/init-script.yaml @@ -648,6 +648,17 @@ stringData: minute in reserve: the deadline counts from the start of the Job, $SECONDS from the start of this script. + Such a rebuild outlives the run that started it: its backend does not + notice that the Job is gone until the rebuild ends. REINDEX finds an + index by name, and once it has waited behind that rebuild the name + belongs to the index the rebuild put in place, which would then be + rebuilt a second time. An index is therefore skipped, and reported like + a failed rebuild, while another session builds an index of its table; + the next run finds the new index above the mark. That check comes + first in the session, before the index is looked up: a rebuild that + ended before it has removed the index the session looks for, and an + orphaned one cannot start another after it. + One index must be rebuilt within one run of the Job, and a retry would otherwise start a rebuild that cannot finish over and over. An interrupted or failed REINDEX CONCURRENTLY leaves an invalid index with @@ -782,6 +793,10 @@ stringData: SET client_min_messages = error; SET search_path = pg_catalog, pg_temp; SET lock_timeout = :'lock_wait'; + SELECT EXISTS (SELECT FROM pg_index i JOIN pg_stat_progress_create_index p ON p.relid = i.indrelid JOIN pg_database d ON d.oid = p.datid WHERE i.indexrelid = :'index'::oid AND d.datname = current_database() AND p.pid <> pg_backend_pid()) AS building \gset + \if :building + SELECT format('DO %L', format('BEGIN RAISE EXCEPTION %L, %L; END', '%', format('index %s in database %s was skipped: another session is building an index of its table, as a rebuild left by an earlier run of the init-job does; the next run of the init-job carries on', :'index'::oid::regclass, current_database()))) \gexec + \endif SELECT count(*) = 1 AS present FROM pg_index WHERE indexrelid = :'index'::oid \gset \if :present SELECT coalesce(current_setting('cozystack.collation_repair', true), '') AS recorded \gset From 3b72c8c8f8f0e97207ef6865c0650b4cb00632a1 Mon Sep 17 00:00:00 2001 From: Aleksei Sviridkin Date: Fri, 27 Nov 2026 18:27:52 +0300 Subject: [PATCH 3/7] fix(postgres): update PostGIS extensions after an image upgrade (#5477) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## What this PR does Refs #5459 (item 2) After an upgrade that moves a `postgis` flavor Postgres to a new PostGIS release (3.6.1 to 3.7.0 for v14-v18 on the current `main`), the PostGIS library is new but the SQL objects in every database stay on the old release: `postgis_full_version()` reports `core procs from "3.6.1 ..." need upgrade`. The release notes tell users to run `ALTER EXTENSION postgis UPDATE`, but the init Job created the extensions as the superuser, so the tenant gets `must be owner of extension postgis` and has no way to run the update. The init Job now runs that update. It covers `postgis`, `postgis_raster`, `postgis_topology`, `postgis_sfcgal`, `postgis_tiger_geocoder`, `address_standardizer` and `address_standardizer_data_us` in every connectable database where they are installed: - The target is the `default_version` the server offers, so the pass only runs once the server is on the new image. If the server is already up to date, it does nothing. - Helm starts the hook while CNPG is still rolling the instances. The pass waits until the server offers the PostGIS version that the Job's own image ships, and stops waiting 120 s before the Job deadline (the same bound the collation pass uses). - If the rollout is slower than that, the Job fails. The init Job is a hook, so a run that ends well does not come again before the next change of the release; a failed one makes the release retry once the server runs the new image. The version probe is bounded by `timeout 10`. - `postgis_extensions_upgrade()` is not used: it leaves out `address_standardizer`, and on every call it updates each installed extension to `ANY` and back, even when nothing changed. Each extension gets `ALTER EXTENSION ... UPDATE TO `, with `postgis` first. Each session pins `search_path` to `pg_catalog, pg_temp`. - If the image ships no update path for an extension, the pass prints a warning and leaves it alone. The check uses `pg_extension_update_paths`. - A tenant transaction can hold a lock an update needs, and one update can wait for several in turn. Before each `ALTER EXTENSION`, the session therefore sets `statement_timeout` and `lock_timeout` to what is left of the Job, keeping the same one-minute reserve as the collation pass. So every update, lock waits included, ends before the Job does. A database reached with no time left counts as failed. - The update scripts run as the superuser and write to tables a tenant's admin role is granted `ALL` on, `spatial_ref_sys` among them (the PostGIS 3.7 script inserts into it). A trigger the tenant attached there would run with the superuser's privileges. - The update session therefore sets `session_replication_role = replica`, so triggers enabled the default way (`ENABLE ORIGIN`, what `CREATE TRIGGER` gives) do not fire. - Only the table's owner, the superuser, can enable a trigger `ALWAYS` or `REPLICA`. A database where such a trigger sits on a table of these extensions is not updated and is reported. - A database whose extensions cannot be looked up counts as failed, and the pass continues with the others. - If an update fails, the other databases are still processed and then the Job fails. Under `RetryOnFailure` the release is retried and shows as failed, so the error does not get lost in the log of a Job that is deleted an hour later. The pass runs after the collation repair, so a failure here cannot block index rebuilds. - The section is rendered only for `flavor: postgis`. For the `postgresql` flavor, the rendered `init.sh` is byte-identical to `main`. **Needs a separate decision:** PostGIS 3.7 renamed the `address_standardizer` library (`address_standardizer-3.so` became `address_standardizer.so`) and ships no update path from 3.6.1. As a result, an `address_standardizer` created under 3.6.1 fails after the upgrade with `could not access file "$libdir/address_standardizer-3"`. `ALTER EXTENSION` cannot fix this; only `DROP EXTENSION` followed by `CREATE EXTENSION` as the superuser can. This PR only reports it. Whether the Job should drop and recreate the extension (which risks tenant objects that depend on it) is left to reviewers. ### Testing - Docker, rendered `init.sh` (`helm template --set flavor=postgis`) run with the Job's environment on the `17.12-3.7.0-standard-trixie` image: - Run against a server still on `17.7-3.6.1`: it waited, printed "the server did not move to PostGIS 3.7.0 in time … failing the init-job" and exited 1. - A tenant transaction held open on `geography_columns` in `appdb`, with `JOB_DEADLINE=85`: - the update in `appdb` was cancelled when the budget ran out (`canceling statement due to statement timeout`, 25 s); - `db2`, reached with no time left, was reported as not updated; - the Job exited 1 after 25 s; - after the blocker ended, the next run updated both databases to 3.7.0 and exited 0; - a further run was a no-op. - Tenant trigger: as a non-superuser `appdb_admin` granted `ALL` on `public` tables, a `BEFORE INSERT ... FOR EACH STATEMENT` trigger on `spatial_ref_sys` whose function runs `ALTER ROLE appdb_admin SUPERUSER`. - Without the guard, the update made `appdb_admin` a superuser. - With it, the update to 3.7.0 passed and `appdb_admin` stayed non-superuser. - With the same trigger set `ENABLE ALWAYS` (superuser only), the database was skipped with an error, the Job exited 1, and the role stayed non-superuser. - The same data directory restarted on `17.12-3.7.0`: `postgis`, `postgis_raster`, `postgis_topology` and `postgis_sfcgal` went from 3.6.1 to 3.7.0 and `postgis_tiger_geocoder` from 3.6.1 to 2025.2 in `appdb`; `postgis` went to 3.7.0 in a second database. Afterwards `postgis_full_version()` no longer reports "need upgrade". The md5 of a spatial join and area query was the same before and after. - A second run was a no-op. - A database with a planted conflicting object failed with `function st_x(geometry) is not a member of extension "postgis"`. The other database was still updated, and the Job exited 1. - `flavor: postgresql`: the rendered `init.sh` is identical to `main`. - `helm unittest packages/apps/postgres`: 31 suites, 247 tests passed. - Dev cluster: v1.7.1 chart installed (postgis, v17, 2 replicas, `postgis` in `appdb` at 3.6.1), then `helm upgrade` to this branch: - The first attempt passed (exit 0). The Job logged `waiting for the server to offer PostGIS 3.7.0`, then `updating extension postgis in database appdb from 3.6.1 to 3.7.0`. - Afterwards the image is `17.12-3.7.0-standard-trixie` and `postgis` is 3.7.0, with no "need upgrade" left. A spatial query gave the same md5 as before. - A second upgrade left the PostGIS section empty. **This change is verified only by hand** (Docker and the dev cluster above). No e2e suite upgrades a postgis-flavor release, and one cannot be added without an upgrade harness. ### Downstream repositories The diff only touches `packages/apps/postgres/templates/init-script.yaml`. It adds no values key, schema field, version enum, default, app, CRD, hack script or naming change, so none of the triggers in the map apply. - [x] No downstream repository is affected by this change - [ ] [cozystack/website](https://github.com/cozystack/website) - follow-up: - [ ] [cozystack/terraform-provider-cozystack](https://github.com/cozystack/terraform-provider-cozystack) - follow-up: - [ ] [cozystack/ansible-cozystack](https://github.com/cozystack/ansible-cozystack) - follow-up: - [ ] [cozystack/ccp](https://github.com/cozystack/ccp) - follow-up: - [ ] [cozystack/talm](https://github.com/cozystack/talm) - follow-up: - [ ] [cozystack/cozyhr](https://github.com/cozystack/cozyhr) - follow-up: - [ ] [cozystack/cozy-proxy](https://github.com/cozystack/cozy-proxy) - follow-up: - [ ] [cozystack/cozystack-telemetry-server](https://github.com/cozystack/cozystack-telemetry-server) - follow-up: - [ ] [cozystack/external-apps-example](https://github.com/cozystack/external-apps-example) - follow-up: - [ ] [cozystack/examples](https://github.com/cozystack/examples) - follow-up: - [ ] [cozystack/community](https://github.com/cozystack/community) - follow-up: If a release note on the website tells users to run `ALTER EXTENSION postgis UPDATE` by hand, that note becomes obsolete. I did not find such a note in the trigger map and did not search the website repository. ### Release note ```release-note [postgres] The init Job of a postgis-flavor Postgres now updates the PostGIS extensions in every database once the server runs the new image, so tenants no longer get "must be owner of extension postgis" or stay on outdated PostGIS SQL objects after an upgrade. An address_standardizer created under PostGIS 3.6 has no update path to 3.7 and is reported, not changed. ``` ## Summary by CodeRabbit * **Improvements** * For PostGIS jobs, installed extensions are checked and updated to the version available in the job environment, with dependencies handled in order. * The process waits for the required PostGIS version and skips extensions without a supported update path, reporting a warning. * Databases with relevant always-enabled or replica triggers are rejected. Checks and updates are bounded by the job deadline; failures are collected across databases, and the job reports an error if any database could not be checked or updated. (cherry picked from commit 8e5600d5e3e60f9ecbeda16590908f84c8f6fd13) Signed-off-by: Andrey Kolkov --- .../apps/postgres/templates/init-script.yaml | 120 +++++++++++++++++- 1 file changed, 118 insertions(+), 2 deletions(-) diff --git a/packages/apps/postgres/templates/init-script.yaml b/packages/apps/postgres/templates/init-script.yaml index efbbfd6eb..df28cd863 100644 --- a/packages/apps/postgres/templates/init-script.yaml +++ b/packages/apps/postgres/templates/init-script.yaml @@ -611,8 +611,9 @@ stringData: This pass comes after the ones that manage roles and databases, so that a rebuild that fails, or does not finish before the Job deadline, - costs none of them. Only the record of an adopted restore follows it: - that record must not be written by a run that failed. + costs none of them. Only the PostGIS update and the record of an + adopted restore follow it: that record must not be written by a run + that failed. Helm runs this hook as soon as the Cluster is patched, while CNPG is still rolling the instances, so the primary may answer from the previous @@ -855,6 +856,121 @@ stringData: echo "index rebuilds failed in:$COLLATION_FAILED (the errors are above); the other indexes were rebuilt. A unique index cannot be rebuilt over rows that the previous ordering kept apart and the new one treats as equal, so remove such duplicates. The next run of the init-job tries again, except for an index an error above reports as left alone" >&2 exit 1 fi + {{- if eq .Values.flavor "postgis" }} + {{- /* + A new PostGIS library leaves the SQL objects of every database on the + release they were installed with until ALTER EXTENSION ... UPDATE runs + there, and postgis_full_version() reports them as needing an upgrade + meanwhile. The extensions were created in this Job's superuser session, + so only the superuser owns them and can update them; a tenant gets + "must be owner of extension". This pass updates them in every database + where they are installed, including ones values no longer list. + + The target is the version the server offers, never one rendered here, + so a database only moves to what the running library implements, and + a database already on it is left alone. While CNPG is still rolling the + instances the server offers the previous release and there is nothing + to update yet, so the pass first waits for the server to offer the + PostGIS release the Job's own image ships, until 120 seconds before + the Job's deadline. A rollout that takes longer fails the Job: this Job + is a hook, so a run that ended well would not come again before the + next change of the release, while a failed one makes the release retry. + + postgis_extensions_upgrade() is not used: it leaves out + address_standardizer, and it updates every installed extension to ANY + and back on each call, even when nothing changed. Each extension is + updated on its own instead, postgis before the ones that require it, + in sessions that pin search_path as the collation pass does. A version + the image ships no update path from is reported and left as it is: the + address_standardizer of PostGIS 3.7 has none from earlier releases. + + ALTER EXTENSION is transactional, so an update that fails leaves its + extension as it was. A tenant transaction can hold a lock an update + needs, and one update can wait for several of them in turn, so each + update, its lock waits included, runs no longer than what is left of + the Job, with the same minute in reserve as the collation pass, and a + database reached with no time left counts as failed. The pass carries + on with the other databases and then fails the Job, so that the + release is retried and reported as failed instead of the error staying + in the log of a Job that is deleted an hour later. + + The update scripts run as the superuser and write to tables a tenant's + admin role may attach triggers to (spatial_ref_sys among them), and a + trigger runs with the privileges of the session that fires it. The + update session therefore runs with session_replication_role = replica, + under which triggers enabled the default way do not fire; only a + table's owner, the superuser, can enable one ALWAYS or REPLICA, and a + database where such a trigger sits on a table of these extensions is + not updated. + */}} + + echo "== update postgis extensions" + POSTGIS_SHIPPED=$(sed -n "s/^default_version *= *'\([^']*\)'.*/\1/p" "$(pg_config --sharedir)/extension/postgis.control") + postgis_offered() { + timeout 10 psql -t -A -c "SELECT default_version FROM pg_catalog.pg_available_extensions WHERE name = 'postgis'" 2>/dev/null + } + ALL_DBS=$(psql -v ON_ERROR_STOP=1 -t -A -c "SELECT datname FROM pg_database WHERE datallowconn AND NOT datistemplate") + POSTGIS_DBS="" + POSTGIS_FAILED="" + for db in $ALL_DBS; do + if ! installed=$(psql -v ON_ERROR_STOP=1 -q -t -A --dbname "$db" -c "SET search_path = pg_catalog, pg_temp" -c "SELECT count(*) FROM pg_extension WHERE extname IN ('postgis', 'postgis_raster', 'postgis_topology', 'postgis_sfcgal', 'postgis_tiger_geocoder', 'address_standardizer', 'address_standardizer_data_us')"); then + echo "the PostGIS extensions in database $db were not checked (the error is above); the next run of the init-job carries on" >&2 + POSTGIS_FAILED="$POSTGIS_FAILED $db" + continue + fi + if [ "$installed" != 0 ]; then + POSTGIS_DBS="$POSTGIS_DBS $db" + fi + done + if [ -n "$POSTGIS_DBS" ] && [ -n "$POSTGIS_SHIPPED" ] && [ "$(postgis_offered)" != "$POSTGIS_SHIPPED" ]; then + echo "waiting for the server to offer PostGIS $POSTGIS_SHIPPED" + until [ "$(postgis_offered)" = "$POSTGIS_SHIPPED" ]; do + if [ "$SECONDS" -ge $((JOB_DEADLINE - 120)) ]; then + echo "the server did not move to PostGIS $POSTGIS_SHIPPED in time (check the rollout of the cnpg.io/Cluster); the PostGIS extensions are not updated yet - failing the init-job, the next run of it updates them" >&2 + exit 1 + fi + sleep 5 + done + fi + for db in $POSTGIS_DBS; do + LEFT=$((JOB_DEADLINE - SECONDS - 60)) + if [ "$LEFT" -lt 10 ]; then + echo "the PostGIS extensions in database $db were not updated: the init-job is out of time, the next run of it carries on" >&2 + POSTGIS_FAILED="$POSTGIS_FAILED $db" + continue + fi + if ! psql -v ON_ERROR_STOP=1 -q -t -A --dbname "$db" -v lock_wait="${LEFT}s" <<\EOT + SET client_min_messages = warning; + SET search_path = pg_catalog, pg_temp; + SET lock_timeout = :'lock_wait'; + SET session_replication_role = replica; + SELECT EXISTS (SELECT FROM pg_trigger t JOIN pg_depend d ON d.classid = 'pg_class'::regclass AND d.objid = t.tgrelid AND d.deptype = 'e' JOIN pg_extension x ON x.oid = d.refobjid WHERE NOT t.tgisinternal AND t.tgenabled IN ('A', 'R') AND x.extname IN ('postgis', 'postgis_raster', 'postgis_topology', 'postgis_sfcgal', 'postgis_tiger_geocoder', 'address_standardizer', 'address_standardizer_data_us')) AS armed \gset + \if :armed + SELECT format('DO %L', format('BEGIN RAISE EXCEPTION %L, %L; END', '%', format('the PostGIS extensions in database %s were not updated: a table of theirs carries a trigger enabled ALWAYS or REPLICA, which would run inside the superuser update; drop that trigger, and the next run of the init-job updates them', current_database()))) \gexec + \endif + SELECT clock_timestamp() + :'lock_wait'::interval AS deadline_at \gset + CREATE TEMP TABLE cozystack_postgis AS + SELECT e.extname, e.extversion, a.default_version, f.position, + EXISTS (SELECT FROM pg_extension_update_paths(e.extname) p WHERE p.source = e.extversion AND p.target = a.default_version AND p.path IS NOT NULL) AS reachable + FROM unnest(ARRAY['postgis', 'postgis_raster', 'postgis_topology', 'postgis_sfcgal', 'postgis_tiger_geocoder', 'address_standardizer', 'address_standardizer_data_us']::name[]) WITH ORDINALITY AS f(name, position) + JOIN pg_extension e ON e.extname = f.name + JOIN pg_available_extensions a ON a.name = e.extname + WHERE e.extversion <> a.default_version; + SELECT format('WARNING: extension %s in database %s stays at version %s: the image ships no update path from it to %s', extname, current_database(), extversion, default_version) FROM cozystack_postgis WHERE NOT reachable ORDER BY position; + SELECT format('updating extension %s in database %s from %s to %s', extname, current_database(), extversion, default_version) FROM cozystack_postgis WHERE reachable ORDER BY position; + SELECT format('DO %L', format('BEGIN PERFORM set_config(%L, greatest(1, floor(extract(epoch FROM %L::timestamptz - clock_timestamp()) * 1000))::bigint::text, false); PERFORM set_config(%L, current_setting(%L), false); END', 'statement_timeout', :'deadline_at', 'lock_timeout', 'statement_timeout')), + format('ALTER EXTENSION %I UPDATE TO %L', extname, default_version) + FROM cozystack_postgis WHERE reachable ORDER BY position \gexec + EOT + then + POSTGIS_FAILED="$POSTGIS_FAILED $db" + fi + done + if [ -n "$POSTGIS_FAILED" ]; then + echo "PostGIS extension updates failed in:$POSTGIS_FAILED (the errors are above); the extensions there stay at their previous version. The next run of the init-job tries again" >&2 + exit 1 + fi + {{- end }} {{- if .Values.bootstrap.newServerName }} echo "== record the adopted restore" From 1a10524bed5a397ec886bbd936a36d3537a9c874 Mon Sep 17 00:00:00 2001 From: Aleksei Sviridkin Date: Fri, 27 Nov 2026 18:42:08 +0300 Subject: [PATCH 4/7] fix(postgres): keep bullseye clusters on their image until a clean locale check (#5472) Refs #5459. Part of bringing #5405 (standard-trixie images) back to release-1.7, which #5461 reverted. This PR covers the `C.UTF-8` item of fixed separately: the repair racing the rollout and the Job budget, the repair skipping `C.UTF-8`, the double REINDEX, and the postgis extension update. Clusters created before #5405 run a bare tag, the system variant on Debian bullseye. Moving them to `standard-trixie` changes glibc and ICU under the data directory. The collation repair pass from #5405 cannot see every case. A libc `C.*` locale such as `C.UTF-8` carries no collation version in any PostgreSQL major, yet Debian bullseye's `C.UTF-8` and the one in glibc 2.35+ sort differently. Until the indexes are rebuilt, replicas return wrong results through `-ro` and unique indexes accept duplicates. PostgreSQL ([Locale data changes](https://wiki.postgresql.org/wiki/Locale_data_changes)) and CloudNativePG ([postgres-containers](https://github.com/cloudnative-pg/postgres-containers): switching the Debian base "is a manual operation because of PostgreSQL locale-data implications") both treat this as a deliberate, owner-driven step. A cluster on one of the bare bullseye tags the chart shipped (13.22, 14.20, 15.15, 16.11, 17.7, 18.1) stays on its image until a check finds it clean. The check fails closed: a cluster not checked yet, one the check could not finish on, and one it found affected all stay. - **The check.** A `pre-upgrade` hook (`locale-check--`) runs before every upgrade of such a cluster, from the cluster's current image. - It looks in every database for columns, indexes, composite or range types, and `jsonb` indexes that depend on a collation other than C, POSIX or builtin, and for a database default (collate or ctype) outside those. - It records `clean`, `affected` or `unknown` in the `postgres.cozystack.io/locale-data` annotation of the Cluster, and the first objects found in `postgres.cozystack.io/locale-data-objects`. - Its Role can only `get`/`patch` that one Cluster. - **What the chart renders.** The chart reads the recorded answer through `lookup`. Helm renders before hooks run, so the hook fails an attempt only when the new answer contradicts that render, before the Cluster is patched. The HelmRelease retry then renders according to the new answer: - A cluster not checked before, or found `affected` or `unknown`, is rendered on its current image. The upgrade passes, and every other value of the app still applies. - A cluster found `clean` fails that attempt once, and the retry moves it to `standard-trixie` with the existing repair. - **Opt-in.** `allowCollationChange: true` moves a held cluster on the next upgrade, in a window the owner picks. - **Version changes.** A held cluster refuses a change of `version` with an explicit render error, since new majors are built only on the new images. - **Restore.** The CNPG backup driver copies the source Cluster's `spec.imageName` into the backup snapshot verbatim, passes it to the restore as `bootstrap.sourceImageName`, and clears it with `bootstrap.enabled`. The core controller knows nothing about the chart's hold rules. - The chart decides: a backup taken on one of the bullseye tags restores onto that image, so the data keeps the library that built it. - The next upgrade then checks the restored data like any other bullseye cluster. - Any other value is ignored, so a tenant cannot choose an image through it. - The driver also reads the major from that image tag when the backup recorded none, and refuses a mismatch with `spec.version` before the purge. - It keeps running its bare bullseye tag. Upstream builds new PostgreSQL minors only on bookworm and trixie, so a held cluster gets **no further minors and none of their security fixes; CVE-2026-116331 stays open on it** for as long as it is held. - The tenant sees only that the image did not change. The answer and the objects found are on the cnpg.io Cluster, which only an administrator can read. - There is no deadline. The hold lasts until the owner takes one of the ways out below. 1. **Remove the dependency.** Move the listed columns and indexes to `C`, or to the builtin `pg_c_utf8` on PostgreSQL 17 and later, or drop them. The next upgrade checks again, finds the cluster `clean` and moves it. 2. **Move explicitly.** In a maintenance window, set `allowCollationChange: true`. The next upgrade moves the cluster and the init Job's repair rebuilds indexes on versioned collations (ICU, libc locales other than `C.*`). Until the separate `C.UTF-8` repair fix lands, rebuild indexes on `C.UTF-8` or another `C.*` locale by hand with `REINDEX INDEX CONCURRENTLY`. Range partitions, CHECK constraints and materialized views on such text are not fixed by a rebuild and need a logical move (pg_dump/restore or logical replication). During the move, replicas restart on the new image first, so reads through `-ro` can be wrong and unique indexes can accept duplicates until the primary's rebuild is done. - `helm unittest packages/apps/postgres`: 276 passed, including `tests/locale_guard_test.yaml`. It covers: - holding on `affected`, `unknown` and a missing result, and moving on `clean`; - the opt-in and the version refusal; - restores from bullseye and trixie backups, hand-set recoveries, and leftover values; - ignoring foreign images, postgis, hook gating, naming and the Role scope. - `go test ./internal/backupcontroller/...` passes, including `cnpg_source_image_test.go` and the restore reconcile cases for passing the image on and refusing the held major before the purge. - The check script was run in Docker against `postgres:13-bullseye` and `postgres:18-bookworm`: - It flags `C.UTF-8`/`C.utf8` columns and defaults, ICU indexes, `en_US` defaults with text, a `C`-collate / `en_US`-ctype database with a `lower()` index, composite and range types over text, and `jsonb` indexes under a non-C default. - It reports `clean` for `C`, `POSIX`, `pg_c_utf8` and `ucs_basic`, and when another database is `default_transaction_read_only`. - It reports `unknown` on an authentication failure or when a database accepts no connections. - The record step was run with a stub `kubectl` for each render (held or moving) and answer: - held + `clean` fails the attempt; held + `affected`/`unknown` passes; - moving + `clean` passes; moving + `affected`/`unknown` fails the attempt; - every answer is recorded. - Dev cluster: apps installed from the v1.7.1 chart (`postgresql:17.7`, bullseye) and upgraded to this branch (results in the PR thread). The trigger map hits `cozystack/terraform-provider-cozystack`, because this adds `allowCollationChange` and `bootstrap.sourceImageName` to the postgres `values.schema.json`. The follow-up is cozystack/terraform-provider-cozystack#91. - [ ] No downstream repository is affected by this change - [ ] [cozystack/website](https://github.com/cozystack/website) - follow-up: - [x] [cozystack/terraform-provider-cozystack](https://github.com/cozystack/terraform-provider-cozystack) - follow-up: cozystack/terraform-provider-cozystack#91 - [ ] [cozystack/ansible-cozystack](https://github.com/cozystack/ansible-cozystack) - follow-up: - [ ] [cozystack/ccp](https://github.com/cozystack/ccp) - follow-up: - [ ] [cozystack/talm](https://github.com/cozystack/talm) - follow-up: - [ ] [cozystack/cozyhr](https://github.com/cozystack/cozyhr) - follow-up: - [ ] [cozystack/cozy-proxy](https://github.com/cozystack/cozy-proxy) - follow-up: - [ ] [cozystack/cozystack-telemetry-server](https://github.com/cozystack/cozystack-telemetry-server) - follow-up: - [ ] [cozystack/external-apps-example](https://github.com/cozystack/external-apps-example) - follow-up: - [ ] [cozystack/examples](https://github.com/cozystack/examples) - follow-up: - [ ] [cozystack/community](https://github.com/cozystack/community) - follow-up: ```release-note [postgres] A cluster still on a Debian bullseye image now stays on that image until a pre-upgrade check finds nothing in it that depends on a collation other than C, POSIX or builtin (an ICU or libc locale, or C.UTF-8), or until `allowCollationChange` is set. A held cluster gets no further PostgreSQL minors or their security fixes. The `postgres.cozystack.io/locale-data` annotation of the cnpg.io Cluster shows the result of the check. ``` - **New Features** - PostgreSQL upgrades from older Debian Bullseye images now check for collation-dependent data and hold the current image when results are affected or unknown. - Added an opt-in setting to allow the image change despite the collation check. Review collation and index-rebuild considerations before enabling it. - PostgreSQL restores retain source-image information to support image selection and compatibility checks. On release-1.7 the CNPG backup driver predates the backup destination and artifact-size changes this builds on on main, so only the image handling is ported: the live Cluster's spec.imageName goes into the backup snapshot, the restore passes it to the chart as bootstrap.sourceImageName and clears it with bootstrap.enabled, and the backup's major is read from that image when the backup recorded none. The tests for the destination and artifact size are not part of this line. (cherry picked from commit 9cf93b85353ba4bc2ff01d4d31635d7ebf88c83d) Signed-off-by: Andrey Kolkov --- api/apps/v1alpha1/postgresql/types.go | 6 + .../cnpg_source_image_test.go | 103 ++++ .../cnpgstrategy_controller.go | 60 +- .../cnpgstrategy_controller_test.go | 57 +- .../backupcontroller/postgresapp/types.go | 13 +- packages/apps/postgres/README.md | 44 +- .../apps/postgres/templates/_versions.tpl | 90 +++ .../postgres/templates/locale-check-hook.yaml | 263 +++++++++ .../postgres/tests/locale_guard_test.yaml | 526 ++++++++++++++++++ packages/apps/postgres/values.schema.json | 10 + packages/apps/postgres/values.yaml | 5 + .../system/postgres-rd/cozyrds/postgres.yaml | 4 +- 12 files changed, 1122 insertions(+), 59 deletions(-) create mode 100644 internal/backupcontroller/cnpg_source_image_test.go create mode 100644 packages/apps/postgres/templates/locale-check-hook.yaml create mode 100644 packages/apps/postgres/tests/locale_guard_test.yaml diff --git a/api/apps/v1alpha1/postgresql/types.go b/api/apps/v1alpha1/postgresql/types.go index 70beb678e..e05f2f350 100644 --- a/api/apps/v1alpha1/postgresql/types.go +++ b/api/apps/v1alpha1/postgresql/types.go @@ -43,6 +43,9 @@ type ConfigSpec struct { // PostgreSQL image flavor, fixed when the cluster is created. `postgresql` uses the CloudNativePG PostgreSQL image. `postgis` uses the CloudNativePG PostGIS image, which adds postgis, postgis_raster, postgis_topology, postgis_sfcgal, postgis_tiger_geocoder and address_standardizer; enable them per database in `databases..extensions`. Changing the flavor of an existing cluster is refused, and a backup restores only into a cluster of the flavor it was taken from: to change flavor, create a new cluster and move the data with a logical dump (pg_dump / pg_restore). // +kubebuilder:default:="postgresql" Flavor Flavor `json:"flavor"` + // Allow a cluster created on a Debian bullseye image (before the move to standard-trixie) to move to the new image without a clean locale check. Such a cluster is checked before each upgrade, except while `bootstrap.enabled` is set (set it back to false once a restore set up by hand has finished), and stays on its current image until the check finds nothing that depends on a collation other than C, POSIX or builtin: while this is false, a cluster the check found affected (an ICU or libc locale, or C.UTF-8) or could not finish on stays put, because glibc and ICU on the new image sort text differently and every index on such text must be rebuilt. A held cluster runs the bare bullseye tag it has, gets no further PostgreSQL minors and so none of their security fixes, and refuses a change of `version`, since new majors are built only on the new images. To leave that state, either remove the dependency (move such columns and indexes to C, or to the builtin `pg_c_utf8` on PostgreSQL 17 and later) and let the next upgrade check again, or set this to true in a maintenance window: the cluster moves on the next upgrade, replicas restart on the new image first and can return wrong results through `-ro`, and unique indexes can accept duplicates, until the indexes are rebuilt on the primary. The init Job rebuilds only indexes on collations that record a version (ICU, and libc locales other than C.*): rebuild indexes on C.UTF-8 or another C.* locale by hand with REINDEX, and check range partitions, CHECK constraints and materialized views on such text, which a rebuild does not fix. A held cluster shows the hold only as an unchanged image; the result and the objects found are in the `postgres.cozystack.io/locale-data` and `postgres.cozystack.io/locale-data-objects` annotations of the cnpg.io Cluster, which an administrator can read. A restore of a backup taken on one of those bullseye images comes back on that image and is checked by the next upgrade. + // +kubebuilder:default:=false + AllowCollationChange bool `json:"allowCollationChange"` // TLS configuration for server connections. // +kubebuilder:default:={} Tls TLS `json:"tls"` @@ -151,6 +154,9 @@ type Bootstrap struct { // Server name (S3 path prefix) used by the original cluster when writing backups; passed to the barman-cloud plugin via `externalClusters[].plugin.parameters.serverName`. Defaults to `bootstrap.oldName`. Set this only when the original cluster wrote backups under an explicit server name that differed from its Kubernetes resource name. // +kubebuilder:default:="" ServerName string `json:"serverName,omitempty"` + // Image of the cluster the backup was taken from. A restore of a backup taken on one of the bare Debian bullseye tags the chart used before standard-trixie comes back on that image (see `allowCollationChange`); any other value is ignored. The CNPG backup driver sets this on restore and clears it with `enabled`. + // +kubebuilder:default:="" + SourceImageName string `json:"sourceImageName,omitempty"` } type Database struct { diff --git a/internal/backupcontroller/cnpg_source_image_test.go b/internal/backupcontroller/cnpg_source_image_test.go new file mode 100644 index 000000000..7c4128f2b --- /dev/null +++ b/internal/backupcontroller/cnpg_source_image_test.go @@ -0,0 +1,103 @@ +package backupcontroller + +import ( + "context" + "testing" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/client-go/kubernetes/scheme" + clientfake "sigs.k8s.io/controller-runtime/pkg/client/fake" + + strategyv1alpha1 "github.com/cozystack/cozystack/api/backups/strategy/v1alpha1" + backupsv1alpha1 "github.com/cozystack/cozystack/api/backups/v1alpha1" + cnpgtypes "github.com/cozystack/cozystack/internal/backupcontroller/cnpgtypes" + "github.com/cozystack/cozystack/internal/backupcontroller/postgresapp" +) + +func TestApplyClusterPluginBackup_RecordsImageName(t *testing.T) { + for _, image := range []string{"ghcr.io/cloudnative-pg/postgresql:17.7", "ghcr.io/cloudnative-pg/postgresql:17.12-standard-trixie"} { + t.Run(image, func(t *testing.T) { + cluster := &cnpgtypes.Cluster{ + ObjectMeta: metav1.ObjectMeta{Namespace: "tenant", Name: "postgres-app", UID: "cluster-uid-123"}, + } + cluster.Spec.ImageName = image + c := newCNPGStrategyTestClient(t, cluster) + r := &BackupJobReconciler{Client: c, Interface: cnpgDynamicFor(t, cluster)} + tmpl := &strategyv1alpha1.CNPGTemplate{ + BarmanObjectStore: strategyv1alpha1.BarmanObjectStoreTemplate{DestinationPath: "s3://bucket/x/"}, + } + + got, err := r.applyClusterPluginBackup(context.Background(), "tenant", "postgres-app", tmpl, "strategy-name", true) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if got.imageName != image { + t.Fatalf("imageName = %q, want %q", got.imageName, image) + } + }) + } +} + +func TestCNPGBackupSnapshot_CarriesImageName(t *testing.T) { + raw, err := marshalCNPGBackupSnapshot(newPostgresApp("pg", "tenant"), nil, "postgresql", "ghcr.io/cloudnative-pg/postgresql:17.7") + if err != nil { + t.Fatalf("marshal snapshot: %v", err) + } + snap, err := unmarshalCNPGBackupSnapshot(&backupsv1alpha1.Backup{Status: backupsv1alpha1.BackupStatus{UnderlyingResources: raw}}) + if err != nil { + t.Fatalf("unmarshal snapshot: %v", err) + } + if snap.ImageName != "ghcr.io/cloudnative-pg/postgresql:17.7" { + t.Fatalf("ImageName = %q", snap.ImageName) + } +} + +func TestBuildPostgresAppRestorePatch_SetsAndClearsSourceImage(t *testing.T) { + app := newPostgresApp("pg", "tenant") + app.Spec.Bootstrap.SourceImageName = "ghcr.io/cloudnative-pg/postgresql:16.11" + + if got := buildPostgresAppRestorePatch(app, "src", "pg-new", "s3://b/", "", "", "", nil, nil, nil, nil, "ghcr.io/cloudnative-pg/postgresql:17.7").Spec.Bootstrap.SourceImageName; got != "ghcr.io/cloudnative-pg/postgresql:17.7" { + t.Errorf("bootstrap.sourceImageName: got %q", got) + } + if got := buildPostgresAppRestorePatch(app, "src", "pg-new", "s3://b/", "", "", "", nil, nil, nil, nil, "").Spec.Bootstrap.SourceImageName; got != "" { + t.Errorf("bootstrap.sourceImageName from a previous restore must be cleared; got %q", got) + } +} + +func TestDisablePostgresAppBootstrap_ClearsSourceImage(t *testing.T) { + app := newPostgresApp("pg", "tenant") + app.Spec.Bootstrap.Enabled = true + app.Spec.Bootstrap.SourceImageName = "ghcr.io/cloudnative-pg/postgresql:17.7" + s := runtime.NewScheme() + _ = scheme.AddToScheme(s) + _ = postgresapp.AddToScheme(s) + r := &RestoreJobReconciler{Client: clientfake.NewClientBuilder().WithScheme(s).WithObjects(app).Build()} + + if err := r.disablePostgresAppBootstrap(context.Background(), "tenant", "pg"); err != nil { + t.Fatalf("disable bootstrap: %v", err) + } + got, err := r.getPostgresApp(context.Background(), "tenant", "pg") + if err != nil { + t.Fatalf("get app: %v", err) + } + if got.Spec.Bootstrap.Enabled || got.Spec.Bootstrap.SourceImageName != "" { + t.Fatalf("bootstrap after disable: enabled=%v sourceImageName=%q", got.Spec.Bootstrap.Enabled, got.Spec.Bootstrap.SourceImageName) + } +} + +func TestCNPGImageMajor(t *testing.T) { + for image, want := range map[string]int{ + "ghcr.io/cloudnative-pg/postgresql:17.7": 17, + "ghcr.io/cloudnative-pg/postgresql:13.22": 13, + "ghcr.io/cloudnative-pg/postgresql:17.12-standard-trixie": 17, + "ghcr.io/cloudnative-pg/postgis:17-3.6.1-standard-trixie": 17, + "ghcr.io/cloudnative-pg/postgresql:18.1@sha256:0123": 18, + "ghcr.io/cloudnative-pg/postgresql": 0, + "": 0, + } { + if got := cnpgImageMajor(image); got != want { + t.Errorf("cnpgImageMajor(%q) = %d, want %d", image, got, want) + } + } +} diff --git a/internal/backupcontroller/cnpgstrategy_controller.go b/internal/backupcontroller/cnpgstrategy_controller.go index 31e8fddfd..0c02efcd3 100644 --- a/internal/backupcontroller/cnpgstrategy_controller.go +++ b/internal/backupcontroller/cnpgstrategy_controller.go @@ -431,7 +431,7 @@ func (r *BackupJobReconciler) reconcileCNPG(ctx context.Context, j *backupsv1alp if j.Status.BackupRef != nil { return ctrl.Result{}, nil } - artifact, err := r.createCNPGBackupArtifact(ctx, j, resolved, cnpgBackup, clusterName, serverName, attachment.flavor, rendered, app) + artifact, err := r.createCNPGBackupArtifact(ctx, j, resolved, cnpgBackup, clusterName, serverName, attachment.flavor, attachment.imageName, rendered, app) if err != nil { return r.markBackupJobFailed(ctx, j, fmt.Sprintf("failed to create Backup artifact: %v", err)) } @@ -616,6 +616,7 @@ func (r *BackupJobReconciler) applyClusterPluginBackup(ctx context.Context, name attachment := cnpgPluginAttachment{ serverName: serverName, flavor: cnpgImageFlavor(existing.Spec.ImageName), + imageName: existing.Spec.ImageName, clusterStatus: existing.Status, } if live := currentBarmanServerName(existing); live != "" { @@ -672,6 +673,9 @@ type cnpgPluginAttachment struct { serverName string // flavor is the image flavor the live Cluster runs. flavor string + // imageName is the live Cluster's spec.imageName, see + // cnpgBackupSnapshot.ImageName. + imageName string // missing reports a Cluster that carried no barman-cloud plugin. missing bool clusterStatus cnpgtypes.ClusterStatus @@ -811,7 +815,7 @@ func (r *BackupJobReconciler) createCNPGBackupArtifact( j *backupsv1alpha1.BackupJob, resolved *ResolvedBackupConfig, cnpgBackup *cnpgtypes.Backup, - clusterName, serverName, flavor string, + clusterName, serverName, flavor, imageName string, rendered *strategyv1alpha1.CNPGTemplate, sourceApp *postgresapp.Postgres, ) (*backupsv1alpha1.Backup, error) { @@ -836,7 +840,7 @@ func (r *BackupJobReconciler) createCNPGBackupArtifact( driverMD[cnpgMajorVersionKey] = strconv.Itoa(cnpgBackup.Status.MajorVersion) } - underlyingResources, err := marshalCNPGBackupSnapshot(sourceApp, resolved.Parameters, flavor) + underlyingResources, err := marshalCNPGBackupSnapshot(sourceApp, resolved.Parameters, flavor, imageName) if err != nil { return nil, fmt.Errorf("encode source snapshot for Backup.status.underlyingResources: %w", err) } @@ -1050,6 +1054,12 @@ func (r *RestoreJobReconciler) reconcileCNPGRestore(ctx context.Context, restore if err != nil { return ctrl.Result{}, err } + if backupMajor == 0 { + // The chart restores a backup taken on a held bullseye image onto + // that image and refuses one of another major than spec.version, + // which would wedge the restore after the purge. + backupMajor = cnpgImageMajor(snapshot.ImageName) + } targetMajor := postgresAppMajorVersion(targetApp.Spec.Version) switch { case backupMajor == 0 || targetMajor == 0: @@ -1158,7 +1168,7 @@ func (r *RestoreJobReconciler) reconcileCNPGRestore(ctx context.Context, restore logger.Info("restored WAL-archive serverName collided with the recovery source", "cluster", clusterName, "serverName", newServerName) } - if err := r.patchPostgresAppForRestore(ctx, targetApp, sourceServerName, newServerName, sourceDestinationPath, sourceEndpointURL, options.RecoveryTime, backupID, rendered.BarmanObjectStore.S3Credentials, rendered.BarmanObjectStore.EndpointCA, sourceDatabases, sourceUsers); err != nil { + if err := r.patchPostgresAppForRestore(ctx, targetApp, sourceServerName, newServerName, sourceDestinationPath, sourceEndpointURL, options.RecoveryTime, backupID, rendered.BarmanObjectStore.S3Credentials, rendered.BarmanObjectStore.EndpointCA, sourceDatabases, sourceUsers, snapshot.ImageName); err != nil { // Resume HR before terminal failure so an operator deleting // the failed RestoreJob does not leave the HR stuck. _ = r.setCNPGRestoreHRSuspended(ctx, target.Namespace, hrName, false) @@ -1469,8 +1479,9 @@ func (r *RestoreJobReconciler) patchPostgresAppForRestore( caRef *strategyv1alpha1.EndpointCARef, sourceDatabases map[string]postgresapp.Database, sourceUsers map[string]postgresapp.User, + sourceImageName string, ) error { - patched := buildPostgresAppRestorePatch(app, sourceServerName, newServerName, sourceDestinationPath, sourceEndpointURL, recoveryTime, backupID, credsRef, caRef, sourceDatabases, sourceUsers) + patched := buildPostgresAppRestorePatch(app, sourceServerName, newServerName, sourceDestinationPath, sourceEndpointURL, recoveryTime, backupID, credsRef, caRef, sourceDatabases, sourceUsers, sourceImageName) return r.Patch(ctx, patched, client.MergeFrom(app), client.FieldOwner(cnpgFieldManager)) } @@ -1497,6 +1508,9 @@ func (r *RestoreJobReconciler) disablePostgresAppBootstrap(ctx context.Context, } patched := app.DeepCopy() patched.Spec.Bootstrap.Enabled = false + // The restored Cluster runs that image from here on; left in the spec, the + // value would outlive the Cluster's own image once it moves. + patched.Spec.Bootstrap.SourceImageName = "" return r.Patch(ctx, patched, client.MergeFrom(app), client.FieldOwner(cnpgFieldManager)) } @@ -1531,6 +1545,7 @@ func buildPostgresAppRestorePatch( caRef *strategyv1alpha1.EndpointCARef, sourceDatabases map[string]postgresapp.Database, sourceUsers map[string]postgresapp.User, + sourceImageName string, ) *postgresapp.Postgres { patched := app.DeepCopy() patched.Spec.Bootstrap.Enabled = true @@ -1541,6 +1556,9 @@ func buildPostgresAppRestorePatch( patched.Spec.Bootstrap.NewServerName = newServerName patched.Spec.Bootstrap.RecoveryTime = recoveryTime patched.Spec.Bootstrap.BackupID = backupID + // Set or cleared on every restore: a value left by an earlier restore of + // another backup would name an image this one was not taken on. + patched.Spec.Bootstrap.SourceImageName = sourceImageName patched.Spec.Backup.DestinationPath = sourceDestinationPath patched.Spec.Backup.EndpointURL = sourceEndpointURL @@ -1608,6 +1626,10 @@ func buildPostgresAppRestorePatch( // safely onto the same family: the two ship different glibc versions, which // invalidates collatable indexes, and postgis objects need the postgis // libraries. +// +// ImageName is the source Cluster's spec.imageName, handed to the chart on +// restore as bootstrap.sourceImageName: the chart decides whether recovered +// data has to stay on the image that built it. type cnpgBackupSnapshot struct { Kind string `json:"kind"` APIVersion string `json:"apiVersion"` @@ -1615,6 +1637,31 @@ type cnpgBackupSnapshot struct { Users map[string]postgresapp.User `json:"users,omitempty"` Parameters map[string]string `json:"parameters,omitempty"` Flavor string `json:"flavor,omitempty"` + ImageName string `json:"imageName,omitempty"` +} + +// cnpgImageMajor reads the PostgreSQL major from a CloudNativePG operand +// image, whose tags all start with it (17.7, 17.12-standard-trixie, +// 17-3.6.1-standard-trixie); 0 when the tag does not. +func cnpgImageMajor(image string) int { + name := image[strings.LastIndex(image, "/")+1:] + if i := strings.Index(name, "@"); i >= 0 { + name = name[:i] + } + i := strings.Index(name, ":") + if i < 0 { + return 0 + } + tag := name[i+1:] + end := strings.IndexFunc(tag, func(r rune) bool { return r < '0' || r > '9' }) + if end < 0 { + end = len(tag) + } + major, err := strconv.Atoi(tag[:end]) + if err != nil { + return 0 + } + return major } const cnpgBackupSnapshotKind = "CNPGBackupSnapshot" @@ -1629,7 +1676,7 @@ var cnpgBackupSnapshotAPIVersion = backupsv1alpha1.GroupVersion.String() // runtime.RawExtension suitable for Backup.Status.UnderlyingResources. // flavor is the live Cluster's, not app.Spec.Flavor: the chart refuses a // flavor change, but the app keeps the refused value. -func marshalCNPGBackupSnapshot(app *postgresapp.Postgres, parameters map[string]string, flavor string) (*runtime.RawExtension, error) { +func marshalCNPGBackupSnapshot(app *postgresapp.Postgres, parameters map[string]string, flavor, imageName string) (*runtime.RawExtension, error) { if app == nil { return nil, nil } @@ -1640,6 +1687,7 @@ func marshalCNPGBackupSnapshot(app *postgresapp.Postgres, parameters map[string] Users: app.Spec.Users, Parameters: parameters, Flavor: flavor, + ImageName: imageName, } raw, err := json.Marshal(snap) if err != nil { diff --git a/internal/backupcontroller/cnpgstrategy_controller_test.go b/internal/backupcontroller/cnpgstrategy_controller_test.go index bc2827371..907acfe80 100644 --- a/internal/backupcontroller/cnpgstrategy_controller_test.go +++ b/internal/backupcontroller/cnpgstrategy_controller_test.go @@ -225,7 +225,7 @@ func TestRenderCNPGTemplate_RoundTripsParametersThroughSnapshot(t *testing.T) { } // Round-trip parameters through Backup.status.underlyingResources. - raw, err := marshalCNPGBackupSnapshot(app, parameters, "") + raw, err := marshalCNPGBackupSnapshot(app, parameters, "", "") if err != nil { t.Fatalf("marshal snapshot: %v", err) } @@ -530,6 +530,7 @@ func TestBuildPostgresAppRestorePatch_ForwardsSecretRef_NotCleartext(t *testing. creds, nil, nil, nil, + "", ) if got := patched.Spec.Backup.S3CredentialsSecret.Name; got != "pg-target-cnpg-backup-creds" { @@ -557,7 +558,7 @@ func TestBuildPostgresAppRestorePatch_ForwardsCustomKeyOverrides(t *testing.T) { SecretAccessKeyKey: "SECRET_KEY", } - patched := buildPostgresAppRestorePatch(app, "src", "pg-new", "s3://b/", "", "", "", creds, nil, nil, nil) + patched := buildPostgresAppRestorePatch(app, "src", "pg-new", "s3://b/", "", "", "", creds, nil, nil, nil, "") want := postgresapp.S3CredentialsSecret{ Name: "creds", @@ -575,7 +576,7 @@ func TestBuildPostgresAppRestorePatch_ForwardsCustomKeyOverrides(t *testing.T) { // Secret name and helm install would fail. func TestBuildPostgresAppRestorePatch_NoSecretRefIsSkipped(t *testing.T) { app := newPostgresApp("pg", "tenant") - patched := buildPostgresAppRestorePatch(app, "src", "pg-new", "s3://b/", "", "", "", nil, nil, nil, nil) + patched := buildPostgresAppRestorePatch(app, "src", "pg-new", "s3://b/", "", "", "", nil, nil, nil, nil, "") if got := patched.Spec.Backup.S3CredentialsSecret; got != (postgresapp.S3CredentialsSecret{}) { t.Errorf("spec.backup.s3CredentialsSecret must be zero when credsRef is nil; got %#v", got) } @@ -773,7 +774,7 @@ func TestBuildPostgresAppRestorePatch_ReplacesTargetUsersAndDatabases(t *testing "appdb": {Extensions: []string{"hstore"}}, } - patched := buildPostgresAppRestorePatch(app, "src", "pg-new", "s3://b/", "", "", "", nil, nil, sourceDatabases, sourceUsers) + patched := buildPostgresAppRestorePatch(app, "src", "pg-new", "s3://b/", "", "", "", nil, nil, sourceDatabases, sourceUsers, "") if _, ok := patched.Spec.Users["stale-target-user"]; ok { t.Errorf("stale target user survived restore; replace semantics regressed") @@ -810,7 +811,7 @@ func TestBuildPostgresAppRestorePatch_ScrubsStaleBackupSettings(t *testing.T) { // Restore with no recoveryTime, no endpointURL, no creds, no CA - // everything stale on the target must be wiped. - patched := buildPostgresAppRestorePatch(app, "src", "pg-new", "s3://b/", "", "", "", nil, nil, nil, nil) + patched := buildPostgresAppRestorePatch(app, "src", "pg-new", "s3://b/", "", "", "", nil, nil, nil, nil, "") if got := patched.Spec.Bootstrap.RecoveryTime; got != "" { t.Errorf("stale recoveryTime survived; got %q", got) @@ -849,7 +850,7 @@ func TestBuildPostgresAppRestorePatch_ForwardsEndpointCA(t *testing.T) { SecretRef: corev1.LocalObjectReference{Name: "pg-cnpg-backup-ca"}, Key: "ca.crt", } - patched := buildPostgresAppRestorePatch(app, "src", "pg-new", "s3://b/", "", "", "", nil, caRef, nil, nil) + patched := buildPostgresAppRestorePatch(app, "src", "pg-new", "s3://b/", "", "", "", nil, caRef, nil, nil, "") want := postgresapp.EndpointCA{Name: "pg-cnpg-backup-ca", Key: "ca.crt"} if got := patched.Spec.Backup.EndpointCA; got != want { @@ -865,7 +866,7 @@ func TestBuildPostgresAppRestorePatch_ArchiveServerNameDiffersFromSource(t *test // An in-place restore is the worst case: source serverName equals the // target cluster's own name. const source = "postgres-pg" - patched := buildPostgresAppRestorePatch(app, source, "postgres-pg-restore-deadbeef", "s3://b/", "", "", "", nil, nil, nil, nil) + patched := buildPostgresAppRestorePatch(app, source, "postgres-pg-restore-deadbeef", "s3://b/", "", "", "", nil, nil, nil, nil, "") if got := patched.Spec.Bootstrap.ServerName; got != source { t.Errorf("recovery serverName must stay the source; got %q want %q", got, source) @@ -920,7 +921,7 @@ func TestMarshalUnmarshalCNPGBackupSnapshot(t *testing.T) { "region": "eu-west-1", } - raw, err := marshalCNPGBackupSnapshot(src, parameters, "") + raw, err := marshalCNPGBackupSnapshot(src, parameters, "", "") if err != nil { t.Fatalf("marshal: %v", err) } @@ -1073,7 +1074,7 @@ func TestCreateCNPGBackupArtifact_AlreadyExistsReturnsExisting(t *testing.T) { } sourceApp := newPostgresApp("pg", "tenant") - got, err := r.createCNPGBackupArtifact(context.Background(), j, resolved, cnpgBk, "postgres-pg", "postgres-pg", "postgresql", rendered, sourceApp) + got, err := r.createCNPGBackupArtifact(context.Background(), j, resolved, cnpgBk, "postgres-pg", "postgres-pg", "postgresql", "", rendered, sourceApp) if err != nil { t.Fatalf("expected AlreadyExists to be swallowed, got error %v", err) } @@ -2835,7 +2836,7 @@ func TestReconcileCNPGRestore_RepeatInPlacePurgesStaleRecoveryCluster(t *testing mkBackupArtifact := func(t *testing.T) *backupsv1alpha1.Backup { t.Helper() - snap, err := marshalCNPGBackupSnapshot(newPostgresApp(appName, ns), nil, "") + snap, err := marshalCNPGBackupSnapshot(newPostgresApp(appName, ns), nil, "", "") if err != nil { t.Fatalf("marshal snapshot: %v", err) } @@ -3097,16 +3098,20 @@ func TestReconcileCNPGRestore_RefusesCrossFlavorRestore(t *testing.T) { name string sourceFlavor string targetFlavor string + targetVersion string + sourceImage string wantFailed bool wantInMessage string }{ {name: "postgis backup into a postgresql app", sourceFlavor: "postgis", targetFlavor: "", wantFailed: true, wantInMessage: "taken from a postgis cluster"}, + {name: "backup hands its source image to the app", sourceImage: "ghcr.io/cloudnative-pg/postgresql:17.7", wantFailed: false}, + {name: "bullseye backup into another major", sourceImage: "ghcr.io/cloudnative-pg/postgresql:17.7", targetVersion: "v18", wantFailed: true, wantInMessage: "taken on PostgreSQL 17"}, {name: "pre-flavor backup into a postgis app", sourceFlavor: "", targetFlavor: "postgis", wantFailed: true, wantInMessage: "taken from a postgresql cluster"}, {name: "postgis backup into a postgis app", sourceFlavor: "postgis", targetFlavor: "postgis", wantFailed: false}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { - snap, err := marshalCNPGBackupSnapshot(newPostgresApp(appName, ns), nil, tc.sourceFlavor) + snap, err := marshalCNPGBackupSnapshot(newPostgresApp(appName, ns), nil, tc.sourceFlavor, tc.sourceImage) if err != nil { t.Fatalf("marshal snapshot: %v", err) } @@ -3125,6 +3130,7 @@ func TestReconcileCNPGRestore_RefusesCrossFlavorRestore(t *testing.T) { } target := newPostgresApp(appName, ns) target.Spec.Flavor = tc.targetFlavor + target.Spec.Version = tc.targetVersion sa := startedAt restoreJob := &backupsv1alpha1.RestoreJob{ ObjectMeta: metav1.ObjectMeta{Namespace: ns, Name: "rj"}, @@ -3165,12 +3171,15 @@ func TestReconcileCNPGRestore_RefusesCrossFlavorRestore(t *testing.T) { if !apierrors.IsNotFound(clusterErr) { t.Fatalf("same-flavor restore must purge the target Cluster, got err=%v", clusterErr) } + if app.Spec.Bootstrap.SourceImageName != tc.sourceImage { + t.Fatalf("bootstrap.sourceImageName = %q, want %q", app.Spec.Bootstrap.SourceImageName, tc.sourceImage) + } return } if got.Status.Phase != backupsv1alpha1.RestoreJobPhaseFailed { t.Fatalf("cross-flavor restore must fail, got phase %q", got.Status.Phase) } - if !strings.Contains(got.Status.Message, tc.wantInMessage) || !strings.Contains(got.Status.Message, "pg_dump") { + if !strings.Contains(got.Status.Message, tc.wantInMessage) || (tc.targetVersion == "" && !strings.Contains(got.Status.Message, "pg_dump")) { t.Errorf("failure message must name the source flavor and point to a logical dump, got %q", got.Status.Message) } if clusterErr != nil { @@ -3206,7 +3215,7 @@ func TestReconcileCNPGRestore_HealthyClusterSucceeds(t *testing.T) { ctx := context.Background() startedAt := metav1.NewTime(time.Now()) - snap, err := marshalCNPGBackupSnapshot(newPostgresApp(appName, ns), nil, "") + snap, err := marshalCNPGBackupSnapshot(newPostgresApp(appName, ns), nil, "", "") if err != nil { t.Fatalf("marshal snapshot: %v", err) } @@ -3325,7 +3334,7 @@ func TestReconcileCNPGRestore_HealthyDisablesBootstrap(t *testing.T) { ctx := context.Background() startedAt := metav1.NewTime(time.Now().Add(-time.Hour)) - snap, err := marshalCNPGBackupSnapshot(newPostgresApp(appName, ns), nil, "") + snap, err := marshalCNPGBackupSnapshot(newPostgresApp(appName, ns), nil, "", "") if err != nil { t.Fatalf("marshal snapshot: %v", err) } @@ -3414,7 +3423,7 @@ func TestReconcileCNPGRestore_BootstrapDisableFailsPastDeadline(t *testing.T) { // Well past the 30m default deadline. startedAt := metav1.NewTime(time.Now().Add(-72 * time.Hour)) - snap, err := marshalCNPGBackupSnapshot(newPostgresApp(appName, ns), nil, "") + snap, err := marshalCNPGBackupSnapshot(newPostgresApp(appName, ns), nil, "", "") if err != nil { t.Fatalf("marshal snapshot: %v", err) } @@ -3527,7 +3536,7 @@ func TestReconcileCNPGRestore_BootstrapDisableTransientErrorRequeues(t *testing. startedAt := metav1.NewTime(time.Now().Add(-72 * time.Hour)) convergedAt := metav1.Now() - snap, err := marshalCNPGBackupSnapshot(newPostgresApp(appName, ns), nil, "") + snap, err := marshalCNPGBackupSnapshot(newPostgresApp(appName, ns), nil, "", "") if err != nil { t.Fatalf("marshal snapshot: %v", err) } @@ -3654,7 +3663,7 @@ func TestReconcileCNPGRestore_BootstrapDisableShortTimeoutHonorsGraceFloor(t *te // within the 5m post-convergence floor. convergedAt := metav1.NewTime(time.Now().Add(-90 * time.Second)) - snap, err := marshalCNPGBackupSnapshot(newPostgresApp(appName, ns), nil, "") + snap, err := marshalCNPGBackupSnapshot(newPostgresApp(appName, ns), nil, "", "") if err != nil { t.Fatalf("marshal snapshot: %v", err) } @@ -3766,7 +3775,7 @@ func TestReconcileCNPGRestore_HealthyPastDeadlineSucceeds(t *testing.T) { // Far past the 30m default deadline: this is the reconcile-gap case. startedAt := metav1.NewTime(time.Now().Add(-72 * time.Hour)) - snap, err := marshalCNPGBackupSnapshot(newPostgresApp(appName, ns), nil, "") + snap, err := marshalCNPGBackupSnapshot(newPostgresApp(appName, ns), nil, "", "") if err != nil { t.Fatalf("marshal snapshot: %v", err) } @@ -3862,7 +3871,7 @@ func TestReconcileCNPGRestore_DeadlineClassifiesRecoveryTargetUnreachable(t *tes // enters the deadline-classification branch. startedAt := metav1.NewTime(time.Now().Add(-72 * time.Hour)) - snap, err := marshalCNPGBackupSnapshot(newPostgresApp(appName, ns), nil, "") + snap, err := marshalCNPGBackupSnapshot(newPostgresApp(appName, ns), nil, "", "") if err != nil { t.Fatalf("marshal snapshot: %v", err) } @@ -4171,10 +4180,10 @@ func TestBuildPostgresAppRestorePatch_ReplacesBackupID(t *testing.T) { app := newPostgresApp("pg", "tenant") app.Spec.Bootstrap.BackupID = "20260101T000000" - if got := buildPostgresAppRestorePatch(app, "src", "pg-new", "s3://b/", "", "", "20260921T062713", nil, nil, nil, nil).Spec.Bootstrap.BackupID; got != "20260921T062713" { + if got := buildPostgresAppRestorePatch(app, "src", "pg-new", "s3://b/", "", "", "20260921T062713", nil, nil, nil, nil, "").Spec.Bootstrap.BackupID; got != "20260921T062713" { t.Errorf("bootstrap.backupID: got %q want %q", got, "20260921T062713") } - if got := buildPostgresAppRestorePatch(app, "src", "pg-new", "s3://b/", "", "", "", nil, nil, nil, nil).Spec.Bootstrap.BackupID; got != "" { + if got := buildPostgresAppRestorePatch(app, "src", "pg-new", "s3://b/", "", "", "", nil, nil, nil, nil, "").Spec.Bootstrap.BackupID; got != "" { t.Errorf("bootstrap.backupID from a previous restore must be cleared; got %q", got) } } @@ -4201,7 +4210,7 @@ func TestReconcileCNPGRestore_PinsTheRequestedBackup(t *testing.T) { mkBackupArtifact := func(t *testing.T) *backupsv1alpha1.Backup { t.Helper() - snap, err := marshalCNPGBackupSnapshot(newPostgresApp(appName, ns), nil, "") + snap, err := marshalCNPGBackupSnapshot(newPostgresApp(appName, ns), nil, "", "") if err != nil { t.Fatalf("marshal snapshot: %v", err) } @@ -4339,7 +4348,7 @@ func TestCreateCNPGBackupArtifact_RecordsMajorVersion(t *testing.T) { rendered := &strategyv1alpha1.CNPGTemplate{ BarmanObjectStore: strategyv1alpha1.BarmanObjectStoreTemplate{DestinationPath: "s3://b/"}, } - got, err := r.createCNPGBackupArtifact(context.Background(), j, resolved, cnpgBk, "postgres-pg", "postgres-pg", "postgresql", rendered, newPostgresApp("pg", "tenant")) + got, err := r.createCNPGBackupArtifact(context.Background(), j, resolved, cnpgBk, "postgres-pg", "postgres-pg", "postgresql", "", rendered, newPostgresApp("pg", "tenant")) if err != nil { t.Fatalf("createCNPGBackupArtifact: %v", err) } @@ -4402,7 +4411,7 @@ func TestReconcileCNPGRestore_RefusesCrossMajorRestore(t *testing.T) { } targetCluster := cnpgClusterNameForApp(targetApp) - snap, err := marshalCNPGBackupSnapshot(newPostgresApp(sourceApp, ns), nil, "") + snap, err := marshalCNPGBackupSnapshot(newPostgresApp(sourceApp, ns), nil, "", "") if err != nil { t.Fatalf("marshal snapshot: %v", err) } diff --git a/internal/backupcontroller/postgresapp/types.go b/internal/backupcontroller/postgresapp/types.go index 914f522fa..9de1b7ac1 100644 --- a/internal/backupcontroller/postgresapp/types.go +++ b/internal/backupcontroller/postgresapp/types.go @@ -81,12 +81,13 @@ type Bootstrap struct { // recovery converges, and a bool+omitempty would drop false from the patch // (it deletes the key instead), leaving the server to fall back to a default // rather than being explicitly cleared. Same rule as Backup.UseSystemBucket. - Enabled bool `json:"enabled"` - OldName string `json:"oldName,omitempty"` - ServerName string `json:"serverName,omitempty"` - NewServerName string `json:"newServerName,omitempty"` - RecoveryTime string `json:"recoveryTime,omitempty"` - BackupID string `json:"backupID,omitempty"` + Enabled bool `json:"enabled"` + OldName string `json:"oldName,omitempty"` + ServerName string `json:"serverName,omitempty"` + NewServerName string `json:"newServerName,omitempty"` + RecoveryTime string `json:"recoveryTime,omitempty"` + BackupID string `json:"backupID,omitempty"` + SourceImageName string `json:"sourceImageName,omitempty"` } type Backup struct { diff --git a/packages/apps/postgres/README.md b/packages/apps/postgres/README.md index ed66d66bb..d3468b9b8 100644 --- a/packages/apps/postgres/README.md +++ b/packages/apps/postgres/README.md @@ -207,18 +207,19 @@ For `sslmode=verify-full` to work, the CA bundle retrieved above must be saved t ### Common parameters -| Name | Description | Type | Value | -| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | ------------ | -| `replicas` | Number of Postgres replicas. Under active autoscaling this is the resting/seed count, not the live count — KEDA drives the live count via `/scale`. Disabling autoscaling does NOT automatically bring the live count back to `replicas`: the client-side merge writes `instances` only when the rendered value changes, so a cluster KEDA grew past `replicas` stays there with no autoscaler left to reduce it — lower `replicas` to the count you want and it rebases down (shedding the surplus replicas + PVCs). Lowering it below the live count, or disabling/dry-running while it sits below the live count, sheds in one step past the scaleDown pacing; stage it to the live count first (suspend the HelmRelease and `kubectl scale` if needed) to avoid a transient. Must stay greater than `quorum.maxSyncReplicas`. | `int` | `2` | -| `resources` | Explicit CPU and memory configuration for each PostgreSQL replica. When omitted, the preset defined in `resourcesPreset` is applied. | `object` | `{}` | -| `resources.cpu` | CPU available to each replica. | `quantity` | `""` | -| `resources.memory` | Memory (RAM) available to each replica. | `quantity` | `""` | -| `resourcesPreset` | Default sizing preset used when `resources` is omitted. | `string` | `t1.micro` | -| `size` | Persistent Volume Claim size available for application data. | `quantity` | `10Gi` | -| `storageClass` | StorageClass used to store the data. | `string` | `""` | -| `external` | Enable external access from outside the cluster. | `bool` | `false` | -| `version` | PostgreSQL major version to deploy | `string` | `v18` | -| `flavor` | PostgreSQL image flavor, fixed when the cluster is created. `postgresql` uses the CloudNativePG PostgreSQL image. `postgis` uses the CloudNativePG PostGIS image, which adds postgis, postgis_raster, postgis_topology, postgis_sfcgal, postgis_tiger_geocoder and address_standardizer; enable them per database in `databases..extensions`. Changing the flavor of an existing cluster is refused, and a backup restores only into a cluster of the flavor it was taken from: to change flavor, create a new cluster and move the data with a logical dump (pg_dump / pg_restore). | `string` | `postgresql` | +| Name | Description | Type | Value | +| ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | ------------ | +| `replicas` | Number of Postgres replicas. Under active autoscaling this is the resting/seed count, not the live count — KEDA drives the live count via `/scale`. Disabling autoscaling does NOT automatically bring the live count back to `replicas`: the client-side merge writes `instances` only when the rendered value changes, so a cluster KEDA grew past `replicas` stays there with no autoscaler left to reduce it — lower `replicas` to the count you want and it rebases down (shedding the surplus replicas + PVCs). Lowering it below the live count, or disabling/dry-running while it sits below the live count, sheds in one step past the scaleDown pacing; stage it to the live count first (suspend the HelmRelease and `kubectl scale` if needed) to avoid a transient. Must stay greater than `quorum.maxSyncReplicas`. | `int` | `2` | +| `resources` | Explicit CPU and memory configuration for each PostgreSQL replica. When omitted, the preset defined in `resourcesPreset` is applied. | `object` | `{}` | +| `resources.cpu` | CPU available to each replica. | `quantity` | `""` | +| `resources.memory` | Memory (RAM) available to each replica. | `quantity` | `""` | +| `resourcesPreset` | Default sizing preset used when `resources` is omitted. | `string` | `t1.micro` | +| `size` | Persistent Volume Claim size available for application data. | `quantity` | `10Gi` | +| `storageClass` | StorageClass used to store the data. | `string` | `""` | +| `external` | Enable external access from outside the cluster. | `bool` | `false` | +| `version` | PostgreSQL major version to deploy | `string` | `v18` | +| `flavor` | PostgreSQL image flavor, fixed when the cluster is created. `postgresql` uses the CloudNativePG PostgreSQL image. `postgis` uses the CloudNativePG PostGIS image, which adds postgis, postgis_raster, postgis_topology, postgis_sfcgal, postgis_tiger_geocoder and address_standardizer; enable them per database in `databases..extensions`. Changing the flavor of an existing cluster is refused, and a backup restores only into a cluster of the flavor it was taken from: to change flavor, create a new cluster and move the data with a logical dump (pg_dump / pg_restore). | `string` | `postgresql` | +| `allowCollationChange` | Allow a cluster created on a Debian bullseye image (before the move to standard-trixie) to move to the new image without a clean locale check. Such a cluster is checked before each upgrade, except while `bootstrap.enabled` is set (set it back to false once a restore set up by hand has finished), and stays on its current image until the check finds nothing that depends on a collation other than C, POSIX or builtin: while this is false, a cluster the check found affected (an ICU or libc locale, or C.UTF-8) or could not finish on stays put, because glibc and ICU on the new image sort text differently and every index on such text must be rebuilt. A held cluster runs the bare bullseye tag it has, gets no further PostgreSQL minors and so none of their security fixes, and refuses a change of `version`, since new majors are built only on the new images. To leave that state, either remove the dependency (move such columns and indexes to C, or to the builtin `pg_c_utf8` on PostgreSQL 17 and later) and let the next upgrade check again, or set this to true in a maintenance window: the cluster moves on the next upgrade, replicas restart on the new image first and can return wrong results through `-ro`, and unique indexes can accept duplicates, until the indexes are rebuilt on the primary. The init Job rebuilds only indexes on collations that record a version (ICU, and libc locales other than C.*): rebuild indexes on C.UTF-8 or another C.* locale by hand with REINDEX, and check range partitions, CHECK constraints and materialized views on such text, which a rebuild does not fix. A held cluster shows the hold only as an unchanged image; the result and the objects found are in the `postgres.cozystack.io/locale-data` and `postgres.cozystack.io/locale-data-objects` annotations of the cnpg.io Cluster, which an administrator can read. A restore of a backup taken on one of those bullseye images comes back on that image and is checked by the next upgrade. | `bool` | `false` | ### TLS configuration @@ -309,15 +310,16 @@ For `sslmode=verify-full` to work, the CA bundle retrieved above must be saved t ### Bootstrap (recovery) parameters -| Name | Description | Type | Value | -| ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | ------- | -| `bootstrap` | Bootstrap configuration. | `object` | `{}` | -| `bootstrap.enabled` | Whether to restore from a backup. | `bool` | `false` | -| `bootstrap.recoveryTime` | Timestamp (RFC3339) for point-in-time recovery; empty means latest. | `string` | `""` | -| `bootstrap.backupID` | Barman ID of the base backup to recover from, passed as `recoveryTarget.backupID`. Empty lets the barman-cloud plugin pick one: the newest backup when `recoveryTime` is empty, otherwise the newest one ending at or before it, on any timeline. The CNPG backup driver sets this on restore. | `string` | `""` | -| `bootstrap.oldName` | Previous cluster name before deletion. | `string` | `""` | -| `bootstrap.serverName` | Server name (S3 path prefix) used by the original cluster when writing backups; passed to the barman-cloud plugin via `externalClusters[].plugin.parameters.serverName`. Defaults to `bootstrap.oldName`. Set this only when the original cluster wrote backups under an explicit server name that differed from its Kubernetes resource name. | `string` | `""` | -| `bootstrap.newServerName` | WAL-archive server name (S3 path prefix) the RESTORED cluster writes to. Must differ from `serverName` (the recovery source) so a restored cluster archives to a fresh, empty prefix and barman-cloud-check-wal-archive passes while it recovers from the source's prefix. The CNPG backup driver sets this on restore; empty means the cluster archives under its own name. | `string` | `""` | +| Name | Description | Type | Value | +| --------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | ------- | +| `bootstrap` | Bootstrap configuration. | `object` | `{}` | +| `bootstrap.enabled` | Whether to restore from a backup. | `bool` | `false` | +| `bootstrap.recoveryTime` | Timestamp (RFC3339) for point-in-time recovery; empty means latest. | `string` | `""` | +| `bootstrap.backupID` | Barman ID of the base backup to recover from, passed as `recoveryTarget.backupID`. Empty lets the barman-cloud plugin pick one: the newest backup when `recoveryTime` is empty, otherwise the newest one ending at or before it, on any timeline. The CNPG backup driver sets this on restore. | `string` | `""` | +| `bootstrap.oldName` | Previous cluster name before deletion. | `string` | `""` | +| `bootstrap.serverName` | Server name (S3 path prefix) used by the original cluster when writing backups; passed to the barman-cloud plugin via `externalClusters[].plugin.parameters.serverName`. Defaults to `bootstrap.oldName`. Set this only when the original cluster wrote backups under an explicit server name that differed from its Kubernetes resource name. | `string` | `""` | +| `bootstrap.newServerName` | WAL-archive server name (S3 path prefix) the RESTORED cluster writes to. Must differ from `serverName` (the recovery source) so a restored cluster archives to a fresh, empty prefix and barman-cloud-check-wal-archive passes while it recovers from the source's prefix. The CNPG backup driver sets this on restore; empty means the cluster archives under its own name. | `string` | `""` | +| `bootstrap.sourceImageName` | Image of the cluster the backup was taken from. A restore of a backup taken on one of the bare Debian bullseye tags the chart used before standard-trixie comes back on that image (see `allowCollationChange`); any other value is ignored. The CNPG backup driver sets this on restore and clears it with `enabled`. | `string` | `""` | ## Parameter examples and reference diff --git a/packages/apps/postgres/templates/_versions.tpl b/packages/apps/postgres/templates/_versions.tpl index 688c16b49..ea46a11c2 100644 --- a/packages/apps/postgres/templates/_versions.tpl +++ b/packages/apps/postgres/templates/_versions.tpl @@ -26,6 +26,10 @@ flavor is on it already, so both image families share one Debian release. */}} {{- define "postgres.imageName" -}} +{{- include "postgres.heldImageName" . | default (include "postgres.targetImageName" .) -}} +{{- end -}} + +{{- define "postgres.targetImageName" -}} {{- if eq (default "postgresql" .Values.flavor) "postgis" -}} ghcr.io/cloudnative-pg/postgis:{{ include "postgres.postgisVersionMap" . | trim }} {{- else -}} @@ -33,6 +37,92 @@ ghcr.io/cloudnative-pg/postgresql:{{ include "postgres.versionMap" . | trim | tr {{- end -}} {{- end -}} +{{/* + The image a cluster on Debian bullseye keeps, or nothing. Clusters created + before the move to trixie run one of the bare tags postgres.bullseyeImage + lists, and moving them changes glibc and ICU under an initialised data + directory. Such a cluster stays on its image until the pre-upgrade locale + check has recorded "clean" on its Cluster, or until allowCollationChange is + set: a cluster not checked yet, one the check could not finish on and one + it found affected all stay. New majors are built only on the new images, so + a held cluster refuses a change of version instead of dropping it. +*/}} +{{- define "postgres.heldImageName" -}} +{{- if and (ne (default "postgresql" .Values.flavor) "postgis") (not .Values.allowCollationChange) -}} +{{- $hold := include "postgres.localeHold" . | fromJson -}} +{{- if and $hold.image (ne $hold.verdict "clean") -}} +{{- $heldMajor := regexFind "^[0-9]+" (last (splitList ":" $hold.image)) -}} +{{- $wantMajor := trimPrefix "v" .Values.version -}} +{{- if ne $heldMajor $wantMajor -}} +{{- fail (printf "postgres: version %s cannot be applied: the cluster stays on %s until the pre-upgrade check finds nothing in it that depends on a collation sorting differently on the images PostgreSQL %s is built on (the postgres.cozystack.io/locale-data annotation of the cnpg.io Cluster). Keep version v%s, or set allowCollationChange: true and rebuild the affected indexes in a maintenance window." .Values.version $hold.image $wantMajor $heldMajor) -}} +{{- end -}} +{{- $hold.image -}} +{{- end -}} +{{- end -}} +{{- end -}} + +{{/* + The bullseye image that applies to this cluster and its check result, as + JSON; the image is empty when the cluster runs any other one. The result is + the postgres.cozystack.io/locale-data annotation the pre-upgrade check + writes on the live Cluster. A physical recovery with no live Cluster yet + (the CNPG backup driver deletes it before the recovery renders) restores + onto the image the backup was taken on, so that the data keeps the library + that built it: bootstrap.sourceImageName, which the driver copies from the + source Cluster, or for a recovery set up by hand the bootstrap.oldName + Cluster while it exists. A recovery has no result of its own and is held + until the first upgrade after it checks the restored data. + + bootstrap.sourceImageName is in the application spec, so anyone who may + edit the application may set it; it only ever selects one of the images + postgres.bullseyeImage lists. +*/}} +{{- define "postgres.localeHold" -}} +{{- $live := lookup "postgresql.cnpg.io/v1" "Cluster" .Release.Namespace .Release.Name -}} +{{- $image := dig "spec" "imageName" "" $live -}} +{{- $verdict := dig "metadata" "annotations" "postgres.cozystack.io/locale-data" "" $live -}} +{{- if and .Values.bootstrap.enabled (not $image) -}} +{{- $image = .Values.bootstrap.sourceImageName | default (dig "spec" "imageName" "" (include "postgres.recoverySource" . | fromJson)) -}} +{{- $verdict = "" -}} +{{- end -}} +{{- if ne (include "postgres.bullseyeImage" $image) "true" -}} +{{- $image = "" -}} +{{- end -}} +{{- dict "image" $image "verdict" $verdict | toJson -}} +{{- end -}} + +{{- define "postgres.recoverySource" -}} +{{- if and .Values.bootstrap.enabled .Values.bootstrap.oldName (not .Values.bootstrap.newServerName) -}} +{{- lookup "postgresql.cnpg.io/v1" "Cluster" .Release.Namespace .Values.bootstrap.oldName | toJson -}} +{{- else -}} +{} +{{- end -}} +{{- end -}} + +{{/* + The images this chart ran clusters on before the move to trixie: the bare + version tags of the CloudNativePG image, which are its system variant on + Debian bullseye, as files/versions.yaml listed them in every release before + standard-trixie. Exact on purpose: a held image reaches spec.imageName. +*/}} +{{- define "postgres.bullseyeImage" -}} +{{- has . (list "ghcr.io/cloudnative-pg/postgresql:13.22" "ghcr.io/cloudnative-pg/postgresql:14.20" "ghcr.io/cloudnative-pg/postgresql:15.15" "ghcr.io/cloudnative-pg/postgresql:16.11" "ghcr.io/cloudnative-pg/postgresql:17.7" "ghcr.io/cloudnative-pg/postgresql:18.1") -}} +{{- end -}} + +{{/* + The live image of a cluster still on bullseye whose owner has not allowed + the collation change, or nothing. The pre-upgrade locale check runs only + then, from that image, against the server it is checking. +*/}} +{{- define "postgres.localeCheckImage" -}} +{{- if and (ne (default "postgresql" .Values.flavor) "postgis") (not .Values.allowCollationChange) (not .Values.bootstrap.enabled) -}} +{{- $live := lookup "postgresql.cnpg.io/v1" "Cluster" .Release.Namespace .Release.Name -}} +{{- if and $live $live.spec $live.spec.imageName (eq (include "postgres.bullseyeImage" $live.spec.imageName) "true") -}} +{{- $live.spec.imageName -}} +{{- end -}} +{{- end -}} +{{- end -}} + {{/* The flavor is fixed at bootstrap. Only the postgis image carries the shared libraries behind PostGIS objects, so the postgis-to-postgresql direction diff --git a/packages/apps/postgres/templates/locale-check-hook.yaml b/packages/apps/postgres/templates/locale-check-hook.yaml new file mode 100644 index 000000000..adbe922e1 --- /dev/null +++ b/packages/apps/postgres/templates/locale-check-hook.yaml @@ -0,0 +1,263 @@ +{{- /* + Runs before every upgrade of a cluster still on Debian bullseye, from the + image the cluster runs now. It looks for anything stored that depends on a + collation other than C, POSIX or builtin and records the answer on the + Cluster as the postgres.cozystack.io/locale-data annotation: clean, + affected, or unknown when the check could not finish. postgres.heldImageName + reads it, and only clean lets the cluster move. Helm renders the manifests + before this hook runs, so when the answer disagrees with what this attempt + rendered, the hook fails the attempt before the Cluster is patched and the + retry renders according to the new answer. +*/ -}} +{{- $liveImage := include "postgres.localeCheckImage" . }} +{{- if $liveImage }} +{{- $held := include "postgres.heldImageName" . }} +{{- /* Prefixed, not suffixed: CNPG names its ServiceAccount and Role after the + Cluster, and before-hook-creation would delete those of a release named + -locale-check. */}} +{{- $name := printf "locale-check-%s-%s" (.Release.Name | trunc 40 | trimSuffix "-") (.Release.Name | sha256sum | trunc 8) }} +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: {{ $name }} + annotations: + helm.sh/hook: pre-upgrade + helm.sh/hook-weight: "1" + helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: {{ $name }} + annotations: + helm.sh/hook: pre-upgrade + helm.sh/hook-weight: "1" + helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded +rules: +- apiGroups: ["postgresql.cnpg.io"] + resources: ["clusters"] + resourceNames: [{{ .Release.Name | quote }}] + verbs: ["get", "patch"] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: {{ $name }} + annotations: + helm.sh/hook: pre-upgrade + helm.sh/hook-weight: "1" + helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: {{ $name }} +subjects: +- kind: ServiceAccount + name: {{ $name }} + namespace: {{ .Release.Namespace | quote }} +--- +apiVersion: v1 +kind: Secret +metadata: + name: {{ $name }} + annotations: + helm.sh/hook: pre-upgrade + helm.sh/hook-weight: "1" + helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded +stringData: + {{- /* + Anything found is an answer, even when another database could not be + checked. The session settings override what a database owner may have set + with ALTER DATABASE, and the time budget ends the check before the Job + deadline, so that a slow check records unknown, which holds the cluster, + rather than failing every retry of the upgrade. + */}} + check.sh: | + set -u + export PGOPTIONS="-c default_transaction_read_only=off -c statement_timeout=60s -c lock_timeout=10s" + export PGCONNECT_TIMEOUT=10 + echo unknown > /work/verdict + : > /work/found + until pg_isready -q; do + if [ "$SECONDS" -ge 60 ]; then + echo "the server did not answer within 60s; the locale data of its databases is not checked" >&2 + exit 0 + fi + sleep 2 + done + psql -v ON_ERROR_STOP=1 -t -A -c "SELECT datname FROM pg_database WHERE datallowconn" > /work/databases || exit 0 + INCOMPLETE="" + CLOSED=$(psql -v ON_ERROR_STOP=1 -t -A -c "SELECT string_agg(datname, ', ') FROM pg_database WHERE NOT datallowconn AND datname <> 'template0'") || exit 0 + if [ -n "$CLOSED" ]; then + echo "databases that accept no connections are not checked: $CLOSED" >&2 + INCOMPLETE=yes + fi + while IFS= read -r db; do + if [ "$SECONDS" -ge 180 ]; then + echo "out of time before database $db was checked" >&2 + INCOMPLETE=yes + break + fi + PGDATABASE="$db" psql -v ON_ERROR_STOP=1 -q -t -A -f /scripts/check.sql >> /work/found || INCOMPLETE=yes + done < /work/databases + if [ -s /work/found ]; then + head -n 50 /work/found + echo affected > /work/verdict + elif [ -z "$INCOMPLETE" ]; then + echo clean > /work/verdict + fi + {{- /* + A collation is safe when its order and character classes cannot change + with the C library or ICU: C and POSIX, the builtin provider of PostgreSQL + 17, and the database default when that is one of them. C.UTF-8 is not: + Debian bullseye patches its order, glibc 2.35 and later sort by code point. + Objects below the first normal OID belong to the system catalogs, which + use C. + */}} + check.sql: | + SET search_path = pg_catalog, pg_temp; + SELECT current_setting('server_version_num')::int >= 150000 AS has_provider \gset + \if :has_provider + SELECT datlocprovider = 'b' OR (datlocprovider = 'c' AND datcollate IN ('C', 'POSIX') AND datctype IN ('C', 'POSIX')) AS default_safe FROM pg_database WHERE datname = current_database() \gset + \else + SELECT datcollate IN ('C', 'POSIX') AND datctype IN ('C', 'POSIX') AS default_safe FROM pg_database WHERE datname = current_database() \gset + \endif + WITH unsafe AS ( + SELECT c.oid FROM pg_collation c + WHERE NOT (c.collprovider = 'b' + OR (c.collprovider = 'c' AND c.collcollate IN ('C', 'POSIX') AND c.collctype IN ('C', 'POSIX')) + OR (c.collprovider = 'd' AND :'default_safe'::boolean)) + ) + SELECT DISTINCT format('%s: %s uses collation %s', current_database(), + pg_describe_object('pg_class'::regclass, a.attrelid, a.attnum), u.oid::regcollation) + FROM pg_attribute a + JOIN pg_class r ON r.oid = a.attrelid + JOIN unsafe u ON u.oid = a.attcollation + WHERE r.oid >= 16384 AND r.relkind IN ('r', 'p', 'm', 'i', 'c') AND r.relpersistence <> 't' + AND a.attnum > 0 AND NOT a.attisdropped + UNION + SELECT format('%s: %s depends on collation %s', current_database(), + pg_describe_object(d.classid, d.objid, d.objsubid), u.oid::regcollation) + FROM pg_depend d + JOIN unsafe u ON u.oid = d.refobjid + WHERE d.refclassid = 'pg_collation'::regclass AND d.objid >= 16384 + UNION + SELECT format('%s: range type %s uses collation %s', current_database(), + g.rngtypid::regtype, u.oid::regcollation) + FROM pg_range g + JOIN unsafe u ON u.oid = g.rngcollation + WHERE g.rngtypid >= 16384 + UNION + SELECT format('%s: %s orders jsonb strings by the database collation', current_database(), + pg_describe_object('pg_class'::regclass, a.attrelid, a.attnum)) + FROM pg_attribute a + JOIN pg_class r ON r.oid = a.attrelid + WHERE NOT :'default_safe'::boolean AND r.oid >= 16384 AND r.relkind = 'i' + AND a.attnum > 0 AND a.atttypid = 'jsonb'::regtype; +--- +apiVersion: batch/v1 +kind: Job +metadata: + name: {{ $name }} + annotations: + helm.sh/hook: pre-upgrade + helm.sh/hook-weight: "2" + {{- /* A failed Job stays, with its pod log, until the next attempt. */}} + helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded +spec: + activeDeadlineSeconds: 420 + backoffLimit: 0 + template: + metadata: + labels: + policy.cozystack.io/allow-to-apiserver: "true" + spec: + serviceAccountName: {{ $name }} + restartPolicy: Never + securityContext: + fsGroup: 26 + runAsGroup: 26 + runAsNonRoot: true + runAsUser: 26 + seccompProfile: + type: RuntimeDefault + initContainers: + - name: check + image: {{ $liveImage }} + command: [bash, /scripts/check.sh] + env: + - name: PGUSER + valueFrom: + secretKeyRef: + name: {{ .Release.Name }}-superuser + key: username + - name: PGPASSWORD + valueFrom: + secretKeyRef: + name: {{ .Release.Name }}-superuser + key: password + - name: PGHOST + value: {{ .Release.Name }}-rw + - name: PGPORT + value: "5432" + - name: PGDATABASE + value: postgres + securityContext: + allowPrivilegeEscalation: false + capabilities: + drop: + - ALL + readOnlyRootFilesystem: true + runAsNonRoot: true + volumeMounts: + - mountPath: /scripts + name: scripts + - mountPath: /work + name: work + {{- include "postgresjobs.resources" . | nindent 8 }} + containers: + - name: record + image: {{ include "cozy-lib.image" (list "clastix/kubectl:v1.32@sha256:b9ef7d8dbe65bcc81a46c09b8dc7543103055021c4f43287bf59e92a8f4fe05c" $) }} + command: [sh, -ec] + args: + - | + verdict=$(cat /work/verdict) + case "$verdict" in + affected) set -- "postgres.cozystack.io/locale-data-objects=$(head -n 20 /work/found | tr '\n' ';' | cut -c 1-4000)" ;; + clean) set -- "postgres.cozystack.io/locale-data-objects-" ;; + *) set -- ;; + esac + kubectl annotate --overwrite cluster.postgresql.cnpg.io/{{ .Release.Name }} postgres.cozystack.io/locale-data="$verdict" "$@" + {{- if not $held }} + if [ "$verdict" != clean ]; then + echo "postgres {{ .Release.Name }} stays on {{ $liveImage }}: the check found data that depends on a collation sorting differently on the new image, or could not finish (the check container log says which). The next attempt of this upgrade keeps the current image. Set allowCollationChange: true to move it, with the index rebuild, in a maintenance window." >&2 + exit 1 + fi + {{- else }} + if [ "$verdict" = clean ]; then + echo "postgres {{ .Release.Name }}: nothing in it depends on a changing collation any more, but this attempt was rendered with the held image {{ $liveImage }}; failing it so that the next attempt moves the cluster to the new image." >&2 + exit 1 + fi + {{- end }} + env: + - name: HOME + value: /work + securityContext: + allowPrivilegeEscalation: false + capabilities: + drop: + - ALL + readOnlyRootFilesystem: true + runAsNonRoot: true + volumeMounts: + - mountPath: /work + name: work + {{- include "postgresjobs.resources" . | nindent 8 }} + volumes: + - name: scripts + secret: + secretName: {{ $name }} + - name: work + emptyDir: {} +{{- end }} diff --git a/packages/apps/postgres/tests/locale_guard_test.yaml b/packages/apps/postgres/tests/locale_guard_test.yaml new file mode 100644 index 000000000..fe62dbb70 --- /dev/null +++ b/packages/apps/postgres/tests/locale_guard_test.yaml @@ -0,0 +1,526 @@ +suite: keep a bullseye cluster on its image until a clean locale check +release: + name: pg-test + namespace: tenant-test + upgrade: true +set: + _cluster: + scheduling: {} +kubernetesProvider: + scheme: + "postgresql.cnpg.io/v1/Cluster": + gvr: + group: postgresql.cnpg.io + version: v1 + resource: clusters + namespaced: true + objects: + - apiVersion: postgresql.cnpg.io/v1 + kind: Cluster + metadata: + name: pg-test + namespace: tenant-test + annotations: + postgres.cozystack.io/locale-data: affected + spec: + imageName: ghcr.io/cloudnative-pg/postgresql:18.1 + - apiVersion: postgresql.cnpg.io/v1 + kind: Cluster + metadata: + name: pg-clean + namespace: tenant-test + annotations: + postgres.cozystack.io/locale-data: clean + spec: + imageName: ghcr.io/cloudnative-pg/postgresql:18.1 + - apiVersion: postgresql.cnpg.io/v1 + kind: Cluster + metadata: + name: pg-unchecked + namespace: tenant-test + spec: + imageName: ghcr.io/cloudnative-pg/postgresql:18.1 + - apiVersion: postgresql.cnpg.io/v1 + kind: Cluster + metadata: + name: pg-unknown + namespace: tenant-test + annotations: + postgres.cozystack.io/locale-data: unknown + spec: + imageName: ghcr.io/cloudnative-pg/postgresql:18.1 + - apiVersion: postgresql.cnpg.io/v1 + kind: Cluster + metadata: + name: pg-trixie + namespace: tenant-test + annotations: + postgres.cozystack.io/locale-data: affected + spec: + imageName: ghcr.io/cloudnative-pg/postgresql:18.1-standard-trixie + - apiVersion: postgresql.cnpg.io/v1 + kind: Cluster + metadata: + name: pg-restored + namespace: tenant-test + spec: + imageName: ghcr.io/cloudnative-pg/postgresql:18.1 + bootstrap: + recovery: + source: pg-gone +tests: + - it: keeps a cluster the check found affected on its image + templates: + - templates/db.yaml + documentSelector: + path: kind + value: Cluster + asserts: + - equal: + path: spec.imageName + value: ghcr.io/cloudnative-pg/postgresql:18.1 + + - it: runs the init Job from the held image + templates: + - templates/init-job.yaml + documentSelector: + path: kind + value: Job + asserts: + - equal: + path: spec.template.spec.containers[0].image + value: ghcr.io/cloudnative-pg/postgresql:18.1 + + - it: keeps a cluster that was never checked on its image + release: + name: pg-unchecked + templates: + - templates/db.yaml + documentSelector: + path: kind + value: Cluster + asserts: + - equal: + path: spec.imageName + value: ghcr.io/cloudnative-pg/postgresql:18.1 + + - it: keeps a cluster the check could not finish on on its image + release: + name: pg-unknown + templates: + - templates/db.yaml + documentSelector: + path: kind + value: Cluster + asserts: + - equal: + path: spec.imageName + value: ghcr.io/cloudnative-pg/postgresql:18.1 + + - it: moves a cluster the check found clean + release: + name: pg-clean + templates: + - templates/db.yaml + documentSelector: + path: kind + value: Cluster + asserts: + - matchRegex: + path: spec.imageName + pattern: "^ghcr\\.io/cloudnative-pg/postgresql:18\\.[0-9]+-standard-trixie$" + + - it: moves an affected cluster once the change is allowed + set: + allowCollationChange: true + templates: + - templates/db.yaml + documentSelector: + path: kind + value: Cluster + asserts: + - matchRegex: + path: spec.imageName + pattern: "^ghcr\\.io/cloudnative-pg/postgresql:18\\.[0-9]+-standard-trixie$" + + - it: does not hold a cluster already on trixie + release: + name: pg-trixie + templates: + - templates/db.yaml + documentSelector: + path: kind + value: Cluster + asserts: + - matchRegex: + path: spec.imageName + pattern: "^ghcr\\.io/cloudnative-pg/postgresql:18\\.[0-9]+-standard-trixie$" + + - it: refuses a version change while held + set: + version: v17 + templates: + - templates/locale-check-hook.yaml + asserts: + - failedTemplate: + errorPattern: "version v17 cannot be applied: the cluster stays on ghcr.io/cloudnative-pg/postgresql:18.1" + + - it: allows a version change once the collation change is allowed + set: + version: v17 + allowCollationChange: true + templates: + - templates/db.yaml + documentSelector: + path: kind + value: Cluster + asserts: + - matchRegex: + path: spec.imageName + pattern: "^ghcr\\.io/cloudnative-pg/postgresql:17\\.[0-9]+-standard-trixie$" + + - it: restores a backup taken on a bullseye image onto that image + release: + name: pg-new + set: + bootstrap: + enabled: true + oldName: postgres-pg-0f1e2d3c + newServerName: pg-new-restore-0123456789abcdef + sourceImageName: ghcr.io/cloudnative-pg/postgresql:18.1 + backup: + s3AccessKey: access + s3SecretKey: secret + templates: + - templates/db.yaml + documentSelector: + path: kind + value: Cluster + asserts: + - equal: + path: spec.imageName + value: ghcr.io/cloudnative-pg/postgresql:18.1 + + - it: restores a backup taken on trixie onto the current image + release: + name: pg-new + set: + bootstrap: + enabled: true + oldName: postgres-pg-0f1e2d3c + newServerName: pg-new-restore-0123456789abcdef + sourceImageName: ghcr.io/cloudnative-pg/postgresql:18.1-standard-trixie + backup: + s3AccessKey: access + s3SecretKey: secret + templates: + - templates/db.yaml + documentSelector: + path: kind + value: Cluster + asserts: + - matchRegex: + path: spec.imageName + pattern: "^ghcr\\.io/cloudnative-pg/postgresql:18\\.[0-9]+-standard-trixie$" + + - it: never renders an image of another registry from bootstrap.sourceImageName + release: + name: pg-new + set: + bootstrap: + enabled: true + oldName: postgres-pg-0f1e2d3c + sourceImageName: "docker.io/attacker/payload:18" + backup: + s3AccessKey: access + s3SecretKey: secret + templates: + - templates/db.yaml + documentSelector: + path: kind + value: Cluster + asserts: + - matchRegex: + path: spec.imageName + pattern: "^ghcr\\.io/cloudnative-pg/postgresql:18\\.[0-9]+-standard-trixie$" + + - it: never renders a bare tag this chart never shipped from bootstrap.sourceImageName + release: + name: pg-new + set: + bootstrap: + enabled: true + oldName: postgres-pg-0f1e2d3c + sourceImageName: "ghcr.io/cloudnative-pg/postgresql:18.0" + backup: + s3AccessKey: access + s3SecretKey: secret + templates: + - templates/db.yaml + documentSelector: + path: kind + value: Cluster + asserts: + - matchRegex: + path: spec.imageName + pattern: "^ghcr\\.io/cloudnative-pg/postgresql:18\\.[0-9]+-standard-trixie$" + + - it: never renders a digest-pinned tag from bootstrap.sourceImageName + release: + name: pg-new + set: + bootstrap: + enabled: true + oldName: postgres-pg-0f1e2d3c + sourceImageName: "ghcr.io/cloudnative-pg/postgresql:18.1@sha256:0000000000000000000000000000000000000000000000000000000000000000" + backup: + s3AccessKey: access + s3SecretKey: secret + templates: + - templates/db.yaml + documentSelector: + path: kind + value: Cluster + asserts: + - matchRegex: + path: spec.imageName + pattern: "^ghcr\\.io/cloudnative-pg/postgresql:18\\.[0-9]+-standard-trixie$" + + - it: keeps a Cluster a recovery created on its image until it is checked + release: + name: pg-restored + set: + bootstrap: + enabled: true + oldName: pg-gone + backup: + s3AccessKey: access + s3SecretKey: secret + templates: + - templates/db.yaml + documentSelector: + path: kind + value: Cluster + asserts: + - equal: + path: spec.imageName + value: ghcr.io/cloudnative-pg/postgresql:18.1 + + - it: reads a live Cluster no recovery created on its own, whatever the bootstrap values say + release: + name: pg-clean + set: + bootstrap: + enabled: true + oldName: pg-test + sourceImageName: ghcr.io/cloudnative-pg/postgresql:18.1 + backup: + s3AccessKey: access + s3SecretKey: secret + templates: + - templates/db.yaml + documentSelector: + path: kind + value: Cluster + asserts: + - matchRegex: + path: spec.imageName + pattern: "^ghcr\\.io/cloudnative-pg/postgresql:18\\.[0-9]+-standard-trixie$" + + - it: restores a hand-set recovery onto the image of its source Cluster + release: + name: pg-new + set: + bootstrap: + enabled: true + oldName: pg-trixie + backup: + s3AccessKey: access + s3SecretKey: secret + templates: + - templates/db.yaml + documentSelector: + path: kind + value: Cluster + asserts: + - matchRegex: + path: spec.imageName + pattern: "^ghcr\\.io/cloudnative-pg/postgresql:18\\.[0-9]+-standard-trixie$" + + - it: holds a hand-set recovery of a bullseye source Cluster + release: + name: pg-new + set: + bootstrap: + enabled: true + oldName: pg-clean + backup: + s3AccessKey: access + s3SecretKey: secret + templates: + - templates/db.yaml + documentSelector: + path: kind + value: Cluster + asserts: + - equal: + path: spec.imageName + value: ghcr.io/cloudnative-pg/postgresql:18.1 + + - it: does not read a Cluster named like the server name of a RestoreJob + release: + name: pg-new + set: + bootstrap: + enabled: true + oldName: pg-test + newServerName: pg-new-restore-0123456789abcdef + backup: + s3AccessKey: access + s3SecretKey: secret + templates: + - templates/db.yaml + documentSelector: + path: kind + value: Cluster + asserts: + - matchRegex: + path: spec.imageName + pattern: "^ghcr\\.io/cloudnative-pg/postgresql:18\\.[0-9]+-standard-trixie$" + + - it: ignores a bootstrap.sourceImageName left over once the recovery is done + release: + name: pg-trixie + set: + bootstrap: + enabled: false + sourceImageName: ghcr.io/cloudnative-pg/postgresql:18.1 + templates: + - templates/db.yaml + documentSelector: + path: kind + value: Cluster + asserts: + - matchRegex: + path: spec.imageName + pattern: "^ghcr\\.io/cloudnative-pg/postgresql:18\\.[0-9]+-standard-trixie$" + + - it: never holds a postgis cluster on a postgresql image + release: + name: pg-new + set: + flavor: postgis + version: v17 + bootstrap: + enabled: true + oldName: postgres-pg-0f1e2d3c + sourceImageName: ghcr.io/cloudnative-pg/postgresql:17.7 + backup: + s3AccessKey: access + s3SecretKey: secret + templates: + - templates/db.yaml + documentSelector: + path: kind + value: Cluster + asserts: + - matchRegex: + path: spec.imageName + pattern: "^ghcr\\.io/cloudnative-pg/postgis:" + + - it: checks a bullseye cluster from its own image + release: + name: pg-unchecked + templates: + - templates/locale-check-hook.yaml + documentSelector: + path: kind + value: Job + asserts: + - equal: + path: spec.template.spec.initContainers[0].image + value: ghcr.io/cloudnative-pg/postgresql:18.1 + + - it: rechecks a held cluster from its held image + templates: + - templates/locale-check-hook.yaml + documentSelector: + path: kind + value: Job + asserts: + - equal: + path: spec.template.spec.initContainers[0].image + value: ghcr.io/cloudnative-pg/postgresql:18.1 + + - it: skips the check once the change is allowed + set: + allowCollationChange: true + templates: + - templates/locale-check-hook.yaml + asserts: + - hasDocuments: + count: 0 + + - it: skips the check for a cluster already on trixie + release: + name: pg-trixie + templates: + - templates/locale-check-hook.yaml + asserts: + - hasDocuments: + count: 0 + + - it: skips the check for a new cluster + release: + name: pg-new + templates: + - templates/locale-check-hook.yaml + asserts: + - hasDocuments: + count: 0 + + - it: does not check a cluster while its restore is in progress + release: + name: pg-unchecked + set: + bootstrap: + enabled: true + oldName: pg-test + backup: + s3AccessKey: access + s3SecretKey: secret + templates: + - templates/locale-check-hook.yaml + asserts: + - hasDocuments: + count: 0 + + - it: names the hook resources so that they cannot take the names CNPG gives another cluster + release: + name: pg-unchecked + templates: + - templates/locale-check-hook.yaml + documentSelector: + path: kind + value: Job + asserts: + - matchRegex: + path: metadata.name + pattern: ^locale-check-pg-unchecked-[0-9a-f]{8}$ + + - it: lets the role patch only its own Cluster + release: + name: pg-unchecked + templates: + - templates/locale-check-hook.yaml + documentSelector: + path: kind + value: Role + asserts: + - equal: + path: rules + value: + - apiGroups: ["postgresql.cnpg.io"] + resources: ["clusters"] + resourceNames: ["pg-unchecked"] + verbs: ["get", "patch"] diff --git a/packages/apps/postgres/values.schema.json b/packages/apps/postgres/values.schema.json index 4b5542d15..df4bce4b9 100644 --- a/packages/apps/postgres/values.schema.json +++ b/packages/apps/postgres/values.schema.json @@ -149,6 +149,11 @@ "postgis" ] }, + "allowCollationChange": { + "description": "Allow a cluster created on a Debian bullseye image (before the move to standard-trixie) to move to the new image without a clean locale check. Such a cluster is checked before each upgrade, except while `bootstrap.enabled` is set (set it back to false once a restore set up by hand has finished), and stays on its current image until the check finds nothing that depends on a collation other than C, POSIX or builtin: while this is false, a cluster the check found affected (an ICU or libc locale, or C.UTF-8) or could not finish on stays put, because glibc and ICU on the new image sort text differently and every index on such text must be rebuilt. A held cluster runs the bare bullseye tag it has, gets no further PostgreSQL minors and so none of their security fixes, and refuses a change of `version`, since new majors are built only on the new images. To leave that state, either remove the dependency (move such columns and indexes to C, or to the builtin `pg_c_utf8` on PostgreSQL 17 and later) and let the next upgrade check again, or set this to true in a maintenance window: the cluster moves on the next upgrade, replicas restart on the new image first and can return wrong results through `-ro`, and unique indexes can accept duplicates, until the indexes are rebuilt on the primary. The init Job rebuilds only indexes on collations that record a version (ICU, and libc locales other than C.*): rebuild indexes on C.UTF-8 or another C.* locale by hand with REINDEX, and check range partitions, CHECK constraints and materialized views on such text, which a rebuild does not fix. A held cluster shows the hold only as an unchanged image; the result and the objects found are in the `postgres.cozystack.io/locale-data` and `postgres.cozystack.io/locale-data-objects` annotations of the cnpg.io Cluster, which an administrator can read. A restore of a backup taken on one of those bullseye images comes back on that image and is checked by the next upgrade.", + "type": "boolean", + "default": false + }, "tls": { "description": "TLS configuration for server connections.", "type": "object", @@ -476,6 +481,11 @@ "description": "Server name (S3 path prefix) used by the original cluster when writing backups; passed to the barman-cloud plugin via `externalClusters[].plugin.parameters.serverName`. Defaults to `bootstrap.oldName`. Set this only when the original cluster wrote backups under an explicit server name that differed from its Kubernetes resource name.", "type": "string", "default": "" + }, + "sourceImageName": { + "description": "Image of the cluster the backup was taken from. A restore of a backup taken on one of the bare Debian bullseye tags the chart used before standard-trixie comes back on that image (see `allowCollationChange`); any other value is ignored. The CNPG backup driver sets this on restore and clears it with `enabled`.", + "type": "string", + "default": "" } } } diff --git a/packages/apps/postgres/values.yaml b/packages/apps/postgres/values.yaml index a8d324dc8..3d31f8b1d 100644 --- a/packages/apps/postgres/values.yaml +++ b/packages/apps/postgres/values.yaml @@ -95,6 +95,9 @@ version: v18 ## @param {Flavor} flavor - PostgreSQL image flavor, fixed when the cluster is created. `postgresql` uses the CloudNativePG PostgreSQL image. `postgis` uses the CloudNativePG PostGIS image, which adds postgis, postgis_raster, postgis_topology, postgis_sfcgal, postgis_tiger_geocoder and address_standardizer; enable them per database in `databases..extensions`. Changing the flavor of an existing cluster is refused, and a backup restores only into a cluster of the flavor it was taken from: to change flavor, create a new cluster and move the data with a logical dump (pg_dump / pg_restore). flavor: postgresql +## @param {bool} allowCollationChange - Allow a cluster created on a Debian bullseye image (before the move to standard-trixie) to move to the new image without a clean locale check. Such a cluster is checked before each upgrade, except while `bootstrap.enabled` is set (set it back to false once a restore set up by hand has finished), and stays on its current image until the check finds nothing that depends on a collation other than C, POSIX or builtin: while this is false, a cluster the check found affected (an ICU or libc locale, or C.UTF-8) or could not finish on stays put, because glibc and ICU on the new image sort text differently and every index on such text must be rebuilt. A held cluster runs the bare bullseye tag it has, gets no further PostgreSQL minors and so none of their security fixes, and refuses a change of `version`, since new majors are built only on the new images. To leave that state, either remove the dependency (move such columns and indexes to C, or to the builtin `pg_c_utf8` on PostgreSQL 17 and later) and let the next upgrade check again, or set this to true in a maintenance window: the cluster moves on the next upgrade, replicas restart on the new image first and can return wrong results through `-ro`, and unique indexes can accept duplicates, until the indexes are rebuilt on the primary. The init Job rebuilds only indexes on collations that record a version (ICU, and libc locales other than C.*): rebuild indexes on C.UTF-8 or another C.* locale by hand with REINDEX, and check range partitions, CHECK constraints and materialized views on such text, which a rebuild does not fix. A held cluster shows the hold only as an unchanged image; the result and the objects found are in the `postgres.cozystack.io/locale-data` and `postgres.cozystack.io/locale-data-objects` annotations of the cnpg.io Cluster, which an administrator can read. A restore of a backup taken on one of those bullseye images comes back on that image and is checked by the next upgrade. +allowCollationChange: false + ## ## @section TLS configuration ## @@ -382,6 +385,7 @@ backup: ## @field {string} oldName - Previous cluster name before deletion. ## @field {string} [serverName] - Server name (S3 path prefix) used by the original cluster when writing backups; passed to the barman-cloud plugin via `externalClusters[].plugin.parameters.serverName`. Defaults to `bootstrap.oldName`. Set this only when the original cluster wrote backups under an explicit server name that differed from its Kubernetes resource name. ## @field {string} [newServerName] - WAL-archive server name (S3 path prefix) the RESTORED cluster writes to. Must differ from `serverName` (the recovery source) so a restored cluster archives to a fresh, empty prefix and barman-cloud-check-wal-archive passes while it recovers from the source's prefix. The CNPG backup driver sets this on restore; empty means the cluster archives under its own name. +## @field {string} [sourceImageName] - Image of the cluster the backup was taken from. A restore of a backup taken on one of the bare Debian bullseye tags the chart used before standard-trixie comes back on that image (see `allowCollationChange`); any other value is ignored. The CNPG backup driver sets this on restore and clears it with `enabled`. ## @param {Bootstrap} bootstrap - Bootstrap configuration. bootstrap: @@ -392,3 +396,4 @@ bootstrap: oldName: "" serverName: "" newServerName: "" + sourceImageName: "" diff --git a/packages/system/postgres-rd/cozyrds/postgres.yaml b/packages/system/postgres-rd/cozyrds/postgres.yaml index 052cb575d..82ce0ac6b 100644 --- a/packages/system/postgres-rd/cozyrds/postgres.yaml +++ b/packages/system/postgres-rd/cozyrds/postgres.yaml @@ -30,7 +30,7 @@ spec: singular: postgres plural: postgreses openAPISchema: |- - {"title":"Chart Values","type":"object","properties":{"replicas":{"description":"Number of Postgres replicas. Under active autoscaling this is the resting/seed count, not the live count — KEDA drives the live count via `/scale`. Disabling autoscaling does NOT automatically bring the live count back to `replicas`: the client-side merge writes `instances` only when the rendered value changes, so a cluster KEDA grew past `replicas` stays there with no autoscaler left to reduce it — lower `replicas` to the count you want and it rebases down (shedding the surplus replicas + PVCs). Lowering it below the live count, or disabling/dry-running while it sits below the live count, sheds in one step past the scaleDown pacing; stage it to the live count first (suspend the HelmRelease and `kubectl scale` if needed) to avoid a transient. Must stay greater than `quorum.maxSyncReplicas`.","type":"integer","default":2},"resources":{"description":"Explicit CPU and memory configuration for each PostgreSQL replica. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","default":{},"properties":{"cpu":{"description":"CPU available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Memory (RAM) available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted.","type":"string","default":"t1.micro","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]},"size":{"description":"Persistent Volume Claim size available for application data.","default":"10Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"storageClass":{"description":"StorageClass used to store the data.","type":"string","default":"","x-kubernetes-validations":[{"rule":"self == oldSelf","message":"storageClass is immutable"}],"x-cozystack-options":{"source":"storageclass"}},"external":{"description":"Enable external access from outside the cluster.","type":"boolean","default":false},"version":{"description":"PostgreSQL major version to deploy","type":"string","default":"v18","enum":["v18","v17","v16","v15","v14","v13"]},"flavor":{"description":"PostgreSQL image flavor, fixed when the cluster is created. `postgresql` uses the CloudNativePG PostgreSQL image. `postgis` uses the CloudNativePG PostGIS image, which adds postgis, postgis_raster, postgis_topology, postgis_sfcgal, postgis_tiger_geocoder and address_standardizer; enable them per database in `databases..extensions`. Changing the flavor of an existing cluster is refused, and a backup restores only into a cluster of the flavor it was taken from: to change flavor, create a new cluster and move the data with a logical dump (pg_dump / pg_restore).","type":"string","default":"postgresql","enum":["postgresql","postgis"]},"tls":{"description":"TLS configuration for server connections.","type":"object","default":{},"properties":{"enabled":{"description":"Tri-state switch controlling whether the chart injects the external hostnames into the operator-managed CNPG cert via spec.certificates.serverAltDNSNames. When omitted, the chart injects them if `external: true` and skips them otherwise. Set explicitly to `true` to inject regardless of `external` (no-op when `external: false` since there is no external hostname to add). Set to `false` to skip injection. Note that CNPG keeps its built-in TLS on the wire regardless of this flag — this toggle only controls the chart-side SAN injection; to disable PostgreSQL TLS entirely set `postgresql.parameters.ssl = \"off\"` at the CNPG layer.","type":"boolean"},"required":{"description":"Tri-state switch controlling whether the server refuses sessions that are not encrypted. When omitted, it is on if `external: true` and off otherwise. When on, the chart renders `spec.postgresql.pg_hba` with `hostssl all all all scram-sha-256` (`md5` on PostgreSQL 13, matching CloudNativePG's default rule) followed by `host all all all reject`, so a client that connects with `sslmode=disable` is refused instead of getting a plaintext session; in-cluster clients are held to the same rule, since the pod network cannot be told apart from an external client. Set to `false` to keep accepting plaintext sessions on an external instance, or to `true` to require TLS on an in-cluster one. Rendering fails if `postgresql.parameters.ssl` is off while this is in effect.","type":"boolean"}}},"postgresql":{"description":"PostgreSQL server configuration.","type":"object","default":{},"properties":{"parameters":{"description":"PostgreSQL server parameters. Values may be strings or integers; integers are coerced to strings by the template (e.g. both `max_connections: 100` and `max_connections: \"100\"` are accepted). BLOCKED (enable arbitrary code execution): archive_command, restore_command, ssl_passphrase_command, archive_cleanup_command, recovery_end_command, dynamic_library_path, local_preload_libraries, session_preload_libraries, shared_preload_libraries. Do NOT override CloudNativePG-managed parameters: archive_mode, primary_conninfo, wal_level, max_replication_slots.","type":"object","default":{"max_connections":"100"},"additionalProperties":{"anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}},"sharedPreloadLibraries":{"description":"Libraries loaded at server start, restricted to an allowlist of modules already shipped in the PostgreSQL image. CloudNativePG also preloads `pg_stat_statements`, `auto_explain` and `pgaudit` by itself whenever `parameters` sets a key under their prefix (e.g. `pg_stat_statements.track`), so removing one of them from this list does not unload it while such a key is set; `pg_prewarm` is preloaded only through this list. Changing the list restarts PostgreSQL on every instance, the primary included, so writes pause briefly.","type":"array","items":{"type":"string","enum":["pg_stat_statements","auto_explain","pgaudit","pg_prewarm"]}}}},"quorum":{"description":"Quorum configuration for synchronous replication.","type":"object","default":{},"required":["maxSyncReplicas","minSyncReplicas"],"properties":{"maxSyncReplicas":{"description":"Maximum number of synchronous replicas allowed (must be less than total replicas). Under autoscaling it also sets the scale-down floor (the effective minimum is `max(minReplicas, maxSyncReplicas+1, 2)`); the chart fails to render if that floor exceeds `autoscaling.maxReplicas`.","type":"integer","default":0},"minSyncReplicas":{"description":"Minimum number of synchronous replicas required for commit.","type":"integer","default":0}}},"autoscaling":{"description":"Read-replica autoscaling configuration.","type":"object","default":{},"required":["dryRun","enabled","maxReplicas","maxReplicationLagSeconds","metric","minReplicas","serverAddress","target","transition"],"properties":{"dryRun":{"description":"Recommendation mode: keep the static count and render the ScaledObject with both scaling directions paused, so KEDA keeps the HPA and keeps serving its trigger metric but actuates neither way. Note both scaling policies are disabled, so the HPA's desiredReplicas is frozen to the current count - read the recommendation from the matching read-load dashboard panel for your metric (connections or CPU): desired = 1 + ceil(read load / target), clamped to [effectiveMin..maxReplicas] where effectiveMin = max(minReplicas, maxSyncReplicas+1, 2), not from the desired-replicas line. Like disabling, flipping a LIVE autoscaled cluster into dryRun re-renders `instances: replicas` (the raw static value, which can be below the autoscaling floor); if `replicas` is below the live count, stage it to the live count first (see the enablement note) or the cluster sheds down to `replicas`. No shed occurs when the rendered value is unchanged (replicas already equals the active seed) — client-side merge is then a no-op and the live count is preserved. Permanent, unlike `transition`.","type":"boolean","default":false},"enabled":{"description":"Enable horizontal autoscaling of read replicas. Requires the platform `keda` package to be enabled by an administrator first; the chart fails to render (rather than break the release) if KEDA is not installed. Prerequisite: the queried vmselect must hold BOTH the CNPG metrics (cnpg_backends_total / container CPU) AND kube_pod_labels (kube-state-metrics). This holds for a tenant on the shared root monitoring stack (`monitoring: false`, both land in tenant-root). A tenant running its OWN Monitoring app (`monitoring: true`) has the CNPG metrics but not kube_pod_labels (KSM is root-only), so it must set `serverAddress` to a vmselect carrying both series or autoscaling never actuates.","type":"boolean","default":false},"maxReplicas":{"description":"Maximum total instances. Must be >= minReplicas and >= the synchronous-quorum floor (maxSyncReplicas+1); the chart fails to render (rather than silently run an unbounded instance count) if the effective floor exceeds it - raise maxReplicas. HAZARD: lowering maxReplicas below the live count makes the HPA cut straight to the new maximum in one step (the current>max branch bypasses the scale-down pacing), shedding the surplus replicas + PVCs at once; to lower it deliberately, suspend the HelmRelease and pin the live count with `kubectl scale` first.","type":"integer","default":6},"maxReplicationLagSeconds":{"description":"Freeze scaling while replication lag exceeds this (seconds) and the primary is writing. 0 disables the brake. Default 0: the freeze branch has only been validated on a live cluster in its non-braking (pass-through) form, so the lag brake is opt-in until the braking path is exercised under load; set a positive value (e.g. 30) to enable it.","type":"integer","default":0},"metric":{"description":"Read-load signal to scale on.","type":"string","default":"ReadConnections","enum":["ReadConnections","ReadCPUUtilization"]},"minReplicas":{"description":"Minimum total instances; raised to the synchronous-quorum floor (`maxSyncReplicas + 1`) and to 2 when either is higher.","type":"integer","default":2},"serverAddress":{"description":"Override the Prometheus/vmselect URL the ScaledObject queries. Empty (default) derives `http://vmselect-shortterm..svc:8481/select/0/prometheus`. Set it when the derived vmselect does not hold both the CNPG metrics and kube_pod_labels (e.g. `monitoring: true` tenants, or a non-default `metricsStorages` name). SSRF constraint: the host must be an in-cluster Service DNS name (`..svc[.]`) whose namespace is within the tenant's own subtree (its namespace, its parents, or `tenant-root`) — the cluster-privileged KEDA operator fetches this URL every poll, so it is refused a metadata endpoint, an external host, or a sibling/system namespace. Residual surface (accepted trade-off): `tenant-root` is always allowed because the derived default points there, so a tenant can still aim the operator at any Service in `tenant-root` on any port/path (a blind in-cluster reachability probe — the operator reads no response body back to the tenant); the egress NetworkPolicy does not narrow that.","type":"string","default":""},"target":{"description":"Target read load per read-serving replica (unit depends on `metric`: active connections, or CPU millicores). Dimensionless integer - a resource.Quantity here would accept `150m`, which PromQL reads as 150 minutes and KEDA cannot use as a threshold.","type":"integer","default":150},"transition":{"description":"Migration phase 1: render `.spec.instances` from `replicas` (which the operator stages to the current live count) AND pause the ScaledObject in both directions, so KEDA stands up with its HPA present but not actuating. Flip to false (phase 2) to hand the runtime count to KEDA. Because the both-direction pause keeps the HPA (not the HPA-deleting full pause), KEDA is genuinely warm at phase 2 — no HPA recreate — and because the active seed is max(replicas, effectiveMin), phase 2 re-renders the same instance count phase 1 did (when `replicas` is staged at/above the floor), so the flip is a merge no-op with no dip. The HPA's scaleUp stabilization window still smooths the first actuation.","type":"boolean","default":false}}},"users":{"description":"Users configuration map. Passwords are always auto-generated and stored in the `-credentials` Secret; they cannot be set from values — read a user's password from that Secret. A `password` left over in values from before the field was removed is ignored by the render and draws an admission warning, but it is not inert on an upgraded release: the chart preserves whatever password is already in the Secret, which on the first upgrade is the value that was set before removal, so that value stays the live credential until it is rotated (dedicated rotation is tracked in cozystack/community#72). The live password lives only in the Secret.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"bypassRls":{"description":"Whether the user can bypass row-level security policies (BYPASSRLS). A role can only create other roles carrying BYPASSRLS if it holds the attribute itself, so this is required alongside `createRole` to provision a privileged service role.","type":"boolean"},"createRole":{"description":"Whether the user can create and manage roles (CREATEROLE). Requires PostgreSQL 16 or newer. Setting it back to `false` withdraws the attribute only: the roles the user created, and its ADMIN and SET memberships in them, stay. Once any user has held it, the chart no longer adopts an existing role it did not create, so a user or database declared later under the name of such a role fails the init job until a platform administrator drops that role.","type":"boolean"},"replication":{"description":"Whether the user has replication privileges.","type":"boolean"}}}},"databases":{"description":"Databases configuration map. The PostgreSQL system databases `postgres`, `template0` and `template1` are refused.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"extensions":{"description":"List of enabled PostgreSQL extensions.","type":"array","items":{"type":"string"}},"roles":{"description":"Roles assigned to users.","type":"object","properties":{"admin":{"description":"List of users with admin privileges.","type":"array","items":{"type":"string"}},"readonly":{"description":"List of users with read-only privileges.","type":"array","items":{"type":"string"}}}}}}},"backup":{"description":"Backup configuration.","type":"object","default":{},"required":["enabled"],"properties":{"destinationPath":{"description":"DEPRECATED. Per-tenant S3 configuration is superseded by the platform-managed `cozy-default` BackupClass and the `cozy-backups` system bucket. Leave empty for new installations; the BackupClass driver picks up the system-managed coordinates. Kept for in-place upgrade compatibility.","type":"string","default":"s3://bucket/path/to/folder/"},"enabled":{"description":"Enable regular backups.","type":"boolean","default":false},"endpointCA":{"description":"DEPRECATED. Pre-existing Secret with the CA bundle the barman-cloud plugin should trust when reaching a self-signed S3 endpoint. Used for both backup and bootstrap recovery in the legacy chart-managed flow.","type":"object","default":{},"properties":{"key":{"description":"Key within the Secret containing the CA bundle. Defaults to `ca.crt`.","type":"string","default":""},"name":{"description":"Name of the Secret in the application namespace. Empty means no endpointCA is emitted (the plugin uses the system trust store).","type":"string","default":""}}},"endpointURL":{"description":"DEPRECATED. See `destinationPath`.","type":"string","default":"http://minio-gateway-service:9000"},"retentionPolicy":{"description":"Retention policy (e.g. \"30d\").","type":"string","default":"30d"},"s3AccessKey":{"description":"DEPRECATED. Tenants no longer supply S3 keys; the system Bucket Secret is projected into the tenant namespace by the backup controller. Ignored when `s3CredentialsSecret.name` is set or `useSystemBucket` is true. The chart skips materialising `-s3-creds` whenever this field is empty so a default install does not leak placeholder credentials into the tenant namespace.","type":"string","default":""},"s3CredentialsSecret":{"description":"DEPRECATED. Pre-existing Secret with S3 credentials. Use the platform-managed `cozy-default` BackupClass instead. When set, the chart references this Secret directly (legacy chart-managed flow). The CNPG backup driver writes this field on restore so credentials never land in the CR `.spec`.","type":"object","default":{},"properties":{"accessKeyIDKey":{"description":"Key in the Secret holding the access key ID. Defaults to `AWS_ACCESS_KEY_ID`.","type":"string","default":""},"name":{"description":"Name of the Secret in the application namespace. Empty means the chart materialises `-s3-creds` from `s3AccessKey`/`s3SecretKey`.","type":"string","default":""},"secretAccessKeyKey":{"description":"Key in the Secret holding the secret access key. Defaults to `AWS_SECRET_ACCESS_KEY`.","type":"string","default":""}}},"s3SecretKey":{"description":"DEPRECATED. See `s3AccessKey`.","type":"string","default":""},"schedule":{"description":"Legacy. Cron schedule for the chart-emitted ScheduledBackup, either a standard five-field cron such as `0 2 * * *` for every day at 02:00, or six fields with leading seconds such as `0 0 2 * * *` for the same time. Empty means no chart-managed schedule, which is the recommended setup when a `BackupClass` from `backups.cozystack.io` already drives backup orchestration. In the legacy chart-managed flow `spec.plugins` plus the barman-cloud ObjectStore is rendered when `backup.enabled=true` AND `useSystemBucket=false` AND `destinationPath` is non-empty AND inline-or-external creds are supplied; in the platform `useSystemBucket=true` flow the chart skips emitting `spec.plugins` and the CNPG driver SSA-applies the ObjectStore and patches `spec.plugins` onto the live Cluster at first BackupJob time.","type":"string","default":""},"useSystemBucket":{"description":"Opt-in: when true, the chart-emitted `-s3-creds` Secret is skipped AND `spec.plugins` (plus the barman-cloud ObjectStore) is left UNSET in the chart-rendered Cluster — the cozy-default BackupClass driver SSA-applies an ObjectStore (carrying destinationPath/endpointURL/credentials) and patches `spec.plugins` on the live Cluster when the first BackupJob runs. Consequence: plugin WAL archiving is NOT active until that first BackupJob fires; WAL accumulates on the PVC in the meantime, so fire an ad-hoc BackupJob immediately after enabling the flag on existing releases. Use together with the platform `cozy-default` BackupClass — tenants do not need to fill `s3AccessKey`/`s3SecretKey` or `destinationPath`/`endpointURL`. The destination path automatically scopes to `s3://cozy-backups///`.","type":"boolean","default":false}}},"bootstrap":{"description":"Bootstrap configuration.","type":"object","default":{},"required":["enabled","oldName"],"properties":{"backupID":{"description":"Barman ID of the base backup to recover from, passed as `recoveryTarget.backupID`. Empty lets the barman-cloud plugin pick one: the newest backup when `recoveryTime` is empty, otherwise the newest one ending at or before it, on any timeline. The CNPG backup driver sets this on restore.","type":"string","default":""},"enabled":{"description":"Whether to restore from a backup.","type":"boolean","default":false},"newServerName":{"description":"WAL-archive server name (S3 path prefix) the RESTORED cluster writes to. Must differ from `serverName` (the recovery source) so a restored cluster archives to a fresh, empty prefix and barman-cloud-check-wal-archive passes while it recovers from the source's prefix. The CNPG backup driver sets this on restore; empty means the cluster archives under its own name.","type":"string","default":""},"oldName":{"description":"Previous cluster name before deletion.","type":"string","default":""},"recoveryTime":{"description":"Timestamp (RFC3339) for point-in-time recovery; empty means latest.","type":"string","default":""},"serverName":{"description":"Server name (S3 path prefix) used by the original cluster when writing backups; passed to the barman-cloud plugin via `externalClusters[].plugin.parameters.serverName`. Defaults to `bootstrap.oldName`. Set this only when the original cluster wrote backups under an explicit server name that differed from its Kubernetes resource name.","type":"string","default":""}}}}} + {"title":"Chart Values","type":"object","properties":{"replicas":{"description":"Number of Postgres replicas. Under active autoscaling this is the resting/seed count, not the live count — KEDA drives the live count via `/scale`. Disabling autoscaling does NOT automatically bring the live count back to `replicas`: the client-side merge writes `instances` only when the rendered value changes, so a cluster KEDA grew past `replicas` stays there with no autoscaler left to reduce it — lower `replicas` to the count you want and it rebases down (shedding the surplus replicas + PVCs). Lowering it below the live count, or disabling/dry-running while it sits below the live count, sheds in one step past the scaleDown pacing; stage it to the live count first (suspend the HelmRelease and `kubectl scale` if needed) to avoid a transient. Must stay greater than `quorum.maxSyncReplicas`.","type":"integer","default":2},"resources":{"description":"Explicit CPU and memory configuration for each PostgreSQL replica. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","default":{},"properties":{"cpu":{"description":"CPU available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Memory (RAM) available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted.","type":"string","default":"t1.micro","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]},"size":{"description":"Persistent Volume Claim size available for application data.","default":"10Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"storageClass":{"description":"StorageClass used to store the data.","type":"string","default":"","x-kubernetes-validations":[{"rule":"self == oldSelf","message":"storageClass is immutable"}],"x-cozystack-options":{"source":"storageclass"}},"external":{"description":"Enable external access from outside the cluster.","type":"boolean","default":false},"version":{"description":"PostgreSQL major version to deploy","type":"string","default":"v18","enum":["v18","v17","v16","v15","v14","v13"]},"flavor":{"description":"PostgreSQL image flavor, fixed when the cluster is created. `postgresql` uses the CloudNativePG PostgreSQL image. `postgis` uses the CloudNativePG PostGIS image, which adds postgis, postgis_raster, postgis_topology, postgis_sfcgal, postgis_tiger_geocoder and address_standardizer; enable them per database in `databases..extensions`. Changing the flavor of an existing cluster is refused, and a backup restores only into a cluster of the flavor it was taken from: to change flavor, create a new cluster and move the data with a logical dump (pg_dump / pg_restore).","type":"string","default":"postgresql","enum":["postgresql","postgis"]},"allowCollationChange":{"description":"Allow a cluster created on a Debian bullseye image (before the move to standard-trixie) to move to the new image without a clean locale check. Such a cluster is checked before each upgrade, except while `bootstrap.enabled` is set (set it back to false once a restore set up by hand has finished), and stays on its current image until the check finds nothing that depends on a collation other than C, POSIX or builtin: while this is false, a cluster the check found affected (an ICU or libc locale, or C.UTF-8) or could not finish on stays put, because glibc and ICU on the new image sort text differently and every index on such text must be rebuilt. A held cluster runs the bare bullseye tag it has, gets no further PostgreSQL minors and so none of their security fixes, and refuses a change of `version`, since new majors are built only on the new images. To leave that state, either remove the dependency (move such columns and indexes to C, or to the builtin `pg_c_utf8` on PostgreSQL 17 and later) and let the next upgrade check again, or set this to true in a maintenance window: the cluster moves on the next upgrade, replicas restart on the new image first and can return wrong results through `-ro`, and unique indexes can accept duplicates, until the indexes are rebuilt on the primary. The init Job rebuilds only indexes on collations that record a version (ICU, and libc locales other than C.*): rebuild indexes on C.UTF-8 or another C.* locale by hand with REINDEX, and check range partitions, CHECK constraints and materialized views on such text, which a rebuild does not fix. A held cluster shows the hold only as an unchanged image; the result and the objects found are in the `postgres.cozystack.io/locale-data` and `postgres.cozystack.io/locale-data-objects` annotations of the cnpg.io Cluster, which an administrator can read. A restore of a backup taken on one of those bullseye images comes back on that image and is checked by the next upgrade.","type":"boolean","default":false},"tls":{"description":"TLS configuration for server connections.","type":"object","default":{},"properties":{"enabled":{"description":"Tri-state switch controlling whether the chart injects the external hostnames into the operator-managed CNPG cert via spec.certificates.serverAltDNSNames. When omitted, the chart injects them if `external: true` and skips them otherwise. Set explicitly to `true` to inject regardless of `external` (no-op when `external: false` since there is no external hostname to add). Set to `false` to skip injection. Note that CNPG keeps its built-in TLS on the wire regardless of this flag — this toggle only controls the chart-side SAN injection; to disable PostgreSQL TLS entirely set `postgresql.parameters.ssl = \"off\"` at the CNPG layer.","type":"boolean"},"required":{"description":"Tri-state switch controlling whether the server refuses sessions that are not encrypted. When omitted, it is on if `external: true` and off otherwise. When on, the chart renders `spec.postgresql.pg_hba` with `hostssl all all all scram-sha-256` (`md5` on PostgreSQL 13, matching CloudNativePG's default rule) followed by `host all all all reject`, so a client that connects with `sslmode=disable` is refused instead of getting a plaintext session; in-cluster clients are held to the same rule, since the pod network cannot be told apart from an external client. Set to `false` to keep accepting plaintext sessions on an external instance, or to `true` to require TLS on an in-cluster one. Rendering fails if `postgresql.parameters.ssl` is off while this is in effect.","type":"boolean"}}},"postgresql":{"description":"PostgreSQL server configuration.","type":"object","default":{},"properties":{"parameters":{"description":"PostgreSQL server parameters. Values may be strings or integers; integers are coerced to strings by the template (e.g. both `max_connections: 100` and `max_connections: \"100\"` are accepted). BLOCKED (enable arbitrary code execution): archive_command, restore_command, ssl_passphrase_command, archive_cleanup_command, recovery_end_command, dynamic_library_path, local_preload_libraries, session_preload_libraries, shared_preload_libraries. Do NOT override CloudNativePG-managed parameters: archive_mode, primary_conninfo, wal_level, max_replication_slots.","type":"object","default":{"max_connections":"100"},"additionalProperties":{"anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}},"sharedPreloadLibraries":{"description":"Libraries loaded at server start, restricted to an allowlist of modules already shipped in the PostgreSQL image. CloudNativePG also preloads `pg_stat_statements`, `auto_explain` and `pgaudit` by itself whenever `parameters` sets a key under their prefix (e.g. `pg_stat_statements.track`), so removing one of them from this list does not unload it while such a key is set; `pg_prewarm` is preloaded only through this list. Changing the list restarts PostgreSQL on every instance, the primary included, so writes pause briefly.","type":"array","items":{"type":"string","enum":["pg_stat_statements","auto_explain","pgaudit","pg_prewarm"]}}}},"quorum":{"description":"Quorum configuration for synchronous replication.","type":"object","default":{},"required":["maxSyncReplicas","minSyncReplicas"],"properties":{"maxSyncReplicas":{"description":"Maximum number of synchronous replicas allowed (must be less than total replicas). Under autoscaling it also sets the scale-down floor (the effective minimum is `max(minReplicas, maxSyncReplicas+1, 2)`); the chart fails to render if that floor exceeds `autoscaling.maxReplicas`.","type":"integer","default":0},"minSyncReplicas":{"description":"Minimum number of synchronous replicas required for commit.","type":"integer","default":0}}},"autoscaling":{"description":"Read-replica autoscaling configuration.","type":"object","default":{},"required":["dryRun","enabled","maxReplicas","maxReplicationLagSeconds","metric","minReplicas","serverAddress","target","transition"],"properties":{"dryRun":{"description":"Recommendation mode: keep the static count and render the ScaledObject with both scaling directions paused, so KEDA keeps the HPA and keeps serving its trigger metric but actuates neither way. Note both scaling policies are disabled, so the HPA's desiredReplicas is frozen to the current count - read the recommendation from the matching read-load dashboard panel for your metric (connections or CPU): desired = 1 + ceil(read load / target), clamped to [effectiveMin..maxReplicas] where effectiveMin = max(minReplicas, maxSyncReplicas+1, 2), not from the desired-replicas line. Like disabling, flipping a LIVE autoscaled cluster into dryRun re-renders `instances: replicas` (the raw static value, which can be below the autoscaling floor); if `replicas` is below the live count, stage it to the live count first (see the enablement note) or the cluster sheds down to `replicas`. No shed occurs when the rendered value is unchanged (replicas already equals the active seed) — client-side merge is then a no-op and the live count is preserved. Permanent, unlike `transition`.","type":"boolean","default":false},"enabled":{"description":"Enable horizontal autoscaling of read replicas. Requires the platform `keda` package to be enabled by an administrator first; the chart fails to render (rather than break the release) if KEDA is not installed. Prerequisite: the queried vmselect must hold BOTH the CNPG metrics (cnpg_backends_total / container CPU) AND kube_pod_labels (kube-state-metrics). This holds for a tenant on the shared root monitoring stack (`monitoring: false`, both land in tenant-root). A tenant running its OWN Monitoring app (`monitoring: true`) has the CNPG metrics but not kube_pod_labels (KSM is root-only), so it must set `serverAddress` to a vmselect carrying both series or autoscaling never actuates.","type":"boolean","default":false},"maxReplicas":{"description":"Maximum total instances. Must be >= minReplicas and >= the synchronous-quorum floor (maxSyncReplicas+1); the chart fails to render (rather than silently run an unbounded instance count) if the effective floor exceeds it - raise maxReplicas. HAZARD: lowering maxReplicas below the live count makes the HPA cut straight to the new maximum in one step (the current>max branch bypasses the scale-down pacing), shedding the surplus replicas + PVCs at once; to lower it deliberately, suspend the HelmRelease and pin the live count with `kubectl scale` first.","type":"integer","default":6},"maxReplicationLagSeconds":{"description":"Freeze scaling while replication lag exceeds this (seconds) and the primary is writing. 0 disables the brake. Default 0: the freeze branch has only been validated on a live cluster in its non-braking (pass-through) form, so the lag brake is opt-in until the braking path is exercised under load; set a positive value (e.g. 30) to enable it.","type":"integer","default":0},"metric":{"description":"Read-load signal to scale on.","type":"string","default":"ReadConnections","enum":["ReadConnections","ReadCPUUtilization"]},"minReplicas":{"description":"Minimum total instances; raised to the synchronous-quorum floor (`maxSyncReplicas + 1`) and to 2 when either is higher.","type":"integer","default":2},"serverAddress":{"description":"Override the Prometheus/vmselect URL the ScaledObject queries. Empty (default) derives `http://vmselect-shortterm..svc:8481/select/0/prometheus`. Set it when the derived vmselect does not hold both the CNPG metrics and kube_pod_labels (e.g. `monitoring: true` tenants, or a non-default `metricsStorages` name). SSRF constraint: the host must be an in-cluster Service DNS name (`..svc[.]`) whose namespace is within the tenant's own subtree (its namespace, its parents, or `tenant-root`) — the cluster-privileged KEDA operator fetches this URL every poll, so it is refused a metadata endpoint, an external host, or a sibling/system namespace. Residual surface (accepted trade-off): `tenant-root` is always allowed because the derived default points there, so a tenant can still aim the operator at any Service in `tenant-root` on any port/path (a blind in-cluster reachability probe — the operator reads no response body back to the tenant); the egress NetworkPolicy does not narrow that.","type":"string","default":""},"target":{"description":"Target read load per read-serving replica (unit depends on `metric`: active connections, or CPU millicores). Dimensionless integer - a resource.Quantity here would accept `150m`, which PromQL reads as 150 minutes and KEDA cannot use as a threshold.","type":"integer","default":150},"transition":{"description":"Migration phase 1: render `.spec.instances` from `replicas` (which the operator stages to the current live count) AND pause the ScaledObject in both directions, so KEDA stands up with its HPA present but not actuating. Flip to false (phase 2) to hand the runtime count to KEDA. Because the both-direction pause keeps the HPA (not the HPA-deleting full pause), KEDA is genuinely warm at phase 2 — no HPA recreate — and because the active seed is max(replicas, effectiveMin), phase 2 re-renders the same instance count phase 1 did (when `replicas` is staged at/above the floor), so the flip is a merge no-op with no dip. The HPA's scaleUp stabilization window still smooths the first actuation.","type":"boolean","default":false}}},"users":{"description":"Users configuration map. Passwords are always auto-generated and stored in the `-credentials` Secret; they cannot be set from values — read a user's password from that Secret. A `password` left over in values from before the field was removed is ignored by the render and draws an admission warning, but it is not inert on an upgraded release: the chart preserves whatever password is already in the Secret, which on the first upgrade is the value that was set before removal, so that value stays the live credential until it is rotated (dedicated rotation is tracked in cozystack/community#72). The live password lives only in the Secret.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"bypassRls":{"description":"Whether the user can bypass row-level security policies (BYPASSRLS). A role can only create other roles carrying BYPASSRLS if it holds the attribute itself, so this is required alongside `createRole` to provision a privileged service role.","type":"boolean"},"createRole":{"description":"Whether the user can create and manage roles (CREATEROLE). Requires PostgreSQL 16 or newer. Setting it back to `false` withdraws the attribute only: the roles the user created, and its ADMIN and SET memberships in them, stay. Once any user has held it, the chart no longer adopts an existing role it did not create, so a user or database declared later under the name of such a role fails the init job until a platform administrator drops that role.","type":"boolean"},"replication":{"description":"Whether the user has replication privileges.","type":"boolean"}}}},"databases":{"description":"Databases configuration map. The PostgreSQL system databases `postgres`, `template0` and `template1` are refused.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"extensions":{"description":"List of enabled PostgreSQL extensions.","type":"array","items":{"type":"string"}},"roles":{"description":"Roles assigned to users.","type":"object","properties":{"admin":{"description":"List of users with admin privileges.","type":"array","items":{"type":"string"}},"readonly":{"description":"List of users with read-only privileges.","type":"array","items":{"type":"string"}}}}}}},"backup":{"description":"Backup configuration.","type":"object","default":{},"required":["enabled"],"properties":{"destinationPath":{"description":"DEPRECATED. Per-tenant S3 configuration is superseded by the platform-managed `cozy-default` BackupClass and the `cozy-backups` system bucket. Leave empty for new installations; the BackupClass driver picks up the system-managed coordinates. Kept for in-place upgrade compatibility.","type":"string","default":"s3://bucket/path/to/folder/"},"enabled":{"description":"Enable regular backups.","type":"boolean","default":false},"endpointCA":{"description":"DEPRECATED. Pre-existing Secret with the CA bundle the barman-cloud plugin should trust when reaching a self-signed S3 endpoint. Used for both backup and bootstrap recovery in the legacy chart-managed flow.","type":"object","default":{},"properties":{"key":{"description":"Key within the Secret containing the CA bundle. Defaults to `ca.crt`.","type":"string","default":""},"name":{"description":"Name of the Secret in the application namespace. Empty means no endpointCA is emitted (the plugin uses the system trust store).","type":"string","default":""}}},"endpointURL":{"description":"DEPRECATED. See `destinationPath`.","type":"string","default":"http://minio-gateway-service:9000"},"retentionPolicy":{"description":"Retention policy (e.g. \"30d\").","type":"string","default":"30d"},"s3AccessKey":{"description":"DEPRECATED. Tenants no longer supply S3 keys; the system Bucket Secret is projected into the tenant namespace by the backup controller. Ignored when `s3CredentialsSecret.name` is set or `useSystemBucket` is true. The chart skips materialising `-s3-creds` whenever this field is empty so a default install does not leak placeholder credentials into the tenant namespace.","type":"string","default":""},"s3CredentialsSecret":{"description":"DEPRECATED. Pre-existing Secret with S3 credentials. Use the platform-managed `cozy-default` BackupClass instead. When set, the chart references this Secret directly (legacy chart-managed flow). The CNPG backup driver writes this field on restore so credentials never land in the CR `.spec`.","type":"object","default":{},"properties":{"accessKeyIDKey":{"description":"Key in the Secret holding the access key ID. Defaults to `AWS_ACCESS_KEY_ID`.","type":"string","default":""},"name":{"description":"Name of the Secret in the application namespace. Empty means the chart materialises `-s3-creds` from `s3AccessKey`/`s3SecretKey`.","type":"string","default":""},"secretAccessKeyKey":{"description":"Key in the Secret holding the secret access key. Defaults to `AWS_SECRET_ACCESS_KEY`.","type":"string","default":""}}},"s3SecretKey":{"description":"DEPRECATED. See `s3AccessKey`.","type":"string","default":""},"schedule":{"description":"Legacy. Cron schedule for the chart-emitted ScheduledBackup, either a standard five-field cron such as `0 2 * * *` for every day at 02:00, or six fields with leading seconds such as `0 0 2 * * *` for the same time. Empty means no chart-managed schedule, which is the recommended setup when a `BackupClass` from `backups.cozystack.io` already drives backup orchestration. In the legacy chart-managed flow `spec.plugins` plus the barman-cloud ObjectStore is rendered when `backup.enabled=true` AND `useSystemBucket=false` AND `destinationPath` is non-empty AND inline-or-external creds are supplied; in the platform `useSystemBucket=true` flow the chart skips emitting `spec.plugins` and the CNPG driver SSA-applies the ObjectStore and patches `spec.plugins` onto the live Cluster at first BackupJob time.","type":"string","default":""},"useSystemBucket":{"description":"Opt-in: when true, the chart-emitted `-s3-creds` Secret is skipped AND `spec.plugins` (plus the barman-cloud ObjectStore) is left UNSET in the chart-rendered Cluster — the cozy-default BackupClass driver SSA-applies an ObjectStore (carrying destinationPath/endpointURL/credentials) and patches `spec.plugins` on the live Cluster when the first BackupJob runs. Consequence: plugin WAL archiving is NOT active until that first BackupJob fires; WAL accumulates on the PVC in the meantime, so fire an ad-hoc BackupJob immediately after enabling the flag on existing releases. Use together with the platform `cozy-default` BackupClass — tenants do not need to fill `s3AccessKey`/`s3SecretKey` or `destinationPath`/`endpointURL`. The destination path automatically scopes to `s3://cozy-backups///`.","type":"boolean","default":false}}},"bootstrap":{"description":"Bootstrap configuration.","type":"object","default":{},"required":["enabled","oldName"],"properties":{"backupID":{"description":"Barman ID of the base backup to recover from, passed as `recoveryTarget.backupID`. Empty lets the barman-cloud plugin pick one: the newest backup when `recoveryTime` is empty, otherwise the newest one ending at or before it, on any timeline. The CNPG backup driver sets this on restore.","type":"string","default":""},"enabled":{"description":"Whether to restore from a backup.","type":"boolean","default":false},"newServerName":{"description":"WAL-archive server name (S3 path prefix) the RESTORED cluster writes to. Must differ from `serverName` (the recovery source) so a restored cluster archives to a fresh, empty prefix and barman-cloud-check-wal-archive passes while it recovers from the source's prefix. The CNPG backup driver sets this on restore; empty means the cluster archives under its own name.","type":"string","default":""},"oldName":{"description":"Previous cluster name before deletion.","type":"string","default":""},"recoveryTime":{"description":"Timestamp (RFC3339) for point-in-time recovery; empty means latest.","type":"string","default":""},"serverName":{"description":"Server name (S3 path prefix) used by the original cluster when writing backups; passed to the barman-cloud plugin via `externalClusters[].plugin.parameters.serverName`. Defaults to `bootstrap.oldName`. Set this only when the original cluster wrote backups under an explicit server name that differed from its Kubernetes resource name.","type":"string","default":""},"sourceImageName":{"description":"Image of the cluster the backup was taken from. A restore of a backup taken on one of the bare Debian bullseye tags the chart used before standard-trixie comes back on that image (see `allowCollationChange`); any other value is ignored. The CNPG backup driver sets this on restore and clears it with `enabled`.","type":"string","default":""}}}}} release: prefix: postgres- labels: @@ -74,7 +74,7 @@ spec: # labelSelector: # helm.toolkit.fluxcd.io/name: "{reqs[0]['metadata','name']}" - keysOrder: [["apiVersion"], ["appVersion"], ["kind"], ["metadata"], ["metadata", "name"], ["spec", "replicas"], ["spec", "resources"], ["spec", "resourcesPreset"], ["spec", "size"], ["spec", "storageClass"], ["spec", "external"], ["spec", "version"], ["spec", "flavor"], ["spec", "tls"], ["spec", "postgresql"], ["spec", "postgresql", "parameters"], ["spec", "postgresql", "parameters", "max_connections"], ["spec", "quorum"], ["spec", "quorum", "minSyncReplicas"], ["spec", "quorum", "maxSyncReplicas"], ["spec", "autoscaling"], ["spec", "autoscaling", "enabled"], ["spec", "autoscaling", "serverAddress"], ["spec", "autoscaling", "minReplicas"], ["spec", "autoscaling", "maxReplicas"], ["spec", "autoscaling", "metric"], ["spec", "autoscaling", "target"], ["spec", "autoscaling", "maxReplicationLagSeconds"], ["spec", "autoscaling", "dryRun"], ["spec", "autoscaling", "transition"], ["spec", "users"], ["spec", "databases"], ["spec", "backup"], ["spec", "backup", "enabled"], ["spec", "backup", "useSystemBucket"], ["spec", "backup", "retentionPolicy"], ["spec", "backup", "destinationPath"], ["spec", "backup", "endpointURL"], ["spec", "backup", "schedule"], ["spec", "backup", "s3AccessKey"], ["spec", "backup", "s3SecretKey"], ["spec", "backup", "s3CredentialsSecret"], ["spec", "backup", "s3CredentialsSecret", "name"], ["spec", "backup", "s3CredentialsSecret", "accessKeyIDKey"], ["spec", "backup", "s3CredentialsSecret", "secretAccessKeyKey"], ["spec", "backup", "endpointCA"], ["spec", "backup", "endpointCA", "name"], ["spec", "backup", "endpointCA", "key"], ["spec", "bootstrap"], ["spec", "bootstrap", "enabled"], ["spec", "bootstrap", "recoveryTime"], ["spec", "bootstrap", "backupID"], ["spec", "bootstrap", "oldName"], ["spec", "bootstrap", "serverName"], ["spec", "bootstrap", "newServerName"]] + keysOrder: [["apiVersion"], ["appVersion"], ["kind"], ["metadata"], ["metadata", "name"], ["spec", "replicas"], ["spec", "resources"], ["spec", "resourcesPreset"], ["spec", "size"], ["spec", "storageClass"], ["spec", "external"], ["spec", "version"], ["spec", "flavor"], ["spec", "allowCollationChange"], ["spec", "tls"], ["spec", "postgresql"], ["spec", "postgresql", "parameters"], ["spec", "postgresql", "parameters", "max_connections"], ["spec", "quorum"], ["spec", "quorum", "minSyncReplicas"], ["spec", "quorum", "maxSyncReplicas"], ["spec", "autoscaling"], ["spec", "autoscaling", "enabled"], ["spec", "autoscaling", "serverAddress"], ["spec", "autoscaling", "minReplicas"], ["spec", "autoscaling", "maxReplicas"], ["spec", "autoscaling", "metric"], ["spec", "autoscaling", "target"], ["spec", "autoscaling", "maxReplicationLagSeconds"], ["spec", "autoscaling", "dryRun"], ["spec", "autoscaling", "transition"], ["spec", "users"], ["spec", "databases"], ["spec", "backup"], ["spec", "backup", "enabled"], ["spec", "backup", "useSystemBucket"], ["spec", "backup", "retentionPolicy"], ["spec", "backup", "destinationPath"], ["spec", "backup", "endpointURL"], ["spec", "backup", "schedule"], ["spec", "backup", "s3AccessKey"], ["spec", "backup", "s3SecretKey"], ["spec", "backup", "s3CredentialsSecret"], ["spec", "backup", "s3CredentialsSecret", "name"], ["spec", "backup", "s3CredentialsSecret", "accessKeyIDKey"], ["spec", "backup", "s3CredentialsSecret", "secretAccessKeyKey"], ["spec", "backup", "endpointCA"], ["spec", "backup", "endpointCA", "name"], ["spec", "backup", "endpointCA", "key"], ["spec", "bootstrap"], ["spec", "bootstrap", "enabled"], ["spec", "bootstrap", "recoveryTime"], ["spec", "bootstrap", "backupID"], ["spec", "bootstrap", "oldName"], ["spec", "bootstrap", "serverName"], ["spec", "bootstrap", "newServerName"], ["spec", "bootstrap", "sourceImageName"]] secrets: exclude: [] include: From 8cbc7375a7c6a1f67cc46af5b2b899855a567e39 Mon Sep 17 00:00:00 2001 From: Aleksei Sviridkin Date: Sun, 29 Nov 2026 21:56:23 +0300 Subject: [PATCH 5/7] fix(postgres): rebuild indexes on C.UTF-8 when the Debian release changes (#5478) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Refs #5459 (item 1: `C.UTF-8` is not repaired and nobody is warned). After the move to the `-standard-trixie` operand images, an index on a `COLLATE "C.UTF-8"` column, or any text index in a database created with `LC_COLLATE 'C.UTF-8'`, is silently corrupt: Debian bullseye's patched `C.UTF-8` and the glibc 2.35+ `C.UTF-8` order characters differently, but PostgreSQL records no collation version for `C.*` locales, so the collation repair in the init Job never selected those indexes. On PostgreSQL 15+ there was not even a warning. Lookups through such an index miss rows, and a unique index on it stops seeing duplicates. One commit. The repair pass now treats libc `C.` collations, and a libc `C.` database default, as versioned by the Debian release of the server's build (the `pgdgNN` suffix of `server_version`). Their indexes then go through the existing resumable rebuild path (OID mark, in-place handling for exclusion constraints, `_ccnew` leftovers, unique-duplicate failure reporting), which this PR leaves unchanged. Because PostgreSQL stores nothing to compare with, the release each database was last repaired for is stored in a new per-database setting, `cozystack.collation_release`, next to the existing `cozystack.collation_repair`: - a database without the setting gets the release of the server the pass first sees it on. The pass looks before it waits for the rollout, so the old release is persisted even if that run fails, and a retry that runs after the primary restarted still rebuilds; - if the server already runs the new glibc when the pass first sees the database, a libc collation whose recorded version differs from the server's (`en_US.utf8` 2.31 vs 2.41, present in every database created from these images) marks it as not repaired for any release; - otherwise (a new cluster, a database added later) the current release is recorded and nothing is rebuilt; - the setting is updated to the current release only when the database is repaired without failures. The PG<15 warning `database ... uses the locale C.UTF-8, for which this PostgreSQL major records no collation version ...` no longer fires for `C.*` locales, since those are now repaired. The range-partition warning says for a `C.*` key that it is reported only once, instead of claiming that a collation version was left as recorded. The e2e postgres suite now also sets another release on its database, creates a unique `C.utf8` column, and checks that the upgrade rebuilds that index, that amcheck passes on it, and that the setting ends at the server's release. The change stays inside the `== refresh collation versions` SQL prelude and its final block. It does not touch the rollout wait, the per-index rebuild session or the extension section, which other open fixes for A cluster where a pass without this change already ran on the new glibc (v1.7.2-rc.1, or `main` since #5405) has already refreshed its libc collation versions, so no trace of the move is left. This pass then records the current release for it and does not rebuild its `C.*` indexes. Rebuild those by hand with `REINDEX INDEX CONCURRENTLY` (or `REINDEX DATABASE`), as the release note says. description to rebuild indexes on `C.UTF-8` by hand. This PR merges second, so it drops that sentence from `values.yaml`, `types.go`, the README, the schema and the cozyrd: the init Job now rebuilds those indexes itself. Docker, no Kubernetes: data written on `ghcr.io/cloudnative-pg/postgresql:17.7` / `13.22` (bullseye, glibc 2.31, `pgdg11`), then the same data directory started on `17.12-standard-trixie` / `13.22-standard-trixie` (glibc 2.41, `pgdg13`). The repair section was rendered with `helm template`, extracted from the init-script Secret, and run from a container of the trixie image with the env the Job sets (`PGHOST`, `PGUSER`, `JOB_DEADLINE`). Data: 200,000 distinct keys mixing ASCII punctuation, `é`, U+FFFD, U+FFFF, U+1D400 and U+1F600. Tables: a `UNIQUE` column `COLLATE "C.UTF-8"`, an `en_US.utf8` column, a plain `C` column, and a `cutf8db` database with `LC_COLLATE 'C.UTF-8'`. | Scenario | Result | | --- | --- | | Pass from `main`, PG17 and PG13 | rebuilds only the `en_US.utf8` index; `t_c_k_key`: `item order invariant violated`, 178,162 of 200,000 keys not found; `cutf8db.t_d_k`: 179,426 not found | | This PR, Job starts on bullseye, server then restarts on trixie (PG17, PG13) | `pgdg11` recorded while waiting; `C.UTF-8` column index, `C.UTF-8` database default index and `en_US.utf8` index rebuilt; amcheck ok, 0 misses; plain `C` index keeps its OID | | This PR, first run times out waiting for the rollout, retry after the restart (libc versions refreshed by hand in between so only the persisted release can trigger) | retry rebuilds both `C.*` indexes; amcheck ok, 0 misses | | This PR, server already on trixie at first run | detected through the stale libc collation versions; both `C.*` indexes rebuilt | | Second and third run | nothing rebuilt, setting stays `pgdg13` | | New cluster created on trixie | nothing rebuilt, `pgdg13` recorded | | Range partitions on `C.UTF-8` and on `en_US.utf8` | partition indexes rebuilt once; the `C.*` partition warned once; later runs rebuild nothing | `helm unittest packages/apps/postgres`: 31 suites, 247 tests passed. Dev cluster (cozystack v1.7.0): - Setup: an app installed from the v1.7.1 chart (`postgresql:17.7`, bullseye, 2 instances). In `appdb`, a `UNIQUE` column `COLLATE "C.UTF-8"` with 50,000 keys built from ASCII letters and punctuation, `é`, U+FFFD, U+1D400 and U+1F600. - `helm upgrade` to this branch passed on the first attempt. The init Job logged `rebuilding index public.t_c_k_key in database appdb: its collation changed version`. - Afterwards: - the Cluster runs `17.12-standard-trixie`; - the index OID changed (16424 → 16507); - `bt_index_check(t_c_k_key, true)` is clean on the primary, on the replica and through `-ro`, with 0 lookup misses; - `cozystack.collation_release` is `pgdg13`. - A second upgrade rebuilt nothing. The extended chainsaw e2e step has not run yet, so CI will be its first run. Docker, with the rendered repair pass run against `17.12-standard-trixie` and `UNIQUE` columns `COLLATE "C.utf8"`: - A database with no recorded release and a stale libc collation (`CREATE COLLATION ... (provider = libc, locale = 'en_US.utf8', version = '0')`): the index is rebuilt and `pgdg13` is recorded. - A database whose only stale piece is its libc default collation (`datcollversion` changed): the index is rebuilt, and `pgdg13` is recorded. - A fresh database: nothing is rebuilt, and `pgdg13` is recorded. - A second run rebuilds nothing. The e2e suite now also covers a database with no recorded release, the state every existing cluster starts from. That database holds a stale `en_US.utf8` libc collation and a `UNIQUE` column on `C.utf8`, and the test asserts the new index OID, `bt_index_check`, and the recorded release. A libc collation on locale `C` with an explicit version cannot serve as the probe: `ALTER COLLATION ... REFRESH VERSION` refuses to move it to the NULL version of a `C` locale. - [ ] No downstream repository is affected by this change - [ ] [cozystack/website](https://github.com/cozystack/website) - follow-up: - [ ] [cozystack/terraform-provider-cozystack](https://github.com/cozystack/terraform-provider-cozystack) - follow-up: - [ ] [cozystack/ansible-cozystack](https://github.com/cozystack/ansible-cozystack) - follow-up: - [ ] [cozystack/ccp](https://github.com/cozystack/ccp) - follow-up: - [ ] [cozystack/talm](https://github.com/cozystack/talm) - follow-up: - [ ] [cozystack/cozyhr](https://github.com/cozystack/cozyhr) - follow-up: - [ ] [cozystack/cozy-proxy](https://github.com/cozystack/cozy-proxy) - follow-up: - [ ] [cozystack/cozystack-telemetry-server](https://github.com/cozystack/cozystack-telemetry-server) - follow-up: - [ ] [cozystack/external-apps-example](https://github.com/cozystack/external-apps-example) - follow-up: - [ ] [cozystack/examples](https://github.com/cozystack/examples) - follow-up: - [ ] [cozystack/community](https://github.com/cozystack/community) - follow-up: The diff touches only `packages/apps/postgres/templates/init-script.yaml` and the postgres e2e test. No values, schema, README, API or CRD change, so none of the generated reference docs move. Boxes are left empty for a maintainer to decide: the website may describe the trixie move and its collation repair in upgrade notes, and if it lists which collations get repaired, `C.UTF-8` should be added there. I did not check that. ```release-note [postgres] The init Job now also rebuilds indexes on libc `C.UTF-8` (and other `C.`) collations, and on databases whose default collation is such a locale, when the server moves to an image built on another Debian release. PostgreSQL records no version for these collations, so before this fix such indexes stayed corrupt after the move to the standard-trixie images, with no warning. The Debian release each database was repaired for is kept in the `cozystack.collation_release` database setting. A cluster that already ran the previous repair on a trixie image (v1.7.2-rc.1 or a `main` build since the move) is not recognised: rebuild its indexes on `C.*` collations by hand with `REINDEX`. ``` * **Bug Fixes** * PostgreSQL collation repair now detects changes affecting `C.` collations across PostgreSQL build releases, including cases where PostgreSQL does not record collation versions. Affected indexes are identified and rebuilt during repair. * Partition-related warnings clarify when collation changes can or cannot be detected. After repair, the process records the PostgreSQL release to help identify when a later repair may be needed. * **Documentation** * Updated `allowCollationChange` guidance to explain that the initialization process rebuilds indexes for `C.UTF-8` and other `C.*` locales, removing the instruction to rebuild those indexes manually. (cherry picked from commit 0f84f1c8dc22f25df80e98c5e9f1abd9f9b42f15) Signed-off-by: Andrey Kolkov --- api/apps/v1alpha1/postgresql/types.go | 2 +- hack/e2e-chainsaw/postgres/chainsaw-test.yaml | 47 ++++++++++++++++-- packages/apps/postgres/README.md | 26 +++++----- .../apps/postgres/templates/init-script.yaml | 49 +++++++++++++++++-- packages/apps/postgres/values.schema.json | 2 +- packages/apps/postgres/values.yaml | 2 +- .../system/postgres-rd/cozyrds/postgres.yaml | 2 +- 7 files changed, 105 insertions(+), 25 deletions(-) diff --git a/api/apps/v1alpha1/postgresql/types.go b/api/apps/v1alpha1/postgresql/types.go index e05f2f350..5e609e5ea 100644 --- a/api/apps/v1alpha1/postgresql/types.go +++ b/api/apps/v1alpha1/postgresql/types.go @@ -43,7 +43,7 @@ type ConfigSpec struct { // PostgreSQL image flavor, fixed when the cluster is created. `postgresql` uses the CloudNativePG PostgreSQL image. `postgis` uses the CloudNativePG PostGIS image, which adds postgis, postgis_raster, postgis_topology, postgis_sfcgal, postgis_tiger_geocoder and address_standardizer; enable them per database in `databases..extensions`. Changing the flavor of an existing cluster is refused, and a backup restores only into a cluster of the flavor it was taken from: to change flavor, create a new cluster and move the data with a logical dump (pg_dump / pg_restore). // +kubebuilder:default:="postgresql" Flavor Flavor `json:"flavor"` - // Allow a cluster created on a Debian bullseye image (before the move to standard-trixie) to move to the new image without a clean locale check. Such a cluster is checked before each upgrade, except while `bootstrap.enabled` is set (set it back to false once a restore set up by hand has finished), and stays on its current image until the check finds nothing that depends on a collation other than C, POSIX or builtin: while this is false, a cluster the check found affected (an ICU or libc locale, or C.UTF-8) or could not finish on stays put, because glibc and ICU on the new image sort text differently and every index on such text must be rebuilt. A held cluster runs the bare bullseye tag it has, gets no further PostgreSQL minors and so none of their security fixes, and refuses a change of `version`, since new majors are built only on the new images. To leave that state, either remove the dependency (move such columns and indexes to C, or to the builtin `pg_c_utf8` on PostgreSQL 17 and later) and let the next upgrade check again, or set this to true in a maintenance window: the cluster moves on the next upgrade, replicas restart on the new image first and can return wrong results through `-ro`, and unique indexes can accept duplicates, until the indexes are rebuilt on the primary. The init Job rebuilds only indexes on collations that record a version (ICU, and libc locales other than C.*): rebuild indexes on C.UTF-8 or another C.* locale by hand with REINDEX, and check range partitions, CHECK constraints and materialized views on such text, which a rebuild does not fix. A held cluster shows the hold only as an unchanged image; the result and the objects found are in the `postgres.cozystack.io/locale-data` and `postgres.cozystack.io/locale-data-objects` annotations of the cnpg.io Cluster, which an administrator can read. A restore of a backup taken on one of those bullseye images comes back on that image and is checked by the next upgrade. + // Allow a cluster created on a Debian bullseye image (before the move to standard-trixie) to move to the new image without a clean locale check. Such a cluster is checked before each upgrade, except while `bootstrap.enabled` is set (set it back to false once a restore set up by hand has finished), and stays on its current image until the check finds nothing that depends on a collation other than C, POSIX or builtin: while this is false, a cluster the check found affected (an ICU or libc locale, or C.UTF-8) or could not finish on stays put, because glibc and ICU on the new image sort text differently and every index on such text must be rebuilt. A held cluster runs the bare bullseye tag it has, gets no further PostgreSQL minors and so none of their security fixes, and refuses a change of `version`, since new majors are built only on the new images. To leave that state, either remove the dependency (move such columns and indexes to C, or to the builtin `pg_c_utf8` on PostgreSQL 17 and later) and let the next upgrade check again, or set this to true in a maintenance window: the cluster moves on the next upgrade, replicas restart on the new image first and can return wrong results through `-ro`, and unique indexes can accept duplicates, until the indexes are rebuilt on the primary. The init Job rebuilds the indexes on such text, those on C.UTF-8 and other C.* locales included; check range partitions, CHECK constraints and materialized views on it, which a rebuild does not fix. A held cluster shows the hold only as an unchanged image; the result and the objects found are in the `postgres.cozystack.io/locale-data` and `postgres.cozystack.io/locale-data-objects` annotations of the cnpg.io Cluster, which an administrator can read. A restore of a backup taken on one of those bullseye images comes back on that image and is checked by the next upgrade. // +kubebuilder:default:=false AllowCollationChange bool `json:"allowCollationChange"` // TLS configuration for server connections. diff --git a/hack/e2e-chainsaw/postgres/chainsaw-test.yaml b/hack/e2e-chainsaw/postgres/chainsaw-test.yaml index 90d1552d3..a2f46b4f2 100644 --- a/hack/e2e-chainsaw/postgres/chainsaw-test.yaml +++ b/hack/e2e-chainsaw/postgres/chainsaw-test.yaml @@ -253,8 +253,12 @@ spec: # The init Job rebuilds an index whose collation changed library version. # The pass is SQL run by a Helm hook, so only a real server can say whether # it works. A collation created with an explicit version reads as stale - # without swapping the operand image, which makes one more upgrade of the - # release enough to run the pass over it. + # without swapping the operand image, and so does a C. collation + # once the database records another Debian release as the one it was + # repaired for, which makes one more upgrade of the release enough to run + # the pass over both. A database created after the last run records no + # release, the state every existing cluster starts from; there a stale libc + # collation is what tells the pass that glibc moved. - name: rebuild-index-after-collation-version-change try: - script: @@ -273,9 +277,19 @@ spec: CREATE EXTENSION IF NOT EXISTS btree_gist; CREATE TABLE collation_probe_excl (s text COLLATE stale_icu, EXCLUDE USING gist (s WITH =)); INSERT INTO collation_probe_excl SELECT 'k' || g FROM generate_series(1, 200) g; + CREATE TABLE collation_probe_c (s text COLLATE "C.utf8" UNIQUE); + INSERT INTO collation_probe_c SELECT 'c' || g FROM generate_series(1, 1000) g; + ALTER DATABASE testdb SET cozystack.collation_release = 'pgdg11'; CREATE TABLE collation_probe_before AS SELECT 'collation_probe_s'::regclass::oid AS index, - (SELECT relfilenode FROM pg_class WHERE oid = 'collation_probe_excl_s_excl'::regclass) AS in_place_file; + (SELECT relfilenode FROM pg_class WHERE oid = 'collation_probe_excl_s_excl'::regclass) AS in_place_file, + 'collation_probe_c_s_key'::regclass::oid AS c_index; + CREATE DATABASE collation_probe_unrecorded; + \c collation_probe_unrecorded + CREATE COLLATION stale_libc (provider = libc, locale = 'en_US.utf8', version = '0'); + CREATE TABLE collation_probe_c (s text COLLATE "C.utf8" UNIQUE); + INSERT INTO collation_probe_c SELECT 'c' || g FROM generate_series(1, 1000) g; + CREATE TABLE collation_probe_before AS SELECT 'collation_probe_c_s_key'::regclass::oid AS c_index; EOF check: ($error == null): true @@ -335,6 +349,33 @@ spec: echo "the init Job did not rebuild the exclusion constraint's index" >&2 exit 1 fi + rebuilt_c=$(q "SELECT 'collation_probe_c_s_key'::regclass::oid <> c_index FROM collation_probe_before") + if [ "$rebuilt_c" != t ]; then + echo "the init Job did not rebuild the index on a C. collation after the Debian release changed" >&2 + exit 1 + fi + q "SELECT bt_index_check('collation_probe_c_s_key', true)" + release=$(q "SELECT current_setting('cozystack.collation_release', true) = substring(current_setting('server_version') from 'pgdg[0-9]+')") + if [ "$release" != t ]; then + echo "the init Job did not record the Debian release it repaired the database for" >&2 + exit 1 + fi + qu() { + kubectl -n "$NAMESPACE" exec "$pod" -c postgres -- \ + psql -U postgres -d collation_probe_unrecorded -v ON_ERROR_STOP=1 -tAc "$1" + } + rebuilt_unrecorded=$(qu "SELECT 'collation_probe_c_s_key'::regclass::oid <> c_index FROM collation_probe_before") + if [ "$rebuilt_unrecorded" != t ]; then + echo "the init Job did not rebuild the index on a C. collation in a database that recorded no release and holds a stale libc collation" >&2 + exit 1 + fi + qu "CREATE EXTENSION IF NOT EXISTS amcheck" + qu "SELECT bt_index_check('collation_probe_c_s_key', true)" + release=$(qu "SELECT current_setting('cozystack.collation_release', true) = substring(current_setting('server_version') from 'pgdg[0-9]+')") + if [ "$release" != t ]; then + echo "the init Job did not record the Debian release it repaired the unrecorded database for" >&2 + exit 1 + fi # The pass keeps its progress in a setting of the database and # removes it once nothing is left to repair. progress=$(q "SELECT count(*) FROM pg_db_role_setting s JOIN pg_database d ON d.oid = s.setdatabase, unnest(s.setconfig) AS c WHERE d.datname = current_database() AND c LIKE 'cozystack.collation_repair=%'") diff --git a/packages/apps/postgres/README.md b/packages/apps/postgres/README.md index d3468b9b8..2286f5bba 100644 --- a/packages/apps/postgres/README.md +++ b/packages/apps/postgres/README.md @@ -207,19 +207,19 @@ For `sslmode=verify-full` to work, the CA bundle retrieved above must be saved t ### Common parameters -| Name | Description | Type | Value | -| ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | ------------ | -| `replicas` | Number of Postgres replicas. Under active autoscaling this is the resting/seed count, not the live count — KEDA drives the live count via `/scale`. Disabling autoscaling does NOT automatically bring the live count back to `replicas`: the client-side merge writes `instances` only when the rendered value changes, so a cluster KEDA grew past `replicas` stays there with no autoscaler left to reduce it — lower `replicas` to the count you want and it rebases down (shedding the surplus replicas + PVCs). Lowering it below the live count, or disabling/dry-running while it sits below the live count, sheds in one step past the scaleDown pacing; stage it to the live count first (suspend the HelmRelease and `kubectl scale` if needed) to avoid a transient. Must stay greater than `quorum.maxSyncReplicas`. | `int` | `2` | -| `resources` | Explicit CPU and memory configuration for each PostgreSQL replica. When omitted, the preset defined in `resourcesPreset` is applied. | `object` | `{}` | -| `resources.cpu` | CPU available to each replica. | `quantity` | `""` | -| `resources.memory` | Memory (RAM) available to each replica. | `quantity` | `""` | -| `resourcesPreset` | Default sizing preset used when `resources` is omitted. | `string` | `t1.micro` | -| `size` | Persistent Volume Claim size available for application data. | `quantity` | `10Gi` | -| `storageClass` | StorageClass used to store the data. | `string` | `""` | -| `external` | Enable external access from outside the cluster. | `bool` | `false` | -| `version` | PostgreSQL major version to deploy | `string` | `v18` | -| `flavor` | PostgreSQL image flavor, fixed when the cluster is created. `postgresql` uses the CloudNativePG PostgreSQL image. `postgis` uses the CloudNativePG PostGIS image, which adds postgis, postgis_raster, postgis_topology, postgis_sfcgal, postgis_tiger_geocoder and address_standardizer; enable them per database in `databases..extensions`. Changing the flavor of an existing cluster is refused, and a backup restores only into a cluster of the flavor it was taken from: to change flavor, create a new cluster and move the data with a logical dump (pg_dump / pg_restore). | `string` | `postgresql` | -| `allowCollationChange` | Allow a cluster created on a Debian bullseye image (before the move to standard-trixie) to move to the new image without a clean locale check. Such a cluster is checked before each upgrade, except while `bootstrap.enabled` is set (set it back to false once a restore set up by hand has finished), and stays on its current image until the check finds nothing that depends on a collation other than C, POSIX or builtin: while this is false, a cluster the check found affected (an ICU or libc locale, or C.UTF-8) or could not finish on stays put, because glibc and ICU on the new image sort text differently and every index on such text must be rebuilt. A held cluster runs the bare bullseye tag it has, gets no further PostgreSQL minors and so none of their security fixes, and refuses a change of `version`, since new majors are built only on the new images. To leave that state, either remove the dependency (move such columns and indexes to C, or to the builtin `pg_c_utf8` on PostgreSQL 17 and later) and let the next upgrade check again, or set this to true in a maintenance window: the cluster moves on the next upgrade, replicas restart on the new image first and can return wrong results through `-ro`, and unique indexes can accept duplicates, until the indexes are rebuilt on the primary. The init Job rebuilds only indexes on collations that record a version (ICU, and libc locales other than C.*): rebuild indexes on C.UTF-8 or another C.* locale by hand with REINDEX, and check range partitions, CHECK constraints and materialized views on such text, which a rebuild does not fix. A held cluster shows the hold only as an unchanged image; the result and the objects found are in the `postgres.cozystack.io/locale-data` and `postgres.cozystack.io/locale-data-objects` annotations of the cnpg.io Cluster, which an administrator can read. A restore of a backup taken on one of those bullseye images comes back on that image and is checked by the next upgrade. | `bool` | `false` | +| Name | Description | Type | Value | +| ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | ------------ | +| `replicas` | Number of Postgres replicas. Under active autoscaling this is the resting/seed count, not the live count — KEDA drives the live count via `/scale`. Disabling autoscaling does NOT automatically bring the live count back to `replicas`: the client-side merge writes `instances` only when the rendered value changes, so a cluster KEDA grew past `replicas` stays there with no autoscaler left to reduce it — lower `replicas` to the count you want and it rebases down (shedding the surplus replicas + PVCs). Lowering it below the live count, or disabling/dry-running while it sits below the live count, sheds in one step past the scaleDown pacing; stage it to the live count first (suspend the HelmRelease and `kubectl scale` if needed) to avoid a transient. Must stay greater than `quorum.maxSyncReplicas`. | `int` | `2` | +| `resources` | Explicit CPU and memory configuration for each PostgreSQL replica. When omitted, the preset defined in `resourcesPreset` is applied. | `object` | `{}` | +| `resources.cpu` | CPU available to each replica. | `quantity` | `""` | +| `resources.memory` | Memory (RAM) available to each replica. | `quantity` | `""` | +| `resourcesPreset` | Default sizing preset used when `resources` is omitted. | `string` | `t1.micro` | +| `size` | Persistent Volume Claim size available for application data. | `quantity` | `10Gi` | +| `storageClass` | StorageClass used to store the data. | `string` | `""` | +| `external` | Enable external access from outside the cluster. | `bool` | `false` | +| `version` | PostgreSQL major version to deploy | `string` | `v18` | +| `flavor` | PostgreSQL image flavor, fixed when the cluster is created. `postgresql` uses the CloudNativePG PostgreSQL image. `postgis` uses the CloudNativePG PostGIS image, which adds postgis, postgis_raster, postgis_topology, postgis_sfcgal, postgis_tiger_geocoder and address_standardizer; enable them per database in `databases..extensions`. Changing the flavor of an existing cluster is refused, and a backup restores only into a cluster of the flavor it was taken from: to change flavor, create a new cluster and move the data with a logical dump (pg_dump / pg_restore). | `string` | `postgresql` | +| `allowCollationChange` | Allow a cluster created on a Debian bullseye image (before the move to standard-trixie) to move to the new image without a clean locale check. Such a cluster is checked before each upgrade, except while `bootstrap.enabled` is set (set it back to false once a restore set up by hand has finished), and stays on its current image until the check finds nothing that depends on a collation other than C, POSIX or builtin: while this is false, a cluster the check found affected (an ICU or libc locale, or C.UTF-8) or could not finish on stays put, because glibc and ICU on the new image sort text differently and every index on such text must be rebuilt. A held cluster runs the bare bullseye tag it has, gets no further PostgreSQL minors and so none of their security fixes, and refuses a change of `version`, since new majors are built only on the new images. To leave that state, either remove the dependency (move such columns and indexes to C, or to the builtin `pg_c_utf8` on PostgreSQL 17 and later) and let the next upgrade check again, or set this to true in a maintenance window: the cluster moves on the next upgrade, replicas restart on the new image first and can return wrong results through `-ro`, and unique indexes can accept duplicates, until the indexes are rebuilt on the primary. The init Job rebuilds the indexes on such text, those on C.UTF-8 and other C.* locales included; check range partitions, CHECK constraints and materialized views on it, which a rebuild does not fix. A held cluster shows the hold only as an unchanged image; the result and the objects found are in the `postgres.cozystack.io/locale-data` and `postgres.cozystack.io/locale-data-objects` annotations of the cnpg.io Cluster, which an administrator can read. A restore of a backup taken on one of those bullseye images comes back on that image and is checked by the next upgrade. | `bool` | `false` | ### TLS configuration diff --git a/packages/apps/postgres/templates/init-script.yaml b/packages/apps/postgres/templates/init-script.yaml index df28cd863..7cd9b14db 100644 --- a/packages/apps/postgres/templates/init-script.yaml +++ b/packages/apps/postgres/templates/init-script.yaml @@ -683,6 +683,29 @@ stringData: the codeset or a hyphen in it. A locale with no such collation cannot be checked, which a run that saw the image change says in a warning. + PostgreSQL records no version for a libc locale named C. + either, yet the one Debian patched into the glibc of bullseye and the + one glibc ships since 2.35 order some characters differently. Such a + collation, and a database whose default collation is such a locale, + therefore take the Debian release of the server's build as their + version. The release a database was last repaired for is another + setting of it, written once a run repairs the database without a + failure. A database without that setting gets the release of the + server the pass first finds it on: that is the previous image whenever + the pass sees the image change, since it looks before it waits for the + rollout, so a retry after the primary has restarted still rebuilds + those indexes. A database that already runs on a new glibc by then is + recognised by a libc collation, or a libc database default, whose + recorded version differs from the server's, and is taken as repaired + for no release. Anything else, a new cluster included, is taken as + repaired for the release it runs. That includes a database a pass + without this rule already repaired on the new glibc: it refreshed the + libc versions and left no sign of the move behind, so its indexes on a + C. collation have to be rebuilt by hand with REINDEX. + With no version for PostgreSQL to complain about, a range partition key + of such a collation is reported only by the run that rebuilds its + indexes. + Every session of the pass pins search_path to pg_catalog: the Job connects as the superuser, and a function or operator a tenant defined in public would otherwise be picked wherever its argument types match @@ -696,17 +719,25 @@ stringData: SET search_path = pg_catalog, pg_temp; SELECT current_setting('server_version_num')::int >= 150000 AS tracks_database \gset \if :tracks_database - SELECT datcollversion IS NOT NULL AS db_versioned, coalesce(pg_database_collation_actual_version(oid), '') AS db_actual, datcollversion IS NOT NULL AND datcollversion IS DISTINCT FROM pg_database_collation_actual_version(oid) AS db_stale, false AS db_unmatched FROM pg_database WHERE datname = current_database() \gset + SELECT datcollversion IS NOT NULL AS db_versioned, coalesce(pg_database_collation_actual_version(oid), '') AS db_actual, datcollversion IS NOT NULL AND datcollversion IS DISTINCT FROM pg_database_collation_actual_version(oid) AS db_stale, false AS db_unmatched, datlocprovider = 'c' AND datcollate ~* '^C\.' AS db_c, datlocprovider = 'c' AND datcollversion IS NOT NULL AND datcollversion IS DISTINCT FROM pg_database_collation_actual_version(oid) AS db_libc_stale FROM pg_database WHERE datname = current_database() \gset \else - SELECT d.datcollate NOT IN ('C', 'POSIX') AS db_versioned, + SELECT d.datcollate NOT IN ('C', 'POSIX') AND d.datcollate !~* '^C\.' AS db_versioned, coalesce(max(pg_collation_actual_version(c.oid)), '') AS db_actual, coalesce(bool_or(c.collversion IS DISTINCT FROM pg_collation_actual_version(c.oid)), false) AS db_stale, - d.datcollate NOT IN ('C', 'POSIX') AND count(c.oid) = 0 AS db_unmatched + d.datcollate NOT IN ('C', 'POSIX') AND d.datcollate !~* '^C\.' AND count(c.oid) = 0 AS db_unmatched, + d.datcollate ~* '^C\.' AS db_c, + false AS db_libc_stale FROM pg_database d LEFT JOIN pg_collation c ON c.collprovider = 'c' AND lower(replace(c.collcollate, '-', '')) = lower(replace(d.datcollate, '-', '')) AND c.collversion IS NOT NULL AND c.collencoding IN (-1, d.encoding) WHERE d.datname = current_database() GROUP BY d.datcollate \gset \endif + SELECT coalesce(substring(current_setting('server_version') from 'pgdg[0-9]+'), '') AS release, coalesce(current_setting('cozystack.collation_release', true), '') AS repaired \gset + SELECT :'repaired' = '' AND :'release' <> '' AS unrecorded \gset + \if :unrecorded + SELECT CASE WHEN :'db_libc_stale'::boolean OR EXISTS (SELECT FROM pg_collation c WHERE c.collprovider = 'c' AND c.collversion IS NOT NULL AND c.collversion IS DISTINCT FROM pg_collation_actual_version(c.oid)) THEN 'unknown' ELSE :'release' END AS repaired \gset + SELECT format('ALTER DATABASE %I SET cozystack.collation_release = %L', current_database(), :'repaired') \gexec + \endif CREATE TEMP TABLE cozystack_collation AS SELECT v.oid, v.actual, v.stale, EXISTS (SELECT FROM pg_partitioned_table p WHERE p.partstrat = 'r' AND v.oid = ANY (p.partcollation::oid[])) AS held @@ -717,7 +748,14 @@ stringData: AND c.collencoding IN (-1, (SELECT encoding FROM pg_database WHERE datname = current_database())) UNION ALL SELECT 100, :'db_actual', :'db_stale'::boolean WHERE :'db_versioned'::boolean - ) v; + ) v + UNION ALL + SELECT c.oid, :'release', :'repaired' <> :'release', false + FROM pg_collation c + WHERE :'release' <> '' AND c.collprovider = 'c' AND c.collversion IS NULL AND c.collcollate ~* '^C\.' + AND c.collencoding IN (-1, (SELECT encoding FROM pg_database WHERE datname = current_database())) + UNION ALL + SELECT 100, :'release', :'repaired' <> :'release', false WHERE :'release' <> '' AND :'db_c'::boolean; CREATE TEMP TABLE cozystack_collation_index AS SELECT i.indexrelid AS index, bool_or(c.stale) AS stale FROM ( @@ -833,7 +871,7 @@ stringData: else collation_run "$db" <<\EOT SELECT format('WARNING: database %s uses the locale %s, for which this PostgreSQL major records no collation version and the catalog has no collation to stand in; the indexes on its default collation were not checked. If this upgrade moved the image to another Debian release, rebuild them with REINDEX DATABASE', datname, datcollate) FROM pg_database WHERE datname = current_database() AND :'db_unmatched'::boolean AND :'moved'::boolean; - SELECT format('WARNING: %s in database %s is range-partitioned on a key whose collation changed version; rows stored before the change may now belong to another partition, and the collation version is left as recorded until that is checked', p.partrelid::regclass, current_database()) FROM pg_partitioned_table p WHERE p.partstrat = 'r' AND EXISTS (SELECT FROM cozystack_collation c WHERE c.stale AND c.oid = ANY (p.partcollation::oid[])); + SELECT format('WARNING: %s in database %s is range-partitioned on a key whose collation changed version; rows stored before the change may now belong to another partition, %s', p.partrelid::regclass, current_database(), CASE WHEN bool_or(c.held) THEN 'and the collation version is left as recorded until that is checked' ELSE 'and no later run says so again: PostgreSQL records no version for that collation' END) FROM pg_partitioned_table p JOIN cozystack_collation c ON c.stale AND c.oid = ANY (p.partcollation::oid[]) WHERE p.partstrat = 'r' GROUP BY p.partrelid; DO $$ DECLARE entry record; @@ -846,6 +884,7 @@ stringData: END LOOP; END$$; SELECT format('ALTER DATABASE %I REFRESH COLLATION VERSION', current_database()) FROM cozystack_collation WHERE oid = 100 AND stale AND NOT held AND current_setting('server_version_num')::int >= 150000 \gexec + SELECT format('ALTER DATABASE %I SET cozystack.collation_release = %L', current_database(), :'release') WHERE :'release' NOT IN ('', :'repaired') \gexec SELECT coalesce(md5(string_agg(oid || '=' || actual, ',' ORDER BY oid)), '') AS remaining FROM cozystack_collation WHERE stale AND held \gset SELECT CASE WHEN :'remaining' = '' THEN '' ELSE :'remaining' || ':0' END AS settled \gset SELECT CASE WHEN :'settled' = '' THEN format('ALTER DATABASE %I RESET cozystack.collation_repair', current_database()) ELSE format('ALTER DATABASE %I SET cozystack.collation_repair = %L', current_database(), :'settled') END WHERE coalesce(current_setting('cozystack.collation_repair', true), '') <> :'settled' \gexec diff --git a/packages/apps/postgres/values.schema.json b/packages/apps/postgres/values.schema.json index df4bce4b9..e426cacce 100644 --- a/packages/apps/postgres/values.schema.json +++ b/packages/apps/postgres/values.schema.json @@ -150,7 +150,7 @@ ] }, "allowCollationChange": { - "description": "Allow a cluster created on a Debian bullseye image (before the move to standard-trixie) to move to the new image without a clean locale check. Such a cluster is checked before each upgrade, except while `bootstrap.enabled` is set (set it back to false once a restore set up by hand has finished), and stays on its current image until the check finds nothing that depends on a collation other than C, POSIX or builtin: while this is false, a cluster the check found affected (an ICU or libc locale, or C.UTF-8) or could not finish on stays put, because glibc and ICU on the new image sort text differently and every index on such text must be rebuilt. A held cluster runs the bare bullseye tag it has, gets no further PostgreSQL minors and so none of their security fixes, and refuses a change of `version`, since new majors are built only on the new images. To leave that state, either remove the dependency (move such columns and indexes to C, or to the builtin `pg_c_utf8` on PostgreSQL 17 and later) and let the next upgrade check again, or set this to true in a maintenance window: the cluster moves on the next upgrade, replicas restart on the new image first and can return wrong results through `-ro`, and unique indexes can accept duplicates, until the indexes are rebuilt on the primary. The init Job rebuilds only indexes on collations that record a version (ICU, and libc locales other than C.*): rebuild indexes on C.UTF-8 or another C.* locale by hand with REINDEX, and check range partitions, CHECK constraints and materialized views on such text, which a rebuild does not fix. A held cluster shows the hold only as an unchanged image; the result and the objects found are in the `postgres.cozystack.io/locale-data` and `postgres.cozystack.io/locale-data-objects` annotations of the cnpg.io Cluster, which an administrator can read. A restore of a backup taken on one of those bullseye images comes back on that image and is checked by the next upgrade.", + "description": "Allow a cluster created on a Debian bullseye image (before the move to standard-trixie) to move to the new image without a clean locale check. Such a cluster is checked before each upgrade, except while `bootstrap.enabled` is set (set it back to false once a restore set up by hand has finished), and stays on its current image until the check finds nothing that depends on a collation other than C, POSIX or builtin: while this is false, a cluster the check found affected (an ICU or libc locale, or C.UTF-8) or could not finish on stays put, because glibc and ICU on the new image sort text differently and every index on such text must be rebuilt. A held cluster runs the bare bullseye tag it has, gets no further PostgreSQL minors and so none of their security fixes, and refuses a change of `version`, since new majors are built only on the new images. To leave that state, either remove the dependency (move such columns and indexes to C, or to the builtin `pg_c_utf8` on PostgreSQL 17 and later) and let the next upgrade check again, or set this to true in a maintenance window: the cluster moves on the next upgrade, replicas restart on the new image first and can return wrong results through `-ro`, and unique indexes can accept duplicates, until the indexes are rebuilt on the primary. The init Job rebuilds the indexes on such text, those on C.UTF-8 and other C.* locales included; check range partitions, CHECK constraints and materialized views on it, which a rebuild does not fix. A held cluster shows the hold only as an unchanged image; the result and the objects found are in the `postgres.cozystack.io/locale-data` and `postgres.cozystack.io/locale-data-objects` annotations of the cnpg.io Cluster, which an administrator can read. A restore of a backup taken on one of those bullseye images comes back on that image and is checked by the next upgrade.", "type": "boolean", "default": false }, diff --git a/packages/apps/postgres/values.yaml b/packages/apps/postgres/values.yaml index 3d31f8b1d..a9974ed3d 100644 --- a/packages/apps/postgres/values.yaml +++ b/packages/apps/postgres/values.yaml @@ -95,7 +95,7 @@ version: v18 ## @param {Flavor} flavor - PostgreSQL image flavor, fixed when the cluster is created. `postgresql` uses the CloudNativePG PostgreSQL image. `postgis` uses the CloudNativePG PostGIS image, which adds postgis, postgis_raster, postgis_topology, postgis_sfcgal, postgis_tiger_geocoder and address_standardizer; enable them per database in `databases..extensions`. Changing the flavor of an existing cluster is refused, and a backup restores only into a cluster of the flavor it was taken from: to change flavor, create a new cluster and move the data with a logical dump (pg_dump / pg_restore). flavor: postgresql -## @param {bool} allowCollationChange - Allow a cluster created on a Debian bullseye image (before the move to standard-trixie) to move to the new image without a clean locale check. Such a cluster is checked before each upgrade, except while `bootstrap.enabled` is set (set it back to false once a restore set up by hand has finished), and stays on its current image until the check finds nothing that depends on a collation other than C, POSIX or builtin: while this is false, a cluster the check found affected (an ICU or libc locale, or C.UTF-8) or could not finish on stays put, because glibc and ICU on the new image sort text differently and every index on such text must be rebuilt. A held cluster runs the bare bullseye tag it has, gets no further PostgreSQL minors and so none of their security fixes, and refuses a change of `version`, since new majors are built only on the new images. To leave that state, either remove the dependency (move such columns and indexes to C, or to the builtin `pg_c_utf8` on PostgreSQL 17 and later) and let the next upgrade check again, or set this to true in a maintenance window: the cluster moves on the next upgrade, replicas restart on the new image first and can return wrong results through `-ro`, and unique indexes can accept duplicates, until the indexes are rebuilt on the primary. The init Job rebuilds only indexes on collations that record a version (ICU, and libc locales other than C.*): rebuild indexes on C.UTF-8 or another C.* locale by hand with REINDEX, and check range partitions, CHECK constraints and materialized views on such text, which a rebuild does not fix. A held cluster shows the hold only as an unchanged image; the result and the objects found are in the `postgres.cozystack.io/locale-data` and `postgres.cozystack.io/locale-data-objects` annotations of the cnpg.io Cluster, which an administrator can read. A restore of a backup taken on one of those bullseye images comes back on that image and is checked by the next upgrade. +## @param {bool} allowCollationChange - Allow a cluster created on a Debian bullseye image (before the move to standard-trixie) to move to the new image without a clean locale check. Such a cluster is checked before each upgrade, except while `bootstrap.enabled` is set (set it back to false once a restore set up by hand has finished), and stays on its current image until the check finds nothing that depends on a collation other than C, POSIX or builtin: while this is false, a cluster the check found affected (an ICU or libc locale, or C.UTF-8) or could not finish on stays put, because glibc and ICU on the new image sort text differently and every index on such text must be rebuilt. A held cluster runs the bare bullseye tag it has, gets no further PostgreSQL minors and so none of their security fixes, and refuses a change of `version`, since new majors are built only on the new images. To leave that state, either remove the dependency (move such columns and indexes to C, or to the builtin `pg_c_utf8` on PostgreSQL 17 and later) and let the next upgrade check again, or set this to true in a maintenance window: the cluster moves on the next upgrade, replicas restart on the new image first and can return wrong results through `-ro`, and unique indexes can accept duplicates, until the indexes are rebuilt on the primary. The init Job rebuilds the indexes on such text, those on C.UTF-8 and other C.* locales included; check range partitions, CHECK constraints and materialized views on it, which a rebuild does not fix. A held cluster shows the hold only as an unchanged image; the result and the objects found are in the `postgres.cozystack.io/locale-data` and `postgres.cozystack.io/locale-data-objects` annotations of the cnpg.io Cluster, which an administrator can read. A restore of a backup taken on one of those bullseye images comes back on that image and is checked by the next upgrade. allowCollationChange: false ## diff --git a/packages/system/postgres-rd/cozyrds/postgres.yaml b/packages/system/postgres-rd/cozyrds/postgres.yaml index 82ce0ac6b..7cc6000aa 100644 --- a/packages/system/postgres-rd/cozyrds/postgres.yaml +++ b/packages/system/postgres-rd/cozyrds/postgres.yaml @@ -30,7 +30,7 @@ spec: singular: postgres plural: postgreses openAPISchema: |- - {"title":"Chart Values","type":"object","properties":{"replicas":{"description":"Number of Postgres replicas. Under active autoscaling this is the resting/seed count, not the live count — KEDA drives the live count via `/scale`. Disabling autoscaling does NOT automatically bring the live count back to `replicas`: the client-side merge writes `instances` only when the rendered value changes, so a cluster KEDA grew past `replicas` stays there with no autoscaler left to reduce it — lower `replicas` to the count you want and it rebases down (shedding the surplus replicas + PVCs). Lowering it below the live count, or disabling/dry-running while it sits below the live count, sheds in one step past the scaleDown pacing; stage it to the live count first (suspend the HelmRelease and `kubectl scale` if needed) to avoid a transient. Must stay greater than `quorum.maxSyncReplicas`.","type":"integer","default":2},"resources":{"description":"Explicit CPU and memory configuration for each PostgreSQL replica. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","default":{},"properties":{"cpu":{"description":"CPU available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Memory (RAM) available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted.","type":"string","default":"t1.micro","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]},"size":{"description":"Persistent Volume Claim size available for application data.","default":"10Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"storageClass":{"description":"StorageClass used to store the data.","type":"string","default":"","x-kubernetes-validations":[{"rule":"self == oldSelf","message":"storageClass is immutable"}],"x-cozystack-options":{"source":"storageclass"}},"external":{"description":"Enable external access from outside the cluster.","type":"boolean","default":false},"version":{"description":"PostgreSQL major version to deploy","type":"string","default":"v18","enum":["v18","v17","v16","v15","v14","v13"]},"flavor":{"description":"PostgreSQL image flavor, fixed when the cluster is created. `postgresql` uses the CloudNativePG PostgreSQL image. `postgis` uses the CloudNativePG PostGIS image, which adds postgis, postgis_raster, postgis_topology, postgis_sfcgal, postgis_tiger_geocoder and address_standardizer; enable them per database in `databases..extensions`. Changing the flavor of an existing cluster is refused, and a backup restores only into a cluster of the flavor it was taken from: to change flavor, create a new cluster and move the data with a logical dump (pg_dump / pg_restore).","type":"string","default":"postgresql","enum":["postgresql","postgis"]},"allowCollationChange":{"description":"Allow a cluster created on a Debian bullseye image (before the move to standard-trixie) to move to the new image without a clean locale check. Such a cluster is checked before each upgrade, except while `bootstrap.enabled` is set (set it back to false once a restore set up by hand has finished), and stays on its current image until the check finds nothing that depends on a collation other than C, POSIX or builtin: while this is false, a cluster the check found affected (an ICU or libc locale, or C.UTF-8) or could not finish on stays put, because glibc and ICU on the new image sort text differently and every index on such text must be rebuilt. A held cluster runs the bare bullseye tag it has, gets no further PostgreSQL minors and so none of their security fixes, and refuses a change of `version`, since new majors are built only on the new images. To leave that state, either remove the dependency (move such columns and indexes to C, or to the builtin `pg_c_utf8` on PostgreSQL 17 and later) and let the next upgrade check again, or set this to true in a maintenance window: the cluster moves on the next upgrade, replicas restart on the new image first and can return wrong results through `-ro`, and unique indexes can accept duplicates, until the indexes are rebuilt on the primary. The init Job rebuilds only indexes on collations that record a version (ICU, and libc locales other than C.*): rebuild indexes on C.UTF-8 or another C.* locale by hand with REINDEX, and check range partitions, CHECK constraints and materialized views on such text, which a rebuild does not fix. A held cluster shows the hold only as an unchanged image; the result and the objects found are in the `postgres.cozystack.io/locale-data` and `postgres.cozystack.io/locale-data-objects` annotations of the cnpg.io Cluster, which an administrator can read. A restore of a backup taken on one of those bullseye images comes back on that image and is checked by the next upgrade.","type":"boolean","default":false},"tls":{"description":"TLS configuration for server connections.","type":"object","default":{},"properties":{"enabled":{"description":"Tri-state switch controlling whether the chart injects the external hostnames into the operator-managed CNPG cert via spec.certificates.serverAltDNSNames. When omitted, the chart injects them if `external: true` and skips them otherwise. Set explicitly to `true` to inject regardless of `external` (no-op when `external: false` since there is no external hostname to add). Set to `false` to skip injection. Note that CNPG keeps its built-in TLS on the wire regardless of this flag — this toggle only controls the chart-side SAN injection; to disable PostgreSQL TLS entirely set `postgresql.parameters.ssl = \"off\"` at the CNPG layer.","type":"boolean"},"required":{"description":"Tri-state switch controlling whether the server refuses sessions that are not encrypted. When omitted, it is on if `external: true` and off otherwise. When on, the chart renders `spec.postgresql.pg_hba` with `hostssl all all all scram-sha-256` (`md5` on PostgreSQL 13, matching CloudNativePG's default rule) followed by `host all all all reject`, so a client that connects with `sslmode=disable` is refused instead of getting a plaintext session; in-cluster clients are held to the same rule, since the pod network cannot be told apart from an external client. Set to `false` to keep accepting plaintext sessions on an external instance, or to `true` to require TLS on an in-cluster one. Rendering fails if `postgresql.parameters.ssl` is off while this is in effect.","type":"boolean"}}},"postgresql":{"description":"PostgreSQL server configuration.","type":"object","default":{},"properties":{"parameters":{"description":"PostgreSQL server parameters. Values may be strings or integers; integers are coerced to strings by the template (e.g. both `max_connections: 100` and `max_connections: \"100\"` are accepted). BLOCKED (enable arbitrary code execution): archive_command, restore_command, ssl_passphrase_command, archive_cleanup_command, recovery_end_command, dynamic_library_path, local_preload_libraries, session_preload_libraries, shared_preload_libraries. Do NOT override CloudNativePG-managed parameters: archive_mode, primary_conninfo, wal_level, max_replication_slots.","type":"object","default":{"max_connections":"100"},"additionalProperties":{"anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}},"sharedPreloadLibraries":{"description":"Libraries loaded at server start, restricted to an allowlist of modules already shipped in the PostgreSQL image. CloudNativePG also preloads `pg_stat_statements`, `auto_explain` and `pgaudit` by itself whenever `parameters` sets a key under their prefix (e.g. `pg_stat_statements.track`), so removing one of them from this list does not unload it while such a key is set; `pg_prewarm` is preloaded only through this list. Changing the list restarts PostgreSQL on every instance, the primary included, so writes pause briefly.","type":"array","items":{"type":"string","enum":["pg_stat_statements","auto_explain","pgaudit","pg_prewarm"]}}}},"quorum":{"description":"Quorum configuration for synchronous replication.","type":"object","default":{},"required":["maxSyncReplicas","minSyncReplicas"],"properties":{"maxSyncReplicas":{"description":"Maximum number of synchronous replicas allowed (must be less than total replicas). Under autoscaling it also sets the scale-down floor (the effective minimum is `max(minReplicas, maxSyncReplicas+1, 2)`); the chart fails to render if that floor exceeds `autoscaling.maxReplicas`.","type":"integer","default":0},"minSyncReplicas":{"description":"Minimum number of synchronous replicas required for commit.","type":"integer","default":0}}},"autoscaling":{"description":"Read-replica autoscaling configuration.","type":"object","default":{},"required":["dryRun","enabled","maxReplicas","maxReplicationLagSeconds","metric","minReplicas","serverAddress","target","transition"],"properties":{"dryRun":{"description":"Recommendation mode: keep the static count and render the ScaledObject with both scaling directions paused, so KEDA keeps the HPA and keeps serving its trigger metric but actuates neither way. Note both scaling policies are disabled, so the HPA's desiredReplicas is frozen to the current count - read the recommendation from the matching read-load dashboard panel for your metric (connections or CPU): desired = 1 + ceil(read load / target), clamped to [effectiveMin..maxReplicas] where effectiveMin = max(minReplicas, maxSyncReplicas+1, 2), not from the desired-replicas line. Like disabling, flipping a LIVE autoscaled cluster into dryRun re-renders `instances: replicas` (the raw static value, which can be below the autoscaling floor); if `replicas` is below the live count, stage it to the live count first (see the enablement note) or the cluster sheds down to `replicas`. No shed occurs when the rendered value is unchanged (replicas already equals the active seed) — client-side merge is then a no-op and the live count is preserved. Permanent, unlike `transition`.","type":"boolean","default":false},"enabled":{"description":"Enable horizontal autoscaling of read replicas. Requires the platform `keda` package to be enabled by an administrator first; the chart fails to render (rather than break the release) if KEDA is not installed. Prerequisite: the queried vmselect must hold BOTH the CNPG metrics (cnpg_backends_total / container CPU) AND kube_pod_labels (kube-state-metrics). This holds for a tenant on the shared root monitoring stack (`monitoring: false`, both land in tenant-root). A tenant running its OWN Monitoring app (`monitoring: true`) has the CNPG metrics but not kube_pod_labels (KSM is root-only), so it must set `serverAddress` to a vmselect carrying both series or autoscaling never actuates.","type":"boolean","default":false},"maxReplicas":{"description":"Maximum total instances. Must be >= minReplicas and >= the synchronous-quorum floor (maxSyncReplicas+1); the chart fails to render (rather than silently run an unbounded instance count) if the effective floor exceeds it - raise maxReplicas. HAZARD: lowering maxReplicas below the live count makes the HPA cut straight to the new maximum in one step (the current>max branch bypasses the scale-down pacing), shedding the surplus replicas + PVCs at once; to lower it deliberately, suspend the HelmRelease and pin the live count with `kubectl scale` first.","type":"integer","default":6},"maxReplicationLagSeconds":{"description":"Freeze scaling while replication lag exceeds this (seconds) and the primary is writing. 0 disables the brake. Default 0: the freeze branch has only been validated on a live cluster in its non-braking (pass-through) form, so the lag brake is opt-in until the braking path is exercised under load; set a positive value (e.g. 30) to enable it.","type":"integer","default":0},"metric":{"description":"Read-load signal to scale on.","type":"string","default":"ReadConnections","enum":["ReadConnections","ReadCPUUtilization"]},"minReplicas":{"description":"Minimum total instances; raised to the synchronous-quorum floor (`maxSyncReplicas + 1`) and to 2 when either is higher.","type":"integer","default":2},"serverAddress":{"description":"Override the Prometheus/vmselect URL the ScaledObject queries. Empty (default) derives `http://vmselect-shortterm..svc:8481/select/0/prometheus`. Set it when the derived vmselect does not hold both the CNPG metrics and kube_pod_labels (e.g. `monitoring: true` tenants, or a non-default `metricsStorages` name). SSRF constraint: the host must be an in-cluster Service DNS name (`..svc[.]`) whose namespace is within the tenant's own subtree (its namespace, its parents, or `tenant-root`) — the cluster-privileged KEDA operator fetches this URL every poll, so it is refused a metadata endpoint, an external host, or a sibling/system namespace. Residual surface (accepted trade-off): `tenant-root` is always allowed because the derived default points there, so a tenant can still aim the operator at any Service in `tenant-root` on any port/path (a blind in-cluster reachability probe — the operator reads no response body back to the tenant); the egress NetworkPolicy does not narrow that.","type":"string","default":""},"target":{"description":"Target read load per read-serving replica (unit depends on `metric`: active connections, or CPU millicores). Dimensionless integer - a resource.Quantity here would accept `150m`, which PromQL reads as 150 minutes and KEDA cannot use as a threshold.","type":"integer","default":150},"transition":{"description":"Migration phase 1: render `.spec.instances` from `replicas` (which the operator stages to the current live count) AND pause the ScaledObject in both directions, so KEDA stands up with its HPA present but not actuating. Flip to false (phase 2) to hand the runtime count to KEDA. Because the both-direction pause keeps the HPA (not the HPA-deleting full pause), KEDA is genuinely warm at phase 2 — no HPA recreate — and because the active seed is max(replicas, effectiveMin), phase 2 re-renders the same instance count phase 1 did (when `replicas` is staged at/above the floor), so the flip is a merge no-op with no dip. The HPA's scaleUp stabilization window still smooths the first actuation.","type":"boolean","default":false}}},"users":{"description":"Users configuration map. Passwords are always auto-generated and stored in the `-credentials` Secret; they cannot be set from values — read a user's password from that Secret. A `password` left over in values from before the field was removed is ignored by the render and draws an admission warning, but it is not inert on an upgraded release: the chart preserves whatever password is already in the Secret, which on the first upgrade is the value that was set before removal, so that value stays the live credential until it is rotated (dedicated rotation is tracked in cozystack/community#72). The live password lives only in the Secret.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"bypassRls":{"description":"Whether the user can bypass row-level security policies (BYPASSRLS). A role can only create other roles carrying BYPASSRLS if it holds the attribute itself, so this is required alongside `createRole` to provision a privileged service role.","type":"boolean"},"createRole":{"description":"Whether the user can create and manage roles (CREATEROLE). Requires PostgreSQL 16 or newer. Setting it back to `false` withdraws the attribute only: the roles the user created, and its ADMIN and SET memberships in them, stay. Once any user has held it, the chart no longer adopts an existing role it did not create, so a user or database declared later under the name of such a role fails the init job until a platform administrator drops that role.","type":"boolean"},"replication":{"description":"Whether the user has replication privileges.","type":"boolean"}}}},"databases":{"description":"Databases configuration map. The PostgreSQL system databases `postgres`, `template0` and `template1` are refused.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"extensions":{"description":"List of enabled PostgreSQL extensions.","type":"array","items":{"type":"string"}},"roles":{"description":"Roles assigned to users.","type":"object","properties":{"admin":{"description":"List of users with admin privileges.","type":"array","items":{"type":"string"}},"readonly":{"description":"List of users with read-only privileges.","type":"array","items":{"type":"string"}}}}}}},"backup":{"description":"Backup configuration.","type":"object","default":{},"required":["enabled"],"properties":{"destinationPath":{"description":"DEPRECATED. Per-tenant S3 configuration is superseded by the platform-managed `cozy-default` BackupClass and the `cozy-backups` system bucket. Leave empty for new installations; the BackupClass driver picks up the system-managed coordinates. Kept for in-place upgrade compatibility.","type":"string","default":"s3://bucket/path/to/folder/"},"enabled":{"description":"Enable regular backups.","type":"boolean","default":false},"endpointCA":{"description":"DEPRECATED. Pre-existing Secret with the CA bundle the barman-cloud plugin should trust when reaching a self-signed S3 endpoint. Used for both backup and bootstrap recovery in the legacy chart-managed flow.","type":"object","default":{},"properties":{"key":{"description":"Key within the Secret containing the CA bundle. Defaults to `ca.crt`.","type":"string","default":""},"name":{"description":"Name of the Secret in the application namespace. Empty means no endpointCA is emitted (the plugin uses the system trust store).","type":"string","default":""}}},"endpointURL":{"description":"DEPRECATED. See `destinationPath`.","type":"string","default":"http://minio-gateway-service:9000"},"retentionPolicy":{"description":"Retention policy (e.g. \"30d\").","type":"string","default":"30d"},"s3AccessKey":{"description":"DEPRECATED. Tenants no longer supply S3 keys; the system Bucket Secret is projected into the tenant namespace by the backup controller. Ignored when `s3CredentialsSecret.name` is set or `useSystemBucket` is true. The chart skips materialising `-s3-creds` whenever this field is empty so a default install does not leak placeholder credentials into the tenant namespace.","type":"string","default":""},"s3CredentialsSecret":{"description":"DEPRECATED. Pre-existing Secret with S3 credentials. Use the platform-managed `cozy-default` BackupClass instead. When set, the chart references this Secret directly (legacy chart-managed flow). The CNPG backup driver writes this field on restore so credentials never land in the CR `.spec`.","type":"object","default":{},"properties":{"accessKeyIDKey":{"description":"Key in the Secret holding the access key ID. Defaults to `AWS_ACCESS_KEY_ID`.","type":"string","default":""},"name":{"description":"Name of the Secret in the application namespace. Empty means the chart materialises `-s3-creds` from `s3AccessKey`/`s3SecretKey`.","type":"string","default":""},"secretAccessKeyKey":{"description":"Key in the Secret holding the secret access key. Defaults to `AWS_SECRET_ACCESS_KEY`.","type":"string","default":""}}},"s3SecretKey":{"description":"DEPRECATED. See `s3AccessKey`.","type":"string","default":""},"schedule":{"description":"Legacy. Cron schedule for the chart-emitted ScheduledBackup, either a standard five-field cron such as `0 2 * * *` for every day at 02:00, or six fields with leading seconds such as `0 0 2 * * *` for the same time. Empty means no chart-managed schedule, which is the recommended setup when a `BackupClass` from `backups.cozystack.io` already drives backup orchestration. In the legacy chart-managed flow `spec.plugins` plus the barman-cloud ObjectStore is rendered when `backup.enabled=true` AND `useSystemBucket=false` AND `destinationPath` is non-empty AND inline-or-external creds are supplied; in the platform `useSystemBucket=true` flow the chart skips emitting `spec.plugins` and the CNPG driver SSA-applies the ObjectStore and patches `spec.plugins` onto the live Cluster at first BackupJob time.","type":"string","default":""},"useSystemBucket":{"description":"Opt-in: when true, the chart-emitted `-s3-creds` Secret is skipped AND `spec.plugins` (plus the barman-cloud ObjectStore) is left UNSET in the chart-rendered Cluster — the cozy-default BackupClass driver SSA-applies an ObjectStore (carrying destinationPath/endpointURL/credentials) and patches `spec.plugins` on the live Cluster when the first BackupJob runs. Consequence: plugin WAL archiving is NOT active until that first BackupJob fires; WAL accumulates on the PVC in the meantime, so fire an ad-hoc BackupJob immediately after enabling the flag on existing releases. Use together with the platform `cozy-default` BackupClass — tenants do not need to fill `s3AccessKey`/`s3SecretKey` or `destinationPath`/`endpointURL`. The destination path automatically scopes to `s3://cozy-backups///`.","type":"boolean","default":false}}},"bootstrap":{"description":"Bootstrap configuration.","type":"object","default":{},"required":["enabled","oldName"],"properties":{"backupID":{"description":"Barman ID of the base backup to recover from, passed as `recoveryTarget.backupID`. Empty lets the barman-cloud plugin pick one: the newest backup when `recoveryTime` is empty, otherwise the newest one ending at or before it, on any timeline. The CNPG backup driver sets this on restore.","type":"string","default":""},"enabled":{"description":"Whether to restore from a backup.","type":"boolean","default":false},"newServerName":{"description":"WAL-archive server name (S3 path prefix) the RESTORED cluster writes to. Must differ from `serverName` (the recovery source) so a restored cluster archives to a fresh, empty prefix and barman-cloud-check-wal-archive passes while it recovers from the source's prefix. The CNPG backup driver sets this on restore; empty means the cluster archives under its own name.","type":"string","default":""},"oldName":{"description":"Previous cluster name before deletion.","type":"string","default":""},"recoveryTime":{"description":"Timestamp (RFC3339) for point-in-time recovery; empty means latest.","type":"string","default":""},"serverName":{"description":"Server name (S3 path prefix) used by the original cluster when writing backups; passed to the barman-cloud plugin via `externalClusters[].plugin.parameters.serverName`. Defaults to `bootstrap.oldName`. Set this only when the original cluster wrote backups under an explicit server name that differed from its Kubernetes resource name.","type":"string","default":""},"sourceImageName":{"description":"Image of the cluster the backup was taken from. A restore of a backup taken on one of the bare Debian bullseye tags the chart used before standard-trixie comes back on that image (see `allowCollationChange`); any other value is ignored. The CNPG backup driver sets this on restore and clears it with `enabled`.","type":"string","default":""}}}}} + {"title":"Chart Values","type":"object","properties":{"replicas":{"description":"Number of Postgres replicas. Under active autoscaling this is the resting/seed count, not the live count — KEDA drives the live count via `/scale`. Disabling autoscaling does NOT automatically bring the live count back to `replicas`: the client-side merge writes `instances` only when the rendered value changes, so a cluster KEDA grew past `replicas` stays there with no autoscaler left to reduce it — lower `replicas` to the count you want and it rebases down (shedding the surplus replicas + PVCs). Lowering it below the live count, or disabling/dry-running while it sits below the live count, sheds in one step past the scaleDown pacing; stage it to the live count first (suspend the HelmRelease and `kubectl scale` if needed) to avoid a transient. Must stay greater than `quorum.maxSyncReplicas`.","type":"integer","default":2},"resources":{"description":"Explicit CPU and memory configuration for each PostgreSQL replica. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","default":{},"properties":{"cpu":{"description":"CPU available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Memory (RAM) available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted.","type":"string","default":"t1.micro","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]},"size":{"description":"Persistent Volume Claim size available for application data.","default":"10Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"storageClass":{"description":"StorageClass used to store the data.","type":"string","default":"","x-kubernetes-validations":[{"rule":"self == oldSelf","message":"storageClass is immutable"}],"x-cozystack-options":{"source":"storageclass"}},"external":{"description":"Enable external access from outside the cluster.","type":"boolean","default":false},"version":{"description":"PostgreSQL major version to deploy","type":"string","default":"v18","enum":["v18","v17","v16","v15","v14","v13"]},"flavor":{"description":"PostgreSQL image flavor, fixed when the cluster is created. `postgresql` uses the CloudNativePG PostgreSQL image. `postgis` uses the CloudNativePG PostGIS image, which adds postgis, postgis_raster, postgis_topology, postgis_sfcgal, postgis_tiger_geocoder and address_standardizer; enable them per database in `databases..extensions`. Changing the flavor of an existing cluster is refused, and a backup restores only into a cluster of the flavor it was taken from: to change flavor, create a new cluster and move the data with a logical dump (pg_dump / pg_restore).","type":"string","default":"postgresql","enum":["postgresql","postgis"]},"allowCollationChange":{"description":"Allow a cluster created on a Debian bullseye image (before the move to standard-trixie) to move to the new image without a clean locale check. Such a cluster is checked before each upgrade, except while `bootstrap.enabled` is set (set it back to false once a restore set up by hand has finished), and stays on its current image until the check finds nothing that depends on a collation other than C, POSIX or builtin: while this is false, a cluster the check found affected (an ICU or libc locale, or C.UTF-8) or could not finish on stays put, because glibc and ICU on the new image sort text differently and every index on such text must be rebuilt. A held cluster runs the bare bullseye tag it has, gets no further PostgreSQL minors and so none of their security fixes, and refuses a change of `version`, since new majors are built only on the new images. To leave that state, either remove the dependency (move such columns and indexes to C, or to the builtin `pg_c_utf8` on PostgreSQL 17 and later) and let the next upgrade check again, or set this to true in a maintenance window: the cluster moves on the next upgrade, replicas restart on the new image first and can return wrong results through `-ro`, and unique indexes can accept duplicates, until the indexes are rebuilt on the primary. The init Job rebuilds the indexes on such text, those on C.UTF-8 and other C.* locales included; check range partitions, CHECK constraints and materialized views on it, which a rebuild does not fix. A held cluster shows the hold only as an unchanged image; the result and the objects found are in the `postgres.cozystack.io/locale-data` and `postgres.cozystack.io/locale-data-objects` annotations of the cnpg.io Cluster, which an administrator can read. A restore of a backup taken on one of those bullseye images comes back on that image and is checked by the next upgrade.","type":"boolean","default":false},"tls":{"description":"TLS configuration for server connections.","type":"object","default":{},"properties":{"enabled":{"description":"Tri-state switch controlling whether the chart injects the external hostnames into the operator-managed CNPG cert via spec.certificates.serverAltDNSNames. When omitted, the chart injects them if `external: true` and skips them otherwise. Set explicitly to `true` to inject regardless of `external` (no-op when `external: false` since there is no external hostname to add). Set to `false` to skip injection. Note that CNPG keeps its built-in TLS on the wire regardless of this flag — this toggle only controls the chart-side SAN injection; to disable PostgreSQL TLS entirely set `postgresql.parameters.ssl = \"off\"` at the CNPG layer.","type":"boolean"},"required":{"description":"Tri-state switch controlling whether the server refuses sessions that are not encrypted. When omitted, it is on if `external: true` and off otherwise. When on, the chart renders `spec.postgresql.pg_hba` with `hostssl all all all scram-sha-256` (`md5` on PostgreSQL 13, matching CloudNativePG's default rule) followed by `host all all all reject`, so a client that connects with `sslmode=disable` is refused instead of getting a plaintext session; in-cluster clients are held to the same rule, since the pod network cannot be told apart from an external client. Set to `false` to keep accepting plaintext sessions on an external instance, or to `true` to require TLS on an in-cluster one. Rendering fails if `postgresql.parameters.ssl` is off while this is in effect.","type":"boolean"}}},"postgresql":{"description":"PostgreSQL server configuration.","type":"object","default":{},"properties":{"parameters":{"description":"PostgreSQL server parameters. Values may be strings or integers; integers are coerced to strings by the template (e.g. both `max_connections: 100` and `max_connections: \"100\"` are accepted). BLOCKED (enable arbitrary code execution): archive_command, restore_command, ssl_passphrase_command, archive_cleanup_command, recovery_end_command, dynamic_library_path, local_preload_libraries, session_preload_libraries, shared_preload_libraries. Do NOT override CloudNativePG-managed parameters: archive_mode, primary_conninfo, wal_level, max_replication_slots.","type":"object","default":{"max_connections":"100"},"additionalProperties":{"anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}},"sharedPreloadLibraries":{"description":"Libraries loaded at server start, restricted to an allowlist of modules already shipped in the PostgreSQL image. CloudNativePG also preloads `pg_stat_statements`, `auto_explain` and `pgaudit` by itself whenever `parameters` sets a key under their prefix (e.g. `pg_stat_statements.track`), so removing one of them from this list does not unload it while such a key is set; `pg_prewarm` is preloaded only through this list. Changing the list restarts PostgreSQL on every instance, the primary included, so writes pause briefly.","type":"array","items":{"type":"string","enum":["pg_stat_statements","auto_explain","pgaudit","pg_prewarm"]}}}},"quorum":{"description":"Quorum configuration for synchronous replication.","type":"object","default":{},"required":["maxSyncReplicas","minSyncReplicas"],"properties":{"maxSyncReplicas":{"description":"Maximum number of synchronous replicas allowed (must be less than total replicas). Under autoscaling it also sets the scale-down floor (the effective minimum is `max(minReplicas, maxSyncReplicas+1, 2)`); the chart fails to render if that floor exceeds `autoscaling.maxReplicas`.","type":"integer","default":0},"minSyncReplicas":{"description":"Minimum number of synchronous replicas required for commit.","type":"integer","default":0}}},"autoscaling":{"description":"Read-replica autoscaling configuration.","type":"object","default":{},"required":["dryRun","enabled","maxReplicas","maxReplicationLagSeconds","metric","minReplicas","serverAddress","target","transition"],"properties":{"dryRun":{"description":"Recommendation mode: keep the static count and render the ScaledObject with both scaling directions paused, so KEDA keeps the HPA and keeps serving its trigger metric but actuates neither way. Note both scaling policies are disabled, so the HPA's desiredReplicas is frozen to the current count - read the recommendation from the matching read-load dashboard panel for your metric (connections or CPU): desired = 1 + ceil(read load / target), clamped to [effectiveMin..maxReplicas] where effectiveMin = max(minReplicas, maxSyncReplicas+1, 2), not from the desired-replicas line. Like disabling, flipping a LIVE autoscaled cluster into dryRun re-renders `instances: replicas` (the raw static value, which can be below the autoscaling floor); if `replicas` is below the live count, stage it to the live count first (see the enablement note) or the cluster sheds down to `replicas`. No shed occurs when the rendered value is unchanged (replicas already equals the active seed) — client-side merge is then a no-op and the live count is preserved. Permanent, unlike `transition`.","type":"boolean","default":false},"enabled":{"description":"Enable horizontal autoscaling of read replicas. Requires the platform `keda` package to be enabled by an administrator first; the chart fails to render (rather than break the release) if KEDA is not installed. Prerequisite: the queried vmselect must hold BOTH the CNPG metrics (cnpg_backends_total / container CPU) AND kube_pod_labels (kube-state-metrics). This holds for a tenant on the shared root monitoring stack (`monitoring: false`, both land in tenant-root). A tenant running its OWN Monitoring app (`monitoring: true`) has the CNPG metrics but not kube_pod_labels (KSM is root-only), so it must set `serverAddress` to a vmselect carrying both series or autoscaling never actuates.","type":"boolean","default":false},"maxReplicas":{"description":"Maximum total instances. Must be >= minReplicas and >= the synchronous-quorum floor (maxSyncReplicas+1); the chart fails to render (rather than silently run an unbounded instance count) if the effective floor exceeds it - raise maxReplicas. HAZARD: lowering maxReplicas below the live count makes the HPA cut straight to the new maximum in one step (the current>max branch bypasses the scale-down pacing), shedding the surplus replicas + PVCs at once; to lower it deliberately, suspend the HelmRelease and pin the live count with `kubectl scale` first.","type":"integer","default":6},"maxReplicationLagSeconds":{"description":"Freeze scaling while replication lag exceeds this (seconds) and the primary is writing. 0 disables the brake. Default 0: the freeze branch has only been validated on a live cluster in its non-braking (pass-through) form, so the lag brake is opt-in until the braking path is exercised under load; set a positive value (e.g. 30) to enable it.","type":"integer","default":0},"metric":{"description":"Read-load signal to scale on.","type":"string","default":"ReadConnections","enum":["ReadConnections","ReadCPUUtilization"]},"minReplicas":{"description":"Minimum total instances; raised to the synchronous-quorum floor (`maxSyncReplicas + 1`) and to 2 when either is higher.","type":"integer","default":2},"serverAddress":{"description":"Override the Prometheus/vmselect URL the ScaledObject queries. Empty (default) derives `http://vmselect-shortterm..svc:8481/select/0/prometheus`. Set it when the derived vmselect does not hold both the CNPG metrics and kube_pod_labels (e.g. `monitoring: true` tenants, or a non-default `metricsStorages` name). SSRF constraint: the host must be an in-cluster Service DNS name (`..svc[.]`) whose namespace is within the tenant's own subtree (its namespace, its parents, or `tenant-root`) — the cluster-privileged KEDA operator fetches this URL every poll, so it is refused a metadata endpoint, an external host, or a sibling/system namespace. Residual surface (accepted trade-off): `tenant-root` is always allowed because the derived default points there, so a tenant can still aim the operator at any Service in `tenant-root` on any port/path (a blind in-cluster reachability probe — the operator reads no response body back to the tenant); the egress NetworkPolicy does not narrow that.","type":"string","default":""},"target":{"description":"Target read load per read-serving replica (unit depends on `metric`: active connections, or CPU millicores). Dimensionless integer - a resource.Quantity here would accept `150m`, which PromQL reads as 150 minutes and KEDA cannot use as a threshold.","type":"integer","default":150},"transition":{"description":"Migration phase 1: render `.spec.instances` from `replicas` (which the operator stages to the current live count) AND pause the ScaledObject in both directions, so KEDA stands up with its HPA present but not actuating. Flip to false (phase 2) to hand the runtime count to KEDA. Because the both-direction pause keeps the HPA (not the HPA-deleting full pause), KEDA is genuinely warm at phase 2 — no HPA recreate — and because the active seed is max(replicas, effectiveMin), phase 2 re-renders the same instance count phase 1 did (when `replicas` is staged at/above the floor), so the flip is a merge no-op with no dip. The HPA's scaleUp stabilization window still smooths the first actuation.","type":"boolean","default":false}}},"users":{"description":"Users configuration map. Passwords are always auto-generated and stored in the `-credentials` Secret; they cannot be set from values — read a user's password from that Secret. A `password` left over in values from before the field was removed is ignored by the render and draws an admission warning, but it is not inert on an upgraded release: the chart preserves whatever password is already in the Secret, which on the first upgrade is the value that was set before removal, so that value stays the live credential until it is rotated (dedicated rotation is tracked in cozystack/community#72). The live password lives only in the Secret.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"bypassRls":{"description":"Whether the user can bypass row-level security policies (BYPASSRLS). A role can only create other roles carrying BYPASSRLS if it holds the attribute itself, so this is required alongside `createRole` to provision a privileged service role.","type":"boolean"},"createRole":{"description":"Whether the user can create and manage roles (CREATEROLE). Requires PostgreSQL 16 or newer. Setting it back to `false` withdraws the attribute only: the roles the user created, and its ADMIN and SET memberships in them, stay. Once any user has held it, the chart no longer adopts an existing role it did not create, so a user or database declared later under the name of such a role fails the init job until a platform administrator drops that role.","type":"boolean"},"replication":{"description":"Whether the user has replication privileges.","type":"boolean"}}}},"databases":{"description":"Databases configuration map. The PostgreSQL system databases `postgres`, `template0` and `template1` are refused.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"extensions":{"description":"List of enabled PostgreSQL extensions.","type":"array","items":{"type":"string"}},"roles":{"description":"Roles assigned to users.","type":"object","properties":{"admin":{"description":"List of users with admin privileges.","type":"array","items":{"type":"string"}},"readonly":{"description":"List of users with read-only privileges.","type":"array","items":{"type":"string"}}}}}}},"backup":{"description":"Backup configuration.","type":"object","default":{},"required":["enabled"],"properties":{"destinationPath":{"description":"DEPRECATED. Per-tenant S3 configuration is superseded by the platform-managed `cozy-default` BackupClass and the `cozy-backups` system bucket. Leave empty for new installations; the BackupClass driver picks up the system-managed coordinates. Kept for in-place upgrade compatibility.","type":"string","default":"s3://bucket/path/to/folder/"},"enabled":{"description":"Enable regular backups.","type":"boolean","default":false},"endpointCA":{"description":"DEPRECATED. Pre-existing Secret with the CA bundle the barman-cloud plugin should trust when reaching a self-signed S3 endpoint. Used for both backup and bootstrap recovery in the legacy chart-managed flow.","type":"object","default":{},"properties":{"key":{"description":"Key within the Secret containing the CA bundle. Defaults to `ca.crt`.","type":"string","default":""},"name":{"description":"Name of the Secret in the application namespace. Empty means no endpointCA is emitted (the plugin uses the system trust store).","type":"string","default":""}}},"endpointURL":{"description":"DEPRECATED. See `destinationPath`.","type":"string","default":"http://minio-gateway-service:9000"},"retentionPolicy":{"description":"Retention policy (e.g. \"30d\").","type":"string","default":"30d"},"s3AccessKey":{"description":"DEPRECATED. Tenants no longer supply S3 keys; the system Bucket Secret is projected into the tenant namespace by the backup controller. Ignored when `s3CredentialsSecret.name` is set or `useSystemBucket` is true. The chart skips materialising `-s3-creds` whenever this field is empty so a default install does not leak placeholder credentials into the tenant namespace.","type":"string","default":""},"s3CredentialsSecret":{"description":"DEPRECATED. Pre-existing Secret with S3 credentials. Use the platform-managed `cozy-default` BackupClass instead. When set, the chart references this Secret directly (legacy chart-managed flow). The CNPG backup driver writes this field on restore so credentials never land in the CR `.spec`.","type":"object","default":{},"properties":{"accessKeyIDKey":{"description":"Key in the Secret holding the access key ID. Defaults to `AWS_ACCESS_KEY_ID`.","type":"string","default":""},"name":{"description":"Name of the Secret in the application namespace. Empty means the chart materialises `-s3-creds` from `s3AccessKey`/`s3SecretKey`.","type":"string","default":""},"secretAccessKeyKey":{"description":"Key in the Secret holding the secret access key. Defaults to `AWS_SECRET_ACCESS_KEY`.","type":"string","default":""}}},"s3SecretKey":{"description":"DEPRECATED. See `s3AccessKey`.","type":"string","default":""},"schedule":{"description":"Legacy. Cron schedule for the chart-emitted ScheduledBackup, either a standard five-field cron such as `0 2 * * *` for every day at 02:00, or six fields with leading seconds such as `0 0 2 * * *` for the same time. Empty means no chart-managed schedule, which is the recommended setup when a `BackupClass` from `backups.cozystack.io` already drives backup orchestration. In the legacy chart-managed flow `spec.plugins` plus the barman-cloud ObjectStore is rendered when `backup.enabled=true` AND `useSystemBucket=false` AND `destinationPath` is non-empty AND inline-or-external creds are supplied; in the platform `useSystemBucket=true` flow the chart skips emitting `spec.plugins` and the CNPG driver SSA-applies the ObjectStore and patches `spec.plugins` onto the live Cluster at first BackupJob time.","type":"string","default":""},"useSystemBucket":{"description":"Opt-in: when true, the chart-emitted `-s3-creds` Secret is skipped AND `spec.plugins` (plus the barman-cloud ObjectStore) is left UNSET in the chart-rendered Cluster — the cozy-default BackupClass driver SSA-applies an ObjectStore (carrying destinationPath/endpointURL/credentials) and patches `spec.plugins` on the live Cluster when the first BackupJob runs. Consequence: plugin WAL archiving is NOT active until that first BackupJob fires; WAL accumulates on the PVC in the meantime, so fire an ad-hoc BackupJob immediately after enabling the flag on existing releases. Use together with the platform `cozy-default` BackupClass — tenants do not need to fill `s3AccessKey`/`s3SecretKey` or `destinationPath`/`endpointURL`. The destination path automatically scopes to `s3://cozy-backups///`.","type":"boolean","default":false}}},"bootstrap":{"description":"Bootstrap configuration.","type":"object","default":{},"required":["enabled","oldName"],"properties":{"backupID":{"description":"Barman ID of the base backup to recover from, passed as `recoveryTarget.backupID`. Empty lets the barman-cloud plugin pick one: the newest backup when `recoveryTime` is empty, otherwise the newest one ending at or before it, on any timeline. The CNPG backup driver sets this on restore.","type":"string","default":""},"enabled":{"description":"Whether to restore from a backup.","type":"boolean","default":false},"newServerName":{"description":"WAL-archive server name (S3 path prefix) the RESTORED cluster writes to. Must differ from `serverName` (the recovery source) so a restored cluster archives to a fresh, empty prefix and barman-cloud-check-wal-archive passes while it recovers from the source's prefix. The CNPG backup driver sets this on restore; empty means the cluster archives under its own name.","type":"string","default":""},"oldName":{"description":"Previous cluster name before deletion.","type":"string","default":""},"recoveryTime":{"description":"Timestamp (RFC3339) for point-in-time recovery; empty means latest.","type":"string","default":""},"serverName":{"description":"Server name (S3 path prefix) used by the original cluster when writing backups; passed to the barman-cloud plugin via `externalClusters[].plugin.parameters.serverName`. Defaults to `bootstrap.oldName`. Set this only when the original cluster wrote backups under an explicit server name that differed from its Kubernetes resource name.","type":"string","default":""},"sourceImageName":{"description":"Image of the cluster the backup was taken from. A restore of a backup taken on one of the bare Debian bullseye tags the chart used before standard-trixie comes back on that image (see `allowCollationChange`); any other value is ignored. The CNPG backup driver sets this on restore and clears it with `enabled`.","type":"string","default":""}}}}} release: prefix: postgres- labels: From fc618c1dcb086886eee591424b4ebaa98116f835 Mon Sep 17 00:00:00 2001 From: Aleksei Sviridkin Date: Mon, 30 Nov 2026 14:04:15 +0300 Subject: [PATCH 6/7] feat(workloadmonitor): report failed Jobs that opt in as not operational (#5505) ## What this PR does Refs #5459 A chart that runs workload-critical work in a Job outside its Helm release has no way to report a failed run on the Application today: `Ready` mirrors the HelmRelease, which is already applied, and `WorkloadsReady` only looks at pods, PVCs, Services, BucketClaims and DataVolumes. The immediate case is #5479, where the postgres collation repair and PostGIS update move out of a blocking hook into a Job started outside the release. If that Job fails (duplicates under a UNIQUE index, a PostGIS update that does not go through), the indexes stay wrong while the Application shows `Ready=True` and `WorkloadsReady=True`. This PR implements the proposal in https://github.com/cozystack/cozystack/issues/5459#issuecomment-7268007229 by adding a generic rule to the WorkloadMonitor controller: a `batch/v1` Job in the monitor's namespace that carries the monitor's selector labels plus `workloads.cozystack.io/report-failure: "true"`, and has `Failed=True`, makes the monitor not operational, with reason `JobFailed` and a message such as `Job postgres-x-collation-repair failed: BackoffLimitExceeded: Job has reached the specified backoff limit`. cozystack-api passes it through unchanged as `WorkloadsReady=False` with that reason and message. The rule knows nothing about postgres: a chart opts a Job in explicitly with that label. A Job with only the selector labels, which every chart and every operator inheriting labels from the workload may carry, never affects the monitor. The postgres side (the labels on the repair Job, no `ttlSecondsAfterFinished`) lands on #5479. Behaviour: - A Job that is deleted, or replaced by a run that does not fail, clears the verdict. Of the Jobs one controller owns, only the newest counts, so a CronJob's failed run that stays in its history after a later success does not keep the monitor down. - The message lists failed Jobs sorted by name, at most three, then `N more Jobs failed`. - Precedence: a DataVolume verdict comes first (unchanged; its stored value is kept while DataVolumes cannot be read), then `JobFailed`, then `BucketClaimNotReady`. `minReplicas` still sets `Operational=false` without a reason, so a failed Job beside too few replicas reports `JobFailed`. - Jobs are watched and mapped to monitors the same way pods are. The manager caches only Jobs that carry the opt-in label, with a transform that keeps only metadata (labels, owners, timestamps) and conditions. - RBAC: a `+kubebuilder:rbac` marker for `jobs.batch` get/list/watch documents the need. The markers under `internal/controller` do not generate YAML, and the cozystack-controller ClusterRole in `packages/system/cozystack-controller/templates/rbac.yaml` already grants get/list/watch on every resource, as it does for pods, PVCs, BucketClaims and DataVolumes, so the chart needs no change. No chart sets the opt-in label yet, so nothing reports until a chart adopts it. The postgres chart sets the selector labels in the Cluster's `inheritedMetadata`, so CNPG's initdb and join Jobs carry them; without the opt-in they are ignored, as are backup CronJob runs and any other labelled Job. ### Testing - `go build ./...`, `go vet` on `./internal/controller/`, `./cmd/cozystack-controller/`, `./api/v1alpha1/`: clean. - `go test ./internal/controller/... ./pkg/registry/apps/application/... ./api/...`: pass. - New unit tests (fake client): a failed Job sets `Operational=false`, reason `JobFailed` and the message; a succeeded, running, `Failed=False` or other-selector Job, and a failed Job without the opt-in label or with it set to anything but `"true"`, has no effect; a failed Job deleted or replaced by a successful run clears the verdict; a stale `JobFailed` is cleared before the DataVolume reader is installed; precedence against `minReplicas`, an unprovisioned BucketClaim and a DataVolume verdict; message sorting, the three-Job bound, newest-run-per-controller and Jobs being deleted; the cache transform keeps what the rule reads. cozystack-api: a monitor with `JobFailed` yields `WorkloadsReady=False` with that reason and message. - `make generate`: no changes. - Not run against a cluster: the Job watch and the transformed cache were not exercised end to end. ### Downstream repositories Walked the trigger map against the diff (`api/v1alpha1/workloadmonitor_types.go` constant only, no CRD schema change; `internal/controller`; `cmd/cozystack-controller`; tests). No package, platform values, ApplicationDefinition, installer, hack tooling, telemetry or commit-convention change. - [x] No downstream repository is affected by this change - [ ] [cozystack/website](https://github.com/cozystack/website) - follow-up: - [ ] [cozystack/terraform-provider-cozystack](https://github.com/cozystack/terraform-provider-cozystack) - follow-up: - [ ] [cozystack/ansible-cozystack](https://github.com/cozystack/ansible-cozystack) - follow-up: - [ ] [cozystack/ccp](https://github.com/cozystack/ccp) - follow-up: - [ ] [cozystack/talm](https://github.com/cozystack/talm) - follow-up: - [ ] [cozystack/cozyhr](https://github.com/cozystack/cozyhr) - follow-up: - [ ] [cozystack/cozy-proxy](https://github.com/cozystack/cozy-proxy) - follow-up: - [ ] [cozystack/cozystack-telemetry-server](https://github.com/cozystack/cozystack-telemetry-server) - follow-up: - [ ] [cozystack/external-apps-example](https://github.com/cozystack/external-apps-example) - follow-up: - [ ] [cozystack/examples](https://github.com/cozystack/examples) - follow-up: - [ ] [cozystack/community](https://github.com/cozystack/community) - follow-up: ### Release note ```release-note feat(workloadmonitor): a failed Job that carries a WorkloadMonitor's selector labels and `workloads.cozystack.io/report-failure: "true"` now makes the workload not operational, so the Application reports `WorkloadsReady=False` with reason `JobFailed` and a message naming the Job and its failure. Deleting the Job, or a later run that does not fail, clears it. ``` (cherry picked from commit 23b94d6d1a42f052dbcbbeb773c7497cc2220491) Signed-off-by: Andrey Kolkov --- api/v1alpha1/workloadmonitor_types.go | 11 + cmd/cozystack-controller/main.go | 2 + .../controller/workloadmonitor_controller.go | 139 +++++++++- .../workloadmonitor_controller_test.go | 254 ++++++++++++++++++ .../apps/application/rest_workloads_test.go | 8 + 5 files changed, 411 insertions(+), 3 deletions(-) diff --git a/api/v1alpha1/workloadmonitor_types.go b/api/v1alpha1/workloadmonitor_types.go index b5089652a..0ffc33e7a 100644 --- a/api/v1alpha1/workloadmonitor_types.go +++ b/api/v1alpha1/workloadmonitor_types.go @@ -43,6 +43,17 @@ const WorkloadMonitorReasonDataVolumeNotReady = "DataVolumeNotReady" // that is not operational because a BucketClaim it selects is not provisioned. const WorkloadMonitorReasonBucketClaimNotReady = "BucketClaimNotReady" +// WorkloadMonitorReasonJobFailed is the status Reason of a monitor that is not +// operational because a Job it selects, opted in with +// WorkloadMonitorReportFailureLabel, has failed. +const WorkloadMonitorReasonJobFailed = "JobFailed" + +// WorkloadMonitorReportFailureLabel set to "true" on a Job that also carries a +// monitor's selector labels makes a failure of that Job a failure of the +// workload. Other Jobs, such as those an operator labels by inheritance from +// the workload, never affect the monitor. +const WorkloadMonitorReportFailureLabel = "workloads.cozystack.io/report-failure" + // WorkloadMonitorStatus defines the observed state of WorkloadMonitor type WorkloadMonitorStatus struct { // Operational indicates if the workload meets all operational requirements diff --git a/cmd/cozystack-controller/main.go b/cmd/cozystack-controller/main.go index 59ba3b515..7cac159ae 100644 --- a/cmd/cozystack-controller/main.go +++ b/cmd/cozystack-controller/main.go @@ -26,6 +26,7 @@ import ( // to ensure that exec-entrypoint and run can make use of them. _ "k8s.io/client-go/plugin/pkg/client/auth" + batchv1 "k8s.io/api/batch/v1" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/runtime" utilruntime "k8s.io/apimachinery/pkg/util/runtime" @@ -216,6 +217,7 @@ func main() { Cache: cache.Options{ ByObject: map[client.Object]cache.ByObject{ &corev1.Secret{}: wildcardsecret.SecretCacheByObject(), + &batchv1.Job{}: controller.JobCacheByObject(), }, }, // LeaderElectionReleaseOnCancel defines if the leader should step down voluntarily diff --git a/internal/controller/workloadmonitor_controller.go b/internal/controller/workloadmonitor_controller.go index 53677a544..d0daf47f6 100644 --- a/internal/controller/workloadmonitor_controller.go +++ b/internal/controller/workloadmonitor_controller.go @@ -19,6 +19,7 @@ import ( apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/api/meta" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/types" @@ -38,6 +39,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/reconcile" "sigs.k8s.io/controller-runtime/pkg/source" + batchv1 "k8s.io/api/batch/v1" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -368,6 +370,7 @@ func (r *WorkloadMonitorReconciler) dataVolumesMessage(ctx context.Context, moni // +kubebuilder:rbac:groups=core,resources=events,verbs=create;patch // +kubebuilder:rbac:groups=objectstorage.k8s.io,resources=bucketclaims,verbs=get;list;watch // +kubebuilder:rbac:groups=cdi.kubevirt.io,resources=datavolumes,verbs=get;list;watch +// +kubebuilder:rbac:groups=batch,resources=jobs,verbs=get;list;watch // isBucketClaimReady checks if the BucketClaim has been provisioned. func (r *WorkloadMonitorReconciler) isBucketClaimReady(bc *cosiv1alpha1.BucketClaim) bool { @@ -393,6 +396,107 @@ func (r *WorkloadMonitorReconciler) bucketClaimsMessage(claims []cosiv1alpha1.Bu return strings.Join(pending, "; ") } +// maxFailedJobsInMessage bounds how many failed Jobs a monitor's message names. +const maxFailedJobsInMessage = 3 + +// jobFailedCondition returns the Failed=True condition of a Job, or nil. +func jobFailedCondition(job *batchv1.Job) *batchv1.JobCondition { + for i := range job.Status.Conditions { + c := &job.Status.Conditions[i] + if c.Type == batchv1.JobFailed && c.Status == corev1.ConditionTrue { + return c + } + } + return nil +} + +func jobIsNewer(a, b *batchv1.Job) bool { + if !a.CreationTimestamp.Equal(&b.CreationTimestamp) { + return b.CreationTimestamp.Before(&a.CreationTimestamp) + } + return a.Name > b.Name +} + +// failedJobsMessage names the failed Jobs with the reason and message of their +// Failed condition, and is empty when there is none. Of the Jobs one controller +// owns, only the newest counts: a CronJob keeps failed runs in its history +// after a later run succeeds. +func failedJobsMessage(jobs []batchv1.Job) string { + var current []*batchv1.Job + newestByOwner := map[types.UID]*batchv1.Job{} + for i := range jobs { + job := &jobs[i] + if job.DeletionTimestamp != nil { + continue + } + owner := metav1.GetControllerOfNoCopy(job) + if owner == nil { + current = append(current, job) + continue + } + if prev, ok := newestByOwner[owner.UID]; !ok || jobIsNewer(job, prev) { + newestByOwner[owner.UID] = job + } + } + for _, job := range newestByOwner { + current = append(current, job) + } + sort.Slice(current, func(i, j int) bool { return current[i].Name < current[j].Name }) + + var failed []string + for _, job := range current { + cond := jobFailedCondition(job) + if cond == nil { + continue + } + entry := fmt.Sprintf("Job %s failed", job.Name) + if cond.Reason != "" { + entry += ": " + cond.Reason + } + if cond.Message != "" { + entry += ": " + cond.Message + } + failed = append(failed, entry) + } + if extra := len(failed) - maxFailedJobsInMessage; extra > 0 { + failed = append(failed[:maxFailedJobsInMessage], fmt.Sprintf("%d more Jobs failed", extra)) + } + return strings.Join(failed, "; ") +} + +// JobCacheByObject returns the cache options the cozystack-controller manager +// applies to Jobs. The WorkloadMonitor reconciler, their only reader there, +// reads only Jobs that opted in with WorkloadMonitorReportFailureLabel, and of +// them only labels, owners and conditions. +func JobCacheByObject() cache.ByObject { + return cache.ByObject{ + Label: labels.SelectorFromSet(labels.Set{cozyv1alpha1.WorkloadMonitorReportFailureLabel: "true"}), + Transform: stripJob, + } +} + +func stripJob(obj any) (any, error) { + job, ok := obj.(*batchv1.Job) + if !ok { + return obj, nil + } + return &batchv1.Job{ + TypeMeta: job.TypeMeta, + ObjectMeta: metav1.ObjectMeta{ + Name: job.Name, + Namespace: job.Namespace, + UID: job.UID, + ResourceVersion: job.ResourceVersion, + Generation: job.Generation, + CreationTimestamp: job.CreationTimestamp, + DeletionTimestamp: job.DeletionTimestamp, + Labels: job.Labels, + OwnerReferences: job.OwnerReferences, + }, + Status: batchv1.JobStatus{Conditions: job.Status.Conditions}, + }, nil +} + // isServiceReady checks if the service has an external IP bound func (r *WorkloadMonitorReconciler) isServiceReady(svc *corev1.Service) bool { return len(svc.Status.LoadBalancer.Ingress) > 0 @@ -1044,6 +1148,22 @@ func (r *WorkloadMonitorReconciler) Reconcile(ctx context.Context, req ctrl.Requ bucketsMessage := r.bucketClaimsMessage(bucketClaimList.Items) + reportedJobs := client.MatchingLabels{cozyv1alpha1.WorkloadMonitorReportFailureLabel: "true"} + for k, v := range monitor.Spec.Selector { + reportedJobs[k] = v + } + jobList := &batchv1.JobList{} + if err := r.List( + ctx, + jobList, + client.InNamespace(monitor.Namespace), + reportedJobs, + ); err != nil { + logger.Error(err, "Unable to list Jobs for WorkloadMonitor", "monitor", monitor.Name) + return ctrl.Result{}, err + } + jobsMessage := failedJobsMessage(jobList.Items) + // Update WorkloadMonitor status based on observed pods monitor.Status.ObservedReplicas = observedReplicas monitor.Status.AvailableReplicas = availableReplicas @@ -1067,18 +1187,26 @@ func (r *WorkloadMonitorReconciler) Reconcile(ctx context.Context, req ctrl.Requ } // A stored DataVolume verdict is the last one: kept while no reader is // installed yet, so a controller restart does not report a stuck disk as - // ready. BucketClaims are listed on every pass, so their verdict is - // recomputed and only fills fields no DataVolume verdict holds. + // ready. Jobs and BucketClaims are listed on every pass, so their + // verdicts are recomputed and only fill fields no DataVolume verdict + // holds. A failed Job outranks an unprovisioned BucketClaim: it stays + // failed until something replaces it, while a claim is usually still + // being provisioned. if dataVolumesRead { fresh.Status.Message = dataVolumesMessage fresh.Status.Reason = "" if dataVolumesMessage != "" { fresh.Status.Reason = cozyv1alpha1.WorkloadMonitorReasonDataVolumeNotReady } - } else if fresh.Status.Reason == cozyv1alpha1.WorkloadMonitorReasonBucketClaimNotReady { + } else if fresh.Status.Reason == cozyv1alpha1.WorkloadMonitorReasonBucketClaimNotReady || + fresh.Status.Reason == cozyv1alpha1.WorkloadMonitorReasonJobFailed { fresh.Status.Message = "" fresh.Status.Reason = "" } + if fresh.Status.Message == "" && jobsMessage != "" { + fresh.Status.Message = jobsMessage + fresh.Status.Reason = cozyv1alpha1.WorkloadMonitorReasonJobFailed + } if fresh.Status.Message == "" && bucketsMessage != "" { fresh.Status.Message = bucketsMessage fresh.Status.Reason = cozyv1alpha1.WorkloadMonitorReasonBucketClaimNotReady @@ -1136,6 +1264,11 @@ func (r *WorkloadMonitorReconciler) SetupWithManager(mgr ctrl.Manager) error { &cosiv1alpha1.BucketClaim{}, handler.EnqueueRequestsFromMapFunc(mapObjectToMonitor(&cosiv1alpha1.BucketClaim{}, r.Client)), ). + // Cached Jobs carry only what JobCacheByObject keeps. + Watches( + &batchv1.Job{}, + handler.EnqueueRequestsFromMapFunc(mapObjectToMonitor(&batchv1.Job{}, r.Client)), + ). // Watch for changes to Workload objects we create (owned by WorkloadMonitor) Owns(&cozyv1alpha1.Workload{}) c, err := builder.Build(r) diff --git a/internal/controller/workloadmonitor_controller_test.go b/internal/controller/workloadmonitor_controller_test.go index 10a6c3eeb..151a832bc 100644 --- a/internal/controller/workloadmonitor_controller_test.go +++ b/internal/controller/workloadmonitor_controller_test.go @@ -13,6 +13,7 @@ import ( "time" cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1" + batchv1 "k8s.io/api/batch/v1" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/meta" "k8s.io/apimachinery/pkg/api/resource" @@ -40,6 +41,7 @@ func TestReconcile_OperationalStatusPersisted(t *testing.T) { scheme := runtime.NewScheme() _ = cozyv1alpha1.AddToScheme(scheme) _ = corev1.AddToScheme(scheme) + _ = batchv1.AddToScheme(scheme) _ = cosiv1alpha1.AddToScheme(scheme) minReplicas := int32(2) @@ -106,6 +108,7 @@ func TestReconcile_OperationalTrue_WhenEnoughReplicas(t *testing.T) { scheme := runtime.NewScheme() _ = cozyv1alpha1.AddToScheme(scheme) _ = corev1.AddToScheme(scheme) + _ = batchv1.AddToScheme(scheme) _ = cosiv1alpha1.AddToScheme(scheme) minReplicas := int32(1) @@ -235,6 +238,7 @@ func TestReconcile_MonitorLabelsPropagatedToPodWorkload(t *testing.T) { scheme := runtime.NewScheme() _ = cozyv1alpha1.AddToScheme(scheme) _ = corev1.AddToScheme(scheme) + _ = batchv1.AddToScheme(scheme) _ = cosiv1alpha1.AddToScheme(scheme) monitor := &cozyv1alpha1.WorkloadMonitor{ @@ -307,6 +311,7 @@ func TestReconcile_BackwardCompat_NoMonitorLabels(t *testing.T) { scheme := runtime.NewScheme() _ = cozyv1alpha1.AddToScheme(scheme) _ = corev1.AddToScheme(scheme) + _ = batchv1.AddToScheme(scheme) _ = cosiv1alpha1.AddToScheme(scheme) monitor := &cozyv1alpha1.WorkloadMonitor{ @@ -359,6 +364,7 @@ func TestReconcile_OperationalTrue_WhenNoMinReplicas(t *testing.T) { scheme := runtime.NewScheme() _ = cozyv1alpha1.AddToScheme(scheme) _ = corev1.AddToScheme(scheme) + _ = batchv1.AddToScheme(scheme) _ = cosiv1alpha1.AddToScheme(scheme) monitor := &cozyv1alpha1.WorkloadMonitor{ @@ -403,6 +409,7 @@ func newTestScheme() *runtime.Scheme { s := runtime.NewScheme() _ = cozyv1alpha1.AddToScheme(s) _ = corev1.AddToScheme(s) + _ = batchv1.AddToScheme(s) _ = cosiv1alpha1.AddToScheme(s) return s } @@ -2565,3 +2572,250 @@ func TestReconcile_DataVolumeVerdictOutranksBucketClaim(t *testing.T) { t.Errorf("Message = %q", got.Status.Message) } } + +func newJob(name string, labels map[string]string, conditions ...batchv1.JobCondition) *batchv1.Job { + return &batchv1.Job{ + ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: "default", Labels: labels}, + Status: batchv1.JobStatus{Conditions: conditions}, + } +} + +func jobFailed(reason, message string) batchv1.JobCondition { + return batchv1.JobCondition{Type: batchv1.JobFailed, Status: corev1.ConditionTrue, Reason: reason, Message: message} +} + +func newJobMonitorClient(s *runtime.Scheme, minReplicas int32, objs ...client.Object) client.Client { + monitor := &cozyv1alpha1.WorkloadMonitor{ + ObjectMeta: metav1.ObjectMeta{Name: "db", Namespace: "default"}, + Spec: cozyv1alpha1.WorkloadMonitorSpec{ + Selector: map[string]string{"app.kubernetes.io/instance": "db"}, + MinReplicas: ptr.To(minReplicas), + }, + } + return fake.NewClientBuilder(). + WithScheme(s). + WithObjects(append([]client.Object{monitor}, objs...)...). + WithStatusSubresource(monitor). + Build() +} + +func reconcileJobMonitor(t *testing.T, c client.Client, s *runtime.Scheme) *cozyv1alpha1.WorkloadMonitor { + t.Helper() + reconciler := &WorkloadMonitorReconciler{Client: c, Scheme: s, DataVolumeReader: c} + req := reconcile.Request{NamespacedName: types.NamespacedName{Name: "db", Namespace: "default"}} + if _, err := reconciler.Reconcile(context.TODO(), req); err != nil { + t.Fatalf("Reconcile returned error: %v", err) + } + updated := &cozyv1alpha1.WorkloadMonitor{} + if err := c.Get(context.TODO(), req.NamespacedName, updated); err != nil { + t.Fatalf("Failed to get updated WorkloadMonitor: %v", err) + } + if updated.Status.Operational == nil { + t.Fatal("Expected Operational to be set, got nil") + } + return updated +} + +func TestReconcile_FailedJobDecidesOperational(t *testing.T) { + selected := map[string]string{"app.kubernetes.io/instance": "db", cozyv1alpha1.WorkloadMonitorReportFailureLabel: "true"} + cases := []struct { + name string + job *batchv1.Job + message string + }{ + { + "failed", + newJob("db-repair", selected, jobFailed("BackoffLimitExceeded", "Job has reached the specified backoff limit")), + "Job db-repair failed: BackoffLimitExceeded: Job has reached the specified backoff limit", + }, + {"failed without a message", newJob("db-repair", selected, jobFailed("DeadlineExceeded", "")), "Job db-repair failed: DeadlineExceeded"}, + {"failed without a reason", newJob("db-repair", selected, jobFailed("", "")), "Job db-repair failed"}, + {"succeeded", newJob("db-repair", selected, batchv1.JobCondition{Type: batchv1.JobComplete, Status: corev1.ConditionTrue}), ""}, + {"running", newJob("db-repair", selected), ""}, + {"Failed condition not true", newJob("db-repair", selected, batchv1.JobCondition{Type: batchv1.JobFailed, Status: corev1.ConditionFalse}), ""}, + {"outside the selector", newJob("other", map[string]string{"app.kubernetes.io/instance": "other", cozyv1alpha1.WorkloadMonitorReportFailureLabel: "true"}, jobFailed("BackoffLimitExceeded", "")), ""}, + {"not opted in", newJob("db-1-initdb", map[string]string{"app.kubernetes.io/instance": "db"}, jobFailed("BackoffLimitExceeded", "")), ""}, + {"opted out", newJob("db-repair", map[string]string{"app.kubernetes.io/instance": "db", cozyv1alpha1.WorkloadMonitorReportFailureLabel: "false"}, jobFailed("BackoffLimitExceeded", "")), ""}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + s := newTestScheme() + got := reconcileJobMonitor(t, newJobMonitorClient(s, 0, tc.job), s) + if *got.Status.Operational != (tc.message == "") { + t.Errorf("Operational = %v, want %v", *got.Status.Operational, tc.message == "") + } + if got.Status.Message != tc.message { + t.Errorf("Message = %q, want %q", got.Status.Message, tc.message) + } + wantReason := "" + if tc.message != "" { + wantReason = cozyv1alpha1.WorkloadMonitorReasonJobFailed + } + if got.Status.Reason != wantReason { + t.Errorf("Reason = %q, want %q", got.Status.Reason, wantReason) + } + }) + } +} + +func TestReconcile_FailedJobVerdictClears(t *testing.T) { + selected := map[string]string{"app.kubernetes.io/instance": "db", cozyv1alpha1.WorkloadMonitorReportFailureLabel: "true"} + for _, tc := range []struct { + name string + clear func(c client.Client, job *batchv1.Job) error + }{ + {"deleted", func(c client.Client, job *batchv1.Job) error { return c.Delete(context.TODO(), job) }}, + {"replaced by a run that succeeded", func(c client.Client, job *batchv1.Job) error { + if err := c.Delete(context.TODO(), job); err != nil { + return err + } + return c.Create(context.TODO(), newJob("db-repair", selected, batchv1.JobCondition{Type: batchv1.JobComplete, Status: corev1.ConditionTrue})) + }}, + } { + t.Run(tc.name, func(t *testing.T) { + s := newTestScheme() + job := newJob("db-repair", selected, jobFailed("BackoffLimitExceeded", "")) + c := newJobMonitorClient(s, 0, job) + got := reconcileJobMonitor(t, c, s) + if *got.Status.Operational || got.Status.Reason != cozyv1alpha1.WorkloadMonitorReasonJobFailed { + t.Fatalf("before: Operational = %v, Reason = %q", *got.Status.Operational, got.Status.Reason) + } + if err := tc.clear(c, job); err != nil { + t.Fatal(err) + } + got = reconcileJobMonitor(t, c, s) + if !*got.Status.Operational || got.Status.Message != "" || got.Status.Reason != "" { + t.Errorf("after: Operational = %v, Message = %q, Reason = %q", *got.Status.Operational, got.Status.Message, got.Status.Reason) + } + }) + } +} + +func TestReconcile_StaleFailedJobVerdictClearsWithoutDataVolumeReader(t *testing.T) { + s := newTestScheme() + monitor := &cozyv1alpha1.WorkloadMonitor{ + ObjectMeta: metav1.ObjectMeta{Name: "db", Namespace: "default"}, + Spec: cozyv1alpha1.WorkloadMonitorSpec{Selector: map[string]string{"app.kubernetes.io/instance": "db"}}, + Status: cozyv1alpha1.WorkloadMonitorStatus{ + Operational: ptr.To(false), + Message: "Job db-repair failed: BackoffLimitExceeded", + Reason: cozyv1alpha1.WorkloadMonitorReasonJobFailed, + }, + } + c := fake.NewClientBuilder().WithScheme(s).WithObjects(monitor).WithStatusSubresource(monitor).Build() + reconciler := &WorkloadMonitorReconciler{Client: c, Scheme: s} + req := reconcile.Request{NamespacedName: types.NamespacedName{Name: "db", Namespace: "default"}} + if _, err := reconciler.Reconcile(context.TODO(), req); err != nil { + t.Fatalf("Reconcile returned error: %v", err) + } + got := &cozyv1alpha1.WorkloadMonitor{} + if err := c.Get(context.TODO(), req.NamespacedName, got); err != nil { + t.Fatal(err) + } + if got.Status.Operational == nil || !*got.Status.Operational || got.Status.Message != "" || got.Status.Reason != "" { + t.Errorf("Operational = %v, Message = %q, Reason = %q, want true and both cleared", got.Status.Operational, got.Status.Message, got.Status.Reason) + } +} + +func TestReconcile_FailedJobPrecedence(t *testing.T) { + selected := map[string]string{"app.kubernetes.io/instance": "db", cozyv1alpha1.WorkloadMonitorReportFailureLabel: "true"} + failed := newJob("db-repair", selected, jobFailed("BackoffLimitExceeded", "")) + importing := "ImportInProgress" + cases := []struct { + name string + minReplicas int32 + objs []client.Object + reason string + message string + }{ + {"below minReplicas", 1, []client.Object{failed}, cozyv1alpha1.WorkloadMonitorReasonJobFailed, "Job db-repair failed: BackoffLimitExceeded"}, + {"outranks an unprovisioned BucketClaim", 0, []client.Object{failed, newBucketClaim("db", selected, "", false)}, cozyv1alpha1.WorkloadMonitorReasonJobFailed, "Job db-repair failed: BackoffLimitExceeded"}, + {"outranked by a DataVolume verdict", 0, []client.Object{failed, newDataVolume("db", selected, &importing)}, cozyv1alpha1.WorkloadMonitorReasonDataVolumeNotReady, "DataVolume db is ImportInProgress"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + s := newTestScheme() + got := reconcileJobMonitor(t, newJobMonitorClient(s, tc.minReplicas, tc.objs...), s) + if *got.Status.Operational { + t.Error("Operational = true, want false") + } + if got.Status.Reason != tc.reason || got.Status.Message != tc.message { + t.Errorf("Reason = %q, Message = %q, want %q, %q", got.Status.Reason, got.Status.Message, tc.reason, tc.message) + } + }) + } +} + +func TestFailedJobsMessage(t *testing.T) { + failed := jobFailed("BackoffLimitExceeded", "") + complete := batchv1.JobCondition{Type: batchv1.JobComplete, Status: corev1.ConditionTrue} + ownedBy := func(job *batchv1.Job, uid types.UID, created time.Time) batchv1.Job { + job.OwnerReferences = []metav1.OwnerReference{{APIVersion: "batch/v1", Kind: "CronJob", Name: "backup", UID: uid, Controller: ptr.To(true)}} + job.CreationTimestamp = metav1.NewTime(created) + return *job + } + now := time.Now() + cases := []struct { + name string + jobs []batchv1.Job + want string + }{ + { + "sorted by name", + []batchv1.Job{*newJob("b", nil, failed), *newJob("a", nil, failed)}, + "Job a failed: BackoffLimitExceeded; Job b failed: BackoffLimitExceeded", + }, + { + "bounded", + []batchv1.Job{*newJob("e", nil, failed), *newJob("d", nil, failed), *newJob("c", nil, failed), *newJob("b", nil, failed), *newJob("a", nil, failed)}, + "Job a failed: BackoffLimitExceeded; Job b failed: BackoffLimitExceeded; Job c failed: BackoffLimitExceeded; 2 more Jobs failed", + }, + { + "a later run of the same controller succeeded", + []batchv1.Job{ownedBy(newJob("backup-1", nil, failed), "cron", now.Add(-time.Hour)), ownedBy(newJob("backup-2", nil, complete), "cron", now)}, + "", + }, + { + "the latest run of the controller failed", + []batchv1.Job{ownedBy(newJob("backup-1", nil, complete), "cron", now.Add(-time.Hour)), ownedBy(newJob("backup-2", nil, failed), "cron", now)}, + "Job backup-2 failed: BackoffLimitExceeded", + }, + { + "being deleted", + []batchv1.Job{func() batchv1.Job { + j := newJob("a", nil, failed) + j.DeletionTimestamp = ptr.To(metav1.NewTime(now)) + return *j + }()}, + "", + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := failedJobsMessage(tc.jobs); got != tc.want { + t.Errorf("failedJobsMessage = %q, want %q", got, tc.want) + } + }) + } +} + +func TestStripJobKeepsWhatTheMonitorReads(t *testing.T) { + job := newJob("db-repair", map[string]string{"app.kubernetes.io/instance": "db"}, jobFailed("BackoffLimitExceeded", "limit")) + job.OwnerReferences = []metav1.OwnerReference{{Name: "owner", UID: "u", Controller: ptr.To(true)}} + job.ResourceVersion = "7" + job.ManagedFields = []metav1.ManagedFieldsEntry{{Manager: "kube-controller-manager"}} + job.Spec.Template.Spec.Containers = []corev1.Container{{Name: "repair", Image: "postgres"}} + + out, err := stripJob(job) + if err != nil { + t.Fatal(err) + } + got := out.(*batchv1.Job) + if got.Name != job.Name || got.Namespace != job.Namespace || got.ResourceVersion != "7" || + len(got.Labels) != 1 || len(got.OwnerReferences) != 1 || failedJobsMessage([]batchv1.Job{*got}) != "Job db-repair failed: BackoffLimitExceeded: limit" { + t.Errorf("stripped Job lost what the monitor reads: %+v", got) + } + if len(got.ManagedFields) != 0 || len(got.Spec.Template.Spec.Containers) != 0 { + t.Errorf("stripped Job kept its spec or managed fields: %+v", got) + } +} diff --git a/pkg/registry/apps/application/rest_workloads_test.go b/pkg/registry/apps/application/rest_workloads_test.go index 1143e9c1d..5be5ee428 100644 --- a/pkg/registry/apps/application/rest_workloads_test.go +++ b/pkg/registry/apps/application/rest_workloads_test.go @@ -394,6 +394,14 @@ func TestConvertConditions_WorkloadsReadyCarriesMonitorMessages(t *testing.T) { "DataVolume b is Failed", cozyv1alpha1.WorkloadMonitorReasonDataVolumeNotReady, }, + { + "a failed Job", + []runtime.Object{ + monitor("mon-a", false, "Job mydb-repair failed: BackoffLimitExceeded: Job has reached the specified backoff limit", cozyv1alpha1.WorkloadMonitorReasonJobFailed), + }, + "Job mydb-repair failed: BackoffLimitExceeded: Job has reached the specified backoff limit", + cozyv1alpha1.WorkloadMonitorReasonJobFailed, + }, { "generic message when no monitor names a cause", []runtime.Object{monitor("mon-a", false, "", "")}, From c4c52beb300275e85ff89782623c2ed72aa23e6c Mon Sep 17 00:00:00 2001 From: Aleksei Sviridkin Date: Mon, 30 Nov 2026 18:24:14 +0300 Subject: [PATCH 7/7] fix(postgres): run the collation repair outside the Helm hook (#5479) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Refs #5459 (item 3: "Waiting for rollout eats Job budget"). **Depends on #5505.** Merge #5505 first or together with this PR. Here a failed repair no longer fails the HelmRelease. #5505 makes the WorkloadMonitor report the failed repair Job as `WorkloadsReady=False` with reason `JobFailed`. Without it the failure shows only on the Job itself. Moving tenant PostgreSQL to another image (for example bullseye `17.7` to `17.12-standard-trixie`) fails the first Helm upgrade of every release whose clients keep sessions open. The collation repair at the end of the post-upgrade init-job waits for CNPG to move the primary to the new image. CNPG rolls the primary last, and every instance spends up to `smartShutdownTimeout` (180 s) in smart shutdown, so the wait uses up the init-job's 540 s deadline and the HelmRelease goes `UpgradeFailed` until Flux retries. When the repair instead meets the primary restart, psql fails with `FATAL: the database system is shutting down` and the upgrade fails the same way. The one commit moves the repair out of the hook. A short post-install/post-upgrade hook, run after the init-job, creates a `-collation-repair` Job through the API (outside the release, so helm-controller does not wait for it) and returns. That Job keeps the OID mark / fingerprint resume and the in-place attempt records. It waits for the new image whenever the image changes, not only when an index already depends on a versioned collation: a plan built on the previous primary would miss an index created meanwhile, which the release recorded at the end would then claim as repaired. In the hook that wait was too expensive to make unconditional. The Job gets an hour, is owned by the Cluster, and its fixed name keeps two repairs from running at once. It carries the WorkloadMonitor's selector labels plus the opt-in `workloads.cozystack.io/report-failure: "true"` from #5505, and has no `ttlSecondsAfterFinished`, so a failed repair stays until the next upgrade replaces it (see the proposal in #5459). Both Jobs now rerun their idempotent script on psql exit status 2 (connection refused or dropped) with backoff instead of failing. Decisions for reviewers: - **Repair failures no longer fail the HelmRelease.** A repair that cannot finish (for example duplicates under a UNIQUE index) shows up as a Failed `-collation-repair` Job and its log, kept until the next upgrade starts a new run. The next upgrade retries it. Before, it showed up as `UpgradeFailed`. - **The repair also runs after install.** The install-time init-job used to record which Debian release each database starts on. Without that record, a cluster whose first upgrade moves the image would have its C.* indexes rebuilt only if the repair reached the primary before it restarted. On a fresh cluster the run only writes that record. The Job sets `PGCONNECT_TIMEOUT=10`. - **A failed rebuild no longer holds back the PostGIS update.** The update runs after the collation pass whatever it found, and the Job still fails at the end if a rebuild failed. - **The e2e upgrades twice.** The second upgrade finds the first repair Job complete on the same image, and the test waits for its replacement to complete. - **Lock waits are bounded by the Job's remaining hour, not about 8 minutes.** This is harmless for `REINDEX CONCURRENTLY`. For the in-place rebuild of an exclusion-constraint index, writers to that table can queue behind its lock wait for longer. Capping it separately means touching the per-index code that the parallel PRs on #5459 also edit, so I left it out. - **The hook's Role** has `get`/`delete` on the repair Job and `get` on the release's Cluster, both by `resourceNames`. It also has `create` on jobs, which RBAC cannot narrow by name. The SA, Role and RoleBinding are deleted once the hooks succeed. - **Verified under Flux.** helm-controller v1.5.0 runs the post-upgrade hooks about a second after it patches the Cluster, without waiting for the rollout. The rollout therefore no longer counts against the release timeout. Details in the PR thread. Rebased onto main after #5477 and #5485. The PostGIS extension update from #5477 waits for the same rollout, so it moves into `repair.sh` after the collation pass; left in the init-job, it would bring the hook-budget problem back for postgis clusters. Every message about a repair or update that did not finish says that the next upgrade of the release starts it again. The starter and the repair Job take their names from one base, which stays distinct and within 63 characters for any release name. - `helm unittest packages/apps/postgres`: 32 suites, 257 tests pass, including a new `collation_repair_test.yaml`. It checks gating (upgrade only, skipped while bootstrap is on), hook order after the init-job, the Role rules, RBAC removal on success, name length, and the init-job command. - Docker, with the rendered `run.sh` + `repair.sh` against `postgres:17-bullseye` and stale ICU / en_US collations: - Killing the `REINDEX INDEX CONCURRENTLY` backend mid-rebuild made the pass exit 2. `run.sh` reran it, the already rebuilt index was skipped by the OID mark, and the other index was rebuilt. amcheck was clean and the versions were refreshed. - With the server stopped before the first connection, the script retried with 5 s and 10 s pauses and finished once the server came back. - An SQL error exits 1 and is not retried. - dev7 (cozystack v1.7.0): two 3-instance v17 releases installed from v1.7.1 (bullseye `17.7`), with ICU and en_US UNIQUE indexes on 200k rows and `pg_sleep(3600)` sessions held on `-rw` and `-ro`. Both were upgraded with `helm upgrade --timeout 10m`: - origin/main: the init-job waited for `PostgreSQL 17.12 pgdg13`, hit `DeadlineExceeded`, and the command failed with `UPGRADE FAILED: post-upgrade hooks failed: resource Job/tenant-root/rr-main-init-job not ready. status: Failed` (exit 1 after 611 s). - This branch: exit 0 after 70 s (init-job 9 s, starter 10 s, starter RBAC removed afterwards). The repair Job waited out the rollout and rebuilt `t_u` and `t_k`. Collation versions were refreshed to `2.41` / `153.128`, `bt_index_check(..., true)` passed on all three instances, and the resume mark was reset. - A second upgrade replaced the finished repair Job, and the rerun found nothing to do. - The rebuild sat in `waiting for old snapshots` behind the test client's open transaction. That is expected for `REINDEX CONCURRENTLY`; I ended that session to finish the run. Walked against the diff (the new template, test and init-script/init-job changes in `packages/apps/postgres`). The diff changes no values, schema, `ApplicationDefinition`, Secret or Service names, package layout, or tooling. The only new objects are a hook-scoped ServiceAccount/Role/RoleBinding/Job and a Job created at runtime, which no listed repository refers to. - [x] No downstream repository is affected by this change - [ ] [cozystack/website](https://github.com/cozystack/website) - follow-up: - [ ] [cozystack/terraform-provider-cozystack](https://github.com/cozystack/terraform-provider-cozystack) - follow-up: - [ ] [cozystack/ansible-cozystack](https://github.com/cozystack/ansible-cozystack) - follow-up: - [ ] [cozystack/ccp](https://github.com/cozystack/ccp) - follow-up: - [ ] [cozystack/talm](https://github.com/cozystack/talm) - follow-up: - [ ] [cozystack/cozyhr](https://github.com/cozystack/cozyhr) - follow-up: - [ ] [cozystack/cozy-proxy](https://github.com/cozystack/cozy-proxy) - follow-up: - [ ] [cozystack/cozystack-telemetry-server](https://github.com/cozystack/cozystack-telemetry-server) - follow-up: - [ ] [cozystack/external-apps-example](https://github.com/cozystack/external-apps-example) - follow-up: - [ ] [cozystack/examples](https://github.com/cozystack/examples) - follow-up: - [ ] [cozystack/community](https://github.com/cozystack/community) - follow-up: - Flux (dev cluster, helm-controller v1.5.0): a tenant app on the v1.7.0 chart (bullseye `17.7`, 3 instances, sessions held on `-rw`/`-ro`) was upgraded by switching the platform's postgres chart. - With this PR, the HelmRelease reached `UpgradeSucceeded` in 21 s, and the repair Job finished after the rollout with `bt_index_check` clean on all instances. - With main, the upgrade took 7 min 06 s of the 10-minute timeout. - Docker: the rendered `repair.sh` for the postgis flavor moved PostGIS 3.6.1 → 3.7.0 after the collation pass. A tenant trigger on `spatial_ref_sys` did not run. ```release-note [postgres] An image change of a tenant PostgreSQL no longer fails the Helm upgrade while CNPG rolls the instances. The collation repair now runs in a separate `-collation-repair` Job, started after each upgrade, which waits for the new image and retries after connection drops. Check that Job's status and log to confirm the repair finished. ``` (cherry picked from commit c8ffc87717b72c9d589ec7ecca3ea9f02ee6ea70) Signed-off-by: Andrey Kolkov --- api/apps/v1alpha1/postgresql/types.go | 2 +- hack/e2e-chainsaw/postgres/chainsaw-test.yaml | 88 ++++++- packages/apps/postgres/README.md | 26 +- .../postgres/templates/collation-repair.yaml | 223 ++++++++++++++++++ .../apps/postgres/templates/init-job.yaml | 1 + .../apps/postgres/templates/init-script.yaml | 138 +++++++---- .../postgres/tests/collation_repair_test.yaml | 167 +++++++++++++ packages/apps/postgres/values.schema.json | 2 +- packages/apps/postgres/values.yaml | 2 +- .../system/postgres-rd/cozyrds/postgres.yaml | 2 +- 10 files changed, 573 insertions(+), 78 deletions(-) create mode 100644 packages/apps/postgres/templates/collation-repair.yaml create mode 100644 packages/apps/postgres/tests/collation_repair_test.yaml diff --git a/api/apps/v1alpha1/postgresql/types.go b/api/apps/v1alpha1/postgresql/types.go index 5e609e5ea..3fe67c299 100644 --- a/api/apps/v1alpha1/postgresql/types.go +++ b/api/apps/v1alpha1/postgresql/types.go @@ -43,7 +43,7 @@ type ConfigSpec struct { // PostgreSQL image flavor, fixed when the cluster is created. `postgresql` uses the CloudNativePG PostgreSQL image. `postgis` uses the CloudNativePG PostGIS image, which adds postgis, postgis_raster, postgis_topology, postgis_sfcgal, postgis_tiger_geocoder and address_standardizer; enable them per database in `databases..extensions`. Changing the flavor of an existing cluster is refused, and a backup restores only into a cluster of the flavor it was taken from: to change flavor, create a new cluster and move the data with a logical dump (pg_dump / pg_restore). // +kubebuilder:default:="postgresql" Flavor Flavor `json:"flavor"` - // Allow a cluster created on a Debian bullseye image (before the move to standard-trixie) to move to the new image without a clean locale check. Such a cluster is checked before each upgrade, except while `bootstrap.enabled` is set (set it back to false once a restore set up by hand has finished), and stays on its current image until the check finds nothing that depends on a collation other than C, POSIX or builtin: while this is false, a cluster the check found affected (an ICU or libc locale, or C.UTF-8) or could not finish on stays put, because glibc and ICU on the new image sort text differently and every index on such text must be rebuilt. A held cluster runs the bare bullseye tag it has, gets no further PostgreSQL minors and so none of their security fixes, and refuses a change of `version`, since new majors are built only on the new images. To leave that state, either remove the dependency (move such columns and indexes to C, or to the builtin `pg_c_utf8` on PostgreSQL 17 and later) and let the next upgrade check again, or set this to true in a maintenance window: the cluster moves on the next upgrade, replicas restart on the new image first and can return wrong results through `-ro`, and unique indexes can accept duplicates, until the indexes are rebuilt on the primary. The init Job rebuilds the indexes on such text, those on C.UTF-8 and other C.* locales included; check range partitions, CHECK constraints and materialized views on it, which a rebuild does not fix. A held cluster shows the hold only as an unchanged image; the result and the objects found are in the `postgres.cozystack.io/locale-data` and `postgres.cozystack.io/locale-data-objects` annotations of the cnpg.io Cluster, which an administrator can read. A restore of a backup taken on one of those bullseye images comes back on that image and is checked by the next upgrade. + // Allow a cluster created on a Debian bullseye image (before the move to standard-trixie) to move to the new image without a clean locale check. Such a cluster is checked before each upgrade, except while `bootstrap.enabled` is set (set it back to false once a restore set up by hand has finished), and stays on its current image until the check finds nothing that depends on a collation other than C, POSIX or builtin: while this is false, a cluster the check found affected (an ICU or libc locale, or C.UTF-8) or could not finish on stays put, because glibc and ICU on the new image sort text differently and every index on such text must be rebuilt. A held cluster runs the bare bullseye tag it has, gets no further PostgreSQL minors and so none of their security fixes, and refuses a change of `version`, since new majors are built only on the new images. To leave that state, either remove the dependency (move such columns and indexes to C, or to the builtin `pg_c_utf8` on PostgreSQL 17 and later) and let the next upgrade check again, or set this to true in a maintenance window: the cluster moves on the next upgrade, replicas restart on the new image first and can return wrong results through `-ro`, and unique indexes can accept duplicates, until the indexes are rebuilt on the primary. The collation repair Job, which a post-upgrade hook starts once the init Job is done, rebuilds the indexes on such text after the rollout, those on C.UTF-8 and other C.* locales included, and its log reports a rebuild that failed; check range partitions, CHECK constraints and materialized views on it, which a rebuild does not fix. A held cluster shows the hold only as an unchanged image; the result and the objects found are in the `postgres.cozystack.io/locale-data` and `postgres.cozystack.io/locale-data-objects` annotations of the cnpg.io Cluster, which an administrator can read. A restore of a backup taken on one of those bullseye images comes back on that image and is checked by the next upgrade. // +kubebuilder:default:=false AllowCollationChange bool `json:"allowCollationChange"` // TLS configuration for server connections. diff --git a/hack/e2e-chainsaw/postgres/chainsaw-test.yaml b/hack/e2e-chainsaw/postgres/chainsaw-test.yaml index a2f46b4f2..4aaf6f117 100644 --- a/hack/e2e-chainsaw/postgres/chainsaw-test.yaml +++ b/hack/e2e-chainsaw/postgres/chainsaw-test.yaml @@ -250,9 +250,9 @@ spec: check: ($error == null): true - # The init Job rebuilds an index whose collation changed library version. - # The pass is SQL run by a Helm hook, so only a real server can say whether - # it works. A collation created with an explicit version reads as stale + # The collation repair Job rebuilds an index whose collation changed library + # version. The pass is SQL run by a Job a Helm hook starts, so only a real + # server can say whether it works. A collation created with an explicit version reads as stale # without swapping the operand image, and so does a C. collation # once the database records another Debian release as the one it was # repaired for, which makes one more upgrade of the release enough to run @@ -293,6 +293,15 @@ spec: EOF check: ($error == null): true + # A repair Job left by the install has completed already; it goes + # first, so that the Job awaited below is the one this upgrade starts. + - script: + timeout: 2m + content: | + set -eu + kubectl -n "$NAMESPACE" delete job postgres-test-collation-repair --ignore-not-found --wait=true + check: + ($error == null): true # A declared user is the smallest change that makes Helm upgrade the # release, and so run the hook, without restarting PostgreSQL. - patch: @@ -317,6 +326,58 @@ spec: status: (conditions[?type == 'Complete']): - status: "True" + # The repair runs in a Job a post-upgrade hook starts outside the + # release, after the init Job. The label is what makes the + # WorkloadMonitor report a failed repair on the Application. + - assert: + timeout: 15m + resource: + apiVersion: batch/v1 + kind: Job + metadata: + name: postgres-test-collation-repair + labels: + app.kubernetes.io/name: postgres.apps.cozystack.io + app.kubernetes.io/instance: postgres-test + workloads.cozystack.io/report-failure: "true" + status: + (conditions[?type == 'Complete']): + - status: "True" + # The next upgrade finds that Job complete on the same image and replaces + # it with a new run under the same name. + - script: + timeout: 1m + content: | + set -eu + # A failed repair must stay visible until the next upgrade replaces it. + ttl=$(kubectl -n "$NAMESPACE" get job postgres-test-collation-repair -o jsonpath='{.spec.ttlSecondsAfterFinished}') + if [ -n "$ttl" ]; then + echo "the collation repair Job has ttlSecondsAfterFinished=$ttl, so a failed repair would disappear" >&2 + exit 1 + fi + kubectl -n "$NAMESPACE" annotate job postgres-test-collation-repair e2e.cozystack.io/previous-run=true + check: + ($error == null): true + - patch: + resource: + apiVersion: apps.cozystack.io/v1alpha1 + kind: Postgres + metadata: + name: test + spec: + users: + collationprobe: {} + collationprobe2: {} + - script: + timeout: 15m + content: | + set -eu + until [ "$(kubectl -n "$NAMESPACE" get job postgres-test-collation-repair --ignore-not-found \ + -o jsonpath='{.metadata.annotations.e2e\.cozystack\.io/previous-run}|{.status.conditions[?(@.type=="Complete")].status}')" = "|True" ]; do + sleep 5 + done + check: + ($error == null): true - script: timeout: 2m content: | @@ -330,14 +391,14 @@ spec: } refreshed=$(q "SELECT collversion = pg_collation_actual_version(oid) FROM pg_collation WHERE collname = 'stale_icu'") if [ "$refreshed" != t ]; then - echo "the init Job left the collation version stale" >&2 + echo "the collation repair Job left the collation version stale" >&2 exit 1 fi # REINDEX CONCURRENTLY gives the index a new OID, so an unchanged # one means the version was refreshed over an index nobody rebuilt. rebuilt=$(q "SELECT 'collation_probe_s'::regclass::oid <> index FROM collation_probe_before") if [ "$rebuilt" != t ]; then - echo "the init Job refreshed the collation version without rebuilding the index" >&2 + echo "the collation repair Job refreshed the collation version without rebuilding the index" >&2 exit 1 fi q "CREATE EXTENSION IF NOT EXISTS amcheck" @@ -346,18 +407,18 @@ spec: # OID and gets a new storage file. rebuilt_in_place=$(q "SELECT c.relfilenode <> b.in_place_file FROM pg_class c, collation_probe_before b WHERE c.oid = 'collation_probe_excl_s_excl'::regclass") if [ "$rebuilt_in_place" != t ]; then - echo "the init Job did not rebuild the exclusion constraint's index" >&2 + echo "the collation repair Job did not rebuild the exclusion constraint's index" >&2 exit 1 fi rebuilt_c=$(q "SELECT 'collation_probe_c_s_key'::regclass::oid <> c_index FROM collation_probe_before") if [ "$rebuilt_c" != t ]; then - echo "the init Job did not rebuild the index on a C. collation after the Debian release changed" >&2 + echo "the collation repair Job did not rebuild the index on a C. collation after the Debian release changed" >&2 exit 1 fi q "SELECT bt_index_check('collation_probe_c_s_key', true)" release=$(q "SELECT current_setting('cozystack.collation_release', true) = substring(current_setting('server_version') from 'pgdg[0-9]+')") if [ "$release" != t ]; then - echo "the init Job did not record the Debian release it repaired the database for" >&2 + echo "the collation repair Job did not record the Debian release it repaired the database for" >&2 exit 1 fi qu() { @@ -366,21 +427,21 @@ spec: } rebuilt_unrecorded=$(qu "SELECT 'collation_probe_c_s_key'::regclass::oid <> c_index FROM collation_probe_before") if [ "$rebuilt_unrecorded" != t ]; then - echo "the init Job did not rebuild the index on a C. collation in a database that recorded no release and holds a stale libc collation" >&2 + echo "the collation repair Job did not rebuild the index on a C. collation in a database that recorded no release and holds a stale libc collation" >&2 exit 1 fi qu "CREATE EXTENSION IF NOT EXISTS amcheck" qu "SELECT bt_index_check('collation_probe_c_s_key', true)" release=$(qu "SELECT current_setting('cozystack.collation_release', true) = substring(current_setting('server_version') from 'pgdg[0-9]+')") if [ "$release" != t ]; then - echo "the init Job did not record the Debian release it repaired the unrecorded database for" >&2 + echo "the collation repair Job did not record the Debian release it repaired the unrecorded database for" >&2 exit 1 fi # The pass keeps its progress in a setting of the database and # removes it once nothing is left to repair. progress=$(q "SELECT count(*) FROM pg_db_role_setting s JOIN pg_database d ON d.oid = s.setdatabase, unnest(s.setconfig) AS c WHERE d.datname = current_database() AND c LIKE 'cozystack.collation_repair=%'") if [ "$progress" != 0 ]; then - echo "the init Job left its repair setting on a database it finished repairing" >&2 + echo "the collation repair Job left its repair setting on a database it finished repairing" >&2 exit 1 fi leftovers=$(q "SELECT count(*) FROM pg_index WHERE NOT indisvalid") @@ -407,6 +468,11 @@ spec: apiVersion: batch/v1 kind: Job name: postgres-test-init-job + - delete: + ref: + apiVersion: batch/v1 + kind: Job + name: postgres-test-collation-repair # The Postgres CR itself was applied by chainsaw and is deleted (and waited # on) automatically during cleanup — no explicit teardown step needed. --- diff --git a/packages/apps/postgres/README.md b/packages/apps/postgres/README.md index 2286f5bba..a737e5468 100644 --- a/packages/apps/postgres/README.md +++ b/packages/apps/postgres/README.md @@ -207,19 +207,19 @@ For `sslmode=verify-full` to work, the CA bundle retrieved above must be saved t ### Common parameters -| Name | Description | Type | Value | -| ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | ------------ | -| `replicas` | Number of Postgres replicas. Under active autoscaling this is the resting/seed count, not the live count — KEDA drives the live count via `/scale`. Disabling autoscaling does NOT automatically bring the live count back to `replicas`: the client-side merge writes `instances` only when the rendered value changes, so a cluster KEDA grew past `replicas` stays there with no autoscaler left to reduce it — lower `replicas` to the count you want and it rebases down (shedding the surplus replicas + PVCs). Lowering it below the live count, or disabling/dry-running while it sits below the live count, sheds in one step past the scaleDown pacing; stage it to the live count first (suspend the HelmRelease and `kubectl scale` if needed) to avoid a transient. Must stay greater than `quorum.maxSyncReplicas`. | `int` | `2` | -| `resources` | Explicit CPU and memory configuration for each PostgreSQL replica. When omitted, the preset defined in `resourcesPreset` is applied. | `object` | `{}` | -| `resources.cpu` | CPU available to each replica. | `quantity` | `""` | -| `resources.memory` | Memory (RAM) available to each replica. | `quantity` | `""` | -| `resourcesPreset` | Default sizing preset used when `resources` is omitted. | `string` | `t1.micro` | -| `size` | Persistent Volume Claim size available for application data. | `quantity` | `10Gi` | -| `storageClass` | StorageClass used to store the data. | `string` | `""` | -| `external` | Enable external access from outside the cluster. | `bool` | `false` | -| `version` | PostgreSQL major version to deploy | `string` | `v18` | -| `flavor` | PostgreSQL image flavor, fixed when the cluster is created. `postgresql` uses the CloudNativePG PostgreSQL image. `postgis` uses the CloudNativePG PostGIS image, which adds postgis, postgis_raster, postgis_topology, postgis_sfcgal, postgis_tiger_geocoder and address_standardizer; enable them per database in `databases..extensions`. Changing the flavor of an existing cluster is refused, and a backup restores only into a cluster of the flavor it was taken from: to change flavor, create a new cluster and move the data with a logical dump (pg_dump / pg_restore). | `string` | `postgresql` | -| `allowCollationChange` | Allow a cluster created on a Debian bullseye image (before the move to standard-trixie) to move to the new image without a clean locale check. Such a cluster is checked before each upgrade, except while `bootstrap.enabled` is set (set it back to false once a restore set up by hand has finished), and stays on its current image until the check finds nothing that depends on a collation other than C, POSIX or builtin: while this is false, a cluster the check found affected (an ICU or libc locale, or C.UTF-8) or could not finish on stays put, because glibc and ICU on the new image sort text differently and every index on such text must be rebuilt. A held cluster runs the bare bullseye tag it has, gets no further PostgreSQL minors and so none of their security fixes, and refuses a change of `version`, since new majors are built only on the new images. To leave that state, either remove the dependency (move such columns and indexes to C, or to the builtin `pg_c_utf8` on PostgreSQL 17 and later) and let the next upgrade check again, or set this to true in a maintenance window: the cluster moves on the next upgrade, replicas restart on the new image first and can return wrong results through `-ro`, and unique indexes can accept duplicates, until the indexes are rebuilt on the primary. The init Job rebuilds the indexes on such text, those on C.UTF-8 and other C.* locales included; check range partitions, CHECK constraints and materialized views on it, which a rebuild does not fix. A held cluster shows the hold only as an unchanged image; the result and the objects found are in the `postgres.cozystack.io/locale-data` and `postgres.cozystack.io/locale-data-objects` annotations of the cnpg.io Cluster, which an administrator can read. A restore of a backup taken on one of those bullseye images comes back on that image and is checked by the next upgrade. | `bool` | `false` | +| Name | Description | Type | Value | +| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | ------------ | +| `replicas` | Number of Postgres replicas. Under active autoscaling this is the resting/seed count, not the live count — KEDA drives the live count via `/scale`. Disabling autoscaling does NOT automatically bring the live count back to `replicas`: the client-side merge writes `instances` only when the rendered value changes, so a cluster KEDA grew past `replicas` stays there with no autoscaler left to reduce it — lower `replicas` to the count you want and it rebases down (shedding the surplus replicas + PVCs). Lowering it below the live count, or disabling/dry-running while it sits below the live count, sheds in one step past the scaleDown pacing; stage it to the live count first (suspend the HelmRelease and `kubectl scale` if needed) to avoid a transient. Must stay greater than `quorum.maxSyncReplicas`. | `int` | `2` | +| `resources` | Explicit CPU and memory configuration for each PostgreSQL replica. When omitted, the preset defined in `resourcesPreset` is applied. | `object` | `{}` | +| `resources.cpu` | CPU available to each replica. | `quantity` | `""` | +| `resources.memory` | Memory (RAM) available to each replica. | `quantity` | `""` | +| `resourcesPreset` | Default sizing preset used when `resources` is omitted. | `string` | `t1.micro` | +| `size` | Persistent Volume Claim size available for application data. | `quantity` | `10Gi` | +| `storageClass` | StorageClass used to store the data. | `string` | `""` | +| `external` | Enable external access from outside the cluster. | `bool` | `false` | +| `version` | PostgreSQL major version to deploy | `string` | `v18` | +| `flavor` | PostgreSQL image flavor, fixed when the cluster is created. `postgresql` uses the CloudNativePG PostgreSQL image. `postgis` uses the CloudNativePG PostGIS image, which adds postgis, postgis_raster, postgis_topology, postgis_sfcgal, postgis_tiger_geocoder and address_standardizer; enable them per database in `databases..extensions`. Changing the flavor of an existing cluster is refused, and a backup restores only into a cluster of the flavor it was taken from: to change flavor, create a new cluster and move the data with a logical dump (pg_dump / pg_restore). | `string` | `postgresql` | +| `allowCollationChange` | Allow a cluster created on a Debian bullseye image (before the move to standard-trixie) to move to the new image without a clean locale check. Such a cluster is checked before each upgrade, except while `bootstrap.enabled` is set (set it back to false once a restore set up by hand has finished), and stays on its current image until the check finds nothing that depends on a collation other than C, POSIX or builtin: while this is false, a cluster the check found affected (an ICU or libc locale, or C.UTF-8) or could not finish on stays put, because glibc and ICU on the new image sort text differently and every index on such text must be rebuilt. A held cluster runs the bare bullseye tag it has, gets no further PostgreSQL minors and so none of their security fixes, and refuses a change of `version`, since new majors are built only on the new images. To leave that state, either remove the dependency (move such columns and indexes to C, or to the builtin `pg_c_utf8` on PostgreSQL 17 and later) and let the next upgrade check again, or set this to true in a maintenance window: the cluster moves on the next upgrade, replicas restart on the new image first and can return wrong results through `-ro`, and unique indexes can accept duplicates, until the indexes are rebuilt on the primary. The collation repair Job, which a post-upgrade hook starts once the init Job is done, rebuilds the indexes on such text after the rollout, those on C.UTF-8 and other C.* locales included, and its log reports a rebuild that failed; check range partitions, CHECK constraints and materialized views on it, which a rebuild does not fix. A held cluster shows the hold only as an unchanged image; the result and the objects found are in the `postgres.cozystack.io/locale-data` and `postgres.cozystack.io/locale-data-objects` annotations of the cnpg.io Cluster, which an administrator can read. A restore of a backup taken on one of those bullseye images comes back on that image and is checked by the next upgrade. | `bool` | `false` | ### TLS configuration diff --git a/packages/apps/postgres/templates/collation-repair.yaml b/packages/apps/postgres/templates/collation-repair.yaml new file mode 100644 index 000000000..2729c93d0 --- /dev/null +++ b/packages/apps/postgres/templates/collation-repair.yaml @@ -0,0 +1,223 @@ +{{- /* + The collation repair (repair.sh in the init-script Secret) must not run as + a Helm hook: it waits for CNPG to move the primary to the new image and then + rebuilds indexes, and both take as long as the data and the clients make + them. Nor can it be an ordinary manifest: helm-controller waits for every + Job of a release to complete within the same upgrade timeout. So this hook + creates it through the API, outside the release, and returns. + + The repair Job has one fixed name, so no two of them run against the + Cluster at once. One still running on the image this release renders, + and not being deleted, is left to finish; any other is deleted, and its pod is gone, before the new + one is created, which also retries a repair that failed. It is owned by + the Cluster, so it goes with it. The hook's Role reaches only those two + objects by name, except for create, which RBAC cannot narrow to a name, + and is removed again once the hooks succeed. Skipped with the init-job + while bootstrap is on: the repair runs from its Secret, and the init-job + must have converged the release first. It runs on install too, where it + only records the Debian release each database starts on: a later image + move is told apart by that record, and the repair of that move may start + only after the primary has moved. +*/}} +{{- if not .Values.bootstrap.enabled }} +{{- /* One base for both names, short enough for the longer suffix: cut + separately, a long release name would give both the same name, and + the starter would take its own Job for a previous repair. */}} +{{- $base := .Release.Name }} +{{- if gt (len $base) 40 }} +{{- $base = printf "%s-%s" ($base | trunc 31 | trimSuffix "-") ($base | sha256sum | trunc 8) }} +{{- end }} +{{- $name := printf "%s-collation-repair" $base }} +{{- $starter := printf "%s-collation-repair-start" $base }} +{{- /* + The repair keeps what is left of an hour for rebuilding once the primary + runs the new image, and it bounds its lock waits by the same clock, so a + longer deadline is not free: an index rebuilt in place waits for its lock + in the queue that writes to its table join. +*/}} +{{- $deadline := 3600 }} +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: {{ $starter }} + annotations: + helm.sh/hook: post-install,post-upgrade + helm.sh/hook-weight: "0" + helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: {{ $starter }} + annotations: + helm.sh/hook: post-install,post-upgrade + helm.sh/hook-weight: "0" + helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded +rules: +- apiGroups: ["batch"] + resources: ["jobs"] + resourceNames: [{{ $name | quote }}] + verbs: ["get", "delete"] +- apiGroups: ["batch"] + resources: ["jobs"] + verbs: ["create"] +- apiGroups: ["postgresql.cnpg.io"] + resources: ["clusters"] + resourceNames: [{{ .Release.Name | quote }}] + verbs: ["get"] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: {{ $starter }} + annotations: + helm.sh/hook: post-install,post-upgrade + helm.sh/hook-weight: "0" + helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: {{ $starter }} +subjects: +- kind: ServiceAccount + name: {{ $starter }} + namespace: {{ .Release.Namespace | quote }} +--- +apiVersion: batch/v1 +kind: Job +metadata: + name: {{ $starter }} + annotations: + helm.sh/hook: post-install,post-upgrade + helm.sh/hook-weight: "1" + helm.sh/hook-delete-policy: before-hook-creation +spec: + activeDeadlineSeconds: 180 + backoffLimit: 0 + ttlSecondsAfterFinished: 3600 + template: + metadata: + labels: + policy.cozystack.io/allow-to-apiserver: "true" + spec: + serviceAccountName: {{ $starter }} + restartPolicy: Never + securityContext: + runAsGroup: 26 + runAsNonRoot: true + runAsUser: 26 + seccompProfile: + type: RuntimeDefault + containers: + - name: kubectl + image: {{ include "cozy-lib.image" (list "clastix/kubectl:v1.32@sha256:b9ef7d8dbe65bcc81a46c09b8dc7543103055021c4f43287bf59e92a8f4fe05c" $) }} + command: [sh, -ec] + args: + - | + name={{ $name | quote }} + image={{ include "postgres.imageName" $ | quote }} + + state=$(kubectl get job "$name" --ignore-not-found -o jsonpath='{.spec.template.spec.containers[0].image}|{.status.conditions[?(@.status=="True")].type}|{.metadata.deletionTimestamp}') + if [ "$state" = "$image||" ]; then + echo "the collation repair for $image is still running; leaving it to finish" + exit 0 + fi + if [ -n "$state" ]; then + echo "replacing the previous collation repair ($state)" + kubectl delete job "$name" --cascade=foreground --wait=false + echo "waiting for the pod of the previous collation repair to terminate; one on an unreachable node keeps it, and fails this upgrade, until the node is back or the pod is force-deleted" + until left=$(kubectl get job "$name" --ignore-not-found -o name) && [ -z "$left" ]; do + sleep 2 + done + fi + + uid=$(kubectl get clusters.postgresql.cnpg.io {{ .Release.Name | quote }} -o jsonpath='{.metadata.uid}') + kubectl create -f - <&2 + sleep "$delay" + delay=$((delay * 2 > 60 ? 60 : delay * 2)) + done init.sh: | #!/bin/bash set -e @@ -591,6 +613,16 @@ stringData: EOT {{- end }} {{- end }} + {{- if .Values.bootstrap.newServerName }} + + echo "== record the adopted restore" + psql -v ON_ERROR_STOP=1 --echo-all -v mark="$RESTORE_MARK" <<\EOT + ALTER DATABASE postgres SET cozystack.adopted_restore = :'mark'; + EOT + {{- end }} + repair.sh: | + #!/bin/bash + set -e {{- /* An operand image built on another Debian release ships another glibc and ICU, and an index ordered by a collation of either library is then @@ -609,22 +641,29 @@ stringData: not need it, and still misses a collation that an expression applies to a column of another one. - This pass comes after the ones that manage roles and databases, so - that a rebuild that fails, or does not finish before the Job deadline, - costs none of them. Only the PostGIS update and the record of an - adopted restore follow it: that record must not be written by a run - that failed. + This pass runs in a Job of its own, which a post-upgrade hook starts + once the init-job has managed roles and databases, and which Helm does + not wait for. The hook runs as soon as the Cluster is patched, while + CNPG is still rolling the instances, the primary last, and an instance + whose clients keep their sessions open waits out smartShutdownTimeout + before it restarts: the rollout alone can take longer than Helm gives a + hook, and the rebuild of a large index as long again, so inside the + hook either one failed the upgrade. Here a rebuild that fails costs + nothing else, and the next upgrade starts the Job again. The PostGIS + update, which waits for the same rollout, follows this pass in the + same Job. - Helm runs this hook as soon as the Cluster is patched, while CNPG is - still rolling the instances, so the primary may answer from the previous - image for minutes. The Job runs the image the Cluster is moving to, so + The primary may therefore answer from the previous image for minutes. + The Job runs the image the Cluster is moving to, so the server is on it once both report the same PostgreSQL version and the same Debian release. The rebuild counter that follows them is left out: a tag is rebuilt in place, so the Job and an instance can run - different rebuilds of one release for good. Waiting is only worth its - time when an index depends on a versioned collation. The wait ends 120 - seconds before the Job's deadline, which is what a first run keeps for - rebuilding. + different rebuilds of one release for good. The pass waits for that + whenever the image changes, even when no index depends on a collation + yet: a plan made on the previous image misses an index created in the + meantime, which the release recorded at the end would then claim as + repaired. The wait ends 120 seconds before the Job's deadline, which is + what a first run keeps for rebuilding. Rebuilds survive a retry: REINDEX CONCURRENTLY gives the index a new OID, so the highest OID seen when the repair began separates the @@ -667,9 +706,9 @@ stringData: failed there: the pass then leaves the table's stale indexes alone until an operator has dropped the leftovers. A rebuild that succeeds drops them itself. A failed or - skipped rebuild does not stop the others: the pass reports them and - exits non-zero at the end, with the recorded versions of that database - left as they are. + skipped rebuild does not stop the others, nor the PostGIS update: the + pass reports them, and the Job exits non-zero at its end, with the + recorded versions of that database left as they are. A collation that a range partition key depends on is never refreshed: rebuilding an index does not move a row to the partition the new @@ -787,24 +826,18 @@ stringData: COLLATION_DBS=$(psql -v ON_ERROR_STOP=1 -t -A -c "SELECT datname FROM pg_database WHERE datallowconn AND NOT datistemplate") if [ "$(server_release)" != "$JOB_RELEASE" ]; then IMAGE_MOVED=true - DEPENDENT="" for db in $COLLATION_DBS; do - DEPENDENT="$DEPENDENT$(collation_run "$db" <<\EOT - SELECT index FROM cozystack_collation_index; - EOT - )" + collation_run "$db" /dev/null done - if [ -n "$DEPENDENT" ]; then - echo "indexes depend on a versioned collation; waiting for the server to run PostgreSQL $JOB_RELEASE" + echo "waiting for the server to run PostgreSQL $JOB_RELEASE" until [ "$(server_release)" = "$JOB_RELEASE" ]; do if [ "$SECONDS" -ge $((JOB_DEADLINE - 120)) ]; then - echo "the server did not move to PostgreSQL $JOB_RELEASE in time (check the rollout of the cnpg.io/Cluster); indexes that depend on a versioned collation are not rebuilt yet - failing the init-job, the next run of it rebuilds them" >&2 + echo "the server did not move to PostgreSQL $JOB_RELEASE in time (check the rollout of the cnpg.io/Cluster); no index is rebuilt yet - failing the collation repair Job, the next upgrade of the release starts it again" >&2 exit 1 fi sleep 5 done fi - fi COLLATION_FAILED="" for db in $COLLATION_DBS; do PLAN=$(collation_run "$db" <<\EOT @@ -824,7 +857,7 @@ stringData: for index in $PLAN; do LEFT=$((JOB_DEADLINE - SECONDS - 60)) if [ "$LEFT" -lt 10 ]; then - echo "index $index in database $db was not rebuilt: the init-job is out of time, the next run of it carries on" >&2 + echo "index $index in database $db was not rebuilt: the collation repair Job is out of time, the next upgrade of the release starts it again" >&2 DB_FAILED=yes continue fi @@ -834,7 +867,7 @@ stringData: SET lock_timeout = :'lock_wait'; SELECT EXISTS (SELECT FROM pg_index i JOIN pg_stat_progress_create_index p ON p.relid = i.indrelid JOIN pg_database d ON d.oid = p.datid WHERE i.indexrelid = :'index'::oid AND d.datname = current_database() AND p.pid <> pg_backend_pid()) AS building \gset \if :building - SELECT format('DO %L', format('BEGIN RAISE EXCEPTION %L, %L; END', '%', format('index %s in database %s was skipped: another session is building an index of its table, as a rebuild left by an earlier run of the init-job does; the next run of the init-job carries on', :'index'::oid::regclass, current_database()))) \gexec + SELECT format('DO %L', format('BEGIN RAISE EXCEPTION %L, %L; END', '%', format('index %s in database %s was skipped: another session is building an index of its table, as a rebuild left by an earlier repair does; the next upgrade of the release starts the repair again', :'index'::oid::regclass, current_database()))) \gexec \endif SELECT count(*) = 1 AS present FROM pg_index WHERE indexrelid = :'index'::oid \gset \if :present @@ -844,11 +877,11 @@ stringData: (SELECT count(*) FROM unnest(string_to_array(split_part(:'recorded', ':', 3), ',')) AS e WHERE e = :'index' || '/' || r.relfilenode) >= 2 AS abandoned_in_place FROM pg_index i JOIN pg_class r ON r.oid = i.indexrelid WHERE i.indexrelid = :'index'::oid \gset \if :abandoned - SELECT format('DO %L', format('BEGIN RAISE EXCEPTION %L, %L; END', '%', format('index %s in database %s was left alone: two earlier runs failed to rebuild an index of its table, and each left an invalid _ccnew index there. Fix what made them fail, then drop those _ccnew indexes; the next run of the init-job rebuilds this one', :'name', current_database()))) \gexec + SELECT format('DO %L', format('BEGIN RAISE EXCEPTION %L, %L; END', '%', format('index %s in database %s was left alone: two earlier runs failed to rebuild an index of its table, and each left an invalid _ccnew index there. Fix what made them fail, then drop those _ccnew indexes; the repair started by the next upgrade of the release rebuilds this one', :'name', current_database()))) \gexec \endif \if :exclusion \if :abandoned_in_place - SELECT format('DO %L', format('BEGIN RAISE EXCEPTION %L, %L; END', '%', format('index %s in database %s was left alone: two earlier runs began rebuilding it in place and did not finish. Rebuild it by hand with REINDEX INDEX, which blocks its table meanwhile; the next run of the init-job sees that it was rebuilt', :'name', current_database()))) \gexec + SELECT format('DO %L', format('BEGIN RAISE EXCEPTION %L, %L; END', '%', format('index %s in database %s was left alone: two earlier runs began rebuilding it in place and did not finish. Rebuild it by hand with REINDEX INDEX, which blocks its table meanwhile; the repair started by the next upgrade of the release sees that it was rebuilt', :'name', current_database()))) \gexec \endif SELECT format('rebuilding index %s in database %s in place: its collation changed version', :'name', current_database()); SELECT format('ALTER DATABASE %I SET cozystack.collation_repair = %L', current_database(), split_part(:'recorded', ':', 1) || ':' || split_part(:'recorded', ':', 2) || ':' || concat_ws(',', nullif(split_part(:'recorded', ':', 3), ''), :'attempt')) WHERE :'recorded' <> '' \gexec @@ -863,6 +896,7 @@ stringData: \endif EOT then + [ "${PIPESTATUS[0]}" != 2 ] || COLLATION_LOST=yes DB_FAILED=yes fi done @@ -891,16 +925,19 @@ stringData: EOT fi done + if [ -n "$COLLATION_LOST" ]; then + echo "lost the connection to the server during index rebuilds in:$COLLATION_FAILED" >&2 + exit 2 + fi if [ -n "$COLLATION_FAILED" ]; then - echo "index rebuilds failed in:$COLLATION_FAILED (the errors are above); the other indexes were rebuilt. A unique index cannot be rebuilt over rows that the previous ordering kept apart and the new one treats as equal, so remove such duplicates. The next run of the init-job tries again, except for an index an error above reports as left alone" >&2 - exit 1 + echo "index rebuilds failed in:$COLLATION_FAILED (the errors are above); the other indexes were rebuilt. A unique index cannot be rebuilt over rows that the previous ordering kept apart and the new one treats as equal, so remove such duplicates. The next upgrade of the release starts the repair again, except for an index an error above reports as left alone" >&2 fi {{- if eq .Values.flavor "postgis" }} {{- /* A new PostGIS library leaves the SQL objects of every database on the release they were installed with until ALTER EXTENSION ... UPDATE runs there, and postgis_full_version() reports them as needing an upgrade - meanwhile. The extensions were created in this Job's superuser session, + meanwhile. The extensions were created in the init-job's superuser session, so only the superuser owns them and can update them; a tenant gets "must be owner of extension". This pass updates them in every database where they are installed, including ones values no longer list. @@ -911,9 +948,8 @@ stringData: instances the server offers the previous release and there is nothing to update yet, so the pass first waits for the server to offer the PostGIS release the Job's own image ships, until 120 seconds before - the Job's deadline. A rollout that takes longer fails the Job: this Job - is a hook, so a run that ended well would not come again before the - next change of the release, while a failed one makes the release retry. + the Job's deadline. A rollout that takes longer fails the Job, and the + next upgrade of the release starts it again. postgis_extensions_upgrade() is not used: it leaves out address_standardizer, and it updates every installed extension to ANY @@ -929,9 +965,8 @@ stringData: update, its lock waits included, runs no longer than what is left of the Job, with the same minute in reserve as the collation pass, and a database reached with no time left counts as failed. The pass carries - on with the other databases and then fails the Job, so that the - release is retried and reported as failed instead of the error staying - in the log of a Job that is deleted an hour later. + on with the other databases and then fails the Job, whose log names + them; the next upgrade of the release starts it again. The update scripts run as the superuser and write to tables a tenant's admin role may attach triggers to (spatial_ref_sys among them), and a @@ -951,9 +986,13 @@ stringData: ALL_DBS=$(psql -v ON_ERROR_STOP=1 -t -A -c "SELECT datname FROM pg_database WHERE datallowconn AND NOT datistemplate") POSTGIS_DBS="" POSTGIS_FAILED="" + POSTGIS_LOST="" for db in $ALL_DBS; do - if ! installed=$(psql -v ON_ERROR_STOP=1 -q -t -A --dbname "$db" -c "SET search_path = pg_catalog, pg_temp" -c "SELECT count(*) FROM pg_extension WHERE extname IN ('postgis', 'postgis_raster', 'postgis_topology', 'postgis_sfcgal', 'postgis_tiger_geocoder', 'address_standardizer', 'address_standardizer_data_us')"); then - echo "the PostGIS extensions in database $db were not checked (the error is above); the next run of the init-job carries on" >&2 + status=0 + installed=$(psql -v ON_ERROR_STOP=1 -q -t -A --dbname "$db" -c "SET search_path = pg_catalog, pg_temp" -c "SELECT count(*) FROM pg_extension WHERE extname IN ('postgis', 'postgis_raster', 'postgis_topology', 'postgis_sfcgal', 'postgis_tiger_geocoder', 'address_standardizer', 'address_standardizer_data_us')") || status=$? + if [ "$status" != 0 ]; then + [ "$status" != 2 ] || POSTGIS_LOST=yes + echo "the PostGIS extensions in database $db were not checked (the error is above); the next upgrade of the release starts the repair again" >&2 POSTGIS_FAILED="$POSTGIS_FAILED $db" continue fi @@ -965,7 +1004,7 @@ stringData: echo "waiting for the server to offer PostGIS $POSTGIS_SHIPPED" until [ "$(postgis_offered)" = "$POSTGIS_SHIPPED" ]; do if [ "$SECONDS" -ge $((JOB_DEADLINE - 120)) ]; then - echo "the server did not move to PostGIS $POSTGIS_SHIPPED in time (check the rollout of the cnpg.io/Cluster); the PostGIS extensions are not updated yet - failing the init-job, the next run of it updates them" >&2 + echo "the server did not move to PostGIS $POSTGIS_SHIPPED in time (check the rollout of the cnpg.io/Cluster); the PostGIS extensions are not updated yet - failing the collation repair Job, the next upgrade of the release starts it again" >&2 exit 1 fi sleep 5 @@ -974,7 +1013,7 @@ stringData: for db in $POSTGIS_DBS; do LEFT=$((JOB_DEADLINE - SECONDS - 60)) if [ "$LEFT" -lt 10 ]; then - echo "the PostGIS extensions in database $db were not updated: the init-job is out of time, the next run of it carries on" >&2 + echo "the PostGIS extensions in database $db were not updated: the collation repair Job is out of time, the next upgrade of the release starts it again" >&2 POSTGIS_FAILED="$POSTGIS_FAILED $db" continue fi @@ -985,7 +1024,7 @@ stringData: SET session_replication_role = replica; SELECT EXISTS (SELECT FROM pg_trigger t JOIN pg_depend d ON d.classid = 'pg_class'::regclass AND d.objid = t.tgrelid AND d.deptype = 'e' JOIN pg_extension x ON x.oid = d.refobjid WHERE NOT t.tgisinternal AND t.tgenabled IN ('A', 'R') AND x.extname IN ('postgis', 'postgis_raster', 'postgis_topology', 'postgis_sfcgal', 'postgis_tiger_geocoder', 'address_standardizer', 'address_standardizer_data_us')) AS armed \gset \if :armed - SELECT format('DO %L', format('BEGIN RAISE EXCEPTION %L, %L; END', '%', format('the PostGIS extensions in database %s were not updated: a table of theirs carries a trigger enabled ALWAYS or REPLICA, which would run inside the superuser update; drop that trigger, and the next run of the init-job updates them', current_database()))) \gexec + SELECT format('DO %L', format('BEGIN RAISE EXCEPTION %L, %L; END', '%', format('the PostGIS extensions in database %s were not updated: a table of theirs carries a trigger enabled ALWAYS or REPLICA, which would run inside the superuser update; drop that trigger, and the next upgrade of the release starts the repair again', current_database()))) \gexec \endif SELECT clock_timestamp() + :'lock_wait'::interval AS deadline_at \gset CREATE TEMP TABLE cozystack_postgis AS @@ -1002,21 +1041,20 @@ stringData: FROM cozystack_postgis WHERE reachable ORDER BY position \gexec EOT then + [ "${PIPESTATUS[0]}" != 2 ] || POSTGIS_LOST=yes POSTGIS_FAILED="$POSTGIS_FAILED $db" fi done + if [ -n "$POSTGIS_LOST" ]; then + echo "lost the connection to the server during the PostGIS update in:$POSTGIS_FAILED" >&2 + exit 2 + fi if [ -n "$POSTGIS_FAILED" ]; then - echo "PostGIS extension updates failed in:$POSTGIS_FAILED (the errors are above); the extensions there stay at their previous version. The next run of the init-job tries again" >&2 + echo "PostGIS extension updates failed in:$POSTGIS_FAILED (the errors are above); the extensions there stay at their previous version. The next upgrade of the release starts the repair again" >&2 exit 1 fi {{- end }} - {{- if .Values.bootstrap.newServerName }} - - echo "== record the adopted restore" - psql -v ON_ERROR_STOP=1 --echo-all -v mark="$RESTORE_MARK" <<\EOT - ALTER DATABASE postgres SET cozystack.adopted_restore = :'mark'; - EOT - {{- end }} + [ -z "$COLLATION_FAILED" ] || exit 1 {{- end }} {{- if hasKey (.Values.users | default dict) "app" }} --- diff --git a/packages/apps/postgres/tests/collation_repair_test.yaml b/packages/apps/postgres/tests/collation_repair_test.yaml new file mode 100644 index 000000000..cdc3b95e2 --- /dev/null +++ b/packages/apps/postgres/tests/collation_repair_test.yaml @@ -0,0 +1,167 @@ +suite: the collation repair is started by a hook and runs outside the release + +# The repair waits for CNPG to roll the new image out and then rebuilds +# indexes; inside the init-job hook that wait alone outlasted the upgrade +# timeout. A post-install/post-upgrade hook now only starts a Job of its own +# through the API, so the hook must never render while bootstrap is on, must +# run after the init-job, and reach nothing but the repair Job and the Cluster. + +templates: + - templates/collation-repair.yaml + - templates/init-job.yaml + - templates/init-script.yaml + +release: + name: pg-test + namespace: tenant-test + +set: + _cluster: + scheduling: {} + users: + app: {} + +tests: + - it: renders the starter and its RBAC on install, to record the release the data starts on + template: templates/collation-repair.yaml + asserts: + - hasDocuments: + count: 4 + + - it: renders nothing while bootstrap is on, like the init-job it follows + template: templates/collation-repair.yaml + release: + upgrade: true + set: + bootstrap: + enabled: true + oldName: pg-old + asserts: + - hasDocuments: + count: 0 + + - it: renders the starter and its RBAC on upgrade + template: templates/collation-repair.yaml + release: + upgrade: true + asserts: + - hasDocuments: + count: 4 + + - it: runs the starter after the init-job, as a post-install and post-upgrade hook + template: templates/collation-repair.yaml + release: + upgrade: true + documentSelector: + path: kind + value: Job + asserts: + - equal: + path: metadata.annotations["helm.sh/hook"] + value: post-install,post-upgrade + - equal: + path: metadata.annotations["helm.sh/hook-weight"] + value: "1" + - equal: + path: spec.backoffLimit + value: 0 + - equal: + path: spec.activeDeadlineSeconds + value: 180 + - equal: + path: spec.template.spec.serviceAccountName + value: pg-test-collation-repair-start + - equal: + path: spec.template.metadata.labels["policy.cozystack.io/allow-to-apiserver"] + value: "true" + + - it: the init-job runs before the starter + template: templates/init-job.yaml + asserts: + - equal: + path: metadata.annotations["helm.sh/hook-weight"] + value: "-5" + + - it: limits the Role to the repair Job and the release's own Cluster + template: templates/collation-repair.yaml + release: + upgrade: true + documentSelector: + path: kind + value: Role + asserts: + - equal: + path: rules + value: + - apiGroups: ["batch"] + resources: ["jobs"] + resourceNames: ["pg-test-collation-repair"] + verbs: ["get", "delete"] + - apiGroups: ["batch"] + resources: ["jobs"] + verbs: ["create"] + - apiGroups: ["postgresql.cnpg.io"] + resources: ["clusters"] + resourceNames: ["pg-test"] + verbs: ["get"] + + - it: removes the RBAC once the hooks succeed + template: templates/collation-repair.yaml + release: + upgrade: true + documentSelector: + path: kind + value: RoleBinding + asserts: + - equal: + path: metadata.annotations["helm.sh/hook-delete-policy"] + value: before-hook-creation,hook-succeeded + - equal: + path: subjects[0].name + value: pg-test-collation-repair-start + + - it: keeps the starter and the repair Job apart for a long release name + template: templates/collation-repair.yaml + release: + name: postgres-a-name-at-the-53-character-release-name-limi + upgrade: true + documentSelector: + path: kind + value: Job + asserts: + - matchRegex: + path: metadata.name + pattern: ^.{1,40}-collation-repair-start$ + + - it: names the repair Job within 63 characters for a long release name + template: templates/collation-repair.yaml + release: + name: postgres-a-name-at-the-53-character-release-name-limi + upgrade: true + documentSelector: + path: kind + value: Role + asserts: + - matchRegex: + path: rules[0].resourceNames[0] + pattern: ^.{1,46}-collation-repair$ + + - it: the init-job runs its script through the reconnecting wrapper + template: templates/init-job.yaml + asserts: + - equal: + path: spec.template.spec.containers[0].command + value: [bash, /scripts/run.sh, /scripts/init.sh] + + - it: the init-script Secret carries the repair apart from the init script + template: templates/init-script.yaml + documentSelector: + path: metadata.name + value: pg-test-init-script + asserts: + - exists: + path: stringData["run.sh"] + - exists: + path: stringData["init.sh"] + - exists: + path: stringData["repair.sh"] diff --git a/packages/apps/postgres/values.schema.json b/packages/apps/postgres/values.schema.json index e426cacce..e9a4f7667 100644 --- a/packages/apps/postgres/values.schema.json +++ b/packages/apps/postgres/values.schema.json @@ -150,7 +150,7 @@ ] }, "allowCollationChange": { - "description": "Allow a cluster created on a Debian bullseye image (before the move to standard-trixie) to move to the new image without a clean locale check. Such a cluster is checked before each upgrade, except while `bootstrap.enabled` is set (set it back to false once a restore set up by hand has finished), and stays on its current image until the check finds nothing that depends on a collation other than C, POSIX or builtin: while this is false, a cluster the check found affected (an ICU or libc locale, or C.UTF-8) or could not finish on stays put, because glibc and ICU on the new image sort text differently and every index on such text must be rebuilt. A held cluster runs the bare bullseye tag it has, gets no further PostgreSQL minors and so none of their security fixes, and refuses a change of `version`, since new majors are built only on the new images. To leave that state, either remove the dependency (move such columns and indexes to C, or to the builtin `pg_c_utf8` on PostgreSQL 17 and later) and let the next upgrade check again, or set this to true in a maintenance window: the cluster moves on the next upgrade, replicas restart on the new image first and can return wrong results through `-ro`, and unique indexes can accept duplicates, until the indexes are rebuilt on the primary. The init Job rebuilds the indexes on such text, those on C.UTF-8 and other C.* locales included; check range partitions, CHECK constraints and materialized views on it, which a rebuild does not fix. A held cluster shows the hold only as an unchanged image; the result and the objects found are in the `postgres.cozystack.io/locale-data` and `postgres.cozystack.io/locale-data-objects` annotations of the cnpg.io Cluster, which an administrator can read. A restore of a backup taken on one of those bullseye images comes back on that image and is checked by the next upgrade.", + "description": "Allow a cluster created on a Debian bullseye image (before the move to standard-trixie) to move to the new image without a clean locale check. Such a cluster is checked before each upgrade, except while `bootstrap.enabled` is set (set it back to false once a restore set up by hand has finished), and stays on its current image until the check finds nothing that depends on a collation other than C, POSIX or builtin: while this is false, a cluster the check found affected (an ICU or libc locale, or C.UTF-8) or could not finish on stays put, because glibc and ICU on the new image sort text differently and every index on such text must be rebuilt. A held cluster runs the bare bullseye tag it has, gets no further PostgreSQL minors and so none of their security fixes, and refuses a change of `version`, since new majors are built only on the new images. To leave that state, either remove the dependency (move such columns and indexes to C, or to the builtin `pg_c_utf8` on PostgreSQL 17 and later) and let the next upgrade check again, or set this to true in a maintenance window: the cluster moves on the next upgrade, replicas restart on the new image first and can return wrong results through `-ro`, and unique indexes can accept duplicates, until the indexes are rebuilt on the primary. The collation repair Job, which a post-upgrade hook starts once the init Job is done, rebuilds the indexes on such text after the rollout, those on C.UTF-8 and other C.* locales included, and its log reports a rebuild that failed; check range partitions, CHECK constraints and materialized views on it, which a rebuild does not fix. A held cluster shows the hold only as an unchanged image; the result and the objects found are in the `postgres.cozystack.io/locale-data` and `postgres.cozystack.io/locale-data-objects` annotations of the cnpg.io Cluster, which an administrator can read. A restore of a backup taken on one of those bullseye images comes back on that image and is checked by the next upgrade.", "type": "boolean", "default": false }, diff --git a/packages/apps/postgres/values.yaml b/packages/apps/postgres/values.yaml index a9974ed3d..b8f87a4ec 100644 --- a/packages/apps/postgres/values.yaml +++ b/packages/apps/postgres/values.yaml @@ -95,7 +95,7 @@ version: v18 ## @param {Flavor} flavor - PostgreSQL image flavor, fixed when the cluster is created. `postgresql` uses the CloudNativePG PostgreSQL image. `postgis` uses the CloudNativePG PostGIS image, which adds postgis, postgis_raster, postgis_topology, postgis_sfcgal, postgis_tiger_geocoder and address_standardizer; enable them per database in `databases..extensions`. Changing the flavor of an existing cluster is refused, and a backup restores only into a cluster of the flavor it was taken from: to change flavor, create a new cluster and move the data with a logical dump (pg_dump / pg_restore). flavor: postgresql -## @param {bool} allowCollationChange - Allow a cluster created on a Debian bullseye image (before the move to standard-trixie) to move to the new image without a clean locale check. Such a cluster is checked before each upgrade, except while `bootstrap.enabled` is set (set it back to false once a restore set up by hand has finished), and stays on its current image until the check finds nothing that depends on a collation other than C, POSIX or builtin: while this is false, a cluster the check found affected (an ICU or libc locale, or C.UTF-8) or could not finish on stays put, because glibc and ICU on the new image sort text differently and every index on such text must be rebuilt. A held cluster runs the bare bullseye tag it has, gets no further PostgreSQL minors and so none of their security fixes, and refuses a change of `version`, since new majors are built only on the new images. To leave that state, either remove the dependency (move such columns and indexes to C, or to the builtin `pg_c_utf8` on PostgreSQL 17 and later) and let the next upgrade check again, or set this to true in a maintenance window: the cluster moves on the next upgrade, replicas restart on the new image first and can return wrong results through `-ro`, and unique indexes can accept duplicates, until the indexes are rebuilt on the primary. The init Job rebuilds the indexes on such text, those on C.UTF-8 and other C.* locales included; check range partitions, CHECK constraints and materialized views on it, which a rebuild does not fix. A held cluster shows the hold only as an unchanged image; the result and the objects found are in the `postgres.cozystack.io/locale-data` and `postgres.cozystack.io/locale-data-objects` annotations of the cnpg.io Cluster, which an administrator can read. A restore of a backup taken on one of those bullseye images comes back on that image and is checked by the next upgrade. +## @param {bool} allowCollationChange - Allow a cluster created on a Debian bullseye image (before the move to standard-trixie) to move to the new image without a clean locale check. Such a cluster is checked before each upgrade, except while `bootstrap.enabled` is set (set it back to false once a restore set up by hand has finished), and stays on its current image until the check finds nothing that depends on a collation other than C, POSIX or builtin: while this is false, a cluster the check found affected (an ICU or libc locale, or C.UTF-8) or could not finish on stays put, because glibc and ICU on the new image sort text differently and every index on such text must be rebuilt. A held cluster runs the bare bullseye tag it has, gets no further PostgreSQL minors and so none of their security fixes, and refuses a change of `version`, since new majors are built only on the new images. To leave that state, either remove the dependency (move such columns and indexes to C, or to the builtin `pg_c_utf8` on PostgreSQL 17 and later) and let the next upgrade check again, or set this to true in a maintenance window: the cluster moves on the next upgrade, replicas restart on the new image first and can return wrong results through `-ro`, and unique indexes can accept duplicates, until the indexes are rebuilt on the primary. The collation repair Job, which a post-upgrade hook starts once the init Job is done, rebuilds the indexes on such text after the rollout, those on C.UTF-8 and other C.* locales included, and its log reports a rebuild that failed; check range partitions, CHECK constraints and materialized views on it, which a rebuild does not fix. A held cluster shows the hold only as an unchanged image; the result and the objects found are in the `postgres.cozystack.io/locale-data` and `postgres.cozystack.io/locale-data-objects` annotations of the cnpg.io Cluster, which an administrator can read. A restore of a backup taken on one of those bullseye images comes back on that image and is checked by the next upgrade. allowCollationChange: false ## diff --git a/packages/system/postgres-rd/cozyrds/postgres.yaml b/packages/system/postgres-rd/cozyrds/postgres.yaml index 7cc6000aa..3e66192ec 100644 --- a/packages/system/postgres-rd/cozyrds/postgres.yaml +++ b/packages/system/postgres-rd/cozyrds/postgres.yaml @@ -30,7 +30,7 @@ spec: singular: postgres plural: postgreses openAPISchema: |- - {"title":"Chart Values","type":"object","properties":{"replicas":{"description":"Number of Postgres replicas. Under active autoscaling this is the resting/seed count, not the live count — KEDA drives the live count via `/scale`. Disabling autoscaling does NOT automatically bring the live count back to `replicas`: the client-side merge writes `instances` only when the rendered value changes, so a cluster KEDA grew past `replicas` stays there with no autoscaler left to reduce it — lower `replicas` to the count you want and it rebases down (shedding the surplus replicas + PVCs). Lowering it below the live count, or disabling/dry-running while it sits below the live count, sheds in one step past the scaleDown pacing; stage it to the live count first (suspend the HelmRelease and `kubectl scale` if needed) to avoid a transient. Must stay greater than `quorum.maxSyncReplicas`.","type":"integer","default":2},"resources":{"description":"Explicit CPU and memory configuration for each PostgreSQL replica. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","default":{},"properties":{"cpu":{"description":"CPU available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Memory (RAM) available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted.","type":"string","default":"t1.micro","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]},"size":{"description":"Persistent Volume Claim size available for application data.","default":"10Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"storageClass":{"description":"StorageClass used to store the data.","type":"string","default":"","x-kubernetes-validations":[{"rule":"self == oldSelf","message":"storageClass is immutable"}],"x-cozystack-options":{"source":"storageclass"}},"external":{"description":"Enable external access from outside the cluster.","type":"boolean","default":false},"version":{"description":"PostgreSQL major version to deploy","type":"string","default":"v18","enum":["v18","v17","v16","v15","v14","v13"]},"flavor":{"description":"PostgreSQL image flavor, fixed when the cluster is created. `postgresql` uses the CloudNativePG PostgreSQL image. `postgis` uses the CloudNativePG PostGIS image, which adds postgis, postgis_raster, postgis_topology, postgis_sfcgal, postgis_tiger_geocoder and address_standardizer; enable them per database in `databases..extensions`. Changing the flavor of an existing cluster is refused, and a backup restores only into a cluster of the flavor it was taken from: to change flavor, create a new cluster and move the data with a logical dump (pg_dump / pg_restore).","type":"string","default":"postgresql","enum":["postgresql","postgis"]},"allowCollationChange":{"description":"Allow a cluster created on a Debian bullseye image (before the move to standard-trixie) to move to the new image without a clean locale check. Such a cluster is checked before each upgrade, except while `bootstrap.enabled` is set (set it back to false once a restore set up by hand has finished), and stays on its current image until the check finds nothing that depends on a collation other than C, POSIX or builtin: while this is false, a cluster the check found affected (an ICU or libc locale, or C.UTF-8) or could not finish on stays put, because glibc and ICU on the new image sort text differently and every index on such text must be rebuilt. A held cluster runs the bare bullseye tag it has, gets no further PostgreSQL minors and so none of their security fixes, and refuses a change of `version`, since new majors are built only on the new images. To leave that state, either remove the dependency (move such columns and indexes to C, or to the builtin `pg_c_utf8` on PostgreSQL 17 and later) and let the next upgrade check again, or set this to true in a maintenance window: the cluster moves on the next upgrade, replicas restart on the new image first and can return wrong results through `-ro`, and unique indexes can accept duplicates, until the indexes are rebuilt on the primary. The init Job rebuilds the indexes on such text, those on C.UTF-8 and other C.* locales included; check range partitions, CHECK constraints and materialized views on it, which a rebuild does not fix. A held cluster shows the hold only as an unchanged image; the result and the objects found are in the `postgres.cozystack.io/locale-data` and `postgres.cozystack.io/locale-data-objects` annotations of the cnpg.io Cluster, which an administrator can read. A restore of a backup taken on one of those bullseye images comes back on that image and is checked by the next upgrade.","type":"boolean","default":false},"tls":{"description":"TLS configuration for server connections.","type":"object","default":{},"properties":{"enabled":{"description":"Tri-state switch controlling whether the chart injects the external hostnames into the operator-managed CNPG cert via spec.certificates.serverAltDNSNames. When omitted, the chart injects them if `external: true` and skips them otherwise. Set explicitly to `true` to inject regardless of `external` (no-op when `external: false` since there is no external hostname to add). Set to `false` to skip injection. Note that CNPG keeps its built-in TLS on the wire regardless of this flag — this toggle only controls the chart-side SAN injection; to disable PostgreSQL TLS entirely set `postgresql.parameters.ssl = \"off\"` at the CNPG layer.","type":"boolean"},"required":{"description":"Tri-state switch controlling whether the server refuses sessions that are not encrypted. When omitted, it is on if `external: true` and off otherwise. When on, the chart renders `spec.postgresql.pg_hba` with `hostssl all all all scram-sha-256` (`md5` on PostgreSQL 13, matching CloudNativePG's default rule) followed by `host all all all reject`, so a client that connects with `sslmode=disable` is refused instead of getting a plaintext session; in-cluster clients are held to the same rule, since the pod network cannot be told apart from an external client. Set to `false` to keep accepting plaintext sessions on an external instance, or to `true` to require TLS on an in-cluster one. Rendering fails if `postgresql.parameters.ssl` is off while this is in effect.","type":"boolean"}}},"postgresql":{"description":"PostgreSQL server configuration.","type":"object","default":{},"properties":{"parameters":{"description":"PostgreSQL server parameters. Values may be strings or integers; integers are coerced to strings by the template (e.g. both `max_connections: 100` and `max_connections: \"100\"` are accepted). BLOCKED (enable arbitrary code execution): archive_command, restore_command, ssl_passphrase_command, archive_cleanup_command, recovery_end_command, dynamic_library_path, local_preload_libraries, session_preload_libraries, shared_preload_libraries. Do NOT override CloudNativePG-managed parameters: archive_mode, primary_conninfo, wal_level, max_replication_slots.","type":"object","default":{"max_connections":"100"},"additionalProperties":{"anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}},"sharedPreloadLibraries":{"description":"Libraries loaded at server start, restricted to an allowlist of modules already shipped in the PostgreSQL image. CloudNativePG also preloads `pg_stat_statements`, `auto_explain` and `pgaudit` by itself whenever `parameters` sets a key under their prefix (e.g. `pg_stat_statements.track`), so removing one of them from this list does not unload it while such a key is set; `pg_prewarm` is preloaded only through this list. Changing the list restarts PostgreSQL on every instance, the primary included, so writes pause briefly.","type":"array","items":{"type":"string","enum":["pg_stat_statements","auto_explain","pgaudit","pg_prewarm"]}}}},"quorum":{"description":"Quorum configuration for synchronous replication.","type":"object","default":{},"required":["maxSyncReplicas","minSyncReplicas"],"properties":{"maxSyncReplicas":{"description":"Maximum number of synchronous replicas allowed (must be less than total replicas). Under autoscaling it also sets the scale-down floor (the effective minimum is `max(minReplicas, maxSyncReplicas+1, 2)`); the chart fails to render if that floor exceeds `autoscaling.maxReplicas`.","type":"integer","default":0},"minSyncReplicas":{"description":"Minimum number of synchronous replicas required for commit.","type":"integer","default":0}}},"autoscaling":{"description":"Read-replica autoscaling configuration.","type":"object","default":{},"required":["dryRun","enabled","maxReplicas","maxReplicationLagSeconds","metric","minReplicas","serverAddress","target","transition"],"properties":{"dryRun":{"description":"Recommendation mode: keep the static count and render the ScaledObject with both scaling directions paused, so KEDA keeps the HPA and keeps serving its trigger metric but actuates neither way. Note both scaling policies are disabled, so the HPA's desiredReplicas is frozen to the current count - read the recommendation from the matching read-load dashboard panel for your metric (connections or CPU): desired = 1 + ceil(read load / target), clamped to [effectiveMin..maxReplicas] where effectiveMin = max(minReplicas, maxSyncReplicas+1, 2), not from the desired-replicas line. Like disabling, flipping a LIVE autoscaled cluster into dryRun re-renders `instances: replicas` (the raw static value, which can be below the autoscaling floor); if `replicas` is below the live count, stage it to the live count first (see the enablement note) or the cluster sheds down to `replicas`. No shed occurs when the rendered value is unchanged (replicas already equals the active seed) — client-side merge is then a no-op and the live count is preserved. Permanent, unlike `transition`.","type":"boolean","default":false},"enabled":{"description":"Enable horizontal autoscaling of read replicas. Requires the platform `keda` package to be enabled by an administrator first; the chart fails to render (rather than break the release) if KEDA is not installed. Prerequisite: the queried vmselect must hold BOTH the CNPG metrics (cnpg_backends_total / container CPU) AND kube_pod_labels (kube-state-metrics). This holds for a tenant on the shared root monitoring stack (`monitoring: false`, both land in tenant-root). A tenant running its OWN Monitoring app (`monitoring: true`) has the CNPG metrics but not kube_pod_labels (KSM is root-only), so it must set `serverAddress` to a vmselect carrying both series or autoscaling never actuates.","type":"boolean","default":false},"maxReplicas":{"description":"Maximum total instances. Must be >= minReplicas and >= the synchronous-quorum floor (maxSyncReplicas+1); the chart fails to render (rather than silently run an unbounded instance count) if the effective floor exceeds it - raise maxReplicas. HAZARD: lowering maxReplicas below the live count makes the HPA cut straight to the new maximum in one step (the current>max branch bypasses the scale-down pacing), shedding the surplus replicas + PVCs at once; to lower it deliberately, suspend the HelmRelease and pin the live count with `kubectl scale` first.","type":"integer","default":6},"maxReplicationLagSeconds":{"description":"Freeze scaling while replication lag exceeds this (seconds) and the primary is writing. 0 disables the brake. Default 0: the freeze branch has only been validated on a live cluster in its non-braking (pass-through) form, so the lag brake is opt-in until the braking path is exercised under load; set a positive value (e.g. 30) to enable it.","type":"integer","default":0},"metric":{"description":"Read-load signal to scale on.","type":"string","default":"ReadConnections","enum":["ReadConnections","ReadCPUUtilization"]},"minReplicas":{"description":"Minimum total instances; raised to the synchronous-quorum floor (`maxSyncReplicas + 1`) and to 2 when either is higher.","type":"integer","default":2},"serverAddress":{"description":"Override the Prometheus/vmselect URL the ScaledObject queries. Empty (default) derives `http://vmselect-shortterm..svc:8481/select/0/prometheus`. Set it when the derived vmselect does not hold both the CNPG metrics and kube_pod_labels (e.g. `monitoring: true` tenants, or a non-default `metricsStorages` name). SSRF constraint: the host must be an in-cluster Service DNS name (`..svc[.]`) whose namespace is within the tenant's own subtree (its namespace, its parents, or `tenant-root`) — the cluster-privileged KEDA operator fetches this URL every poll, so it is refused a metadata endpoint, an external host, or a sibling/system namespace. Residual surface (accepted trade-off): `tenant-root` is always allowed because the derived default points there, so a tenant can still aim the operator at any Service in `tenant-root` on any port/path (a blind in-cluster reachability probe — the operator reads no response body back to the tenant); the egress NetworkPolicy does not narrow that.","type":"string","default":""},"target":{"description":"Target read load per read-serving replica (unit depends on `metric`: active connections, or CPU millicores). Dimensionless integer - a resource.Quantity here would accept `150m`, which PromQL reads as 150 minutes and KEDA cannot use as a threshold.","type":"integer","default":150},"transition":{"description":"Migration phase 1: render `.spec.instances` from `replicas` (which the operator stages to the current live count) AND pause the ScaledObject in both directions, so KEDA stands up with its HPA present but not actuating. Flip to false (phase 2) to hand the runtime count to KEDA. Because the both-direction pause keeps the HPA (not the HPA-deleting full pause), KEDA is genuinely warm at phase 2 — no HPA recreate — and because the active seed is max(replicas, effectiveMin), phase 2 re-renders the same instance count phase 1 did (when `replicas` is staged at/above the floor), so the flip is a merge no-op with no dip. The HPA's scaleUp stabilization window still smooths the first actuation.","type":"boolean","default":false}}},"users":{"description":"Users configuration map. Passwords are always auto-generated and stored in the `-credentials` Secret; they cannot be set from values — read a user's password from that Secret. A `password` left over in values from before the field was removed is ignored by the render and draws an admission warning, but it is not inert on an upgraded release: the chart preserves whatever password is already in the Secret, which on the first upgrade is the value that was set before removal, so that value stays the live credential until it is rotated (dedicated rotation is tracked in cozystack/community#72). The live password lives only in the Secret.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"bypassRls":{"description":"Whether the user can bypass row-level security policies (BYPASSRLS). A role can only create other roles carrying BYPASSRLS if it holds the attribute itself, so this is required alongside `createRole` to provision a privileged service role.","type":"boolean"},"createRole":{"description":"Whether the user can create and manage roles (CREATEROLE). Requires PostgreSQL 16 or newer. Setting it back to `false` withdraws the attribute only: the roles the user created, and its ADMIN and SET memberships in them, stay. Once any user has held it, the chart no longer adopts an existing role it did not create, so a user or database declared later under the name of such a role fails the init job until a platform administrator drops that role.","type":"boolean"},"replication":{"description":"Whether the user has replication privileges.","type":"boolean"}}}},"databases":{"description":"Databases configuration map. The PostgreSQL system databases `postgres`, `template0` and `template1` are refused.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"extensions":{"description":"List of enabled PostgreSQL extensions.","type":"array","items":{"type":"string"}},"roles":{"description":"Roles assigned to users.","type":"object","properties":{"admin":{"description":"List of users with admin privileges.","type":"array","items":{"type":"string"}},"readonly":{"description":"List of users with read-only privileges.","type":"array","items":{"type":"string"}}}}}}},"backup":{"description":"Backup configuration.","type":"object","default":{},"required":["enabled"],"properties":{"destinationPath":{"description":"DEPRECATED. Per-tenant S3 configuration is superseded by the platform-managed `cozy-default` BackupClass and the `cozy-backups` system bucket. Leave empty for new installations; the BackupClass driver picks up the system-managed coordinates. Kept for in-place upgrade compatibility.","type":"string","default":"s3://bucket/path/to/folder/"},"enabled":{"description":"Enable regular backups.","type":"boolean","default":false},"endpointCA":{"description":"DEPRECATED. Pre-existing Secret with the CA bundle the barman-cloud plugin should trust when reaching a self-signed S3 endpoint. Used for both backup and bootstrap recovery in the legacy chart-managed flow.","type":"object","default":{},"properties":{"key":{"description":"Key within the Secret containing the CA bundle. Defaults to `ca.crt`.","type":"string","default":""},"name":{"description":"Name of the Secret in the application namespace. Empty means no endpointCA is emitted (the plugin uses the system trust store).","type":"string","default":""}}},"endpointURL":{"description":"DEPRECATED. See `destinationPath`.","type":"string","default":"http://minio-gateway-service:9000"},"retentionPolicy":{"description":"Retention policy (e.g. \"30d\").","type":"string","default":"30d"},"s3AccessKey":{"description":"DEPRECATED. Tenants no longer supply S3 keys; the system Bucket Secret is projected into the tenant namespace by the backup controller. Ignored when `s3CredentialsSecret.name` is set or `useSystemBucket` is true. The chart skips materialising `-s3-creds` whenever this field is empty so a default install does not leak placeholder credentials into the tenant namespace.","type":"string","default":""},"s3CredentialsSecret":{"description":"DEPRECATED. Pre-existing Secret with S3 credentials. Use the platform-managed `cozy-default` BackupClass instead. When set, the chart references this Secret directly (legacy chart-managed flow). The CNPG backup driver writes this field on restore so credentials never land in the CR `.spec`.","type":"object","default":{},"properties":{"accessKeyIDKey":{"description":"Key in the Secret holding the access key ID. Defaults to `AWS_ACCESS_KEY_ID`.","type":"string","default":""},"name":{"description":"Name of the Secret in the application namespace. Empty means the chart materialises `-s3-creds` from `s3AccessKey`/`s3SecretKey`.","type":"string","default":""},"secretAccessKeyKey":{"description":"Key in the Secret holding the secret access key. Defaults to `AWS_SECRET_ACCESS_KEY`.","type":"string","default":""}}},"s3SecretKey":{"description":"DEPRECATED. See `s3AccessKey`.","type":"string","default":""},"schedule":{"description":"Legacy. Cron schedule for the chart-emitted ScheduledBackup, either a standard five-field cron such as `0 2 * * *` for every day at 02:00, or six fields with leading seconds such as `0 0 2 * * *` for the same time. Empty means no chart-managed schedule, which is the recommended setup when a `BackupClass` from `backups.cozystack.io` already drives backup orchestration. In the legacy chart-managed flow `spec.plugins` plus the barman-cloud ObjectStore is rendered when `backup.enabled=true` AND `useSystemBucket=false` AND `destinationPath` is non-empty AND inline-or-external creds are supplied; in the platform `useSystemBucket=true` flow the chart skips emitting `spec.plugins` and the CNPG driver SSA-applies the ObjectStore and patches `spec.plugins` onto the live Cluster at first BackupJob time.","type":"string","default":""},"useSystemBucket":{"description":"Opt-in: when true, the chart-emitted `-s3-creds` Secret is skipped AND `spec.plugins` (plus the barman-cloud ObjectStore) is left UNSET in the chart-rendered Cluster — the cozy-default BackupClass driver SSA-applies an ObjectStore (carrying destinationPath/endpointURL/credentials) and patches `spec.plugins` on the live Cluster when the first BackupJob runs. Consequence: plugin WAL archiving is NOT active until that first BackupJob fires; WAL accumulates on the PVC in the meantime, so fire an ad-hoc BackupJob immediately after enabling the flag on existing releases. Use together with the platform `cozy-default` BackupClass — tenants do not need to fill `s3AccessKey`/`s3SecretKey` or `destinationPath`/`endpointURL`. The destination path automatically scopes to `s3://cozy-backups///`.","type":"boolean","default":false}}},"bootstrap":{"description":"Bootstrap configuration.","type":"object","default":{},"required":["enabled","oldName"],"properties":{"backupID":{"description":"Barman ID of the base backup to recover from, passed as `recoveryTarget.backupID`. Empty lets the barman-cloud plugin pick one: the newest backup when `recoveryTime` is empty, otherwise the newest one ending at or before it, on any timeline. The CNPG backup driver sets this on restore.","type":"string","default":""},"enabled":{"description":"Whether to restore from a backup.","type":"boolean","default":false},"newServerName":{"description":"WAL-archive server name (S3 path prefix) the RESTORED cluster writes to. Must differ from `serverName` (the recovery source) so a restored cluster archives to a fresh, empty prefix and barman-cloud-check-wal-archive passes while it recovers from the source's prefix. The CNPG backup driver sets this on restore; empty means the cluster archives under its own name.","type":"string","default":""},"oldName":{"description":"Previous cluster name before deletion.","type":"string","default":""},"recoveryTime":{"description":"Timestamp (RFC3339) for point-in-time recovery; empty means latest.","type":"string","default":""},"serverName":{"description":"Server name (S3 path prefix) used by the original cluster when writing backups; passed to the barman-cloud plugin via `externalClusters[].plugin.parameters.serverName`. Defaults to `bootstrap.oldName`. Set this only when the original cluster wrote backups under an explicit server name that differed from its Kubernetes resource name.","type":"string","default":""},"sourceImageName":{"description":"Image of the cluster the backup was taken from. A restore of a backup taken on one of the bare Debian bullseye tags the chart used before standard-trixie comes back on that image (see `allowCollationChange`); any other value is ignored. The CNPG backup driver sets this on restore and clears it with `enabled`.","type":"string","default":""}}}}} + {"title":"Chart Values","type":"object","properties":{"replicas":{"description":"Number of Postgres replicas. Under active autoscaling this is the resting/seed count, not the live count — KEDA drives the live count via `/scale`. Disabling autoscaling does NOT automatically bring the live count back to `replicas`: the client-side merge writes `instances` only when the rendered value changes, so a cluster KEDA grew past `replicas` stays there with no autoscaler left to reduce it — lower `replicas` to the count you want and it rebases down (shedding the surplus replicas + PVCs). Lowering it below the live count, or disabling/dry-running while it sits below the live count, sheds in one step past the scaleDown pacing; stage it to the live count first (suspend the HelmRelease and `kubectl scale` if needed) to avoid a transient. Must stay greater than `quorum.maxSyncReplicas`.","type":"integer","default":2},"resources":{"description":"Explicit CPU and memory configuration for each PostgreSQL replica. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","default":{},"properties":{"cpu":{"description":"CPU available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Memory (RAM) available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted.","type":"string","default":"t1.micro","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]},"size":{"description":"Persistent Volume Claim size available for application data.","default":"10Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"storageClass":{"description":"StorageClass used to store the data.","type":"string","default":"","x-kubernetes-validations":[{"rule":"self == oldSelf","message":"storageClass is immutable"}],"x-cozystack-options":{"source":"storageclass"}},"external":{"description":"Enable external access from outside the cluster.","type":"boolean","default":false},"version":{"description":"PostgreSQL major version to deploy","type":"string","default":"v18","enum":["v18","v17","v16","v15","v14","v13"]},"flavor":{"description":"PostgreSQL image flavor, fixed when the cluster is created. `postgresql` uses the CloudNativePG PostgreSQL image. `postgis` uses the CloudNativePG PostGIS image, which adds postgis, postgis_raster, postgis_topology, postgis_sfcgal, postgis_tiger_geocoder and address_standardizer; enable them per database in `databases..extensions`. Changing the flavor of an existing cluster is refused, and a backup restores only into a cluster of the flavor it was taken from: to change flavor, create a new cluster and move the data with a logical dump (pg_dump / pg_restore).","type":"string","default":"postgresql","enum":["postgresql","postgis"]},"allowCollationChange":{"description":"Allow a cluster created on a Debian bullseye image (before the move to standard-trixie) to move to the new image without a clean locale check. Such a cluster is checked before each upgrade, except while `bootstrap.enabled` is set (set it back to false once a restore set up by hand has finished), and stays on its current image until the check finds nothing that depends on a collation other than C, POSIX or builtin: while this is false, a cluster the check found affected (an ICU or libc locale, or C.UTF-8) or could not finish on stays put, because glibc and ICU on the new image sort text differently and every index on such text must be rebuilt. A held cluster runs the bare bullseye tag it has, gets no further PostgreSQL minors and so none of their security fixes, and refuses a change of `version`, since new majors are built only on the new images. To leave that state, either remove the dependency (move such columns and indexes to C, or to the builtin `pg_c_utf8` on PostgreSQL 17 and later) and let the next upgrade check again, or set this to true in a maintenance window: the cluster moves on the next upgrade, replicas restart on the new image first and can return wrong results through `-ro`, and unique indexes can accept duplicates, until the indexes are rebuilt on the primary. The collation repair Job, which a post-upgrade hook starts once the init Job is done, rebuilds the indexes on such text after the rollout, those on C.UTF-8 and other C.* locales included, and its log reports a rebuild that failed; check range partitions, CHECK constraints and materialized views on it, which a rebuild does not fix. A held cluster shows the hold only as an unchanged image; the result and the objects found are in the `postgres.cozystack.io/locale-data` and `postgres.cozystack.io/locale-data-objects` annotations of the cnpg.io Cluster, which an administrator can read. A restore of a backup taken on one of those bullseye images comes back on that image and is checked by the next upgrade.","type":"boolean","default":false},"tls":{"description":"TLS configuration for server connections.","type":"object","default":{},"properties":{"enabled":{"description":"Tri-state switch controlling whether the chart injects the external hostnames into the operator-managed CNPG cert via spec.certificates.serverAltDNSNames. When omitted, the chart injects them if `external: true` and skips them otherwise. Set explicitly to `true` to inject regardless of `external` (no-op when `external: false` since there is no external hostname to add). Set to `false` to skip injection. Note that CNPG keeps its built-in TLS on the wire regardless of this flag — this toggle only controls the chart-side SAN injection; to disable PostgreSQL TLS entirely set `postgresql.parameters.ssl = \"off\"` at the CNPG layer.","type":"boolean"},"required":{"description":"Tri-state switch controlling whether the server refuses sessions that are not encrypted. When omitted, it is on if `external: true` and off otherwise. When on, the chart renders `spec.postgresql.pg_hba` with `hostssl all all all scram-sha-256` (`md5` on PostgreSQL 13, matching CloudNativePG's default rule) followed by `host all all all reject`, so a client that connects with `sslmode=disable` is refused instead of getting a plaintext session; in-cluster clients are held to the same rule, since the pod network cannot be told apart from an external client. Set to `false` to keep accepting plaintext sessions on an external instance, or to `true` to require TLS on an in-cluster one. Rendering fails if `postgresql.parameters.ssl` is off while this is in effect.","type":"boolean"}}},"postgresql":{"description":"PostgreSQL server configuration.","type":"object","default":{},"properties":{"parameters":{"description":"PostgreSQL server parameters. Values may be strings or integers; integers are coerced to strings by the template (e.g. both `max_connections: 100` and `max_connections: \"100\"` are accepted). BLOCKED (enable arbitrary code execution): archive_command, restore_command, ssl_passphrase_command, archive_cleanup_command, recovery_end_command, dynamic_library_path, local_preload_libraries, session_preload_libraries, shared_preload_libraries. Do NOT override CloudNativePG-managed parameters: archive_mode, primary_conninfo, wal_level, max_replication_slots.","type":"object","default":{"max_connections":"100"},"additionalProperties":{"anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}},"sharedPreloadLibraries":{"description":"Libraries loaded at server start, restricted to an allowlist of modules already shipped in the PostgreSQL image. CloudNativePG also preloads `pg_stat_statements`, `auto_explain` and `pgaudit` by itself whenever `parameters` sets a key under their prefix (e.g. `pg_stat_statements.track`), so removing one of them from this list does not unload it while such a key is set; `pg_prewarm` is preloaded only through this list. Changing the list restarts PostgreSQL on every instance, the primary included, so writes pause briefly.","type":"array","items":{"type":"string","enum":["pg_stat_statements","auto_explain","pgaudit","pg_prewarm"]}}}},"quorum":{"description":"Quorum configuration for synchronous replication.","type":"object","default":{},"required":["maxSyncReplicas","minSyncReplicas"],"properties":{"maxSyncReplicas":{"description":"Maximum number of synchronous replicas allowed (must be less than total replicas). Under autoscaling it also sets the scale-down floor (the effective minimum is `max(minReplicas, maxSyncReplicas+1, 2)`); the chart fails to render if that floor exceeds `autoscaling.maxReplicas`.","type":"integer","default":0},"minSyncReplicas":{"description":"Minimum number of synchronous replicas required for commit.","type":"integer","default":0}}},"autoscaling":{"description":"Read-replica autoscaling configuration.","type":"object","default":{},"required":["dryRun","enabled","maxReplicas","maxReplicationLagSeconds","metric","minReplicas","serverAddress","target","transition"],"properties":{"dryRun":{"description":"Recommendation mode: keep the static count and render the ScaledObject with both scaling directions paused, so KEDA keeps the HPA and keeps serving its trigger metric but actuates neither way. Note both scaling policies are disabled, so the HPA's desiredReplicas is frozen to the current count - read the recommendation from the matching read-load dashboard panel for your metric (connections or CPU): desired = 1 + ceil(read load / target), clamped to [effectiveMin..maxReplicas] where effectiveMin = max(minReplicas, maxSyncReplicas+1, 2), not from the desired-replicas line. Like disabling, flipping a LIVE autoscaled cluster into dryRun re-renders `instances: replicas` (the raw static value, which can be below the autoscaling floor); if `replicas` is below the live count, stage it to the live count first (see the enablement note) or the cluster sheds down to `replicas`. No shed occurs when the rendered value is unchanged (replicas already equals the active seed) — client-side merge is then a no-op and the live count is preserved. Permanent, unlike `transition`.","type":"boolean","default":false},"enabled":{"description":"Enable horizontal autoscaling of read replicas. Requires the platform `keda` package to be enabled by an administrator first; the chart fails to render (rather than break the release) if KEDA is not installed. Prerequisite: the queried vmselect must hold BOTH the CNPG metrics (cnpg_backends_total / container CPU) AND kube_pod_labels (kube-state-metrics). This holds for a tenant on the shared root monitoring stack (`monitoring: false`, both land in tenant-root). A tenant running its OWN Monitoring app (`monitoring: true`) has the CNPG metrics but not kube_pod_labels (KSM is root-only), so it must set `serverAddress` to a vmselect carrying both series or autoscaling never actuates.","type":"boolean","default":false},"maxReplicas":{"description":"Maximum total instances. Must be >= minReplicas and >= the synchronous-quorum floor (maxSyncReplicas+1); the chart fails to render (rather than silently run an unbounded instance count) if the effective floor exceeds it - raise maxReplicas. HAZARD: lowering maxReplicas below the live count makes the HPA cut straight to the new maximum in one step (the current>max branch bypasses the scale-down pacing), shedding the surplus replicas + PVCs at once; to lower it deliberately, suspend the HelmRelease and pin the live count with `kubectl scale` first.","type":"integer","default":6},"maxReplicationLagSeconds":{"description":"Freeze scaling while replication lag exceeds this (seconds) and the primary is writing. 0 disables the brake. Default 0: the freeze branch has only been validated on a live cluster in its non-braking (pass-through) form, so the lag brake is opt-in until the braking path is exercised under load; set a positive value (e.g. 30) to enable it.","type":"integer","default":0},"metric":{"description":"Read-load signal to scale on.","type":"string","default":"ReadConnections","enum":["ReadConnections","ReadCPUUtilization"]},"minReplicas":{"description":"Minimum total instances; raised to the synchronous-quorum floor (`maxSyncReplicas + 1`) and to 2 when either is higher.","type":"integer","default":2},"serverAddress":{"description":"Override the Prometheus/vmselect URL the ScaledObject queries. Empty (default) derives `http://vmselect-shortterm..svc:8481/select/0/prometheus`. Set it when the derived vmselect does not hold both the CNPG metrics and kube_pod_labels (e.g. `monitoring: true` tenants, or a non-default `metricsStorages` name). SSRF constraint: the host must be an in-cluster Service DNS name (`..svc[.]`) whose namespace is within the tenant's own subtree (its namespace, its parents, or `tenant-root`) — the cluster-privileged KEDA operator fetches this URL every poll, so it is refused a metadata endpoint, an external host, or a sibling/system namespace. Residual surface (accepted trade-off): `tenant-root` is always allowed because the derived default points there, so a tenant can still aim the operator at any Service in `tenant-root` on any port/path (a blind in-cluster reachability probe — the operator reads no response body back to the tenant); the egress NetworkPolicy does not narrow that.","type":"string","default":""},"target":{"description":"Target read load per read-serving replica (unit depends on `metric`: active connections, or CPU millicores). Dimensionless integer - a resource.Quantity here would accept `150m`, which PromQL reads as 150 minutes and KEDA cannot use as a threshold.","type":"integer","default":150},"transition":{"description":"Migration phase 1: render `.spec.instances` from `replicas` (which the operator stages to the current live count) AND pause the ScaledObject in both directions, so KEDA stands up with its HPA present but not actuating. Flip to false (phase 2) to hand the runtime count to KEDA. Because the both-direction pause keeps the HPA (not the HPA-deleting full pause), KEDA is genuinely warm at phase 2 — no HPA recreate — and because the active seed is max(replicas, effectiveMin), phase 2 re-renders the same instance count phase 1 did (when `replicas` is staged at/above the floor), so the flip is a merge no-op with no dip. The HPA's scaleUp stabilization window still smooths the first actuation.","type":"boolean","default":false}}},"users":{"description":"Users configuration map. Passwords are always auto-generated and stored in the `-credentials` Secret; they cannot be set from values — read a user's password from that Secret. A `password` left over in values from before the field was removed is ignored by the render and draws an admission warning, but it is not inert on an upgraded release: the chart preserves whatever password is already in the Secret, which on the first upgrade is the value that was set before removal, so that value stays the live credential until it is rotated (dedicated rotation is tracked in cozystack/community#72). The live password lives only in the Secret.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"bypassRls":{"description":"Whether the user can bypass row-level security policies (BYPASSRLS). A role can only create other roles carrying BYPASSRLS if it holds the attribute itself, so this is required alongside `createRole` to provision a privileged service role.","type":"boolean"},"createRole":{"description":"Whether the user can create and manage roles (CREATEROLE). Requires PostgreSQL 16 or newer. Setting it back to `false` withdraws the attribute only: the roles the user created, and its ADMIN and SET memberships in them, stay. Once any user has held it, the chart no longer adopts an existing role it did not create, so a user or database declared later under the name of such a role fails the init job until a platform administrator drops that role.","type":"boolean"},"replication":{"description":"Whether the user has replication privileges.","type":"boolean"}}}},"databases":{"description":"Databases configuration map. The PostgreSQL system databases `postgres`, `template0` and `template1` are refused.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"extensions":{"description":"List of enabled PostgreSQL extensions.","type":"array","items":{"type":"string"}},"roles":{"description":"Roles assigned to users.","type":"object","properties":{"admin":{"description":"List of users with admin privileges.","type":"array","items":{"type":"string"}},"readonly":{"description":"List of users with read-only privileges.","type":"array","items":{"type":"string"}}}}}}},"backup":{"description":"Backup configuration.","type":"object","default":{},"required":["enabled"],"properties":{"destinationPath":{"description":"DEPRECATED. Per-tenant S3 configuration is superseded by the platform-managed `cozy-default` BackupClass and the `cozy-backups` system bucket. Leave empty for new installations; the BackupClass driver picks up the system-managed coordinates. Kept for in-place upgrade compatibility.","type":"string","default":"s3://bucket/path/to/folder/"},"enabled":{"description":"Enable regular backups.","type":"boolean","default":false},"endpointCA":{"description":"DEPRECATED. Pre-existing Secret with the CA bundle the barman-cloud plugin should trust when reaching a self-signed S3 endpoint. Used for both backup and bootstrap recovery in the legacy chart-managed flow.","type":"object","default":{},"properties":{"key":{"description":"Key within the Secret containing the CA bundle. Defaults to `ca.crt`.","type":"string","default":""},"name":{"description":"Name of the Secret in the application namespace. Empty means no endpointCA is emitted (the plugin uses the system trust store).","type":"string","default":""}}},"endpointURL":{"description":"DEPRECATED. See `destinationPath`.","type":"string","default":"http://minio-gateway-service:9000"},"retentionPolicy":{"description":"Retention policy (e.g. \"30d\").","type":"string","default":"30d"},"s3AccessKey":{"description":"DEPRECATED. Tenants no longer supply S3 keys; the system Bucket Secret is projected into the tenant namespace by the backup controller. Ignored when `s3CredentialsSecret.name` is set or `useSystemBucket` is true. The chart skips materialising `-s3-creds` whenever this field is empty so a default install does not leak placeholder credentials into the tenant namespace.","type":"string","default":""},"s3CredentialsSecret":{"description":"DEPRECATED. Pre-existing Secret with S3 credentials. Use the platform-managed `cozy-default` BackupClass instead. When set, the chart references this Secret directly (legacy chart-managed flow). The CNPG backup driver writes this field on restore so credentials never land in the CR `.spec`.","type":"object","default":{},"properties":{"accessKeyIDKey":{"description":"Key in the Secret holding the access key ID. Defaults to `AWS_ACCESS_KEY_ID`.","type":"string","default":""},"name":{"description":"Name of the Secret in the application namespace. Empty means the chart materialises `-s3-creds` from `s3AccessKey`/`s3SecretKey`.","type":"string","default":""},"secretAccessKeyKey":{"description":"Key in the Secret holding the secret access key. Defaults to `AWS_SECRET_ACCESS_KEY`.","type":"string","default":""}}},"s3SecretKey":{"description":"DEPRECATED. See `s3AccessKey`.","type":"string","default":""},"schedule":{"description":"Legacy. Cron schedule for the chart-emitted ScheduledBackup, either a standard five-field cron such as `0 2 * * *` for every day at 02:00, or six fields with leading seconds such as `0 0 2 * * *` for the same time. Empty means no chart-managed schedule, which is the recommended setup when a `BackupClass` from `backups.cozystack.io` already drives backup orchestration. In the legacy chart-managed flow `spec.plugins` plus the barman-cloud ObjectStore is rendered when `backup.enabled=true` AND `useSystemBucket=false` AND `destinationPath` is non-empty AND inline-or-external creds are supplied; in the platform `useSystemBucket=true` flow the chart skips emitting `spec.plugins` and the CNPG driver SSA-applies the ObjectStore and patches `spec.plugins` onto the live Cluster at first BackupJob time.","type":"string","default":""},"useSystemBucket":{"description":"Opt-in: when true, the chart-emitted `-s3-creds` Secret is skipped AND `spec.plugins` (plus the barman-cloud ObjectStore) is left UNSET in the chart-rendered Cluster — the cozy-default BackupClass driver SSA-applies an ObjectStore (carrying destinationPath/endpointURL/credentials) and patches `spec.plugins` on the live Cluster when the first BackupJob runs. Consequence: plugin WAL archiving is NOT active until that first BackupJob fires; WAL accumulates on the PVC in the meantime, so fire an ad-hoc BackupJob immediately after enabling the flag on existing releases. Use together with the platform `cozy-default` BackupClass — tenants do not need to fill `s3AccessKey`/`s3SecretKey` or `destinationPath`/`endpointURL`. The destination path automatically scopes to `s3://cozy-backups///`.","type":"boolean","default":false}}},"bootstrap":{"description":"Bootstrap configuration.","type":"object","default":{},"required":["enabled","oldName"],"properties":{"backupID":{"description":"Barman ID of the base backup to recover from, passed as `recoveryTarget.backupID`. Empty lets the barman-cloud plugin pick one: the newest backup when `recoveryTime` is empty, otherwise the newest one ending at or before it, on any timeline. The CNPG backup driver sets this on restore.","type":"string","default":""},"enabled":{"description":"Whether to restore from a backup.","type":"boolean","default":false},"newServerName":{"description":"WAL-archive server name (S3 path prefix) the RESTORED cluster writes to. Must differ from `serverName` (the recovery source) so a restored cluster archives to a fresh, empty prefix and barman-cloud-check-wal-archive passes while it recovers from the source's prefix. The CNPG backup driver sets this on restore; empty means the cluster archives under its own name.","type":"string","default":""},"oldName":{"description":"Previous cluster name before deletion.","type":"string","default":""},"recoveryTime":{"description":"Timestamp (RFC3339) for point-in-time recovery; empty means latest.","type":"string","default":""},"serverName":{"description":"Server name (S3 path prefix) used by the original cluster when writing backups; passed to the barman-cloud plugin via `externalClusters[].plugin.parameters.serverName`. Defaults to `bootstrap.oldName`. Set this only when the original cluster wrote backups under an explicit server name that differed from its Kubernetes resource name.","type":"string","default":""},"sourceImageName":{"description":"Image of the cluster the backup was taken from. A restore of a backup taken on one of the bare Debian bullseye tags the chart used before standard-trixie comes back on that image (see `allowCollationChange`); any other value is ignored. The CNPG backup driver sets this on restore and clears it with `enabled`.","type":"string","default":""}}}}} release: prefix: postgres- labels: