From 34a50b6bfa789657d429d208373ca675d28a980f Mon Sep 17 00:00:00 2001 From: Andrey Kolkov Date: Thu, 26 Nov 2026 13:13:56 +0700 Subject: [PATCH 1/7] fix(postgres): rebuild indexes whose collation changed version An operand image built on another Debian release ships another glibc and ICU. An index ordered by a collation of either library is then ordered by rules the server no longer applies: lookups through it miss rows, and a unique index stops seeing duplicates. PostgreSQL only logs a warning. The init Job compares the library version each collation was created with against the one the server reports, rebuilds the indexes that depend on a collation whose version changed, and refreshes the recorded versions once every rebuild in the database succeeded. A database on the C or POSIX collation with no explicitly collated index, which is what the chart creates by default, has nothing to rebuild and is not delayed. The pass has to hold on a hook that starts while the instances are still rolling, runs as the superuser in databases tenants own, and is retried after a failure: - It runs after the passes that manage roles and databases, so that a rebuild that fails costs none of them, and it waits for the server to report the PostgreSQL version and Debian release of its own image when an index depends on a versioned collation. The rebuild counter of the package is left out of that comparison, because a tag is rebuilt in place. - Every session pins search_path to pg_catalog, so that a function or an operator a tenant defined in public cannot stand in for a built-in. - A retry continues where the last run stopped. REINDEX CONCURRENTLY gives an index a new OID, so the highest OID seen when a repair begins marks what is left; an index rebuilt in place keeps its OID and is told apart by its storage file. Both live in a setting of the database. - A rebuild that cannot finish is not started for ever: after two attempts the index is left to an operator, the pass says how to clear it, and the release stays failed until then. Lock waits and in-place rebuilds are bounded by what is left of the Job. - A collation that a range partition key depends on keeps its recorded version, because rebuilding an index moves no row between partitions. PostgreSQL records a collation for an index only where it orders a key, so the collations of the columns an index reads in its expressions and predicate count as well. Before PostgreSQL 15 the server records no version for a database's default collation, and the libc collation of the same locale stands in for it. The e2e suite creates a collation with a stale version and checks that an upgrade rebuilds a unique index and an exclusion constraint's index on it, refreshes the version and removes the repair setting. On release-1.6 the init Job had no deadline. It gets activeDeadlineSeconds, backoffLimit 0 and a JOB_DEADLINE env that the pass bounds its waits by, and the e2e lib gains HELMRELEASE_HISTORY_JSONPATH, which the new step reads and main defines there. (cherry picked from commit a10e449a564b5288e4dbd604f792e96a0403be07) Assisted-By: LLM Signed-off-by: Andrey Kolkov --- hack/e2e-chainsaw/_lib/remediation-guard.sh | 7 + hack/e2e-chainsaw/postgres/chainsaw-test.yaml | 117 +++++++++ .../apps/postgres/templates/init-job.yaml | 19 ++ .../apps/postgres/templates/init-script.yaml | 248 ++++++++++++++++++ 4 files changed, 391 insertions(+) diff --git a/hack/e2e-chainsaw/_lib/remediation-guard.sh b/hack/e2e-chainsaw/_lib/remediation-guard.sh index 7ad66371e..6fec4a5d2 100644 --- a/hack/e2e-chainsaw/_lib/remediation-guard.sh +++ b/hack/e2e-chainsaw/_lib/remediation-guard.sh @@ -22,6 +22,13 @@ # "uninstalled", 1 otherwise. Empty input is treated as "no history yet, # no cycle observed". +# The jsonpath a caller hands to kubectl to read those statuses, one per +# line. Defined here so the postgres e2e step reads it as it does on main. +# On this branch nothing checks it against the Flux HelmRelease type: a +# renamed field makes it return nothing and the guard report no cycle. +# shellcheck disable=SC2034 # used by callers that source this file +HELMRELEASE_HISTORY_JSONPATH='{range .status.history[*]}{.status}{"\n"}{end}' + helmrelease_has_remediation_cycle() { statuses="$1" if [ -z "${statuses}" ]; then diff --git a/hack/e2e-chainsaw/postgres/chainsaw-test.yaml b/hack/e2e-chainsaw/postgres/chainsaw-test.yaml index 2ab873ad6..5ff6e4384 100644 --- a/hack/e2e-chainsaw/postgres/chainsaw-test.yaml +++ b/hack/e2e-chainsaw/postgres/chainsaw-test.yaml @@ -126,6 +126,123 @@ spec: 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. + + # 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 --- # Full barman-cloud backup -> to-copy RestoreJob round-trip, driving the # validated example scripts (examples/backups/postgres) as the harness so the diff --git a/packages/apps/postgres/templates/init-job.yaml b/packages/apps/postgres/templates/init-job.yaml index d3f027d5f..7d99c36c9 100644 --- a/packages/apps/postgres/templates/init-job.yaml +++ b/packages/apps/postgres/templates/init-job.yaml @@ -20,6 +20,23 @@ metadata: "helm.sh/hook-weight": "-5" "helm.sh/hook-delete-policy": before-hook-creation spec: + {{- /* + This Job is a post-install,post-upgrade Helm hook Helm blocks on. Bound it under + the 10m hook budget so its own DeadlineExceeded surfaces first, instead of Helm's + generic 10m timeout that says nothing about why. The script reads the value back + as JOB_DEADLINE and bounds its collation-rebuild waits by what is left of it. + On UPGRADE the Cluster is already up and the readiness loop answers in seconds, + so 540s leaves the grant and rebuild passes ~9m. On INSTALL the same release is + still provisioning the Cluster (PVC, image pull, initdb) and Helm's wait does not + cover a CR, so the cold start gets 570s. Do not retry the pod either way: the + collation pass bounds lock_timeout and the in-place statement_timeout by + JOB_DEADLINE minus $SECONDS, and $SECONDS counts from the pod's start while + activeDeadlineSeconds counts from the Job's. A retried pod would hand the server + a bound longer than the Job has left, so a rebuild or lock wait would outlive it. + */}} + {{- $deadline := ternary 570 540 .Release.IsInstall }} + activeDeadlineSeconds: {{ $deadline }} + backoffLimit: 0 ttlSecondsAfterFinished: 3600 template: metadata: @@ -51,6 +68,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 89a1ea3b2..ff685d557 100644 --- a/packages/apps/postgres/templates/init-script.yaml +++ b/packages/apps/postgres/templates/init-script.yaml @@ -229,6 +229,254 @@ 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. + + 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 {{- end }} {{- if hasKey (.Values.users | default dict) "app" }} --- From eaecde82ad3d1518e6b0fefef7d16c02bf4a1053 Mon Sep 17 00:00:00 2001 From: Andrey Kolkov Date: Thu, 26 Nov 2026 16:17:35 +0700 Subject: [PATCH 2/7] fix(postgres): move tenant PostgreSQL to patched standard-trixie images The chart pinned bare image tags, which are the system variant on Debian bullseye. Upstream stopped building that variant, so the minors that fix CVE-2026-116331 (18.7, 17.12, 16.16, 15.20, 14.25) are published for bookworm and trixie only. The CVE is a type confusion in the min/max aggregate optimisation that lets a role able to create objects run code as the operating system user of the server, and tenants hold such roles. Pin the patched minors on standard-trixie. The standard variant, because backups go through the barman-cloud plugin and need none of the barman binaries the system variant adds. trixie, because main is on it and release-1.7 moves to it with the backport batch that carries this change, so a 1.6 cluster that upgrades to such a 1.7 release does not move its Debian release a second time. PostgreSQL 13 has no patched release: it keeps 13.22 and moves to trixie with the rest. For a running cluster this changes the Debian release under the data directory. The init Job rebuilds the indexes that depend on a collation whose library version changed. release-1.6 has no postgis flavor, so its version map, its unit test and the flavor guard are not carried over, and postgres.imageName has only the postgresql branch. (cherry picked from commit b40be51a6b3dc521d28ed06f7603a32f01a88955) Assisted-By: LLM Signed-off-by: Andrey Kolkov --- packages/apps/postgres/files/versions.yaml | 10 +++++----- packages/apps/postgres/hack/update-versions.sh | 5 +++-- packages/apps/postgres/templates/_versions.tpl | 13 +++++++++++++ packages/apps/postgres/templates/db.yaml | 10 ++++------ packages/apps/postgres/templates/init-job.yaml | 2 +- 5 files changed, 26 insertions(+), 14 deletions(-) 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 c92b3895b..8567402a8 100755 --- a/packages/apps/postgres/hack/update-versions.sh +++ b/packages/apps/postgres/hack/update-versions.sh @@ -32,9 +32,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 ca0ff2a27..e81086303 100644 --- a/packages/apps/postgres/templates/_versions.tpl +++ b/packages/apps/postgres/templates/_versions.tpl @@ -6,3 +6,16 @@ {{- index $versionMap .Values.version }} {{- end }} +{{/* + Single source for the operand image: the init Job runs psql against the + 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. +*/}} +{{- define "postgres.imageName" -}} +ghcr.io/cloudnative-pg/postgresql:{{ include "postgres.versionMap" . | trim | trimPrefix "v" }}-standard-trixie +{{- end -}} diff --git a/packages/apps/postgres/templates/db.yaml b/packages/apps/postgres/templates/db.yaml index 9cfb93def..a6a05b59a 100644 --- a/packages/apps/postgres/templates/db.yaml +++ b/packages/apps/postgres/templates/db.yaml @@ -107,11 +107,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) "") }} @@ -213,7 +211,7 @@ spec: resources: {{- include "cozy-lib.resources.defaultingSanitize" (list .Values.resourcesPreset .Values.resources $) | nindent 4 }} - imageName: ghcr.io/cloudnative-pg/postgresql:{{ include "postgres.versionMap" $ | trimPrefix "v" }} + imageName: {{ include "postgres.imageName" $ }} enableSuperuserAccess: true {{- if .Values._cluster.scheduling }} {{- $rawConstraints := get .Values._cluster.scheduling "globalAppTopologySpreadConstraints" }} diff --git a/packages/apps/postgres/templates/init-job.yaml b/packages/apps/postgres/templates/init-job.yaml index 7d99c36c9..af8c89af4 100644 --- a/packages/apps/postgres/templates/init-job.yaml +++ b/packages/apps/postgres/templates/init-job.yaml @@ -47,7 +47,7 @@ spec: restartPolicy: Never containers: - name: postgres - image: ghcr.io/cloudnative-pg/postgresql:{{ include "postgres.versionMap" $ | trimPrefix "v" }} + image: {{ include "postgres.imageName" $ }} command: - bash - /scripts/init.sh From 4ea048e466ddce192642743a8bb5ed501b917655 Mon Sep 17 00:00:00 2001 From: Aleksei Sviridkin Date: Fri, 27 Nov 2026 18:21:49 +0300 Subject: [PATCH 3/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 ff685d557..61b3a84b9 100644 --- a/packages/apps/postgres/templates/init-script.yaml +++ b/packages/apps/postgres/templates/init-script.yaml @@ -285,6 +285,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 @@ -419,6 +430,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 df12079583ac8e80f979b05ed1cae8038291efd4 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) ## What this PR does 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 #5459 by keeping such clusters off the new image. The other items are 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. ### Why 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. ### What it does 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. ### What a held cluster is left with - 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. ### How a held cluster leaves that state 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. ### Testing - `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). ### Screenshots ### Downstream repositories 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 ```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. ``` ## Summary by CodeRabbit - **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.6 the CNPG backup driver predates the backup destination, artifact-size, flavor and major-version changes this builds on on main, so only the image handling is ported: the live Cluster's spec.imageName goes into the backup snapshot and the restore passes it to the chart as bootstrap.sourceImageName. The 1.6 driver never patches bootstrap.enabled back to false after a restore and has no check of the backup's major against spec.version, so there is nowhere to clear the value or to read the major from the image; the next restore sets or clears it, and the chart uses it only while no live Cluster exists. The cnpgtypes Cluster spec gains the read-only imageName field, which main added with the flavor record, and the unmarshal helper returns the snapshot struct, as on main, so the restore can read the image. The tests for the destination and artifact size, and those for the bootstrap clearing and the major, are not part of this line. release-1.6 has no postgis flavor, so the flavor conditions in the hold rules, the flavor guard, the postgis branch of the target image, the flavor value and the postgis test case are not carried over. (cherry picked from commit 9cf93b85353ba4bc2ff01d4d31635d7ebf88c83d) Assisted-By: LLM Signed-off-by: Andrey Kolkov --- api/apps/v1alpha1/postgresql/types.go | 6 + .../cnpg_source_image_test.go | 62 +++ .../cnpgstrategy_controller.go | 53 +- .../cnpgstrategy_controller_test.go | 73 ++- internal/backupcontroller/cnpgtypes/types.go | 3 + .../backupcontroller/postgresapp/types.go | 11 +- packages/apps/postgres/README.md | 40 +- .../apps/postgres/templates/_versions.tpl | 90 ++++ .../postgres/templates/locale-check-hook.yaml | 263 +++++++++ .../postgres/tests/locale_guard_test.yaml | 503 ++++++++++++++++++ packages/apps/postgres/values.schema.json | 10 + packages/apps/postgres/values.yaml | 6 + .../system/postgres-rd/cozyrds/postgres.yaml | 4 +- 13 files changed, 1056 insertions(+), 68 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 51698e558..d53f3daf4 100644 --- a/api/apps/v1alpha1/postgresql/types.go +++ b/api/apps/v1alpha1/postgresql/types.go @@ -40,6 +40,9 @@ type ConfigSpec struct { // PostgreSQL major version to deploy // +kubebuilder:default:="v18" Version Version `json:"version"` + // 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 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"` @@ -112,6 +115,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 every restore, and clears it when the backup carries no image. + // +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..10abcef43 --- /dev/null +++ b/internal/backupcontroller/cnpg_source_image_test.go @@ -0,0 +1,62 @@ +package backupcontroller + +import ( + "context" + "testing" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + 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" +) + +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") + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if got != image { + t.Fatalf("imageName = %q, want %q", got, image) + } + }) + } +} + +func TestCNPGBackupSnapshot_CarriesImageName(t *testing.T) { + raw, err := marshalCNPGBackupSnapshot(newPostgresApp("pg", "tenant"), nil, "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) + } +} diff --git a/internal/backupcontroller/cnpgstrategy_controller.go b/internal/backupcontroller/cnpgstrategy_controller.go index 499336730..ad3662d79 100644 --- a/internal/backupcontroller/cnpgstrategy_controller.go +++ b/internal/backupcontroller/cnpgstrategy_controller.go @@ -213,7 +213,7 @@ func (r *BackupJobReconciler) reconcileCNPG(ctx context.Context, j *backupsv1alp serverName = clusterName } - effectiveServerName, err := r.applyClusterPluginBackup(ctx, j.Namespace, clusterName, rendered, serverName) + effectiveServerName, imageName, err := r.applyClusterPluginBackup(ctx, j.Namespace, clusterName, rendered, serverName) if err != nil { if apierrors.IsNotFound(err) { // HelmRelease has not yet rendered the Cluster (fresh app, or @@ -260,7 +260,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, rendered, app) + artifact, err := r.createCNPGBackupArtifact(ctx, j, resolved, cnpgBackup, clusterName, serverName, imageName, rendered, app) if err != nil { return r.markBackupJobFailed(ctx, j, fmt.Sprintf("failed to create Backup artifact: %v", err)) } @@ -418,16 +418,19 @@ var cnpgClusterGVR = schema.GroupVersionResource{ // mid-stream splits the archive across two prefixes — WALs around the flip // land under the old prefix while the base backup indexes under the new one, // and the eventual restore fails with "WAL not found". -func (r *BackupJobReconciler) applyClusterPluginBackup(ctx context.Context, namespace, clusterName string, t *strategyv1alpha1.CNPGTemplate, serverName string) (string, error) { +// +// It also returns the live Cluster's spec.imageName, see +// cnpgBackupSnapshot.ImageName. +func (r *BackupJobReconciler) applyClusterPluginBackup(ctx context.Context, namespace, clusterName string, t *strategyv1alpha1.CNPGTemplate, serverName string) (string, string, error) { // Live read: the cached Cluster can predate a restore re-render, and both // the serverName and the UID below must come from the current object. existing := &cnpgtypes.Cluster{} live, err := r.Resource(cnpgClusterGVR).Namespace(namespace).Get(ctx, clusterName, metav1.GetOptions{}) if err != nil { - return "", err + return "", "", err } if err := runtime.DefaultUnstructuredConverter.FromUnstructured(live.Object, existing); err != nil { - return "", fmt.Errorf("decode Cluster %s/%s: %w", namespace, clusterName, err) + return "", "", fmt.Errorf("decode Cluster %s/%s: %w", namespace, clusterName, err) } if live := currentBarmanServerName(existing); live != "" { serverName = live @@ -459,15 +462,15 @@ func (r *BackupJobReconciler) applyClusterPluginBackup(ctx context.Context, name InstanceSidecarConfiguration: barmanSidecarConfiguration(), } if err := r.Patch(ctx, objStore, client.Apply, client.FieldOwner(cnpgFieldManager), client.ForceOwnership); err != nil { - return "", fmt.Errorf("apply ObjectStore %s/%s: %w", namespace, objStoreName, err) + return "", "", fmt.Errorf("apply ObjectStore %s/%s: %w", namespace, objStoreName, err) } patch := newCNPGClusterPatch(namespace, clusterName) patch.Spec.Plugins = []cnpgtypes.PluginConfiguration{buildBarmanPlugin(objStoreName, serverName)} if err := r.Patch(ctx, patch, client.Apply, client.FieldOwner(cnpgFieldManager), client.ForceOwnership); err != nil { - return "", err + return "", "", err } - return serverName, nil + return serverName, existing.Spec.ImageName, nil } // currentBarmanServerName returns the serverName the Cluster's barman-cloud @@ -552,7 +555,7 @@ func (r *BackupJobReconciler) createCNPGBackupArtifact( j *backupsv1alpha1.BackupJob, resolved *ResolvedBackupConfig, cnpgBackup *cnpgtypes.Backup, - clusterName, serverName string, + clusterName, serverName, imageName string, rendered *strategyv1alpha1.CNPGTemplate, sourceApp *postgresapp.Postgres, ) (*backupsv1alpha1.Backup, error) { @@ -572,7 +575,7 @@ func (r *BackupJobReconciler) createCNPGBackupArtifact( driverMD[cnpgS3SecretRefKey] = rendered.BarmanObjectStore.S3Credentials.SecretRef.Name } - underlyingResources, err := marshalCNPGBackupSnapshot(sourceApp, resolved.Parameters) + underlyingResources, err := marshalCNPGBackupSnapshot(sourceApp, resolved.Parameters, imageName) if err != nil { return nil, fmt.Errorf("encode source snapshot for Backup.status.underlyingResources: %w", err) } @@ -718,13 +721,14 @@ func (r *RestoreJobReconciler) reconcileCNPGRestore(ctx context.Context, restore // time. Without this, restore-time rendering with parameters=nil // silently produced `` and patched the target Postgres app // with broken Secret references. - sourceDatabases, sourceUsers, sourceParameters, err := unmarshalCNPGBackupSnapshot(backup) + snapshot, err := unmarshalCNPGBackupSnapshot(backup) if err != nil { return r.markRestoreJobFailed(ctx, restoreJob, fmt.Sprintf( "Backup %s/%s carries no usable source-spec snapshot in status.underlyingResources: %v "+ "(re-take the backup with a controller version that persists source spec)", backup.Namespace, backup.Name, err)) } + sourceDatabases, sourceUsers, sourceParameters := snapshot.Databases, snapshot.Users, snapshot.Parameters rendered, err := renderCNPGTemplate(strategy.Spec.Template, targetApp, sourceParameters) if err != nil { @@ -847,7 +851,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, rendered.BarmanObjectStore.S3Credentials, rendered.BarmanObjectStore.EndpointCA, sourceDatabases, sourceUsers); err != nil { + if err := r.patchPostgresAppForRestore(ctx, targetApp, sourceServerName, newServerName, sourceDestinationPath, sourceEndpointURL, options.RecoveryTime, 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) @@ -988,8 +992,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, credsRef, caRef, sourceDatabases, sourceUsers) + patched := buildPostgresAppRestorePatch(app, sourceServerName, newServerName, sourceDestinationPath, sourceEndpointURL, recoveryTime, credsRef, caRef, sourceDatabases, sourceUsers, sourceImageName) return r.Patch(ctx, patched, client.MergeFrom(app), client.FieldOwner(cnpgFieldManager)) } @@ -1024,6 +1029,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 @@ -1033,6 +1039,9 @@ func buildPostgresAppRestorePatch( // in-place restore fails barman-cloud-check-wal-archive ("Expected empty archive"). patched.Spec.Bootstrap.NewServerName = newServerName patched.Spec.Bootstrap.RecoveryTime = recoveryTime + // 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 @@ -1095,12 +1104,17 @@ func buildPostgresAppRestorePatch( // names, prefixes, secret references), never cleartext credentials - // credentials are always referenced through `secretRef`, not inlined, and // the Secret content stays in etcd's encryption-at-rest store. +// +// 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"` Databases map[string]postgresapp.Database `json:"databases,omitempty"` Users map[string]postgresapp.User `json:"users,omitempty"` Parameters map[string]string `json:"parameters,omitempty"` + ImageName string `json:"imageName,omitempty"` } const cnpgBackupSnapshotKind = "CNPGBackupSnapshot" @@ -1113,7 +1127,7 @@ var cnpgBackupSnapshotAPIVersion = backupsv1alpha1.GroupVersion.String() // marshalCNPGBackupSnapshot serializes the source app's spec.databases / // spec.users plus the BackupClassStrategy parameters into a // runtime.RawExtension suitable for Backup.Status.UnderlyingResources. -func marshalCNPGBackupSnapshot(app *postgresapp.Postgres, parameters map[string]string) (*runtime.RawExtension, error) { +func marshalCNPGBackupSnapshot(app *postgresapp.Postgres, parameters map[string]string, imageName string) (*runtime.RawExtension, error) { if app == nil { return nil, nil } @@ -1123,6 +1137,7 @@ func marshalCNPGBackupSnapshot(app *postgresapp.Postgres, parameters map[string] Databases: app.Spec.Databases, Users: app.Spec.Users, Parameters: parameters, + ImageName: imageName, } raw, err := json.Marshal(snap) if err != nil { @@ -1142,18 +1157,18 @@ func marshalCNPGBackupSnapshot(app *postgresapp.Postgres, parameters map[string] // by a controller version that pre-dates parameter persistence has no // parameters block at all). The caller must treat a nil/empty map the // same as "no parameter overrides" rather than failing. -func unmarshalCNPGBackupSnapshot(backup *backupsv1alpha1.Backup) (map[string]postgresapp.Database, map[string]postgresapp.User, map[string]string, error) { +func unmarshalCNPGBackupSnapshot(backup *backupsv1alpha1.Backup) (*cnpgBackupSnapshot, error) { if backup == nil || backup.Status.UnderlyingResources == nil || len(backup.Status.UnderlyingResources.Raw) == 0 { - return nil, nil, nil, fmt.Errorf("status.underlyingResources is empty") + return nil, fmt.Errorf("status.underlyingResources is empty") } var snap cnpgBackupSnapshot if err := json.Unmarshal(backup.Status.UnderlyingResources.Raw, &snap); err != nil { - return nil, nil, nil, fmt.Errorf("decode snapshot: %w", err) + return nil, fmt.Errorf("decode snapshot: %w", err) } if snap.Kind != cnpgBackupSnapshotKind { - return nil, nil, nil, fmt.Errorf("unexpected snapshot kind %q (want %q)", snap.Kind, cnpgBackupSnapshotKind) + return nil, fmt.Errorf("unexpected snapshot kind %q (want %q)", snap.Kind, cnpgBackupSnapshotKind) } - return snap.Databases, snap.Users, snap.Parameters, nil + return &snap, nil } // purgeExistingCluster deletes the live cnpg.io Cluster and its PVCs so the diff --git a/internal/backupcontroller/cnpgstrategy_controller_test.go b/internal/backupcontroller/cnpgstrategy_controller_test.go index 4b7a1b3b4..78b1a6b6d 100644 --- a/internal/backupcontroller/cnpgstrategy_controller_test.go +++ b/internal/backupcontroller/cnpgstrategy_controller_test.go @@ -222,15 +222,16 @@ 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) } bk := &backupsv1alpha1.Backup{Status: backupsv1alpha1.BackupStatus{UnderlyingResources: raw}} - _, _, gotParams, err := unmarshalCNPGBackupSnapshot(bk) + snap, err := unmarshalCNPGBackupSnapshot(bk) if err != nil { t.Fatalf("unmarshal snapshot: %v", err) } + gotParams := snap.Parameters // Restore-time render with retrieved parameters: same values out. rendRestore, err := renderCNPGTemplate(tmpl, app, gotParams) @@ -496,7 +497,7 @@ func TestBuildPostgresAppRestorePatch_ForwardsSecretRef_NotCleartext(t *testing. creds, nil, nil, nil, - ) + "") if got := patched.Spec.Backup.S3CredentialsSecret.Name; got != "pg-target-cnpg-backup-creds" { t.Errorf("s3CredentialsSecret.name: got %q want %q", got, "pg-target-cnpg-backup-creds") @@ -523,7 +524,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", @@ -541,7 +542,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) } @@ -699,7 +700,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") @@ -736,7 +737,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) @@ -775,7 +776,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 { @@ -791,7 +792,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) @@ -846,7 +847,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) } @@ -855,10 +856,11 @@ func TestMarshalUnmarshalCNPGBackupSnapshot(t *testing.T) { } bk := &backupsv1alpha1.Backup{Status: backupsv1alpha1.BackupStatus{UnderlyingResources: raw}} - dbs, users, params, err := unmarshalCNPGBackupSnapshot(bk) + snap, err := unmarshalCNPGBackupSnapshot(bk) if err != nil { t.Fatalf("unmarshal: %v", err) } + dbs, users, params := snap.Databases, snap.Users, snap.Parameters if dbs["app"].Extensions[0] != "pgcrypto" { t.Errorf("databases round-trip mismatch: %#v", dbs) } @@ -883,11 +885,11 @@ func TestMarshalUnmarshalCNPGBackupSnapshot(t *testing.T) { func TestMarshalUnmarshalCNPGBackupSnapshot_BackwardCompat(t *testing.T) { legacyRaw := []byte(`{"kind":"CNPGBackupSnapshot","apiVersion":"backups.cozystack.io/v1alpha1","databases":{"app":{}},"users":{"app":{}}}`) bk := &backupsv1alpha1.Backup{Status: backupsv1alpha1.BackupStatus{UnderlyingResources: &runtime.RawExtension{Raw: legacyRaw}}} - _, _, params, err := unmarshalCNPGBackupSnapshot(bk) + snap, err := unmarshalCNPGBackupSnapshot(bk) if err != nil { t.Fatalf("unmarshal legacy snapshot: %v", err) } - if len(params) != 0 { + if params := snap.Parameters; len(params) != 0 { t.Errorf("legacy snapshot must yield empty parameters, got %#v", params) } } @@ -909,7 +911,7 @@ func TestUnmarshalCNPGBackupSnapshot_RejectsMissingOrWrongKind(t *testing.T) { for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { bk := &backupsv1alpha1.Backup{Status: backupsv1alpha1.BackupStatus{UnderlyingResources: tc.ur}} - _, _, _, err := unmarshalCNPGBackupSnapshot(bk) + _, err := unmarshalCNPGBackupSnapshot(bk) if err == nil { t.Fatalf("expected error, got nil") } @@ -993,7 +995,7 @@ func TestCreateCNPGBackupArtifact_AlreadyExistsReturnsExisting(t *testing.T) { } sourceApp := newPostgresApp("pg", "tenant") - got, err := r.createCNPGBackupArtifact(context.Background(), j, resolved, cnpgBk, "postgres-pg", "postgres-pg", rendered, sourceApp) + got, err := r.createCNPGBackupArtifact(context.Background(), j, resolved, cnpgBk, "postgres-pg", "postgres-pg", "", rendered, sourceApp) if err != nil { t.Fatalf("expected AlreadyExists to be swallowed, got error %v", err) } @@ -1019,7 +1021,7 @@ func TestApplyClusterPluginBackup_NotFoundOnMissingCluster(t *testing.T) { }, } - _, err := r.applyClusterPluginBackup(context.Background(), "tenant", "postgres-missing", tmpl, "postgres-missing") + _, _, err := r.applyClusterPluginBackup(context.Background(), "tenant", "postgres-missing", tmpl, "postgres-missing") if err == nil { t.Fatalf("expected NotFound error, got nil") } @@ -1424,7 +1426,7 @@ func TestApplyClusterPluginBackup_ReadsTheLiveClusterNotTheCache(t *testing.T) { BarmanObjectStore: strategyv1alpha1.BarmanObjectStoreTemplate{DestinationPath: "s3://bucket/x/"}, } - got, err := r.applyClusterPluginBackup(context.Background(), "tenant", "postgres-app", tmpl, "strategy-name") + got, _, err := r.applyClusterPluginBackup(context.Background(), "tenant", "postgres-app", tmpl, "strategy-name") if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -1532,7 +1534,7 @@ func TestApplyClusterPluginBackup_PreservesLiveServerName(t *testing.T) { BarmanObjectStore: strategyv1alpha1.BarmanObjectStoreTemplate{DestinationPath: "s3://bucket/x/"}, } - got, err := r.applyClusterPluginBackup(context.Background(), "tenant", "postgres-app", tmpl, "strategy-name") + got, _, err := r.applyClusterPluginBackup(context.Background(), "tenant", "postgres-app", tmpl, "strategy-name") if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -1571,7 +1573,7 @@ func TestApplyClusterPluginBackup_PatchesExistingCluster(t *testing.T) { }, } - if _, err := r.applyClusterPluginBackup(context.Background(), "tenant", "postgres-app", tmpl, "tenant-app"); err != nil { + if _, _, err := r.applyClusterPluginBackup(context.Background(), "tenant", "postgres-app", tmpl, "tenant-app"); err != nil { t.Fatalf("unexpected error: %v", err) } @@ -1905,9 +1907,9 @@ func TestReconcileCNPGRestore_RepeatInPlacePurgesStaleRecoveryCluster(t *testing // it, a freshly-recovered one postdates it. startedAt := metav1.NewTime(time.Now()) - mkBackupArtifact := func(t *testing.T) *backupsv1alpha1.Backup { + mkBackupArtifact := func(t *testing.T, sourceImage string) *backupsv1alpha1.Backup { t.Helper() - snap, err := marshalCNPGBackupSnapshot(newPostgresApp(appName, ns), nil) + snap, err := marshalCNPGBackupSnapshot(newPostgresApp(appName, ns), nil, sourceImage) if err != nil { t.Fatalf("marshal snapshot: %v", err) } @@ -1965,7 +1967,7 @@ func TestReconcileCNPGRestore_RepeatInPlacePurgesStaleRecoveryCluster(t *testing } t.Run("stale leftover recovery cluster from a prior restore is purged", func(t *testing.T) { - backup := mkBackupArtifact(t) + backup := mkBackupArtifact(t, "") // creationTimestamp an hour before StartedAt: leftover from a prior restore. stale := metav1.NewTime(startedAt.Add(-time.Hour)) c := newCNPGStrategyTestClient(t, backup, mkRestoreJob(), strategy, cnpgBackup, @@ -1994,8 +1996,33 @@ func TestReconcileCNPGRestore_RepeatInPlacePurgesStaleRecoveryCluster(t *testing } }) + t.Run("backup hands its source image to the app", func(t *testing.T) { + const sourceImage = "ghcr.io/cloudnative-pg/postgresql:17.7" + backup := mkBackupArtifact(t, sourceImage) + stale := metav1.NewTime(startedAt.Add(-time.Hour)) + c := newCNPGStrategyTestClient(t, backup, mkRestoreJob(), strategy, cnpgBackup, + newPostgresApp(appName, ns), mkRecoveryCluster(stale), mkClusterPVC()) + r := &RestoreJobReconciler{Client: c, Interface: dynamicfake.NewSimpleDynamicClient(testCNPGScheme(t))} + + rj := &backupsv1alpha1.RestoreJob{} + if err := c.Get(ctx, client.ObjectKey{Namespace: ns, Name: "rj"}, rj); err != nil { + t.Fatalf("get seeded RestoreJob: %v", err) + } + if _, err := r.reconcileCNPGRestore(ctx, rj, backup); err != nil { + t.Fatalf("reconcileCNPGRestore: %v", err) + } + app, err := r.getPostgresApp(ctx, ns, appName) + if err != nil { + t.Fatalf("get app: %v", err) + } + if !app.Spec.Bootstrap.Enabled || app.Spec.Bootstrap.SourceImageName != sourceImage { + t.Fatalf("bootstrap after restore patch: enabled=%v sourceImageName=%q, want true/%q", + app.Spec.Bootstrap.Enabled, app.Spec.Bootstrap.SourceImageName, sourceImage) + } + }) + t.Run("freshly-recovered cluster from this restore is not re-purged", func(t *testing.T) { - backup := mkBackupArtifact(t) + backup := mkBackupArtifact(t, "") // creationTimestamp a minute after StartedAt: this restore's own re-render. fresh := metav1.NewTime(startedAt.Add(time.Minute)) c := newCNPGStrategyTestClient(t, backup, mkRestoreJob(), strategy, cnpgBackup, diff --git a/internal/backupcontroller/cnpgtypes/types.go b/internal/backupcontroller/cnpgtypes/types.go index 4a7c4e58c..e47a9d014 100644 --- a/internal/backupcontroller/cnpgtypes/types.go +++ b/internal/backupcontroller/cnpgtypes/types.go @@ -75,6 +75,9 @@ type ClusterList struct { } type ClusterSpec struct { + // ImageName is read, never patched: the backup driver records the image + // the data directory runs on. Empty means CNPG's default postgresql image. + ImageName string `json:"imageName,omitempty"` Backup *BackupConfiguration `json:"backup,omitempty"` Bootstrap *BootstrapConfiguration `json:"bootstrap,omitempty"` // Plugins wires CNPG-I plugins (here barman-cloud) onto the Cluster. The diff --git a/internal/backupcontroller/postgresapp/types.go b/internal/backupcontroller/postgresapp/types.go index 1b5036ec0..07db293f7 100644 --- a/internal/backupcontroller/postgresapp/types.go +++ b/internal/backupcontroller/postgresapp/types.go @@ -71,11 +71,12 @@ type PostgresSpec struct { } type Bootstrap struct { - Enabled bool `json:"enabled,omitempty"` - OldName string `json:"oldName,omitempty"` - ServerName string `json:"serverName,omitempty"` - NewServerName string `json:"newServerName,omitempty"` - RecoveryTime string `json:"recoveryTime,omitempty"` + Enabled bool `json:"enabled,omitempty"` + OldName string `json:"oldName,omitempty"` + ServerName string `json:"serverName,omitempty"` + NewServerName string `json:"newServerName,omitempty"` + RecoveryTime string `json:"recoveryTime,omitempty"` + SourceImageName string `json:"sourceImageName,omitempty"` } type Backup struct { diff --git a/packages/apps/postgres/README.md b/packages/apps/postgres/README.md index 649e2e177..0ac45d04b 100644 --- a/packages/apps/postgres/README.md +++ b/packages/apps/postgres/README.md @@ -195,17 +195,18 @@ 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. | `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` | +| Name | Description | Type | Value | +| ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | ---------- | +| `replicas` | Number of Postgres replicas. | `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` | +| `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 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 @@ -277,14 +278,15 @@ 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.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.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 every restore, and clears it when the backup carries no image. | `string` | `""` | ## Parameter examples and reference diff --git a/packages/apps/postgres/templates/_versions.tpl b/packages/apps/postgres/templates/_versions.tpl index e81086303..06fdbb96e 100644 --- a/packages/apps/postgres/templates/_versions.tpl +++ b/packages/apps/postgres/templates/_versions.tpl @@ -17,5 +17,95 @@ barman binaries the system variant adds. */}} {{- define "postgres.imageName" -}} +{{- include "postgres.heldImageName" . | default (include "postgres.targetImageName" .) -}} +{{- end -}} + +{{- define "postgres.targetImageName" -}} ghcr.io/cloudnative-pg/postgresql:{{ include "postgres.versionMap" . | trim | trimPrefix "v" }}-standard-trixie {{- 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 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 (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 -}} 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..4413760c2 --- /dev/null +++ b/packages/apps/postgres/tests/locale_guard_test.yaml @@ -0,0 +1,503 @@ +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: 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 bd5331788..56bf8a51c 100644 --- a/packages/apps/postgres/values.schema.json +++ b/packages/apps/postgres/values.schema.json @@ -140,6 +140,11 @@ "v13" ] }, + "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 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", @@ -374,6 +379,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 every restore, and clears it when the backup carries no image.", + "type": "string", + "default": "" } } } diff --git a/packages/apps/postgres/values.yaml b/packages/apps/postgres/values.yaml index 3c6d68f59..64495395c 100644 --- a/packages/apps/postgres/values.yaml +++ b/packages/apps/postgres/values.yaml @@ -87,6 +87,10 @@ external: false ## @param {Version} version - PostgreSQL major version to deploy version: v18 +## +## @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 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 ## @@ -272,6 +276,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 every restore, and clears it when the backup carries no image. ## @param {Bootstrap} bootstrap - Bootstrap configuration. bootstrap: @@ -281,3 +286,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 ef67e44cd..cb88095e9 100644 --- a/packages/system/postgres-rd/cozyrds/postgres.yaml +++ b/packages/system/postgres-rd/cozyrds/postgres.yaml @@ -8,7 +8,7 @@ spec: singular: postgres plural: postgreses openAPISchema: |- - {"title":"Chart Values","type":"object","properties":{"replicas":{"description":"Number of Postgres replicas.","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"]},"tls":{"description":"TLS configuration for server connections.","type":"object","default":{},"properties":{"enabled":{"description":"Tri-state switch controlling whether the chart injects the external hostname into the operator-managed CNPG cert via spec.certificates.serverAltDNSNames. When omitted, the chart injects the SAN if `external: true` and skips it 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"}}},"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}}}},"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).","type":"integer","default":0},"minSyncReplicas":{"description":"Minimum number of synchronous replicas required for commit.","type":"integer","default":0}}},"users":{"description":"Users configuration map.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"password":{"description":"Password for the user.","type":"string"},"replication":{"description":"Whether the user has replication privileges.","type":"boolean"}}}},"databases":{"description":"Databases configuration map.","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":{"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.","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"]},"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 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 hostname into the operator-managed CNPG cert via spec.certificates.serverAltDNSNames. When omitted, the chart injects the SAN if `external: true` and skips it 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"}}},"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}}}},"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).","type":"integer","default":0},"minSyncReplicas":{"description":"Minimum number of synchronous replicas required for commit.","type":"integer","default":0}}},"users":{"description":"Users configuration map.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"password":{"description":"Password for the user.","type":"string"},"replication":{"description":"Whether the user has replication privileges.","type":"boolean"}}}},"databases":{"description":"Databases configuration map.","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":{"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 every restore, and clears it when the backup carries no image.","type":"string","default":""}}}}} release: prefix: postgres- labels: @@ -33,7 +33,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", "tls"], ["spec", "postgresql"], ["spec", "postgresql", "parameters"], ["spec", "postgresql", "parameters", "max_connections"], ["spec", "quorum"], ["spec", "quorum", "minSyncReplicas"], ["spec", "quorum", "maxSyncReplicas"], ["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", "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", "allowCollationChange"], ["spec", "tls"], ["spec", "postgresql"], ["spec", "postgresql", "parameters"], ["spec", "postgresql", "parameters", "max_connections"], ["spec", "quorum"], ["spec", "quorum", "minSyncReplicas"], ["spec", "quorum", "maxSyncReplicas"], ["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", "oldName"], ["spec", "bootstrap", "serverName"], ["spec", "bootstrap", "newServerName"], ["spec", "bootstrap", "sourceImageName"]] secrets: exclude: [] include: From 653d29f1a275940a3547582826cf7d9efb748ba8 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 | 24 ++++----- .../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, 104 insertions(+), 24 deletions(-) diff --git a/api/apps/v1alpha1/postgresql/types.go b/api/apps/v1alpha1/postgresql/types.go index d53f3daf4..c680ccf1c 100644 --- a/api/apps/v1alpha1/postgresql/types.go +++ b/api/apps/v1alpha1/postgresql/types.go @@ -40,7 +40,7 @@ type ConfigSpec struct { // PostgreSQL major version to deploy // +kubebuilder:default:="v18" Version Version `json:"version"` - // 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 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 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 5ff6e4384..41f68fc4e 100644 --- a/hack/e2e-chainsaw/postgres/chainsaw-test.yaml +++ b/hack/e2e-chainsaw/postgres/chainsaw-test.yaml @@ -130,8 +130,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: @@ -150,9 +154,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 @@ -212,6 +226,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 0ac45d04b..738d6db5a 100644 --- a/packages/apps/postgres/README.md +++ b/packages/apps/postgres/README.md @@ -195,18 +195,18 @@ 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. | `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` | -| `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 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. | `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` | +| `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 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 61b3a84b9..dca7bcdd0 100644 --- a/packages/apps/postgres/templates/init-script.yaml +++ b/packages/apps/postgres/templates/init-script.yaml @@ -319,6 +319,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 @@ -332,17 +355,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 @@ -353,7 +384,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 ( @@ -469,7 +507,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; @@ -482,6 +520,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 56bf8a51c..9213bd00b 100644 --- a/packages/apps/postgres/values.schema.json +++ b/packages/apps/postgres/values.schema.json @@ -141,7 +141,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 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 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 64495395c..4a209fc25 100644 --- a/packages/apps/postgres/values.yaml +++ b/packages/apps/postgres/values.yaml @@ -88,7 +88,7 @@ external: false version: v18 ## -## @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 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 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 cb88095e9..98948a34a 100644 --- a/packages/system/postgres-rd/cozyrds/postgres.yaml +++ b/packages/system/postgres-rd/cozyrds/postgres.yaml @@ -8,7 +8,7 @@ spec: singular: postgres plural: postgreses openAPISchema: |- - {"title":"Chart Values","type":"object","properties":{"replicas":{"description":"Number of Postgres replicas.","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"]},"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 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 hostname into the operator-managed CNPG cert via spec.certificates.serverAltDNSNames. When omitted, the chart injects the SAN if `external: true` and skips it 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"}}},"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}}}},"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).","type":"integer","default":0},"minSyncReplicas":{"description":"Minimum number of synchronous replicas required for commit.","type":"integer","default":0}}},"users":{"description":"Users configuration map.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"password":{"description":"Password for the user.","type":"string"},"replication":{"description":"Whether the user has replication privileges.","type":"boolean"}}}},"databases":{"description":"Databases configuration map.","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":{"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 every restore, and clears it when the backup carries no image.","type":"string","default":""}}}}} + {"title":"Chart Values","type":"object","properties":{"replicas":{"description":"Number of Postgres replicas.","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"]},"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 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 hostname into the operator-managed CNPG cert via spec.certificates.serverAltDNSNames. When omitted, the chart injects the SAN if `external: true` and skips it 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"}}},"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}}}},"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).","type":"integer","default":0},"minSyncReplicas":{"description":"Minimum number of synchronous replicas required for commit.","type":"integer","default":0}}},"users":{"description":"Users configuration map.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"password":{"description":"Password for the user.","type":"string"},"replication":{"description":"Whether the user has replication privileges.","type":"boolean"}}}},"databases":{"description":"Databases configuration map.","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":{"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 every restore, and clears it when the backup carries no image.","type":"string","default":""}}}}} release: prefix: postgres- labels: From 7c55a5e5fe298948093056d03f7e9b9f0554b8e4 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. ``` On release-1.6 the WorkloadMonitor status has only operational, with no reason or message, and adding them is a CRD change a patch release does not take. Only the rule is ported: a Job in the monitor's namespace that carries the monitor's selector labels and workloads.cozystack.io/report-failure: "true" and has Failed=True makes the monitor not operational, counting only the newest Job per controller owner, with the Job cache filtered by that label and stripped by the transform. The application then shows WorkloadsReady=False with the generic WorkloadMonitorCheck reason instead of JobFailed; the failed Jobs are named in the controller log. The JobFailed reason constant, the status precedence against BucketClaim and DataVolume verdicts (1.6 has neither as a status cause) and the registry test are not carried over, and the tests assert operational instead of reason and message. (cherry picked from commit 23b94d6d1a42f052dbcbbeb773c7497cc2220491) Assisted-By: LLM Signed-off-by: Andrey Kolkov --- api/v1alpha1/workloadmonitor_types.go | 6 + cmd/cozystack-controller/main.go | 2 + .../controller/workloadmonitor_controller.go | 134 ++++++++++++ .../workloadmonitor_controller_test.go | 203 ++++++++++++++++++ 4 files changed, 345 insertions(+) diff --git a/api/v1alpha1/workloadmonitor_types.go b/api/v1alpha1/workloadmonitor_types.go index e7639edb4..64e94a789 100644 --- a/api/v1alpha1/workloadmonitor_types.go +++ b/api/v1alpha1/workloadmonitor_types.go @@ -34,6 +34,12 @@ type WorkloadMonitorSpec struct { Replicas *int32 `json:"replicas,omitempty"` } +// 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 3a4077463..445d98798 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" @@ -200,6 +201,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 daf3a682a..b1e647b65 100644 --- a/internal/controller/workloadmonitor_controller.go +++ b/internal/controller/workloadmonitor_controller.go @@ -13,17 +13,20 @@ import ( "time" apierrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" "k8s.io/client-go/tools/record" "k8s.io/client-go/util/retry" "k8s.io/utils/pointer" ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/cache" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/handler" "sigs.k8s.io/controller-runtime/pkg/log" "sigs.k8s.io/controller-runtime/pkg/reconcile" + 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" @@ -77,12 +80,114 @@ type WorkloadMonitorReconciler struct { // +kubebuilder:rbac:groups=core,resources=namespaces,verbs=get // +kubebuilder:rbac:groups=core,resources=events,verbs=create;patch // +kubebuilder:rbac:groups=objectstorage.k8s.io,resources=bucketclaims,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 { return bc.Status.BucketReady } +// 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 @@ -708,6 +813,27 @@ func (r *WorkloadMonitorReconciler) Reconcile(ctx context.Context, req ctrl.Requ } } + 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 + } + // The status has no field for the cause on this line, so the failed Jobs + // are named in the log only. + jobsMessage := failedJobsMessage(jobList.Items) + if jobsMessage != "" { + logger.Info("WorkloadMonitor is not operational: a Job that reports failure has failed", "monitor", monitor.Name, "jobs", jobsMessage) + } + // Update WorkloadMonitor status based on observed pods monitor.Status.ObservedReplicas = observedReplicas monitor.Status.AvailableReplicas = availableReplicas @@ -728,6 +854,9 @@ func (r *WorkloadMonitorReconciler) Reconcile(ctx context.Context, req ctrl.Requ if fresh.Spec.MinReplicas != nil && availableReplicas < *fresh.Spec.MinReplicas { fresh.Status.Operational = pointer.Bool(false) } + if jobsMessage != "" { + fresh.Status.Operational = pointer.Bool(false) + } return r.Status().Update(ctx, fresh) }) if err != nil { @@ -771,6 +900,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{}). Complete(r) diff --git a/internal/controller/workloadmonitor_controller_test.go b/internal/controller/workloadmonitor_controller_test.go index ee85f422c..7d7a47bd0 100644 --- a/internal/controller/workloadmonitor_controller_test.go +++ b/internal/controller/workloadmonitor_controller_test.go @@ -7,8 +7,10 @@ import ( "net/http/httptest" "strings" "testing" + "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/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -16,6 +18,7 @@ import ( "k8s.io/apimachinery/pkg/types" "k8s.io/utils/ptr" cosiv1alpha1 "sigs.k8s.io/container-object-storage-interface-api/apis/objectstorage/v1alpha1" + "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client/fake" "sigs.k8s.io/controller-runtime/pkg/reconcile" ) @@ -24,6 +27,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) @@ -90,6 +94,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) @@ -219,6 +224,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{ @@ -291,6 +297,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{ @@ -343,6 +350,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{ @@ -387,6 +395,7 @@ func newTestScheme() *runtime.Scheme { s := runtime.NewScheme() _ = cozyv1alpha1.AddToScheme(s) _ = corev1.AddToScheme(s) + _ = batchv1.AddToScheme(s) _ = cosiv1alpha1.AddToScheme(s) return s } @@ -1300,3 +1309,197 @@ func TestReconcile_PVCStorageClassResourceKey(t *testing.T) { }) } } + +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} + 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 + operational bool + }{ + {"failed", newJob("db-repair", selected, jobFailed("BackoffLimitExceeded", "Job has reached the specified backoff limit")), false}, + {"failed without a reason", newJob("db-repair", selected, jobFailed("", "")), false}, + {"succeeded", newJob("db-repair", selected, batchv1.JobCondition{Type: batchv1.JobComplete, Status: corev1.ConditionTrue}), true}, + {"running", newJob("db-repair", selected), true}, + {"Failed condition not true", newJob("db-repair", selected, batchv1.JobCondition{Type: batchv1.JobFailed, Status: corev1.ConditionFalse}), true}, + {"outside the selector", newJob("other", map[string]string{"app.kubernetes.io/instance": "other", cozyv1alpha1.WorkloadMonitorReportFailureLabel: "true"}, jobFailed("BackoffLimitExceeded", "")), true}, + {"not opted in", newJob("db-1-initdb", map[string]string{"app.kubernetes.io/instance": "db"}, jobFailed("BackoffLimitExceeded", "")), true}, + {"opted out", newJob("db-repair", map[string]string{"app.kubernetes.io/instance": "db", cozyv1alpha1.WorkloadMonitorReportFailureLabel: "false"}, jobFailed("BackoffLimitExceeded", "")), true}, + } + 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.operational { + t.Errorf("Operational = %v, want %v", *got.Status.Operational, tc.operational) + } + }) + } +} + +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) + if got := reconcileJobMonitor(t, c, s); *got.Status.Operational { + t.Fatal("before: Operational = true, want false") + } + if err := tc.clear(c, job); err != nil { + t.Fatal(err) + } + if got := reconcileJobMonitor(t, c, s); !*got.Status.Operational { + t.Error("after: Operational = false, want true") + } + }) + } +} + +func TestReconcile_FailedJobWithEnoughReplicas(t *testing.T) { + selected := map[string]string{"app.kubernetes.io/instance": "db", cozyv1alpha1.WorkloadMonitorReportFailureLabel: "true"} + s := newTestScheme() + pod := &corev1.Pod{ + ObjectMeta: metav1.ObjectMeta{Name: "db-1", Namespace: "default", Labels: map[string]string{"app.kubernetes.io/instance": "db"}}, + Status: corev1.PodStatus{ + Phase: corev1.PodRunning, + Conditions: []corev1.PodCondition{{Type: corev1.PodReady, Status: corev1.ConditionTrue}}, + }, + } + got := reconcileJobMonitor(t, newJobMonitorClient(s, 1, pod, newJob("db-repair", selected, jobFailed("BackoffLimitExceeded", ""))), s) + if got.Status.AvailableReplicas != 1 { + t.Fatalf("AvailableReplicas = %d, want 1", got.Status.AvailableReplicas) + } + if *got.Status.Operational { + t.Error("Operational = true, want false: a failed Job outranks enough ready replicas") + } +} + +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) + } +} From fd1c38e1954e367c23387171a802888c8a5ea4d8 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. ``` release-1.6 has no postgis flavor, so the PostGIS extension update that follows the collation pass in repair.sh on main is not carried over, and repair.sh ends with the collation pass's own exit status; nothing in the chart reads .Values.flavor. It has no adopted-restore record either, so the step that writes one, which the split moved to the end of init.sh on main, is not carried over. The init-job comment no longer describes the collation pass, which left that Job here, and says what JOB_DEADLINE bounds there now: the reruns of run.sh. (cherry picked from commit c8ffc87717b72c9d589ec7ecca3ea9f02ee6ea70) Assisted-By: LLM 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 | 24 +- .../postgres/templates/collation-repair.yaml | 223 ++++++++++++++++++ .../apps/postgres/templates/init-job.yaml | 20 +- .../apps/postgres/templates/init-script.yaml | 89 ++++--- .../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, 553 insertions(+), 66 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 c680ccf1c..ae86282cc 100644 --- a/api/apps/v1alpha1/postgresql/types.go +++ b/api/apps/v1alpha1/postgresql/types.go @@ -40,7 +40,7 @@ type ConfigSpec struct { // PostgreSQL major version to deploy // +kubebuilder:default:="v18" Version Version `json:"version"` - // 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 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 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 41f68fc4e..9cade81a7 100644 --- a/hack/e2e-chainsaw/postgres/chainsaw-test.yaml +++ b/hack/e2e-chainsaw/postgres/chainsaw-test.yaml @@ -127,9 +127,9 @@ spec: # The Postgres CR itself was applied by chainsaw and is deleted (and waited # on) automatically during cleanup — no explicit teardown step needed. - # 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 @@ -170,6 +170,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: @@ -194,6 +203,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: | @@ -207,14 +268,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" @@ -223,18 +284,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() { @@ -243,21 +304,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") @@ -284,6 +345,11 @@ spec: apiVersion: batch/v1 kind: Job name: postgres-test-init-job + - delete: + ref: + apiVersion: batch/v1 + kind: Job + name: postgres-test-collation-repair --- # Full barman-cloud backup -> to-copy RestoreJob round-trip, driving the # validated example scripts (examples/backups/postgres) as the harness so the diff --git a/packages/apps/postgres/README.md b/packages/apps/postgres/README.md index 738d6db5a..62bac38c0 100644 --- a/packages/apps/postgres/README.md +++ b/packages/apps/postgres/README.md @@ -195,18 +195,18 @@ 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. | `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` | -| `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 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. | `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` | +| `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 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 @@ -229,6 +251,9 @@ stringData: EOT {{- end }} {{- 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 @@ -247,20 +272,27 @@ 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. + 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. - 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 @@ -303,9 +335,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: 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 @@ -423,24 +455,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 @@ -460,7 +486,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 @@ -470,7 +496,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 @@ -480,11 +506,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 @@ -499,6 +525,7 @@ stringData: \endif EOT then + [ "${PIPESTATUS[0]}" != 2 ] || COLLATION_LOST=yes DB_FAILED=yes fi done @@ -527,10 +554,14 @@ stringData: 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 + 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 upgrade of the release starts the repair again, except for an index an error above reports as left alone" >&2 + fi + [ -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 9213bd00b..c00ac7409 100644 --- a/packages/apps/postgres/values.schema.json +++ b/packages/apps/postgres/values.schema.json @@ -141,7 +141,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 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 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 4a209fc25..2feb9d890 100644 --- a/packages/apps/postgres/values.yaml +++ b/packages/apps/postgres/values.yaml @@ -88,7 +88,7 @@ external: false version: v18 ## -## @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 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 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 98948a34a..b424650f8 100644 --- a/packages/system/postgres-rd/cozyrds/postgres.yaml +++ b/packages/system/postgres-rd/cozyrds/postgres.yaml @@ -8,7 +8,7 @@ spec: singular: postgres plural: postgreses openAPISchema: |- - {"title":"Chart Values","type":"object","properties":{"replicas":{"description":"Number of Postgres replicas.","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"]},"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 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 hostname into the operator-managed CNPG cert via spec.certificates.serverAltDNSNames. When omitted, the chart injects the SAN if `external: true` and skips it 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"}}},"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}}}},"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).","type":"integer","default":0},"minSyncReplicas":{"description":"Minimum number of synchronous replicas required for commit.","type":"integer","default":0}}},"users":{"description":"Users configuration map.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"password":{"description":"Password for the user.","type":"string"},"replication":{"description":"Whether the user has replication privileges.","type":"boolean"}}}},"databases":{"description":"Databases configuration map.","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":{"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 every restore, and clears it when the backup carries no image.","type":"string","default":""}}}}} + {"title":"Chart Values","type":"object","properties":{"replicas":{"description":"Number of Postgres replicas.","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"]},"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 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 hostname into the operator-managed CNPG cert via spec.certificates.serverAltDNSNames. When omitted, the chart injects the SAN if `external: true` and skips it 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"}}},"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}}}},"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).","type":"integer","default":0},"minSyncReplicas":{"description":"Minimum number of synchronous replicas required for commit.","type":"integer","default":0}}},"users":{"description":"Users configuration map.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"password":{"description":"Password for the user.","type":"string"},"replication":{"description":"Whether the user has replication privileges.","type":"boolean"}}}},"databases":{"description":"Databases configuration map.","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":{"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 every restore, and clears it when the backup carries no image.","type":"string","default":""}}}}} release: prefix: postgres- labels: