diff --git a/hack/e2e-chainsaw/postgres/chainsaw-test.yaml b/hack/e2e-chainsaw/postgres/chainsaw-test.yaml index 90d1552d3..bc0bc1c98 100644 --- a/hack/e2e-chainsaw/postgres/chainsaw-test.yaml +++ b/hack/e2e-chainsaw/postgres/chainsaw-test.yaml @@ -249,123 +249,6 @@ spec: fi check: ($error == null): true - - # The init Job rebuilds an index whose collation changed library version. - # The pass is SQL run by a Helm hook, so only a real server can say whether - # it works. A collation created with an explicit version reads as stale - # without swapping the operand image, which makes one more upgrade of the - # release enough to run the pass over it. - - name: rebuild-index-after-collation-version-change - try: - - script: - timeout: 2m - content: | - set -eu - pod=$(kubectl -n "$NAMESPACE" get pod \ - -l cnpg.io/cluster=postgres-test,cnpg.io/instanceRole=primary \ - -o name | head -n1) - kubectl -n "$NAMESPACE" exec -i "$pod" -c postgres -- \ - psql -U postgres -d testdb -v ON_ERROR_STOP=1 <<'EOF' - CREATE COLLATION stale_icu (provider = icu, locale = 'en', version = '0'); - CREATE TABLE collation_probe (s text COLLATE stale_icu); - INSERT INTO collation_probe SELECT 'v' || g FROM generate_series(1, 1000) g; - CREATE UNIQUE INDEX collation_probe_s ON collation_probe (s); - CREATE EXTENSION IF NOT EXISTS btree_gist; - CREATE TABLE collation_probe_excl (s text COLLATE stale_icu, EXCLUDE USING gist (s WITH =)); - INSERT INTO collation_probe_excl SELECT 'k' || g FROM generate_series(1, 200) g; - CREATE TABLE collation_probe_before AS - SELECT 'collation_probe_s'::regclass::oid AS index, - (SELECT relfilenode FROM pg_class WHERE oid = 'collation_probe_excl_s_excl'::regclass) AS in_place_file; - EOF - check: - ($error == null): true - # A declared user is the smallest change that makes Helm upgrade the - # release, and so run the hook, without restarting PostgreSQL. - - patch: - resource: - apiVersion: apps.cozystack.io/v1alpha1 - kind: Postgres - metadata: - name: test - spec: - users: - collationprobe: {} - # 11m: above the 600s upgrade timeout cozystack-api gives this release. - # The step above that waited for this Job deleted it, so the Job found - # here is the one the upgrade created. - - assert: - timeout: 11m - resource: - apiVersion: batch/v1 - kind: Job - metadata: - name: postgres-test-init-job - status: - (conditions[?type == 'Complete']): - - status: "True" - - script: - timeout: 2m - content: | - set -eu - pod=$(kubectl -n "$NAMESPACE" get pod \ - -l cnpg.io/cluster=postgres-test,cnpg.io/instanceRole=primary \ - -o name | head -n1) - q() { - kubectl -n "$NAMESPACE" exec "$pod" -c postgres -- \ - psql -U postgres -d testdb -v ON_ERROR_STOP=1 -tAc "$1" - } - refreshed=$(q "SELECT collversion = pg_collation_actual_version(oid) FROM pg_collation WHERE collname = 'stale_icu'") - if [ "$refreshed" != t ]; then - echo "the init Job left the collation version stale" >&2 - exit 1 - fi - # REINDEX CONCURRENTLY gives the index a new OID, so an unchanged - # one means the version was refreshed over an index nobody rebuilt. - rebuilt=$(q "SELECT 'collation_probe_s'::regclass::oid <> index FROM collation_probe_before") - if [ "$rebuilt" != t ]; then - echo "the init Job refreshed the collation version without rebuilding the index" >&2 - exit 1 - fi - q "CREATE EXTENSION IF NOT EXISTS amcheck" - q "SELECT bt_index_check('collation_probe_s', true)" - # An exclusion constraint's index is rebuilt in place: it keeps its - # OID and gets a new storage file. - rebuilt_in_place=$(q "SELECT c.relfilenode <> b.in_place_file FROM pg_class c, collation_probe_before b WHERE c.oid = 'collation_probe_excl_s_excl'::regclass") - if [ "$rebuilt_in_place" != t ]; then - echo "the init Job did not rebuild the exclusion constraint's index" >&2 - exit 1 - fi - # The pass keeps its progress in a setting of the database and - # removes it once nothing is left to repair. - progress=$(q "SELECT count(*) FROM pg_db_role_setting s JOIN pg_database d ON d.oid = s.setdatabase, unnest(s.setconfig) AS c WHERE d.datname = current_database() AND c LIKE 'cozystack.collation_repair=%'") - if [ "$progress" != 0 ]; then - echo "the init Job left its repair setting on a database it finished repairing" >&2 - exit 1 - fi - leftovers=$(q "SELECT count(*) FROM pg_index WHERE NOT indisvalid") - if [ "$leftovers" != 0 ]; then - echo "the rebuild left $leftovers invalid index(es) behind" >&2 - exit 1 - fi - # The Job above also completes on a retry, so a hook that failed - # first would pass unseen without this. - cd ../../.. - . hack/e2e-chainsaw/_lib/remediation-guard.sh - statuses=$(kubectl -n "$NAMESPACE" get helmrelease postgres-test \ - -o jsonpath="$HELMRELEASE_HISTORY_JSONPATH") - printf 'HelmRelease postgres-test history statuses:\n%s\n' "${statuses:-}" - if helmrelease_has_remediation_cycle "$statuses"; then - echo "HelmRelease postgres-test failed an action while the index was rebuilt" >&2 - exit 1 - fi - check: - ($error == null): true - finally: - - delete: - ref: - apiVersion: batch/v1 - kind: Job - name: postgres-test-init-job # The Postgres CR itself was applied by chainsaw and is deleted (and waited # on) automatically during cleanup — no explicit teardown step needed. --- diff --git a/packages/apps/postgres/files/postgis-versions.yaml b/packages/apps/postgres/files/postgis-versions.yaml index 12d800143..4b1ad284c 100644 --- a/packages/apps/postgres/files/postgis-versions.yaml +++ b/packages/apps/postgres/files/postgis-versions.yaml @@ -1,6 +1,6 @@ -"v18": "18.7-3.7.0-standard-trixie" -"v17": "17.12-3.7.0-standard-trixie" -"v16": "16.16-3.7.0-standard-trixie" -"v15": "15.20-3.7.0-standard-trixie" -"v14": "14.25-3.7.0-standard-trixie" +"v18": "18.1-3.6.1-standard-trixie" +"v17": "17.7-3.6.1-standard-trixie" +"v16": "16.11-3.6.1-standard-trixie" +"v15": "15.15-3.6.1-standard-trixie" +"v14": "14.20-3.6.1-standard-trixie" "v13": "13.22-3.6.0-standard-trixie" diff --git a/packages/apps/postgres/files/versions.yaml b/packages/apps/postgres/files/versions.yaml index 2624066e3..e4fe13ead 100644 --- a/packages/apps/postgres/files/versions.yaml +++ b/packages/apps/postgres/files/versions.yaml @@ -1,6 +1,6 @@ -"v18": "v18.7" -"v17": "v17.12" -"v16": "v16.16" -"v15": "v15.20" -"v14": "v14.25" +"v18": "v18.1" +"v17": "v17.7" +"v16": "v16.11" +"v15": "v15.15" +"v14": "v14.20" "v13": "v13.22" diff --git a/packages/apps/postgres/hack/update-versions.sh b/packages/apps/postgres/hack/update-versions.sh index 0afc55afa..3a4f0a745 100755 --- a/packages/apps/postgres/hack/update-versions.sh +++ b/packages/apps/postgres/hack/update-versions.sh @@ -33,10 +33,9 @@ if ! command -v jq &> /dev/null; then exit 1 fi -# Get available image tags. Only standard-trixie builds count: the chart -# appends that suffix to the minor it reads from versions.yaml. +# Get available image tags 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]+-standard-trixie$")) | sub("-standard-trixie$"; "")' | sort -V) +AVAILABLE_TAGS=$(skopeo list-tags docker://ghcr.io/cloudnative-pg/postgresql | jq -r '.Tags[] | select(test("^[0-9]+\\.[0-9]+$"))' | 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 688c16b49..b7cdb8c13 100644 --- a/packages/apps/postgres/templates/_versions.tpl +++ b/packages/apps/postgres/templates/_versions.tpl @@ -16,33 +16,25 @@ {{/* 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. trixie, because the postgis - flavor is on it already, so both image families share one Debian release. + Cluster, so both must resolve the same image. */}} {{- define "postgres.imageName" -}} {{- if eq (default "postgresql" .Values.flavor) "postgis" -}} ghcr.io/cloudnative-pg/postgis:{{ include "postgres.postgisVersionMap" . | trim }} {{- else -}} -ghcr.io/cloudnative-pg/postgresql:{{ include "postgres.versionMap" . | trim | trimPrefix "v" }}-standard-trixie +ghcr.io/cloudnative-pg/postgresql:{{ include "postgres.versionMap" . | trim | trimPrefix "v" }} {{- end -}} {{- end -}} {{/* - The flavor is fixed at bootstrap. Only the postgis image carries the shared - libraries behind PostGIS objects, so the postgis-to-postgresql direction - leaves every one of them without its code. The two families are also built - and released separately, and nothing keeps their Debian release in step, so - either direction can swap glibc and ICU under an initialised data directory - together with the flavor. CNPG would roll either change out as an ordinary - image update, so refuse it here, before the Cluster is patched. Only the - image name is compared: a minor bump, a move to another variant of the same - family, or a registry mirror rewriting the host must keep passing. + The flavor is fixed at bootstrap. The two image families are built on + different Debian releases, so moving a live cluster from one to the other + swaps glibc under an initialised data directory and silently invalidates + every index on collatable text; the postgis-to-postgresql direction also + drops the shared libraries behind every PostGIS object. CNPG would roll + either change out as an ordinary image update, so refuse it here, before + the Cluster is patched. Only the image name is compared: a minor bump or + a registry mirror rewriting the host must keep passing. A physical recovery carries the same data directory across, so it is held to the same rule. With no live Cluster of its own yet, the release is @@ -57,14 +49,14 @@ ghcr.io/cloudnative-pg/postgresql:{{ include "postgres.versionMap" . | trim | tr {{- if and $live $live.spec $live.spec.imageName -}} {{- $liveName := regexReplaceAll "[:@].*$" (last (splitList "/" $live.spec.imageName)) "" -}} {{- if ne $liveName $wantName -}} -{{- fail (printf "postgres: flavor cannot change on an existing cluster (running %s, requested %s). Only the postgis image carries the PostGIS libraries, and the two image families can differ in glibc and ICU, which corrupts text indexes. Create a new Postgres with the wanted flavor and move the data with a logical dump (pg_dump / pg_restore); restoring a backup keeps the flavor it was taken from." $liveName $wantName) -}} +{{- fail (printf "postgres: flavor cannot change on an existing cluster (running %s, requested %s). The image families use different glibc versions, which would corrupt text indexes. Create a new Postgres with the wanted flavor and move the data with a logical dump (pg_dump / pg_restore); restoring a backup keeps the flavor it was taken from." $liveName $wantName) -}} {{- end -}} {{- else if and .Values.bootstrap.enabled .Values.bootstrap.oldName -}} {{- $source := lookup "postgresql.cnpg.io/v1" "Cluster" .Release.Namespace .Values.bootstrap.oldName -}} {{- if and $source $source.spec $source.spec.imageName -}} {{- $sourceName := regexReplaceAll "[:@].*$" (last (splitList "/" $source.spec.imageName)) "" -}} {{- if ne $sourceName $wantName -}} -{{- fail (printf "postgres: cannot recover a %s backup of %s into the %s flavor. A physical restore carries over a data directory built with the source's libraries: PostGIS objects need the postgis image, and a glibc or ICU difference corrupts text indexes. Set flavor to match the source, or create the new Postgres empty and move the data with a logical dump (pg_dump / pg_restore)." $sourceName .Values.bootstrap.oldName $wantName) -}} +{{- fail (printf "postgres: cannot recover a %s backup of %s into the %s flavor. A physical restore keeps the source's glibc and libraries, which would corrupt text indexes. Set flavor to match the source, or create the new Postgres empty and move the data with a logical dump (pg_dump / pg_restore)." $sourceName .Values.bootstrap.oldName $wantName) -}} {{- end -}} {{- end -}} {{- end -}} diff --git a/packages/apps/postgres/templates/db.yaml b/packages/apps/postgres/templates/db.yaml index 7afeb0f16..80f141187 100644 --- a/packages/apps/postgres/templates/db.yaml +++ b/packages/apps/postgres/templates/db.yaml @@ -176,9 +176,11 @@ 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, 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. + 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. */}} {{- $hasInlineCreds := and (ne (default "" .Values.backup.s3AccessKey) "") (ne (default "" .Values.backup.s3SecretKey) "") }} {{- $hasLegacyCreds := or $hasInlineCreds (ne (default "" $credCfg.name) "") }} diff --git a/packages/apps/postgres/templates/init-job.yaml b/packages/apps/postgres/templates/init-job.yaml index 26120839c..31eb67ff3 100644 --- a/packages/apps/postgres/templates/init-job.yaml +++ b/packages/apps/postgres/templates/init-job.yaml @@ -44,8 +44,7 @@ spec: is idempotent and the purged pod stays Pending on the missing mount, so a retry buys nothing. */}} - {{- $deadline := ternary 570 540 .Release.IsInstall }} - activeDeadlineSeconds: {{ $deadline }} + activeDeadlineSeconds: {{ if .Release.IsInstall }}570{{ else }}540{{ end }} backoffLimit: 0 ttlSecondsAfterFinished: 3600 template: @@ -78,8 +77,6 @@ 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 35b4d3043..8787f1961 100644 --- a/packages/apps/postgres/templates/init-script.yaml +++ b/packages/apps/postgres/templates/init-script.yaml @@ -591,255 +591,6 @@ stringData: EOT {{- end }} {{- end }} - {{- /* - An operand image built on another Debian release ships another glibc and - ICU, and an index ordered by a collation of either library is then - ordered by rules the server no longer applies: lookups miss rows and a - unique index stops seeing duplicates. PostgreSQL records the library - version each collation was created with, so a collation whose recorded - version differs from the one the server reports marks the indexes to - rebuild. The C and POSIX collations carry no version and never qualify, - which is every index of a database this chart created with its defaults. - - PostgreSQL records a collation for an index only where it orders a key. - A collation can also decide what an index holds without ordering it, in - a predicate or inside an expression, and for those the catalog names - the columns the index reads and nothing else. The collations of those - columns therefore count as well. That rebuilds an index or two that did - not need it, and still misses a collation that an expression applies to - a column of another one. - - This pass comes after the ones that manage roles and databases, so - that a rebuild that fails, or does not finish before the Job deadline, - costs none of them. Only the record of an adopted restore follows it: - that record must not be written by a run that failed. - - Helm runs this hook as soon as the Cluster is patched, while CNPG is - still rolling the instances, so the primary may answer from the previous - image for minutes. The Job runs the image the Cluster is moving to, so - the server is on it once both report the same PostgreSQL version and - the same Debian release. The rebuild counter that follows them is left - out: a tag is rebuilt in place, so the Job and an instance can run - different rebuilds of one release for good. Waiting is only worth its - time when an index depends on a versioned collation. The wait ends 120 - seconds before the Job's deadline, which is what a first run keeps for - rebuilding. - - Rebuilds survive a retry: REINDEX CONCURRENTLY gives the index a new - OID, so the highest OID seen when the repair began separates the - indexes still to rebuild from the ones already done. That mark is kept - as a setting of the database, next to a fingerprint of the stale - collations and their new versions, so another library change starts a - new repair. An exclusion constraint's index cannot be rebuilt - concurrently: its table is neither read nor written while it is rebuilt - in place, and it keeps its OID. The same setting therefore records each - attempt at one together with the index's storage file: a file that has - changed since means the index was rebuilt, by a run or by hand, and two - attempts on the same file mean two runs did not finish, after which the - index is left to an operator. The rebuild is given what is left of the - Job and no more, so that the table is not kept locked by a backend the - Job no longer waits for. - - A transaction that stays open on the table makes a rebuild wait for a - lock. That wait is bounded by what is left of the Job as well, so that - no backend is left waiting for a lock after the Job is gone. A - concurrent rebuild that is already running is not cut short: it blocks - nobody, and the index it finishes counts as done. Both bounds keep a - minute in reserve: the deadline counts from the start of the Job, - $SECONDS from the start of this script. - - One index must be rebuilt within one run of the Job, and a retry would - otherwise start a rebuild that cannot finish over and over. An - interrupted or failed REINDEX CONCURRENTLY leaves an invalid index with - a _ccnew suffix on the table, so two of those mean two runs already - failed there: the pass then leaves the table's stale indexes alone - until an operator has dropped the leftovers. A rebuild that succeeds - drops them itself. A failed or - skipped rebuild does not stop the others: the pass reports them and - exits non-zero at the end, with the recorded versions of that database - left as they are. - - A collation that a range partition key depends on is never refreshed: - rebuilding an index does not move a row to the partition the new - ordering assigns it, and the version mismatch PostgreSQL keeps logging - is the only lasting sign of that. Its indexes are still rebuilt, and - again only when another collation of the database goes stale. - Before PostgreSQL 15 the server records no version for a database's - default collation. The version recorded for the libc collation of the - same locale stands in for it there, and is refreshed in its place; the - two are matched as glibc matches them, without regard to the case of - the codeset or a hyphen in it. A locale with no such collation cannot - be checked, which a run that saw the image change says in a warning. - - Every session of the pass pins search_path to pg_catalog: the Job - connects as the superuser, and a function or operator a tenant defined - in public would otherwise be picked wherever its argument types match - a call more exactly than the built-in does. - */}} - - echo "== refresh collation versions" - collation_sql() { - cat <<\EOT - SET client_min_messages = error; - SET search_path = pg_catalog, pg_temp; - SELECT current_setting('server_version_num')::int >= 150000 AS tracks_database \gset - \if :tracks_database - SELECT datcollversion IS NOT NULL AS db_versioned, coalesce(pg_database_collation_actual_version(oid), '') AS db_actual, datcollversion IS NOT NULL AND datcollversion IS DISTINCT FROM pg_database_collation_actual_version(oid) AS db_stale, false AS db_unmatched FROM pg_database WHERE datname = current_database() \gset - \else - SELECT d.datcollate NOT IN ('C', 'POSIX') AS db_versioned, - coalesce(max(pg_collation_actual_version(c.oid)), '') AS db_actual, - coalesce(bool_or(c.collversion IS DISTINCT FROM pg_collation_actual_version(c.oid)), false) AS db_stale, - d.datcollate NOT IN ('C', 'POSIX') AND count(c.oid) = 0 AS db_unmatched - FROM pg_database d - LEFT JOIN pg_collation c ON c.collprovider = 'c' AND lower(replace(c.collcollate, '-', '')) = lower(replace(d.datcollate, '-', '')) AND c.collversion IS NOT NULL AND c.collencoding IN (-1, d.encoding) - WHERE d.datname = current_database() - GROUP BY d.datcollate \gset - \endif - CREATE TEMP TABLE cozystack_collation AS - SELECT v.oid, v.actual, v.stale, - EXISTS (SELECT FROM pg_partitioned_table p WHERE p.partstrat = 'r' AND v.oid = ANY (p.partcollation::oid[])) AS held - FROM ( - SELECT c.oid, coalesce(pg_collation_actual_version(c.oid), '') AS actual, c.collversion IS DISTINCT FROM pg_collation_actual_version(c.oid) AS stale - FROM pg_collation c - WHERE c.collversion IS NOT NULL - AND c.collencoding IN (-1, (SELECT encoding FROM pg_database WHERE datname = current_database())) - UNION ALL - SELECT 100, :'db_actual', :'db_stale'::boolean WHERE :'db_versioned'::boolean - ) v; - CREATE TEMP TABLE cozystack_collation_index AS - SELECT i.indexrelid AS index, bool_or(c.stale) AS stale - FROM ( - SELECT x.indexrelid, k.used FROM pg_index x, unnest(x.indcollation::oid[]) AS k(used) - UNION - SELECT d.objid, d.refobjid FROM pg_depend d WHERE d.classid = 'pg_class'::regclass AND d.refclassid = 'pg_collation'::regclass - UNION - SELECT d.objid, a.attcollation FROM pg_depend d JOIN pg_attribute a ON a.attrelid = d.refobjid AND a.attnum = d.refobjsubid - WHERE d.classid = 'pg_class'::regclass AND d.refclassid = 'pg_class'::regclass AND d.refobjsubid > 0 AND a.attcollation <> 0 - ) u - JOIN cozystack_collation c ON c.oid = u.used - JOIN pg_index i ON i.indexrelid = u.indexrelid - JOIN pg_class r ON r.oid = i.indexrelid - WHERE r.relkind = 'i' AND r.relpersistence <> 't' AND i.indisvalid - GROUP BY 1; - EOT - } - collation_run() { - { collation_sql; cat; } | psql -v ON_ERROR_STOP=1 -q -t -A --dbname "$1" -v moved="$IMAGE_MOVED" - } - IMAGE_MOVED=false - pg_release() { - sed -E 's/^([0-9.]+) \(Debian [^)]*(pgdg[0-9]+)\+[0-9]+\)$/\1 \2/' - } - server_release() { - psql -t -A -c 'SHOW server_version' 2>/dev/null | pg_release - } - JOB_RELEASE=$(psql -V | sed 's/^psql (PostgreSQL) //' | pg_release) - COLLATION_DBS=$(psql -v ON_ERROR_STOP=1 -t -A -c "SELECT datname FROM pg_database WHERE datallowconn AND NOT datistemplate") - if [ "$(server_release)" != "$JOB_RELEASE" ]; then - IMAGE_MOVED=true - DEPENDENT="" - for db in $COLLATION_DBS; do - DEPENDENT="$DEPENDENT$(collation_run "$db" <<\EOT - SELECT index FROM cozystack_collation_index; - EOT - )" - done - if [ -n "$DEPENDENT" ]; then - echo "indexes depend on a versioned collation; waiting for the server to run PostgreSQL $JOB_RELEASE" - until [ "$(server_release)" = "$JOB_RELEASE" ]; do - if [ "$SECONDS" -ge $((JOB_DEADLINE - 120)) ]; then - echo "the server did not move to PostgreSQL $JOB_RELEASE in time (check the rollout of the cnpg.io/Cluster); indexes that depend on a versioned collation are not rebuilt yet - failing the init-job, the next run of it rebuilds them" >&2 - exit 1 - fi - sleep 5 - done - fi - fi - COLLATION_FAILED="" - for db in $COLLATION_DBS; do - PLAN=$(collation_run "$db" <<\EOT - SELECT coalesce(md5(string_agg(oid || '=' || actual, ',' ORDER BY oid)), '') AS fingerprint FROM cozystack_collation WHERE stale \gset - SELECT coalesce(current_setting('cozystack.collation_repair', true), '') AS recorded \gset - SELECT :'fingerprint' <> '' AND split_part(:'recorded', ':', 1) = :'fingerprint' AS resumed \gset - \if :resumed - SELECT split_part(:'recorded', ':', 2) AS mark, split_part(:'recorded', ':', 3) AS inplace \gset - \else - SELECT max(oid)::bigint AS mark, '' AS inplace FROM pg_class \gset - SELECT format('ALTER DATABASE %I SET cozystack.collation_repair = %L', current_database(), :'fingerprint' || ':' || :'mark') WHERE :'fingerprint' <> '' \gexec - \endif - SELECT index::bigint FROM cozystack_collation_index WHERE stale AND index::bigint <= :'mark'::bigint AND NOT EXISTS (SELECT FROM unnest(string_to_array(:'inplace', ',')) AS e JOIN pg_class r ON r.oid = index WHERE split_part(e, '/', 1) = index::text AND split_part(e, '/', 2) <> r.relfilenode::text) ORDER BY pg_relation_size(index); - EOT - ) - DB_FAILED="" - for index in $PLAN; do - LEFT=$((JOB_DEADLINE - SECONDS - 60)) - if [ "$LEFT" -lt 10 ]; then - echo "index $index in database $db was not rebuilt: the init-job is out of time, the next run of it carries on" >&2 - DB_FAILED=yes - continue - fi - if ! psql -v ON_ERROR_STOP=1 -q -t -A --dbname "$db" -v index="$index" -v lock_wait="${LEFT}s" <<\EOT - SET client_min_messages = error; - SET search_path = pg_catalog, pg_temp; - SET lock_timeout = :'lock_wait'; - SELECT count(*) = 1 AS present FROM pg_index WHERE indexrelid = :'index'::oid \gset - \if :present - SELECT coalesce(current_setting('cozystack.collation_repair', true), '') AS recorded \gset - SELECT i.indrelid AS relation, i.indisexclusion AS exclusion, i.indexrelid::regclass AS name, :'index' || '/' || r.relfilenode AS attempt, - (SELECT count(*) FROM pg_index l JOIN pg_class n ON n.oid = l.indexrelid WHERE l.indrelid = i.indrelid AND NOT l.indisvalid AND n.relname ~ '_ccnew[0-9]*$') >= 2 AS abandoned, - (SELECT count(*) FROM unnest(string_to_array(split_part(:'recorded', ':', 3), ',')) AS e WHERE e = :'index' || '/' || r.relfilenode) >= 2 AS abandoned_in_place - FROM pg_index i JOIN pg_class r ON r.oid = i.indexrelid WHERE i.indexrelid = :'index'::oid \gset - \if :abandoned - SELECT format('DO %L', format('BEGIN RAISE EXCEPTION %L, %L; END', '%', format('index %s in database %s was left alone: two earlier runs failed to rebuild an index of its table, and each left an invalid _ccnew index there. Fix what made them fail, then drop those _ccnew indexes; the next run of the init-job rebuilds this one', :'name', current_database()))) \gexec - \endif - \if :exclusion - \if :abandoned_in_place - SELECT format('DO %L', format('BEGIN RAISE EXCEPTION %L, %L; END', '%', format('index %s in database %s was left alone: two earlier runs began rebuilding it in place and did not finish. Rebuild it by hand with REINDEX INDEX, which blocks its table meanwhile; the next run of the init-job sees that it was rebuilt', :'name', current_database()))) \gexec - \endif - SELECT format('rebuilding index %s in database %s in place: its collation changed version', :'name', current_database()); - SELECT format('ALTER DATABASE %I SET cozystack.collation_repair = %L', current_database(), split_part(:'recorded', ':', 1) || ':' || split_part(:'recorded', ':', 2) || ':' || concat_ws(',', nullif(split_part(:'recorded', ':', 3), ''), :'attempt')) WHERE :'recorded' <> '' \gexec - SET statement_timeout = :'lock_wait'; - SELECT format('REINDEX INDEX %s', :'name') \gexec - RESET statement_timeout; - \else - SELECT format('rebuilding index %s in database %s: its collation changed version', :'name', current_database()); - SELECT format('REINDEX INDEX CONCURRENTLY %s', :'name') \gexec - \endif - SELECT format('DROP INDEX CONCURRENTLY IF EXISTS %s', l.indexrelid::regclass) FROM pg_index l JOIN pg_class n ON n.oid = l.indexrelid WHERE l.indrelid = :'relation'::oid AND NOT l.indisvalid AND n.relname ~ '_ccnew[0-9]*$' \gexec - \endif - EOT - then - DB_FAILED=yes - fi - done - if [ -n "$DB_FAILED" ]; then - COLLATION_FAILED="$COLLATION_FAILED $db" - else - collation_run "$db" <<\EOT - SELECT format('WARNING: database %s uses the locale %s, for which this PostgreSQL major records no collation version and the catalog has no collation to stand in; the indexes on its default collation were not checked. If this upgrade moved the image to another Debian release, rebuild them with REINDEX DATABASE', datname, datcollate) FROM pg_database WHERE datname = current_database() AND :'db_unmatched'::boolean AND :'moved'::boolean; - SELECT format('WARNING: %s in database %s is range-partitioned on a key whose collation changed version; rows stored before the change may now belong to another partition, and the collation version is left as recorded until that is checked', p.partrelid::regclass, current_database()) FROM pg_partitioned_table p WHERE p.partstrat = 'r' AND EXISTS (SELECT FROM cozystack_collation c WHERE c.stale AND c.oid = ANY (p.partcollation::oid[])); - DO $$ - DECLARE - entry record; - BEGIN - FOR entry IN SELECT c.oid::regcollation AS name FROM cozystack_collation c WHERE c.stale AND NOT c.held AND c.oid <> 100 - AND NOT (current_setting('server_version_num')::int < 150000 - AND EXISTS (SELECT FROM cozystack_collation d WHERE d.oid = 100 AND d.held) - AND c.oid IN (SELECT n.oid FROM pg_collation n JOIN pg_database d ON d.datname = current_database() WHERE n.collprovider = 'c' AND lower(replace(n.collcollate, '-', '')) = lower(replace(d.datcollate, '-', '')))) LOOP - EXECUTE format('ALTER COLLATION %s REFRESH VERSION', entry.name); - END LOOP; - END$$; - SELECT format('ALTER DATABASE %I REFRESH COLLATION VERSION', current_database()) FROM cozystack_collation WHERE oid = 100 AND stale AND NOT held AND current_setting('server_version_num')::int >= 150000 \gexec - SELECT coalesce(md5(string_agg(oid || '=' || actual, ',' ORDER BY oid)), '') AS remaining FROM cozystack_collation WHERE stale AND held \gset - SELECT CASE WHEN :'remaining' = '' THEN '' ELSE :'remaining' || ':0' END AS settled \gset - SELECT CASE WHEN :'settled' = '' THEN format('ALTER DATABASE %I RESET cozystack.collation_repair', current_database()) ELSE format('ALTER DATABASE %I SET cozystack.collation_repair = %L', current_database(), :'settled') END WHERE coalesce(current_setting('cozystack.collation_repair', true), '') <> :'settled' \gexec - EOT - fi - done - if [ -n "$COLLATION_FAILED" ]; then - echo "index rebuilds failed in:$COLLATION_FAILED (the errors are above); the other indexes were rebuilt. A unique index cannot be rebuilt over rows that the previous ordering kept apart and the new one treats as equal, so remove such duplicates. The next run of the init-job tries again, except for an index an error above reports as left alone" >&2 - exit 1 - fi {{- if .Values.bootstrap.newServerName }} echo "== record the adopted restore" diff --git a/packages/apps/postgres/tests/flavor_test.yaml b/packages/apps/postgres/tests/flavor_test.yaml index 80461d143..a5f740da4 100644 --- a/packages/apps/postgres/tests/flavor_test.yaml +++ b/packages/apps/postgres/tests/flavor_test.yaml @@ -1,8 +1,8 @@ suite: postgres image flavor # The Cluster and the init Job must resolve the same image, and a live -# cluster must never be moved to the other flavor: only one image family -# carries the PostGIS libraries, and CNPG would roll the swap out as an -# ordinary image update. Tags are matched by pattern so that +# cluster must never be moved to the other flavor: the two image families +# ship different glibc versions, so CNPG would roll an image swap that +# corrupts collatable indexes. Tags are matched by pattern so that # hack/update-versions.sh can bump minors without touching this suite. release: name: pg-test @@ -20,7 +20,7 @@ tests: asserts: - matchRegex: path: spec.imageName - pattern: ^ghcr\.io/cloudnative-pg/postgresql:18\.[0-9]+-standard-trixie$ + pattern: ^ghcr\.io/cloudnative-pg/postgresql:18\.[0-9]+$ - it: postgis flavor switches the Cluster to the standard-trixie PostGIS image set: