diff --git a/api/apps/v1alpha1/postgresql/types.go b/api/apps/v1alpha1/postgresql/types.go index 70beb678e..3fe67c299 100644 --- a/api/apps/v1alpha1/postgresql/types.go +++ b/api/apps/v1alpha1/postgresql/types.go @@ -43,6 +43,9 @@ type ConfigSpec struct { // PostgreSQL image flavor, fixed when the cluster is created. `postgresql` uses the CloudNativePG PostgreSQL image. `postgis` uses the CloudNativePG PostGIS image, which adds postgis, postgis_raster, postgis_topology, postgis_sfcgal, postgis_tiger_geocoder and address_standardizer; enable them per database in `databases..extensions`. Changing the flavor of an existing cluster is refused, and a backup restores only into a cluster of the flavor it was taken from: to change flavor, create a new cluster and move the data with a logical dump (pg_dump / pg_restore). // +kubebuilder:default:="postgresql" Flavor Flavor `json:"flavor"` + // Allow a cluster created on a Debian bullseye image (before the move to standard-trixie) to move to the new image without a clean locale check. Such a cluster is checked before each upgrade, except while `bootstrap.enabled` is set (set it back to false once a restore set up by hand has finished), and stays on its current image until the check finds nothing that depends on a collation other than C, POSIX or builtin: while this is false, a cluster the check found affected (an ICU or libc locale, or C.UTF-8) or could not finish on stays put, because glibc and ICU on the new image sort text differently and every index on such text must be rebuilt. A held cluster runs the bare bullseye tag it has, gets no further PostgreSQL minors and so none of their security fixes, and refuses a change of `version`, since new majors are built only on the new images. To leave that state, either remove the dependency (move such columns and indexes to C, or to the builtin `pg_c_utf8` on PostgreSQL 17 and later) and let the next upgrade check again, or set this to true in a maintenance window: the cluster moves on the next upgrade, replicas restart on the new image first and can return wrong results through `-ro`, and unique indexes can accept duplicates, until the indexes are rebuilt on the primary. The 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. // +kubebuilder:default:={} Tls TLS `json:"tls"` @@ -151,6 +154,9 @@ type Bootstrap struct { // Server name (S3 path prefix) used by the original cluster when writing backups; passed to the barman-cloud plugin via `externalClusters[].plugin.parameters.serverName`. Defaults to `bootstrap.oldName`. Set this only when the original cluster wrote backups under an explicit server name that differed from its Kubernetes resource name. // +kubebuilder:default:="" ServerName string `json:"serverName,omitempty"` + // Image of the cluster the backup was taken from. A restore of a backup taken on one of the bare Debian bullseye tags the chart used before standard-trixie comes back on that image (see `allowCollationChange`); any other value is ignored. The CNPG backup driver sets this on restore and clears it with `enabled`. + // +kubebuilder:default:="" + SourceImageName string `json:"sourceImageName,omitempty"` } type Database struct { diff --git a/api/v1alpha1/workloadmonitor_types.go b/api/v1alpha1/workloadmonitor_types.go index b5089652a..0ffc33e7a 100644 --- a/api/v1alpha1/workloadmonitor_types.go +++ b/api/v1alpha1/workloadmonitor_types.go @@ -43,6 +43,17 @@ const WorkloadMonitorReasonDataVolumeNotReady = "DataVolumeNotReady" // that is not operational because a BucketClaim it selects is not provisioned. const WorkloadMonitorReasonBucketClaimNotReady = "BucketClaimNotReady" +// WorkloadMonitorReasonJobFailed is the status Reason of a monitor that is not +// operational because a Job it selects, opted in with +// WorkloadMonitorReportFailureLabel, has failed. +const WorkloadMonitorReasonJobFailed = "JobFailed" + +// WorkloadMonitorReportFailureLabel set to "true" on a Job that also carries a +// monitor's selector labels makes a failure of that Job a failure of the +// workload. Other Jobs, such as those an operator labels by inheritance from +// the workload, never affect the monitor. +const WorkloadMonitorReportFailureLabel = "workloads.cozystack.io/report-failure" + // WorkloadMonitorStatus defines the observed state of WorkloadMonitor type WorkloadMonitorStatus struct { // Operational indicates if the workload meets all operational requirements diff --git a/cmd/cozystack-controller/main.go b/cmd/cozystack-controller/main.go index 59ba3b515..7cac159ae 100644 --- a/cmd/cozystack-controller/main.go +++ b/cmd/cozystack-controller/main.go @@ -26,6 +26,7 @@ import ( // to ensure that exec-entrypoint and run can make use of them. _ "k8s.io/client-go/plugin/pkg/client/auth" + batchv1 "k8s.io/api/batch/v1" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/runtime" utilruntime "k8s.io/apimachinery/pkg/util/runtime" @@ -216,6 +217,7 @@ func main() { Cache: cache.Options{ ByObject: map[client.Object]cache.ByObject{ &corev1.Secret{}: wildcardsecret.SecretCacheByObject(), + &batchv1.Job{}: controller.JobCacheByObject(), }, }, // LeaderElectionReleaseOnCancel defines if the leader should step down voluntarily diff --git a/hack/e2e-chainsaw/postgres/chainsaw-test.yaml b/hack/e2e-chainsaw/postgres/chainsaw-test.yaml index bc0bc1c98..4aaf6f117 100644 --- a/hack/e2e-chainsaw/postgres/chainsaw-test.yaml +++ b/hack/e2e-chainsaw/postgres/chainsaw-test.yaml @@ -249,6 +249,230 @@ spec: fi check: ($error == null): true + + # 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 + # 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: + 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_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, + '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 + # 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: + 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" + # 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: | + 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 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 collation repair 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 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 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 collation repair 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 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 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 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") + 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 + - delete: + ref: + apiVersion: batch/v1 + kind: Job + name: postgres-test-collation-repair # The Postgres CR itself was applied by chainsaw and is deleted (and waited # on) automatically during cleanup — no explicit teardown step needed. --- diff --git a/internal/backupcontroller/cnpg_source_image_test.go b/internal/backupcontroller/cnpg_source_image_test.go new file mode 100644 index 000000000..7c4128f2b --- /dev/null +++ b/internal/backupcontroller/cnpg_source_image_test.go @@ -0,0 +1,103 @@ +package backupcontroller + +import ( + "context" + "testing" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/client-go/kubernetes/scheme" + clientfake "sigs.k8s.io/controller-runtime/pkg/client/fake" + + strategyv1alpha1 "github.com/cozystack/cozystack/api/backups/strategy/v1alpha1" + backupsv1alpha1 "github.com/cozystack/cozystack/api/backups/v1alpha1" + cnpgtypes "github.com/cozystack/cozystack/internal/backupcontroller/cnpgtypes" + "github.com/cozystack/cozystack/internal/backupcontroller/postgresapp" +) + +func TestApplyClusterPluginBackup_RecordsImageName(t *testing.T) { + for _, image := range []string{"ghcr.io/cloudnative-pg/postgresql:17.7", "ghcr.io/cloudnative-pg/postgresql:17.12-standard-trixie"} { + t.Run(image, func(t *testing.T) { + cluster := &cnpgtypes.Cluster{ + ObjectMeta: metav1.ObjectMeta{Namespace: "tenant", Name: "postgres-app", UID: "cluster-uid-123"}, + } + cluster.Spec.ImageName = image + c := newCNPGStrategyTestClient(t, cluster) + r := &BackupJobReconciler{Client: c, Interface: cnpgDynamicFor(t, cluster)} + tmpl := &strategyv1alpha1.CNPGTemplate{ + BarmanObjectStore: strategyv1alpha1.BarmanObjectStoreTemplate{DestinationPath: "s3://bucket/x/"}, + } + + got, err := r.applyClusterPluginBackup(context.Background(), "tenant", "postgres-app", tmpl, "strategy-name", true) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if got.imageName != image { + t.Fatalf("imageName = %q, want %q", got.imageName, image) + } + }) + } +} + +func TestCNPGBackupSnapshot_CarriesImageName(t *testing.T) { + raw, err := marshalCNPGBackupSnapshot(newPostgresApp("pg", "tenant"), nil, "postgresql", "ghcr.io/cloudnative-pg/postgresql:17.7") + if err != nil { + t.Fatalf("marshal snapshot: %v", err) + } + snap, err := unmarshalCNPGBackupSnapshot(&backupsv1alpha1.Backup{Status: backupsv1alpha1.BackupStatus{UnderlyingResources: raw}}) + if err != nil { + t.Fatalf("unmarshal snapshot: %v", err) + } + if snap.ImageName != "ghcr.io/cloudnative-pg/postgresql:17.7" { + t.Fatalf("ImageName = %q", snap.ImageName) + } +} + +func TestBuildPostgresAppRestorePatch_SetsAndClearsSourceImage(t *testing.T) { + app := newPostgresApp("pg", "tenant") + app.Spec.Bootstrap.SourceImageName = "ghcr.io/cloudnative-pg/postgresql:16.11" + + if got := buildPostgresAppRestorePatch(app, "src", "pg-new", "s3://b/", "", "", "", nil, nil, nil, nil, "ghcr.io/cloudnative-pg/postgresql:17.7").Spec.Bootstrap.SourceImageName; got != "ghcr.io/cloudnative-pg/postgresql:17.7" { + t.Errorf("bootstrap.sourceImageName: got %q", got) + } + if got := buildPostgresAppRestorePatch(app, "src", "pg-new", "s3://b/", "", "", "", nil, nil, nil, nil, "").Spec.Bootstrap.SourceImageName; got != "" { + t.Errorf("bootstrap.sourceImageName from a previous restore must be cleared; got %q", got) + } +} + +func TestDisablePostgresAppBootstrap_ClearsSourceImage(t *testing.T) { + app := newPostgresApp("pg", "tenant") + app.Spec.Bootstrap.Enabled = true + app.Spec.Bootstrap.SourceImageName = "ghcr.io/cloudnative-pg/postgresql:17.7" + s := runtime.NewScheme() + _ = scheme.AddToScheme(s) + _ = postgresapp.AddToScheme(s) + r := &RestoreJobReconciler{Client: clientfake.NewClientBuilder().WithScheme(s).WithObjects(app).Build()} + + if err := r.disablePostgresAppBootstrap(context.Background(), "tenant", "pg"); err != nil { + t.Fatalf("disable bootstrap: %v", err) + } + got, err := r.getPostgresApp(context.Background(), "tenant", "pg") + if err != nil { + t.Fatalf("get app: %v", err) + } + if got.Spec.Bootstrap.Enabled || got.Spec.Bootstrap.SourceImageName != "" { + t.Fatalf("bootstrap after disable: enabled=%v sourceImageName=%q", got.Spec.Bootstrap.Enabled, got.Spec.Bootstrap.SourceImageName) + } +} + +func TestCNPGImageMajor(t *testing.T) { + for image, want := range map[string]int{ + "ghcr.io/cloudnative-pg/postgresql:17.7": 17, + "ghcr.io/cloudnative-pg/postgresql:13.22": 13, + "ghcr.io/cloudnative-pg/postgresql:17.12-standard-trixie": 17, + "ghcr.io/cloudnative-pg/postgis:17-3.6.1-standard-trixie": 17, + "ghcr.io/cloudnative-pg/postgresql:18.1@sha256:0123": 18, + "ghcr.io/cloudnative-pg/postgresql": 0, + "": 0, + } { + if got := cnpgImageMajor(image); got != want { + t.Errorf("cnpgImageMajor(%q) = %d, want %d", image, got, want) + } + } +} diff --git a/internal/backupcontroller/cnpgstrategy_controller.go b/internal/backupcontroller/cnpgstrategy_controller.go index 31e8fddfd..0c02efcd3 100644 --- a/internal/backupcontroller/cnpgstrategy_controller.go +++ b/internal/backupcontroller/cnpgstrategy_controller.go @@ -431,7 +431,7 @@ func (r *BackupJobReconciler) reconcileCNPG(ctx context.Context, j *backupsv1alp if j.Status.BackupRef != nil { return ctrl.Result{}, nil } - artifact, err := r.createCNPGBackupArtifact(ctx, j, resolved, cnpgBackup, clusterName, serverName, attachment.flavor, rendered, app) + artifact, err := r.createCNPGBackupArtifact(ctx, j, resolved, cnpgBackup, clusterName, serverName, attachment.flavor, attachment.imageName, rendered, app) if err != nil { return r.markBackupJobFailed(ctx, j, fmt.Sprintf("failed to create Backup artifact: %v", err)) } @@ -616,6 +616,7 @@ func (r *BackupJobReconciler) applyClusterPluginBackup(ctx context.Context, name attachment := cnpgPluginAttachment{ serverName: serverName, flavor: cnpgImageFlavor(existing.Spec.ImageName), + imageName: existing.Spec.ImageName, clusterStatus: existing.Status, } if live := currentBarmanServerName(existing); live != "" { @@ -672,6 +673,9 @@ type cnpgPluginAttachment struct { serverName string // flavor is the image flavor the live Cluster runs. flavor string + // imageName is the live Cluster's spec.imageName, see + // cnpgBackupSnapshot.ImageName. + imageName string // missing reports a Cluster that carried no barman-cloud plugin. missing bool clusterStatus cnpgtypes.ClusterStatus @@ -811,7 +815,7 @@ func (r *BackupJobReconciler) createCNPGBackupArtifact( j *backupsv1alpha1.BackupJob, resolved *ResolvedBackupConfig, cnpgBackup *cnpgtypes.Backup, - clusterName, serverName, flavor string, + clusterName, serverName, flavor, imageName string, rendered *strategyv1alpha1.CNPGTemplate, sourceApp *postgresapp.Postgres, ) (*backupsv1alpha1.Backup, error) { @@ -836,7 +840,7 @@ func (r *BackupJobReconciler) createCNPGBackupArtifact( driverMD[cnpgMajorVersionKey] = strconv.Itoa(cnpgBackup.Status.MajorVersion) } - underlyingResources, err := marshalCNPGBackupSnapshot(sourceApp, resolved.Parameters, flavor) + underlyingResources, err := marshalCNPGBackupSnapshot(sourceApp, resolved.Parameters, flavor, imageName) if err != nil { return nil, fmt.Errorf("encode source snapshot for Backup.status.underlyingResources: %w", err) } @@ -1050,6 +1054,12 @@ func (r *RestoreJobReconciler) reconcileCNPGRestore(ctx context.Context, restore if err != nil { return ctrl.Result{}, err } + if backupMajor == 0 { + // The chart restores a backup taken on a held bullseye image onto + // that image and refuses one of another major than spec.version, + // which would wedge the restore after the purge. + backupMajor = cnpgImageMajor(snapshot.ImageName) + } targetMajor := postgresAppMajorVersion(targetApp.Spec.Version) switch { case backupMajor == 0 || targetMajor == 0: @@ -1158,7 +1168,7 @@ func (r *RestoreJobReconciler) reconcileCNPGRestore(ctx context.Context, restore logger.Info("restored WAL-archive serverName collided with the recovery source", "cluster", clusterName, "serverName", newServerName) } - if err := r.patchPostgresAppForRestore(ctx, targetApp, sourceServerName, newServerName, sourceDestinationPath, sourceEndpointURL, options.RecoveryTime, backupID, rendered.BarmanObjectStore.S3Credentials, rendered.BarmanObjectStore.EndpointCA, sourceDatabases, sourceUsers); err != nil { + if err := r.patchPostgresAppForRestore(ctx, targetApp, sourceServerName, newServerName, sourceDestinationPath, sourceEndpointURL, options.RecoveryTime, backupID, rendered.BarmanObjectStore.S3Credentials, rendered.BarmanObjectStore.EndpointCA, sourceDatabases, sourceUsers, snapshot.ImageName); err != nil { // Resume HR before terminal failure so an operator deleting // the failed RestoreJob does not leave the HR stuck. _ = r.setCNPGRestoreHRSuspended(ctx, target.Namespace, hrName, false) @@ -1469,8 +1479,9 @@ func (r *RestoreJobReconciler) patchPostgresAppForRestore( caRef *strategyv1alpha1.EndpointCARef, sourceDatabases map[string]postgresapp.Database, sourceUsers map[string]postgresapp.User, + sourceImageName string, ) error { - patched := buildPostgresAppRestorePatch(app, sourceServerName, newServerName, sourceDestinationPath, sourceEndpointURL, recoveryTime, backupID, credsRef, caRef, sourceDatabases, sourceUsers) + patched := buildPostgresAppRestorePatch(app, sourceServerName, newServerName, sourceDestinationPath, sourceEndpointURL, recoveryTime, backupID, credsRef, caRef, sourceDatabases, sourceUsers, sourceImageName) return r.Patch(ctx, patched, client.MergeFrom(app), client.FieldOwner(cnpgFieldManager)) } @@ -1497,6 +1508,9 @@ func (r *RestoreJobReconciler) disablePostgresAppBootstrap(ctx context.Context, } patched := app.DeepCopy() patched.Spec.Bootstrap.Enabled = false + // The restored Cluster runs that image from here on; left in the spec, the + // value would outlive the Cluster's own image once it moves. + patched.Spec.Bootstrap.SourceImageName = "" return r.Patch(ctx, patched, client.MergeFrom(app), client.FieldOwner(cnpgFieldManager)) } @@ -1531,6 +1545,7 @@ func buildPostgresAppRestorePatch( caRef *strategyv1alpha1.EndpointCARef, sourceDatabases map[string]postgresapp.Database, sourceUsers map[string]postgresapp.User, + sourceImageName string, ) *postgresapp.Postgres { patched := app.DeepCopy() patched.Spec.Bootstrap.Enabled = true @@ -1541,6 +1556,9 @@ func buildPostgresAppRestorePatch( patched.Spec.Bootstrap.NewServerName = newServerName patched.Spec.Bootstrap.RecoveryTime = recoveryTime patched.Spec.Bootstrap.BackupID = backupID + // Set or cleared on every restore: a value left by an earlier restore of + // another backup would name an image this one was not taken on. + patched.Spec.Bootstrap.SourceImageName = sourceImageName patched.Spec.Backup.DestinationPath = sourceDestinationPath patched.Spec.Backup.EndpointURL = sourceEndpointURL @@ -1608,6 +1626,10 @@ func buildPostgresAppRestorePatch( // safely onto the same family: the two ship different glibc versions, which // invalidates collatable indexes, and postgis objects need the postgis // libraries. +// +// ImageName is the source Cluster's spec.imageName, handed to the chart on +// restore as bootstrap.sourceImageName: the chart decides whether recovered +// data has to stay on the image that built it. type cnpgBackupSnapshot struct { Kind string `json:"kind"` APIVersion string `json:"apiVersion"` @@ -1615,6 +1637,31 @@ type cnpgBackupSnapshot struct { Users map[string]postgresapp.User `json:"users,omitempty"` Parameters map[string]string `json:"parameters,omitempty"` Flavor string `json:"flavor,omitempty"` + ImageName string `json:"imageName,omitempty"` +} + +// cnpgImageMajor reads the PostgreSQL major from a CloudNativePG operand +// image, whose tags all start with it (17.7, 17.12-standard-trixie, +// 17-3.6.1-standard-trixie); 0 when the tag does not. +func cnpgImageMajor(image string) int { + name := image[strings.LastIndex(image, "/")+1:] + if i := strings.Index(name, "@"); i >= 0 { + name = name[:i] + } + i := strings.Index(name, ":") + if i < 0 { + return 0 + } + tag := name[i+1:] + end := strings.IndexFunc(tag, func(r rune) bool { return r < '0' || r > '9' }) + if end < 0 { + end = len(tag) + } + major, err := strconv.Atoi(tag[:end]) + if err != nil { + return 0 + } + return major } const cnpgBackupSnapshotKind = "CNPGBackupSnapshot" @@ -1629,7 +1676,7 @@ var cnpgBackupSnapshotAPIVersion = backupsv1alpha1.GroupVersion.String() // runtime.RawExtension suitable for Backup.Status.UnderlyingResources. // flavor is the live Cluster's, not app.Spec.Flavor: the chart refuses a // flavor change, but the app keeps the refused value. -func marshalCNPGBackupSnapshot(app *postgresapp.Postgres, parameters map[string]string, flavor string) (*runtime.RawExtension, error) { +func marshalCNPGBackupSnapshot(app *postgresapp.Postgres, parameters map[string]string, flavor, imageName string) (*runtime.RawExtension, error) { if app == nil { return nil, nil } @@ -1640,6 +1687,7 @@ func marshalCNPGBackupSnapshot(app *postgresapp.Postgres, parameters map[string] Users: app.Spec.Users, Parameters: parameters, Flavor: flavor, + ImageName: imageName, } raw, err := json.Marshal(snap) if err != nil { diff --git a/internal/backupcontroller/cnpgstrategy_controller_test.go b/internal/backupcontroller/cnpgstrategy_controller_test.go index bc2827371..907acfe80 100644 --- a/internal/backupcontroller/cnpgstrategy_controller_test.go +++ b/internal/backupcontroller/cnpgstrategy_controller_test.go @@ -225,7 +225,7 @@ func TestRenderCNPGTemplate_RoundTripsParametersThroughSnapshot(t *testing.T) { } // Round-trip parameters through Backup.status.underlyingResources. - raw, err := marshalCNPGBackupSnapshot(app, parameters, "") + raw, err := marshalCNPGBackupSnapshot(app, parameters, "", "") if err != nil { t.Fatalf("marshal snapshot: %v", err) } @@ -530,6 +530,7 @@ func TestBuildPostgresAppRestorePatch_ForwardsSecretRef_NotCleartext(t *testing. creds, nil, nil, nil, + "", ) if got := patched.Spec.Backup.S3CredentialsSecret.Name; got != "pg-target-cnpg-backup-creds" { @@ -557,7 +558,7 @@ func TestBuildPostgresAppRestorePatch_ForwardsCustomKeyOverrides(t *testing.T) { SecretAccessKeyKey: "SECRET_KEY", } - patched := buildPostgresAppRestorePatch(app, "src", "pg-new", "s3://b/", "", "", "", creds, nil, nil, nil) + patched := buildPostgresAppRestorePatch(app, "src", "pg-new", "s3://b/", "", "", "", creds, nil, nil, nil, "") want := postgresapp.S3CredentialsSecret{ Name: "creds", @@ -575,7 +576,7 @@ func TestBuildPostgresAppRestorePatch_ForwardsCustomKeyOverrides(t *testing.T) { // Secret name and helm install would fail. func TestBuildPostgresAppRestorePatch_NoSecretRefIsSkipped(t *testing.T) { app := newPostgresApp("pg", "tenant") - patched := buildPostgresAppRestorePatch(app, "src", "pg-new", "s3://b/", "", "", "", nil, nil, nil, nil) + patched := buildPostgresAppRestorePatch(app, "src", "pg-new", "s3://b/", "", "", "", nil, nil, nil, nil, "") if got := patched.Spec.Backup.S3CredentialsSecret; got != (postgresapp.S3CredentialsSecret{}) { t.Errorf("spec.backup.s3CredentialsSecret must be zero when credsRef is nil; got %#v", got) } @@ -773,7 +774,7 @@ func TestBuildPostgresAppRestorePatch_ReplacesTargetUsersAndDatabases(t *testing "appdb": {Extensions: []string{"hstore"}}, } - patched := buildPostgresAppRestorePatch(app, "src", "pg-new", "s3://b/", "", "", "", nil, nil, sourceDatabases, sourceUsers) + patched := buildPostgresAppRestorePatch(app, "src", "pg-new", "s3://b/", "", "", "", nil, nil, sourceDatabases, sourceUsers, "") if _, ok := patched.Spec.Users["stale-target-user"]; ok { t.Errorf("stale target user survived restore; replace semantics regressed") @@ -810,7 +811,7 @@ func TestBuildPostgresAppRestorePatch_ScrubsStaleBackupSettings(t *testing.T) { // Restore with no recoveryTime, no endpointURL, no creds, no CA - // everything stale on the target must be wiped. - patched := buildPostgresAppRestorePatch(app, "src", "pg-new", "s3://b/", "", "", "", nil, nil, nil, nil) + patched := buildPostgresAppRestorePatch(app, "src", "pg-new", "s3://b/", "", "", "", nil, nil, nil, nil, "") if got := patched.Spec.Bootstrap.RecoveryTime; got != "" { t.Errorf("stale recoveryTime survived; got %q", got) @@ -849,7 +850,7 @@ func TestBuildPostgresAppRestorePatch_ForwardsEndpointCA(t *testing.T) { SecretRef: corev1.LocalObjectReference{Name: "pg-cnpg-backup-ca"}, Key: "ca.crt", } - patched := buildPostgresAppRestorePatch(app, "src", "pg-new", "s3://b/", "", "", "", nil, caRef, nil, nil) + patched := buildPostgresAppRestorePatch(app, "src", "pg-new", "s3://b/", "", "", "", nil, caRef, nil, nil, "") want := postgresapp.EndpointCA{Name: "pg-cnpg-backup-ca", Key: "ca.crt"} if got := patched.Spec.Backup.EndpointCA; got != want { @@ -865,7 +866,7 @@ func TestBuildPostgresAppRestorePatch_ArchiveServerNameDiffersFromSource(t *test // An in-place restore is the worst case: source serverName equals the // target cluster's own name. const source = "postgres-pg" - patched := buildPostgresAppRestorePatch(app, source, "postgres-pg-restore-deadbeef", "s3://b/", "", "", "", nil, nil, nil, nil) + patched := buildPostgresAppRestorePatch(app, source, "postgres-pg-restore-deadbeef", "s3://b/", "", "", "", nil, nil, nil, nil, "") if got := patched.Spec.Bootstrap.ServerName; got != source { t.Errorf("recovery serverName must stay the source; got %q want %q", got, source) @@ -920,7 +921,7 @@ func TestMarshalUnmarshalCNPGBackupSnapshot(t *testing.T) { "region": "eu-west-1", } - raw, err := marshalCNPGBackupSnapshot(src, parameters, "") + raw, err := marshalCNPGBackupSnapshot(src, parameters, "", "") if err != nil { t.Fatalf("marshal: %v", err) } @@ -1073,7 +1074,7 @@ func TestCreateCNPGBackupArtifact_AlreadyExistsReturnsExisting(t *testing.T) { } sourceApp := newPostgresApp("pg", "tenant") - got, err := r.createCNPGBackupArtifact(context.Background(), j, resolved, cnpgBk, "postgres-pg", "postgres-pg", "postgresql", rendered, sourceApp) + got, err := r.createCNPGBackupArtifact(context.Background(), j, resolved, cnpgBk, "postgres-pg", "postgres-pg", "postgresql", "", rendered, sourceApp) if err != nil { t.Fatalf("expected AlreadyExists to be swallowed, got error %v", err) } @@ -2835,7 +2836,7 @@ func TestReconcileCNPGRestore_RepeatInPlacePurgesStaleRecoveryCluster(t *testing mkBackupArtifact := func(t *testing.T) *backupsv1alpha1.Backup { t.Helper() - snap, err := marshalCNPGBackupSnapshot(newPostgresApp(appName, ns), nil, "") + snap, err := marshalCNPGBackupSnapshot(newPostgresApp(appName, ns), nil, "", "") if err != nil { t.Fatalf("marshal snapshot: %v", err) } @@ -3097,16 +3098,20 @@ func TestReconcileCNPGRestore_RefusesCrossFlavorRestore(t *testing.T) { name string sourceFlavor string targetFlavor string + targetVersion string + sourceImage string wantFailed bool wantInMessage string }{ {name: "postgis backup into a postgresql app", sourceFlavor: "postgis", targetFlavor: "", wantFailed: true, wantInMessage: "taken from a postgis cluster"}, + {name: "backup hands its source image to the app", sourceImage: "ghcr.io/cloudnative-pg/postgresql:17.7", wantFailed: false}, + {name: "bullseye backup into another major", sourceImage: "ghcr.io/cloudnative-pg/postgresql:17.7", targetVersion: "v18", wantFailed: true, wantInMessage: "taken on PostgreSQL 17"}, {name: "pre-flavor backup into a postgis app", sourceFlavor: "", targetFlavor: "postgis", wantFailed: true, wantInMessage: "taken from a postgresql cluster"}, {name: "postgis backup into a postgis app", sourceFlavor: "postgis", targetFlavor: "postgis", wantFailed: false}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { - snap, err := marshalCNPGBackupSnapshot(newPostgresApp(appName, ns), nil, tc.sourceFlavor) + snap, err := marshalCNPGBackupSnapshot(newPostgresApp(appName, ns), nil, tc.sourceFlavor, tc.sourceImage) if err != nil { t.Fatalf("marshal snapshot: %v", err) } @@ -3125,6 +3130,7 @@ func TestReconcileCNPGRestore_RefusesCrossFlavorRestore(t *testing.T) { } target := newPostgresApp(appName, ns) target.Spec.Flavor = tc.targetFlavor + target.Spec.Version = tc.targetVersion sa := startedAt restoreJob := &backupsv1alpha1.RestoreJob{ ObjectMeta: metav1.ObjectMeta{Namespace: ns, Name: "rj"}, @@ -3165,12 +3171,15 @@ func TestReconcileCNPGRestore_RefusesCrossFlavorRestore(t *testing.T) { if !apierrors.IsNotFound(clusterErr) { t.Fatalf("same-flavor restore must purge the target Cluster, got err=%v", clusterErr) } + if app.Spec.Bootstrap.SourceImageName != tc.sourceImage { + t.Fatalf("bootstrap.sourceImageName = %q, want %q", app.Spec.Bootstrap.SourceImageName, tc.sourceImage) + } return } if got.Status.Phase != backupsv1alpha1.RestoreJobPhaseFailed { t.Fatalf("cross-flavor restore must fail, got phase %q", got.Status.Phase) } - if !strings.Contains(got.Status.Message, tc.wantInMessage) || !strings.Contains(got.Status.Message, "pg_dump") { + if !strings.Contains(got.Status.Message, tc.wantInMessage) || (tc.targetVersion == "" && !strings.Contains(got.Status.Message, "pg_dump")) { t.Errorf("failure message must name the source flavor and point to a logical dump, got %q", got.Status.Message) } if clusterErr != nil { @@ -3206,7 +3215,7 @@ func TestReconcileCNPGRestore_HealthyClusterSucceeds(t *testing.T) { ctx := context.Background() startedAt := metav1.NewTime(time.Now()) - snap, err := marshalCNPGBackupSnapshot(newPostgresApp(appName, ns), nil, "") + snap, err := marshalCNPGBackupSnapshot(newPostgresApp(appName, ns), nil, "", "") if err != nil { t.Fatalf("marshal snapshot: %v", err) } @@ -3325,7 +3334,7 @@ func TestReconcileCNPGRestore_HealthyDisablesBootstrap(t *testing.T) { ctx := context.Background() startedAt := metav1.NewTime(time.Now().Add(-time.Hour)) - snap, err := marshalCNPGBackupSnapshot(newPostgresApp(appName, ns), nil, "") + snap, err := marshalCNPGBackupSnapshot(newPostgresApp(appName, ns), nil, "", "") if err != nil { t.Fatalf("marshal snapshot: %v", err) } @@ -3414,7 +3423,7 @@ func TestReconcileCNPGRestore_BootstrapDisableFailsPastDeadline(t *testing.T) { // Well past the 30m default deadline. startedAt := metav1.NewTime(time.Now().Add(-72 * time.Hour)) - snap, err := marshalCNPGBackupSnapshot(newPostgresApp(appName, ns), nil, "") + snap, err := marshalCNPGBackupSnapshot(newPostgresApp(appName, ns), nil, "", "") if err != nil { t.Fatalf("marshal snapshot: %v", err) } @@ -3527,7 +3536,7 @@ func TestReconcileCNPGRestore_BootstrapDisableTransientErrorRequeues(t *testing. startedAt := metav1.NewTime(time.Now().Add(-72 * time.Hour)) convergedAt := metav1.Now() - snap, err := marshalCNPGBackupSnapshot(newPostgresApp(appName, ns), nil, "") + snap, err := marshalCNPGBackupSnapshot(newPostgresApp(appName, ns), nil, "", "") if err != nil { t.Fatalf("marshal snapshot: %v", err) } @@ -3654,7 +3663,7 @@ func TestReconcileCNPGRestore_BootstrapDisableShortTimeoutHonorsGraceFloor(t *te // within the 5m post-convergence floor. convergedAt := metav1.NewTime(time.Now().Add(-90 * time.Second)) - snap, err := marshalCNPGBackupSnapshot(newPostgresApp(appName, ns), nil, "") + snap, err := marshalCNPGBackupSnapshot(newPostgresApp(appName, ns), nil, "", "") if err != nil { t.Fatalf("marshal snapshot: %v", err) } @@ -3766,7 +3775,7 @@ func TestReconcileCNPGRestore_HealthyPastDeadlineSucceeds(t *testing.T) { // Far past the 30m default deadline: this is the reconcile-gap case. startedAt := metav1.NewTime(time.Now().Add(-72 * time.Hour)) - snap, err := marshalCNPGBackupSnapshot(newPostgresApp(appName, ns), nil, "") + snap, err := marshalCNPGBackupSnapshot(newPostgresApp(appName, ns), nil, "", "") if err != nil { t.Fatalf("marshal snapshot: %v", err) } @@ -3862,7 +3871,7 @@ func TestReconcileCNPGRestore_DeadlineClassifiesRecoveryTargetUnreachable(t *tes // enters the deadline-classification branch. startedAt := metav1.NewTime(time.Now().Add(-72 * time.Hour)) - snap, err := marshalCNPGBackupSnapshot(newPostgresApp(appName, ns), nil, "") + snap, err := marshalCNPGBackupSnapshot(newPostgresApp(appName, ns), nil, "", "") if err != nil { t.Fatalf("marshal snapshot: %v", err) } @@ -4171,10 +4180,10 @@ func TestBuildPostgresAppRestorePatch_ReplacesBackupID(t *testing.T) { app := newPostgresApp("pg", "tenant") app.Spec.Bootstrap.BackupID = "20260101T000000" - if got := buildPostgresAppRestorePatch(app, "src", "pg-new", "s3://b/", "", "", "20260921T062713", nil, nil, nil, nil).Spec.Bootstrap.BackupID; got != "20260921T062713" { + if got := buildPostgresAppRestorePatch(app, "src", "pg-new", "s3://b/", "", "", "20260921T062713", nil, nil, nil, nil, "").Spec.Bootstrap.BackupID; got != "20260921T062713" { t.Errorf("bootstrap.backupID: got %q want %q", got, "20260921T062713") } - if got := buildPostgresAppRestorePatch(app, "src", "pg-new", "s3://b/", "", "", "", nil, nil, nil, nil).Spec.Bootstrap.BackupID; got != "" { + if got := buildPostgresAppRestorePatch(app, "src", "pg-new", "s3://b/", "", "", "", nil, nil, nil, nil, "").Spec.Bootstrap.BackupID; got != "" { t.Errorf("bootstrap.backupID from a previous restore must be cleared; got %q", got) } } @@ -4201,7 +4210,7 @@ func TestReconcileCNPGRestore_PinsTheRequestedBackup(t *testing.T) { mkBackupArtifact := func(t *testing.T) *backupsv1alpha1.Backup { t.Helper() - snap, err := marshalCNPGBackupSnapshot(newPostgresApp(appName, ns), nil, "") + snap, err := marshalCNPGBackupSnapshot(newPostgresApp(appName, ns), nil, "", "") if err != nil { t.Fatalf("marshal snapshot: %v", err) } @@ -4339,7 +4348,7 @@ func TestCreateCNPGBackupArtifact_RecordsMajorVersion(t *testing.T) { rendered := &strategyv1alpha1.CNPGTemplate{ BarmanObjectStore: strategyv1alpha1.BarmanObjectStoreTemplate{DestinationPath: "s3://b/"}, } - got, err := r.createCNPGBackupArtifact(context.Background(), j, resolved, cnpgBk, "postgres-pg", "postgres-pg", "postgresql", rendered, newPostgresApp("pg", "tenant")) + got, err := r.createCNPGBackupArtifact(context.Background(), j, resolved, cnpgBk, "postgres-pg", "postgres-pg", "postgresql", "", rendered, newPostgresApp("pg", "tenant")) if err != nil { t.Fatalf("createCNPGBackupArtifact: %v", err) } @@ -4402,7 +4411,7 @@ func TestReconcileCNPGRestore_RefusesCrossMajorRestore(t *testing.T) { } targetCluster := cnpgClusterNameForApp(targetApp) - snap, err := marshalCNPGBackupSnapshot(newPostgresApp(sourceApp, ns), nil, "") + snap, err := marshalCNPGBackupSnapshot(newPostgresApp(sourceApp, ns), nil, "", "") if err != nil { t.Fatalf("marshal snapshot: %v", err) } diff --git a/internal/backupcontroller/postgresapp/types.go b/internal/backupcontroller/postgresapp/types.go index 914f522fa..9de1b7ac1 100644 --- a/internal/backupcontroller/postgresapp/types.go +++ b/internal/backupcontroller/postgresapp/types.go @@ -81,12 +81,13 @@ type Bootstrap struct { // recovery converges, and a bool+omitempty would drop false from the patch // (it deletes the key instead), leaving the server to fall back to a default // rather than being explicitly cleared. Same rule as Backup.UseSystemBucket. - Enabled bool `json:"enabled"` - OldName string `json:"oldName,omitempty"` - ServerName string `json:"serverName,omitempty"` - NewServerName string `json:"newServerName,omitempty"` - RecoveryTime string `json:"recoveryTime,omitempty"` - BackupID string `json:"backupID,omitempty"` + Enabled bool `json:"enabled"` + OldName string `json:"oldName,omitempty"` + ServerName string `json:"serverName,omitempty"` + NewServerName string `json:"newServerName,omitempty"` + RecoveryTime string `json:"recoveryTime,omitempty"` + BackupID string `json:"backupID,omitempty"` + SourceImageName string `json:"sourceImageName,omitempty"` } type Backup struct { diff --git a/internal/controller/workloadmonitor_controller.go b/internal/controller/workloadmonitor_controller.go index 53677a544..d0daf47f6 100644 --- a/internal/controller/workloadmonitor_controller.go +++ b/internal/controller/workloadmonitor_controller.go @@ -19,6 +19,7 @@ import ( apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/api/meta" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/types" @@ -38,6 +39,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/reconcile" "sigs.k8s.io/controller-runtime/pkg/source" + batchv1 "k8s.io/api/batch/v1" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -368,6 +370,7 @@ func (r *WorkloadMonitorReconciler) dataVolumesMessage(ctx context.Context, moni // +kubebuilder:rbac:groups=core,resources=events,verbs=create;patch // +kubebuilder:rbac:groups=objectstorage.k8s.io,resources=bucketclaims,verbs=get;list;watch // +kubebuilder:rbac:groups=cdi.kubevirt.io,resources=datavolumes,verbs=get;list;watch +// +kubebuilder:rbac:groups=batch,resources=jobs,verbs=get;list;watch // isBucketClaimReady checks if the BucketClaim has been provisioned. func (r *WorkloadMonitorReconciler) isBucketClaimReady(bc *cosiv1alpha1.BucketClaim) bool { @@ -393,6 +396,107 @@ func (r *WorkloadMonitorReconciler) bucketClaimsMessage(claims []cosiv1alpha1.Bu return strings.Join(pending, "; ") } +// maxFailedJobsInMessage bounds how many failed Jobs a monitor's message names. +const maxFailedJobsInMessage = 3 + +// jobFailedCondition returns the Failed=True condition of a Job, or nil. +func jobFailedCondition(job *batchv1.Job) *batchv1.JobCondition { + for i := range job.Status.Conditions { + c := &job.Status.Conditions[i] + if c.Type == batchv1.JobFailed && c.Status == corev1.ConditionTrue { + return c + } + } + return nil +} + +func jobIsNewer(a, b *batchv1.Job) bool { + if !a.CreationTimestamp.Equal(&b.CreationTimestamp) { + return b.CreationTimestamp.Before(&a.CreationTimestamp) + } + return a.Name > b.Name +} + +// failedJobsMessage names the failed Jobs with the reason and message of their +// Failed condition, and is empty when there is none. Of the Jobs one controller +// owns, only the newest counts: a CronJob keeps failed runs in its history +// after a later run succeeds. +func failedJobsMessage(jobs []batchv1.Job) string { + var current []*batchv1.Job + newestByOwner := map[types.UID]*batchv1.Job{} + for i := range jobs { + job := &jobs[i] + if job.DeletionTimestamp != nil { + continue + } + owner := metav1.GetControllerOfNoCopy(job) + if owner == nil { + current = append(current, job) + continue + } + if prev, ok := newestByOwner[owner.UID]; !ok || jobIsNewer(job, prev) { + newestByOwner[owner.UID] = job + } + } + for _, job := range newestByOwner { + current = append(current, job) + } + sort.Slice(current, func(i, j int) bool { return current[i].Name < current[j].Name }) + + var failed []string + for _, job := range current { + cond := jobFailedCondition(job) + if cond == nil { + continue + } + entry := fmt.Sprintf("Job %s failed", job.Name) + if cond.Reason != "" { + entry += ": " + cond.Reason + } + if cond.Message != "" { + entry += ": " + cond.Message + } + failed = append(failed, entry) + } + if extra := len(failed) - maxFailedJobsInMessage; extra > 0 { + failed = append(failed[:maxFailedJobsInMessage], fmt.Sprintf("%d more Jobs failed", extra)) + } + return strings.Join(failed, "; ") +} + +// JobCacheByObject returns the cache options the cozystack-controller manager +// applies to Jobs. The WorkloadMonitor reconciler, their only reader there, +// reads only Jobs that opted in with WorkloadMonitorReportFailureLabel, and of +// them only labels, owners and conditions. +func JobCacheByObject() cache.ByObject { + return cache.ByObject{ + Label: labels.SelectorFromSet(labels.Set{cozyv1alpha1.WorkloadMonitorReportFailureLabel: "true"}), + Transform: stripJob, + } +} + +func stripJob(obj any) (any, error) { + job, ok := obj.(*batchv1.Job) + if !ok { + return obj, nil + } + return &batchv1.Job{ + TypeMeta: job.TypeMeta, + ObjectMeta: metav1.ObjectMeta{ + Name: job.Name, + Namespace: job.Namespace, + UID: job.UID, + ResourceVersion: job.ResourceVersion, + Generation: job.Generation, + CreationTimestamp: job.CreationTimestamp, + DeletionTimestamp: job.DeletionTimestamp, + Labels: job.Labels, + OwnerReferences: job.OwnerReferences, + }, + Status: batchv1.JobStatus{Conditions: job.Status.Conditions}, + }, nil +} + // isServiceReady checks if the service has an external IP bound func (r *WorkloadMonitorReconciler) isServiceReady(svc *corev1.Service) bool { return len(svc.Status.LoadBalancer.Ingress) > 0 @@ -1044,6 +1148,22 @@ func (r *WorkloadMonitorReconciler) Reconcile(ctx context.Context, req ctrl.Requ bucketsMessage := r.bucketClaimsMessage(bucketClaimList.Items) + reportedJobs := client.MatchingLabels{cozyv1alpha1.WorkloadMonitorReportFailureLabel: "true"} + for k, v := range monitor.Spec.Selector { + reportedJobs[k] = v + } + jobList := &batchv1.JobList{} + if err := r.List( + ctx, + jobList, + client.InNamespace(monitor.Namespace), + reportedJobs, + ); err != nil { + logger.Error(err, "Unable to list Jobs for WorkloadMonitor", "monitor", monitor.Name) + return ctrl.Result{}, err + } + jobsMessage := failedJobsMessage(jobList.Items) + // Update WorkloadMonitor status based on observed pods monitor.Status.ObservedReplicas = observedReplicas monitor.Status.AvailableReplicas = availableReplicas @@ -1067,18 +1187,26 @@ func (r *WorkloadMonitorReconciler) Reconcile(ctx context.Context, req ctrl.Requ } // A stored DataVolume verdict is the last one: kept while no reader is // installed yet, so a controller restart does not report a stuck disk as - // ready. BucketClaims are listed on every pass, so their verdict is - // recomputed and only fills fields no DataVolume verdict holds. + // ready. Jobs and BucketClaims are listed on every pass, so their + // verdicts are recomputed and only fill fields no DataVolume verdict + // holds. A failed Job outranks an unprovisioned BucketClaim: it stays + // failed until something replaces it, while a claim is usually still + // being provisioned. if dataVolumesRead { fresh.Status.Message = dataVolumesMessage fresh.Status.Reason = "" if dataVolumesMessage != "" { fresh.Status.Reason = cozyv1alpha1.WorkloadMonitorReasonDataVolumeNotReady } - } else if fresh.Status.Reason == cozyv1alpha1.WorkloadMonitorReasonBucketClaimNotReady { + } else if fresh.Status.Reason == cozyv1alpha1.WorkloadMonitorReasonBucketClaimNotReady || + fresh.Status.Reason == cozyv1alpha1.WorkloadMonitorReasonJobFailed { fresh.Status.Message = "" fresh.Status.Reason = "" } + if fresh.Status.Message == "" && jobsMessage != "" { + fresh.Status.Message = jobsMessage + fresh.Status.Reason = cozyv1alpha1.WorkloadMonitorReasonJobFailed + } if fresh.Status.Message == "" && bucketsMessage != "" { fresh.Status.Message = bucketsMessage fresh.Status.Reason = cozyv1alpha1.WorkloadMonitorReasonBucketClaimNotReady @@ -1136,6 +1264,11 @@ func (r *WorkloadMonitorReconciler) SetupWithManager(mgr ctrl.Manager) error { &cosiv1alpha1.BucketClaim{}, handler.EnqueueRequestsFromMapFunc(mapObjectToMonitor(&cosiv1alpha1.BucketClaim{}, r.Client)), ). + // Cached Jobs carry only what JobCacheByObject keeps. + Watches( + &batchv1.Job{}, + handler.EnqueueRequestsFromMapFunc(mapObjectToMonitor(&batchv1.Job{}, r.Client)), + ). // Watch for changes to Workload objects we create (owned by WorkloadMonitor) Owns(&cozyv1alpha1.Workload{}) c, err := builder.Build(r) diff --git a/internal/controller/workloadmonitor_controller_test.go b/internal/controller/workloadmonitor_controller_test.go index 10a6c3eeb..151a832bc 100644 --- a/internal/controller/workloadmonitor_controller_test.go +++ b/internal/controller/workloadmonitor_controller_test.go @@ -13,6 +13,7 @@ import ( "time" cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1" + batchv1 "k8s.io/api/batch/v1" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/meta" "k8s.io/apimachinery/pkg/api/resource" @@ -40,6 +41,7 @@ func TestReconcile_OperationalStatusPersisted(t *testing.T) { scheme := runtime.NewScheme() _ = cozyv1alpha1.AddToScheme(scheme) _ = corev1.AddToScheme(scheme) + _ = batchv1.AddToScheme(scheme) _ = cosiv1alpha1.AddToScheme(scheme) minReplicas := int32(2) @@ -106,6 +108,7 @@ func TestReconcile_OperationalTrue_WhenEnoughReplicas(t *testing.T) { scheme := runtime.NewScheme() _ = cozyv1alpha1.AddToScheme(scheme) _ = corev1.AddToScheme(scheme) + _ = batchv1.AddToScheme(scheme) _ = cosiv1alpha1.AddToScheme(scheme) minReplicas := int32(1) @@ -235,6 +238,7 @@ func TestReconcile_MonitorLabelsPropagatedToPodWorkload(t *testing.T) { scheme := runtime.NewScheme() _ = cozyv1alpha1.AddToScheme(scheme) _ = corev1.AddToScheme(scheme) + _ = batchv1.AddToScheme(scheme) _ = cosiv1alpha1.AddToScheme(scheme) monitor := &cozyv1alpha1.WorkloadMonitor{ @@ -307,6 +311,7 @@ func TestReconcile_BackwardCompat_NoMonitorLabels(t *testing.T) { scheme := runtime.NewScheme() _ = cozyv1alpha1.AddToScheme(scheme) _ = corev1.AddToScheme(scheme) + _ = batchv1.AddToScheme(scheme) _ = cosiv1alpha1.AddToScheme(scheme) monitor := &cozyv1alpha1.WorkloadMonitor{ @@ -359,6 +364,7 @@ func TestReconcile_OperationalTrue_WhenNoMinReplicas(t *testing.T) { scheme := runtime.NewScheme() _ = cozyv1alpha1.AddToScheme(scheme) _ = corev1.AddToScheme(scheme) + _ = batchv1.AddToScheme(scheme) _ = cosiv1alpha1.AddToScheme(scheme) monitor := &cozyv1alpha1.WorkloadMonitor{ @@ -403,6 +409,7 @@ func newTestScheme() *runtime.Scheme { s := runtime.NewScheme() _ = cozyv1alpha1.AddToScheme(s) _ = corev1.AddToScheme(s) + _ = batchv1.AddToScheme(s) _ = cosiv1alpha1.AddToScheme(s) return s } @@ -2565,3 +2572,250 @@ func TestReconcile_DataVolumeVerdictOutranksBucketClaim(t *testing.T) { t.Errorf("Message = %q", got.Status.Message) } } + +func newJob(name string, labels map[string]string, conditions ...batchv1.JobCondition) *batchv1.Job { + return &batchv1.Job{ + ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: "default", Labels: labels}, + Status: batchv1.JobStatus{Conditions: conditions}, + } +} + +func jobFailed(reason, message string) batchv1.JobCondition { + return batchv1.JobCondition{Type: batchv1.JobFailed, Status: corev1.ConditionTrue, Reason: reason, Message: message} +} + +func newJobMonitorClient(s *runtime.Scheme, minReplicas int32, objs ...client.Object) client.Client { + monitor := &cozyv1alpha1.WorkloadMonitor{ + ObjectMeta: metav1.ObjectMeta{Name: "db", Namespace: "default"}, + Spec: cozyv1alpha1.WorkloadMonitorSpec{ + Selector: map[string]string{"app.kubernetes.io/instance": "db"}, + MinReplicas: ptr.To(minReplicas), + }, + } + return fake.NewClientBuilder(). + WithScheme(s). + WithObjects(append([]client.Object{monitor}, objs...)...). + WithStatusSubresource(monitor). + Build() +} + +func reconcileJobMonitor(t *testing.T, c client.Client, s *runtime.Scheme) *cozyv1alpha1.WorkloadMonitor { + t.Helper() + reconciler := &WorkloadMonitorReconciler{Client: c, Scheme: s, DataVolumeReader: c} + req := reconcile.Request{NamespacedName: types.NamespacedName{Name: "db", Namespace: "default"}} + if _, err := reconciler.Reconcile(context.TODO(), req); err != nil { + t.Fatalf("Reconcile returned error: %v", err) + } + updated := &cozyv1alpha1.WorkloadMonitor{} + if err := c.Get(context.TODO(), req.NamespacedName, updated); err != nil { + t.Fatalf("Failed to get updated WorkloadMonitor: %v", err) + } + if updated.Status.Operational == nil { + t.Fatal("Expected Operational to be set, got nil") + } + return updated +} + +func TestReconcile_FailedJobDecidesOperational(t *testing.T) { + selected := map[string]string{"app.kubernetes.io/instance": "db", cozyv1alpha1.WorkloadMonitorReportFailureLabel: "true"} + cases := []struct { + name string + job *batchv1.Job + message string + }{ + { + "failed", + newJob("db-repair", selected, jobFailed("BackoffLimitExceeded", "Job has reached the specified backoff limit")), + "Job db-repair failed: BackoffLimitExceeded: Job has reached the specified backoff limit", + }, + {"failed without a message", newJob("db-repair", selected, jobFailed("DeadlineExceeded", "")), "Job db-repair failed: DeadlineExceeded"}, + {"failed without a reason", newJob("db-repair", selected, jobFailed("", "")), "Job db-repair failed"}, + {"succeeded", newJob("db-repair", selected, batchv1.JobCondition{Type: batchv1.JobComplete, Status: corev1.ConditionTrue}), ""}, + {"running", newJob("db-repair", selected), ""}, + {"Failed condition not true", newJob("db-repair", selected, batchv1.JobCondition{Type: batchv1.JobFailed, Status: corev1.ConditionFalse}), ""}, + {"outside the selector", newJob("other", map[string]string{"app.kubernetes.io/instance": "other", cozyv1alpha1.WorkloadMonitorReportFailureLabel: "true"}, jobFailed("BackoffLimitExceeded", "")), ""}, + {"not opted in", newJob("db-1-initdb", map[string]string{"app.kubernetes.io/instance": "db"}, jobFailed("BackoffLimitExceeded", "")), ""}, + {"opted out", newJob("db-repair", map[string]string{"app.kubernetes.io/instance": "db", cozyv1alpha1.WorkloadMonitorReportFailureLabel: "false"}, jobFailed("BackoffLimitExceeded", "")), ""}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + s := newTestScheme() + got := reconcileJobMonitor(t, newJobMonitorClient(s, 0, tc.job), s) + if *got.Status.Operational != (tc.message == "") { + t.Errorf("Operational = %v, want %v", *got.Status.Operational, tc.message == "") + } + if got.Status.Message != tc.message { + t.Errorf("Message = %q, want %q", got.Status.Message, tc.message) + } + wantReason := "" + if tc.message != "" { + wantReason = cozyv1alpha1.WorkloadMonitorReasonJobFailed + } + if got.Status.Reason != wantReason { + t.Errorf("Reason = %q, want %q", got.Status.Reason, wantReason) + } + }) + } +} + +func TestReconcile_FailedJobVerdictClears(t *testing.T) { + selected := map[string]string{"app.kubernetes.io/instance": "db", cozyv1alpha1.WorkloadMonitorReportFailureLabel: "true"} + for _, tc := range []struct { + name string + clear func(c client.Client, job *batchv1.Job) error + }{ + {"deleted", func(c client.Client, job *batchv1.Job) error { return c.Delete(context.TODO(), job) }}, + {"replaced by a run that succeeded", func(c client.Client, job *batchv1.Job) error { + if err := c.Delete(context.TODO(), job); err != nil { + return err + } + return c.Create(context.TODO(), newJob("db-repair", selected, batchv1.JobCondition{Type: batchv1.JobComplete, Status: corev1.ConditionTrue})) + }}, + } { + t.Run(tc.name, func(t *testing.T) { + s := newTestScheme() + job := newJob("db-repair", selected, jobFailed("BackoffLimitExceeded", "")) + c := newJobMonitorClient(s, 0, job) + got := reconcileJobMonitor(t, c, s) + if *got.Status.Operational || got.Status.Reason != cozyv1alpha1.WorkloadMonitorReasonJobFailed { + t.Fatalf("before: Operational = %v, Reason = %q", *got.Status.Operational, got.Status.Reason) + } + if err := tc.clear(c, job); err != nil { + t.Fatal(err) + } + got = reconcileJobMonitor(t, c, s) + if !*got.Status.Operational || got.Status.Message != "" || got.Status.Reason != "" { + t.Errorf("after: Operational = %v, Message = %q, Reason = %q", *got.Status.Operational, got.Status.Message, got.Status.Reason) + } + }) + } +} + +func TestReconcile_StaleFailedJobVerdictClearsWithoutDataVolumeReader(t *testing.T) { + s := newTestScheme() + monitor := &cozyv1alpha1.WorkloadMonitor{ + ObjectMeta: metav1.ObjectMeta{Name: "db", Namespace: "default"}, + Spec: cozyv1alpha1.WorkloadMonitorSpec{Selector: map[string]string{"app.kubernetes.io/instance": "db"}}, + Status: cozyv1alpha1.WorkloadMonitorStatus{ + Operational: ptr.To(false), + Message: "Job db-repair failed: BackoffLimitExceeded", + Reason: cozyv1alpha1.WorkloadMonitorReasonJobFailed, + }, + } + c := fake.NewClientBuilder().WithScheme(s).WithObjects(monitor).WithStatusSubresource(monitor).Build() + reconciler := &WorkloadMonitorReconciler{Client: c, Scheme: s} + req := reconcile.Request{NamespacedName: types.NamespacedName{Name: "db", Namespace: "default"}} + if _, err := reconciler.Reconcile(context.TODO(), req); err != nil { + t.Fatalf("Reconcile returned error: %v", err) + } + got := &cozyv1alpha1.WorkloadMonitor{} + if err := c.Get(context.TODO(), req.NamespacedName, got); err != nil { + t.Fatal(err) + } + if got.Status.Operational == nil || !*got.Status.Operational || got.Status.Message != "" || got.Status.Reason != "" { + t.Errorf("Operational = %v, Message = %q, Reason = %q, want true and both cleared", got.Status.Operational, got.Status.Message, got.Status.Reason) + } +} + +func TestReconcile_FailedJobPrecedence(t *testing.T) { + selected := map[string]string{"app.kubernetes.io/instance": "db", cozyv1alpha1.WorkloadMonitorReportFailureLabel: "true"} + failed := newJob("db-repair", selected, jobFailed("BackoffLimitExceeded", "")) + importing := "ImportInProgress" + cases := []struct { + name string + minReplicas int32 + objs []client.Object + reason string + message string + }{ + {"below minReplicas", 1, []client.Object{failed}, cozyv1alpha1.WorkloadMonitorReasonJobFailed, "Job db-repair failed: BackoffLimitExceeded"}, + {"outranks an unprovisioned BucketClaim", 0, []client.Object{failed, newBucketClaim("db", selected, "", false)}, cozyv1alpha1.WorkloadMonitorReasonJobFailed, "Job db-repair failed: BackoffLimitExceeded"}, + {"outranked by a DataVolume verdict", 0, []client.Object{failed, newDataVolume("db", selected, &importing)}, cozyv1alpha1.WorkloadMonitorReasonDataVolumeNotReady, "DataVolume db is ImportInProgress"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + s := newTestScheme() + got := reconcileJobMonitor(t, newJobMonitorClient(s, tc.minReplicas, tc.objs...), s) + if *got.Status.Operational { + t.Error("Operational = true, want false") + } + if got.Status.Reason != tc.reason || got.Status.Message != tc.message { + t.Errorf("Reason = %q, Message = %q, want %q, %q", got.Status.Reason, got.Status.Message, tc.reason, tc.message) + } + }) + } +} + +func TestFailedJobsMessage(t *testing.T) { + failed := jobFailed("BackoffLimitExceeded", "") + complete := batchv1.JobCondition{Type: batchv1.JobComplete, Status: corev1.ConditionTrue} + ownedBy := func(job *batchv1.Job, uid types.UID, created time.Time) batchv1.Job { + job.OwnerReferences = []metav1.OwnerReference{{APIVersion: "batch/v1", Kind: "CronJob", Name: "backup", UID: uid, Controller: ptr.To(true)}} + job.CreationTimestamp = metav1.NewTime(created) + return *job + } + now := time.Now() + cases := []struct { + name string + jobs []batchv1.Job + want string + }{ + { + "sorted by name", + []batchv1.Job{*newJob("b", nil, failed), *newJob("a", nil, failed)}, + "Job a failed: BackoffLimitExceeded; Job b failed: BackoffLimitExceeded", + }, + { + "bounded", + []batchv1.Job{*newJob("e", nil, failed), *newJob("d", nil, failed), *newJob("c", nil, failed), *newJob("b", nil, failed), *newJob("a", nil, failed)}, + "Job a failed: BackoffLimitExceeded; Job b failed: BackoffLimitExceeded; Job c failed: BackoffLimitExceeded; 2 more Jobs failed", + }, + { + "a later run of the same controller succeeded", + []batchv1.Job{ownedBy(newJob("backup-1", nil, failed), "cron", now.Add(-time.Hour)), ownedBy(newJob("backup-2", nil, complete), "cron", now)}, + "", + }, + { + "the latest run of the controller failed", + []batchv1.Job{ownedBy(newJob("backup-1", nil, complete), "cron", now.Add(-time.Hour)), ownedBy(newJob("backup-2", nil, failed), "cron", now)}, + "Job backup-2 failed: BackoffLimitExceeded", + }, + { + "being deleted", + []batchv1.Job{func() batchv1.Job { + j := newJob("a", nil, failed) + j.DeletionTimestamp = ptr.To(metav1.NewTime(now)) + return *j + }()}, + "", + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := failedJobsMessage(tc.jobs); got != tc.want { + t.Errorf("failedJobsMessage = %q, want %q", got, tc.want) + } + }) + } +} + +func TestStripJobKeepsWhatTheMonitorReads(t *testing.T) { + job := newJob("db-repair", map[string]string{"app.kubernetes.io/instance": "db"}, jobFailed("BackoffLimitExceeded", "limit")) + job.OwnerReferences = []metav1.OwnerReference{{Name: "owner", UID: "u", Controller: ptr.To(true)}} + job.ResourceVersion = "7" + job.ManagedFields = []metav1.ManagedFieldsEntry{{Manager: "kube-controller-manager"}} + job.Spec.Template.Spec.Containers = []corev1.Container{{Name: "repair", Image: "postgres"}} + + out, err := stripJob(job) + if err != nil { + t.Fatal(err) + } + got := out.(*batchv1.Job) + if got.Name != job.Name || got.Namespace != job.Namespace || got.ResourceVersion != "7" || + len(got.Labels) != 1 || len(got.OwnerReferences) != 1 || failedJobsMessage([]batchv1.Job{*got}) != "Job db-repair failed: BackoffLimitExceeded: limit" { + t.Errorf("stripped Job lost what the monitor reads: %+v", got) + } + if len(got.ManagedFields) != 0 || len(got.Spec.Template.Spec.Containers) != 0 { + t.Errorf("stripped Job kept its spec or managed fields: %+v", got) + } +} diff --git a/packages/apps/postgres/README.md b/packages/apps/postgres/README.md index ed66d66bb..a737e5468 100644 --- a/packages/apps/postgres/README.md +++ b/packages/apps/postgres/README.md @@ -207,18 +207,19 @@ For `sslmode=verify-full` to work, the CA bundle retrieved above must be saved t ### Common parameters -| Name | Description | Type | Value | -| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | ------------ | -| `replicas` | Number of Postgres replicas. Under active autoscaling this is the resting/seed count, not the live count — KEDA drives the live count via `/scale`. Disabling autoscaling does NOT automatically bring the live count back to `replicas`: the client-side merge writes `instances` only when the rendered value changes, so a cluster KEDA grew past `replicas` stays there with no autoscaler left to reduce it — lower `replicas` to the count you want and it rebases down (shedding the surplus replicas + PVCs). Lowering it below the live count, or disabling/dry-running while it sits below the live count, sheds in one step past the scaleDown pacing; stage it to the live count first (suspend the HelmRelease and `kubectl scale` if needed) to avoid a transient. Must stay greater than `quorum.maxSyncReplicas`. | `int` | `2` | -| `resources` | Explicit CPU and memory configuration for each PostgreSQL replica. When omitted, the preset defined in `resourcesPreset` is applied. | `object` | `{}` | -| `resources.cpu` | CPU available to each replica. | `quantity` | `""` | -| `resources.memory` | Memory (RAM) available to each replica. | `quantity` | `""` | -| `resourcesPreset` | Default sizing preset used when `resources` is omitted. | `string` | `t1.micro` | -| `size` | Persistent Volume Claim size available for application data. | `quantity` | `10Gi` | -| `storageClass` | StorageClass used to store the data. | `string` | `""` | -| `external` | Enable external access from outside the cluster. | `bool` | `false` | -| `version` | PostgreSQL major version to deploy | `string` | `v18` | -| `flavor` | PostgreSQL image flavor, fixed when the cluster is created. `postgresql` uses the CloudNativePG PostgreSQL image. `postgis` uses the CloudNativePG PostGIS image, which adds postgis, postgis_raster, postgis_topology, postgis_sfcgal, postgis_tiger_geocoder and address_standardizer; enable them per database in `databases..extensions`. Changing the flavor of an existing cluster is refused, and a backup restores only into a cluster of the flavor it was taken from: to change flavor, create a new cluster and move the data with a logical dump (pg_dump / pg_restore). | `string` | `postgresql` | +| Name | Description | Type | Value | +| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | ------------ | +| `replicas` | Number of Postgres replicas. Under active autoscaling this is the resting/seed count, not the live count — KEDA drives the live count via `/scale`. Disabling autoscaling does NOT automatically bring the live count back to `replicas`: the client-side merge writes `instances` only when the rendered value changes, so a cluster KEDA grew past `replicas` stays there with no autoscaler left to reduce it — lower `replicas` to the count you want and it rebases down (shedding the surplus replicas + PVCs). Lowering it below the live count, or disabling/dry-running while it sits below the live count, sheds in one step past the scaleDown pacing; stage it to the live count first (suspend the HelmRelease and `kubectl scale` if needed) to avoid a transient. Must stay greater than `quorum.maxSyncReplicas`. | `int` | `2` | +| `resources` | Explicit CPU and memory configuration for each PostgreSQL replica. When omitted, the preset defined in `resourcesPreset` is applied. | `object` | `{}` | +| `resources.cpu` | CPU available to each replica. | `quantity` | `""` | +| `resources.memory` | Memory (RAM) available to each replica. | `quantity` | `""` | +| `resourcesPreset` | Default sizing preset used when `resources` is omitted. | `string` | `t1.micro` | +| `size` | Persistent Volume Claim size available for application data. | `quantity` | `10Gi` | +| `storageClass` | StorageClass used to store the data. | `string` | `""` | +| `external` | Enable external access from outside the cluster. | `bool` | `false` | +| `version` | PostgreSQL major version to deploy | `string` | `v18` | +| `flavor` | PostgreSQL image flavor, fixed when the cluster is created. `postgresql` uses the CloudNativePG PostgreSQL image. `postgis` uses the CloudNativePG PostGIS image, which adds postgis, postgis_raster, postgis_topology, postgis_sfcgal, postgis_tiger_geocoder and address_standardizer; enable them per database in `databases..extensions`. Changing the flavor of an existing cluster is refused, and a backup restores only into a cluster of the flavor it was taken from: to change flavor, create a new cluster and move the data with a logical dump (pg_dump / pg_restore). | `string` | `postgresql` | +| `allowCollationChange` | Allow a cluster created on a Debian bullseye image (before the move to standard-trixie) to move to the new image without a clean locale check. Such a cluster is checked before each upgrade, except while `bootstrap.enabled` is set (set it back to false once a restore set up by hand has finished), and stays on its current image until the check finds nothing that depends on a collation other than C, POSIX or builtin: while this is false, a cluster the check found affected (an ICU or libc locale, or C.UTF-8) or could not finish on stays put, because glibc and ICU on the new image sort text differently and every index on such text must be rebuilt. A held cluster runs the bare bullseye tag it has, gets no further PostgreSQL minors and so none of their security fixes, and refuses a change of `version`, since new majors are built only on the new images. To leave that state, either remove the dependency (move such columns and indexes to C, or to the builtin `pg_c_utf8` on PostgreSQL 17 and later) and let the next upgrade check again, or set this to true in a maintenance window: the cluster moves on the next upgrade, replicas restart on the new image first and can return wrong results through `-ro`, and unique indexes can accept duplicates, until the indexes are rebuilt on the primary. The 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 @@ -309,15 +310,16 @@ For `sslmode=verify-full` to work, the CA bundle retrieved above must be saved t ### Bootstrap (recovery) parameters -| Name | Description | Type | Value | -| ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | ------- | -| `bootstrap` | Bootstrap configuration. | `object` | `{}` | -| `bootstrap.enabled` | Whether to restore from a backup. | `bool` | `false` | -| `bootstrap.recoveryTime` | Timestamp (RFC3339) for point-in-time recovery; empty means latest. | `string` | `""` | -| `bootstrap.backupID` | Barman ID of the base backup to recover from, passed as `recoveryTarget.backupID`. Empty lets the barman-cloud plugin pick one: the newest backup when `recoveryTime` is empty, otherwise the newest one ending at or before it, on any timeline. The CNPG backup driver sets this on restore. | `string` | `""` | -| `bootstrap.oldName` | Previous cluster name before deletion. | `string` | `""` | -| `bootstrap.serverName` | Server name (S3 path prefix) used by the original cluster when writing backups; passed to the barman-cloud plugin via `externalClusters[].plugin.parameters.serverName`. Defaults to `bootstrap.oldName`. Set this only when the original cluster wrote backups under an explicit server name that differed from its Kubernetes resource name. | `string` | `""` | -| `bootstrap.newServerName` | WAL-archive server name (S3 path prefix) the RESTORED cluster writes to. Must differ from `serverName` (the recovery source) so a restored cluster archives to a fresh, empty prefix and barman-cloud-check-wal-archive passes while it recovers from the source's prefix. The CNPG backup driver sets this on restore; empty means the cluster archives under its own name. | `string` | `""` | +| Name | Description | Type | Value | +| --------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | ------- | +| `bootstrap` | Bootstrap configuration. | `object` | `{}` | +| `bootstrap.enabled` | Whether to restore from a backup. | `bool` | `false` | +| `bootstrap.recoveryTime` | Timestamp (RFC3339) for point-in-time recovery; empty means latest. | `string` | `""` | +| `bootstrap.backupID` | Barman ID of the base backup to recover from, passed as `recoveryTarget.backupID`. Empty lets the barman-cloud plugin pick one: the newest backup when `recoveryTime` is empty, otherwise the newest one ending at or before it, on any timeline. The CNPG backup driver sets this on restore. | `string` | `""` | +| `bootstrap.oldName` | Previous cluster name before deletion. | `string` | `""` | +| `bootstrap.serverName` | Server name (S3 path prefix) used by the original cluster when writing backups; passed to the barman-cloud plugin via `externalClusters[].plugin.parameters.serverName`. Defaults to `bootstrap.oldName`. Set this only when the original cluster wrote backups under an explicit server name that differed from its Kubernetes resource name. | `string` | `""` | +| `bootstrap.newServerName` | WAL-archive server name (S3 path prefix) the RESTORED cluster writes to. Must differ from `serverName` (the recovery source) so a restored cluster archives to a fresh, empty prefix and barman-cloud-check-wal-archive passes while it recovers from the source's prefix. The CNPG backup driver sets this on restore; empty means the cluster archives under its own name. | `string` | `""` | +| `bootstrap.sourceImageName` | Image of the cluster the backup was taken from. A restore of a backup taken on one of the bare Debian bullseye tags the chart used before standard-trixie comes back on that image (see `allowCollationChange`); any other value is ignored. The CNPG backup driver sets this on restore and clears it with `enabled`. | `string` | `""` | ## Parameter examples and reference diff --git a/packages/apps/postgres/files/postgis-versions.yaml b/packages/apps/postgres/files/postgis-versions.yaml index 4b1ad284c..12d800143 100644 --- a/packages/apps/postgres/files/postgis-versions.yaml +++ b/packages/apps/postgres/files/postgis-versions.yaml @@ -1,6 +1,6 @@ -"v18": "18.1-3.6.1-standard-trixie" -"v17": "17.7-3.6.1-standard-trixie" -"v16": "16.11-3.6.1-standard-trixie" -"v15": "15.15-3.6.1-standard-trixie" -"v14": "14.20-3.6.1-standard-trixie" +"v18": "18.7-3.7.0-standard-trixie" +"v17": "17.12-3.7.0-standard-trixie" +"v16": "16.16-3.7.0-standard-trixie" +"v15": "15.20-3.7.0-standard-trixie" +"v14": "14.25-3.7.0-standard-trixie" "v13": "13.22-3.6.0-standard-trixie" diff --git a/packages/apps/postgres/files/versions.yaml b/packages/apps/postgres/files/versions.yaml index e4fe13ead..2624066e3 100644 --- a/packages/apps/postgres/files/versions.yaml +++ b/packages/apps/postgres/files/versions.yaml @@ -1,6 +1,6 @@ -"v18": "v18.1" -"v17": "v17.7" -"v16": "v16.11" -"v15": "v15.15" -"v14": "v14.20" +"v18": "v18.7" +"v17": "v17.12" +"v16": "v16.16" +"v15": "v15.20" +"v14": "v14.25" "v13": "v13.22" diff --git a/packages/apps/postgres/hack/update-versions.sh b/packages/apps/postgres/hack/update-versions.sh index 3a4f0a745..0afc55afa 100755 --- a/packages/apps/postgres/hack/update-versions.sh +++ b/packages/apps/postgres/hack/update-versions.sh @@ -33,9 +33,10 @@ if ! command -v jq &> /dev/null; then exit 1 fi -# Get available image tags +# Get available image tags. Only standard-trixie builds count: the chart +# appends that suffix to the minor it reads from versions.yaml. echo "Fetching available image tags from registry..." -AVAILABLE_TAGS=$(skopeo list-tags docker://ghcr.io/cloudnative-pg/postgresql | jq -r '.Tags[] | select(test("^[0-9]+\\.[0-9]+$"))' | sort -V) +AVAILABLE_TAGS=$(skopeo list-tags docker://ghcr.io/cloudnative-pg/postgresql | jq -r '.Tags[] | select(test("^[0-9]+\\.[0-9]+-standard-trixie$")) | sub("-standard-trixie$"; "")' | sort -V) if [ -z "$AVAILABLE_TAGS" ]; then echo "Error: Could not fetch available image tags" >&2 diff --git a/packages/apps/postgres/templates/_versions.tpl b/packages/apps/postgres/templates/_versions.tpl index b7cdb8c13..ea46a11c2 100644 --- a/packages/apps/postgres/templates/_versions.tpl +++ b/packages/apps/postgres/templates/_versions.tpl @@ -16,25 +16,123 @@ {{/* Single source for the operand image: the init Job runs psql against the - Cluster, so both must resolve the same image. + Cluster, so both must resolve the same image, and the Job compares its own + PostgreSQL build with the server's to tell when a new image has rolled out. + + standard-trixie, not the bare tag: a bare tag is the system variant on + Debian bullseye, which upstream stopped building. The standard variant, + because backups go through the barman-cloud plugin and need none of the + barman binaries the system variant adds. trixie, because the postgis + flavor is on it already, so both image families share one Debian release. */}} {{- define "postgres.imageName" -}} +{{- include "postgres.heldImageName" . | default (include "postgres.targetImageName" .) -}} +{{- end -}} + +{{- define "postgres.targetImageName" -}} {{- if eq (default "postgresql" .Values.flavor) "postgis" -}} ghcr.io/cloudnative-pg/postgis:{{ include "postgres.postgisVersionMap" . | trim }} {{- else -}} -ghcr.io/cloudnative-pg/postgresql:{{ include "postgres.versionMap" . | trim | trimPrefix "v" }} +ghcr.io/cloudnative-pg/postgresql:{{ include "postgres.versionMap" . | trim | trimPrefix "v" }}-standard-trixie {{- end -}} {{- end -}} {{/* - The flavor is fixed at bootstrap. The two image families are built on - different Debian releases, so moving a live cluster from one to the other - swaps glibc under an initialised data directory and silently invalidates - every index on collatable text; the postgis-to-postgresql direction also - drops the shared libraries behind every PostGIS object. CNPG would roll - either change out as an ordinary image update, so refuse it here, before - the Cluster is patched. Only the image name is compared: a minor bump or - a registry mirror rewriting the host must keep passing. + The image a cluster on Debian bullseye keeps, or nothing. Clusters created + before the move to trixie run one of the bare tags postgres.bullseyeImage + lists, and moving them changes glibc and ICU under an initialised data + directory. Such a cluster stays on its image until the pre-upgrade locale + check has recorded "clean" on its Cluster, or until allowCollationChange is + set: a cluster not checked yet, one the check could not finish on and one + it found affected all stay. New majors are built only on the new images, so + a held cluster refuses a change of version instead of dropping it. +*/}} +{{- define "postgres.heldImageName" -}} +{{- if and (ne (default "postgresql" .Values.flavor) "postgis") (not .Values.allowCollationChange) -}} +{{- $hold := include "postgres.localeHold" . | fromJson -}} +{{- if and $hold.image (ne $hold.verdict "clean") -}} +{{- $heldMajor := regexFind "^[0-9]+" (last (splitList ":" $hold.image)) -}} +{{- $wantMajor := trimPrefix "v" .Values.version -}} +{{- if ne $heldMajor $wantMajor -}} +{{- fail (printf "postgres: version %s cannot be applied: the cluster stays on %s until the pre-upgrade check finds nothing in it that depends on a collation sorting differently on the images PostgreSQL %s is built on (the postgres.cozystack.io/locale-data annotation of the cnpg.io Cluster). Keep version v%s, or set allowCollationChange: true and rebuild the affected indexes in a maintenance window." .Values.version $hold.image $wantMajor $heldMajor) -}} +{{- end -}} +{{- $hold.image -}} +{{- end -}} +{{- end -}} +{{- end -}} + +{{/* + The bullseye image that applies to this cluster and its check result, as + JSON; the image is empty when the cluster runs any other one. The result is + the postgres.cozystack.io/locale-data annotation the pre-upgrade check + writes on the live Cluster. A physical recovery with no live Cluster yet + (the CNPG backup driver deletes it before the recovery renders) restores + onto the image the backup was taken on, so that the data keeps the library + that built it: bootstrap.sourceImageName, which the driver copies from the + source Cluster, or for a recovery set up by hand the bootstrap.oldName + Cluster while it exists. A recovery has no result of its own and is held + until the first upgrade after it checks the restored data. + + bootstrap.sourceImageName is in the application spec, so anyone who may + edit the application may set it; it only ever selects one of the images + postgres.bullseyeImage lists. +*/}} +{{- define "postgres.localeHold" -}} +{{- $live := lookup "postgresql.cnpg.io/v1" "Cluster" .Release.Namespace .Release.Name -}} +{{- $image := dig "spec" "imageName" "" $live -}} +{{- $verdict := dig "metadata" "annotations" "postgres.cozystack.io/locale-data" "" $live -}} +{{- if and .Values.bootstrap.enabled (not $image) -}} +{{- $image = .Values.bootstrap.sourceImageName | default (dig "spec" "imageName" "" (include "postgres.recoverySource" . | fromJson)) -}} +{{- $verdict = "" -}} +{{- end -}} +{{- if ne (include "postgres.bullseyeImage" $image) "true" -}} +{{- $image = "" -}} +{{- end -}} +{{- dict "image" $image "verdict" $verdict | toJson -}} +{{- end -}} + +{{- define "postgres.recoverySource" -}} +{{- if and .Values.bootstrap.enabled .Values.bootstrap.oldName (not .Values.bootstrap.newServerName) -}} +{{- lookup "postgresql.cnpg.io/v1" "Cluster" .Release.Namespace .Values.bootstrap.oldName | toJson -}} +{{- else -}} +{} +{{- end -}} +{{- end -}} + +{{/* + The images this chart ran clusters on before the move to trixie: the bare + version tags of the CloudNativePG image, which are its system variant on + Debian bullseye, as files/versions.yaml listed them in every release before + standard-trixie. Exact on purpose: a held image reaches spec.imageName. +*/}} +{{- define "postgres.bullseyeImage" -}} +{{- has . (list "ghcr.io/cloudnative-pg/postgresql:13.22" "ghcr.io/cloudnative-pg/postgresql:14.20" "ghcr.io/cloudnative-pg/postgresql:15.15" "ghcr.io/cloudnative-pg/postgresql:16.11" "ghcr.io/cloudnative-pg/postgresql:17.7" "ghcr.io/cloudnative-pg/postgresql:18.1") -}} +{{- end -}} + +{{/* + The live image of a cluster still on bullseye whose owner has not allowed + the collation change, or nothing. The pre-upgrade locale check runs only + then, from that image, against the server it is checking. +*/}} +{{- define "postgres.localeCheckImage" -}} +{{- if and (ne (default "postgresql" .Values.flavor) "postgis") (not .Values.allowCollationChange) (not .Values.bootstrap.enabled) -}} +{{- $live := lookup "postgresql.cnpg.io/v1" "Cluster" .Release.Namespace .Release.Name -}} +{{- if and $live $live.spec $live.spec.imageName (eq (include "postgres.bullseyeImage" $live.spec.imageName) "true") -}} +{{- $live.spec.imageName -}} +{{- end -}} +{{- end -}} +{{- end -}} + +{{/* + The flavor is fixed at bootstrap. Only the postgis image carries the shared + libraries behind PostGIS objects, so the postgis-to-postgresql direction + leaves every one of them without its code. The two families are also built + and released separately, and nothing keeps their Debian release in step, so + either direction can swap glibc and ICU under an initialised data directory + together with the flavor. CNPG would roll either change out as an ordinary + image update, so refuse it here, before the Cluster is patched. Only the + image name is compared: a minor bump, a move to another variant of the same + family, or a registry mirror rewriting the host must keep passing. A physical recovery carries the same data directory across, so it is held to the same rule. With no live Cluster of its own yet, the release is @@ -49,14 +147,14 @@ ghcr.io/cloudnative-pg/postgresql:{{ include "postgres.versionMap" . | trim | tr {{- if and $live $live.spec $live.spec.imageName -}} {{- $liveName := regexReplaceAll "[:@].*$" (last (splitList "/" $live.spec.imageName)) "" -}} {{- if ne $liveName $wantName -}} -{{- fail (printf "postgres: flavor cannot change on an existing cluster (running %s, requested %s). The image families use different glibc versions, which would corrupt text indexes. Create a new Postgres with the wanted flavor and move the data with a logical dump (pg_dump / pg_restore); restoring a backup keeps the flavor it was taken from." $liveName $wantName) -}} +{{- fail (printf "postgres: flavor cannot change on an existing cluster (running %s, requested %s). Only the postgis image carries the PostGIS libraries, and the two image families can differ in glibc and ICU, which corrupts text indexes. Create a new Postgres with the wanted flavor and move the data with a logical dump (pg_dump / pg_restore); restoring a backup keeps the flavor it was taken from." $liveName $wantName) -}} {{- end -}} {{- else if and .Values.bootstrap.enabled .Values.bootstrap.oldName -}} {{- $source := lookup "postgresql.cnpg.io/v1" "Cluster" .Release.Namespace .Values.bootstrap.oldName -}} {{- if and $source $source.spec $source.spec.imageName -}} {{- $sourceName := regexReplaceAll "[:@].*$" (last (splitList "/" $source.spec.imageName)) "" -}} {{- if ne $sourceName $wantName -}} -{{- fail (printf "postgres: cannot recover a %s backup of %s into the %s flavor. A physical restore keeps the source's glibc and libraries, which would corrupt text indexes. Set flavor to match the source, or create the new Postgres empty and move the data with a logical dump (pg_dump / pg_restore)." $sourceName .Values.bootstrap.oldName $wantName) -}} +{{- fail (printf "postgres: cannot recover a %s backup of %s into the %s flavor. A physical restore carries over a data directory built with the source's libraries: PostGIS objects need the postgis image, and a glibc or ICU difference corrupts text indexes. Set flavor to match the source, or create the new Postgres empty and move the data with a logical dump (pg_dump / pg_restore)." $sourceName .Values.bootstrap.oldName $wantName) -}} {{- end -}} {{- end -}} {{- end -}} diff --git a/packages/apps/postgres/templates/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 @@ -598,6 +620,441 @@ stringData: ALTER DATABASE postgres SET cozystack.adopted_restore = :'mark'; EOT {{- end }} + repair.sh: | + #!/bin/bash + set -e + {{- /* + An operand image built on another Debian release ships another glibc and + ICU, and an index ordered by a collation of either library is then + 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 runs in a Job of its own, which a post-upgrade hook starts + once the init-job has managed roles and databases, and which Helm does + not wait for. The hook runs as soon as the Cluster is patched, while + CNPG is still rolling the instances, the primary last, and an instance + whose clients keep their sessions open waits out smartShutdownTimeout + before it restarts: the rollout alone can take longer than Helm gives a + hook, and the rebuild of a large index as long again, so inside the + hook either one failed the upgrade. Here a rebuild that fails costs + nothing else, and the next upgrade starts the Job again. The PostGIS + update, which waits for the same rollout, follows this pass in the + same Job. + + 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. 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 + 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. + + 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 + 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, nor the PostGIS update: the + pass reports them, and the Job exits non-zero at its end, with the + recorded versions of that database left as they are. + + A collation that a range partition key depends on is never refreshed: + rebuilding an index does not move a row to the partition the new + 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. + + 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 + 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, 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') 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 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 + 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 + 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 ( + 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 + for db in $COLLATION_DBS; do + collation_run "$db" /dev/null + done + 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); 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 + 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 collation repair Job is out of time, the next upgrade of the release starts it again" >&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 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 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 + 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 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 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 + 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 + [ "${PIPESTATUS[0]}" != 2 ] || COLLATION_LOST=yes + 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, %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; + 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 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 + EOT + fi + done + if [ -n "$COLLATION_LOST" ]; then + echo "lost the connection to the server during index rebuilds in:$COLLATION_FAILED" >&2 + exit 2 + fi + if [ -n "$COLLATION_FAILED" ]; then + echo "index rebuilds failed in:$COLLATION_FAILED (the errors are above); the other indexes were rebuilt. A unique index cannot be rebuilt over rows that the previous ordering kept apart and the new one treats as equal, so remove such duplicates. The next upgrade of the release starts the repair again, except for an index an error above reports as left alone" >&2 + fi + {{- if eq .Values.flavor "postgis" }} + {{- /* + A new PostGIS library leaves the SQL objects of every database on the + release they were installed with until ALTER EXTENSION ... UPDATE runs + there, and postgis_full_version() reports them as needing an upgrade + meanwhile. The extensions were created in the init-job's superuser session, + so only the superuser owns them and can update them; a tenant gets + "must be owner of extension". This pass updates them in every database + where they are installed, including ones values no longer list. + + The target is the version the server offers, never one rendered here, + so a database only moves to what the running library implements, and + a database already on it is left alone. While CNPG is still rolling the + instances the server offers the previous release and there is nothing + to update yet, so the pass first waits for the server to offer the + PostGIS release the Job's own image ships, until 120 seconds before + the Job's deadline. A rollout that takes longer fails the Job, and the + next upgrade of the release starts it again. + + postgis_extensions_upgrade() is not used: it leaves out + address_standardizer, and it updates every installed extension to ANY + and back on each call, even when nothing changed. Each extension is + updated on its own instead, postgis before the ones that require it, + in sessions that pin search_path as the collation pass does. A version + the image ships no update path from is reported and left as it is: the + address_standardizer of PostGIS 3.7 has none from earlier releases. + + ALTER EXTENSION is transactional, so an update that fails leaves its + extension as it was. A tenant transaction can hold a lock an update + needs, and one update can wait for several of them in turn, so each + update, its lock waits included, runs no longer than what is left of + the Job, with the same minute in reserve as the collation pass, and a + database reached with no time left counts as failed. The pass carries + on with the other databases and then fails the Job, whose log names + them; the next upgrade of the release starts it again. + + The update scripts run as the superuser and write to tables a tenant's + admin role may attach triggers to (spatial_ref_sys among them), and a + trigger runs with the privileges of the session that fires it. The + update session therefore runs with session_replication_role = replica, + under which triggers enabled the default way do not fire; only a + table's owner, the superuser, can enable one ALWAYS or REPLICA, and a + database where such a trigger sits on a table of these extensions is + not updated. + */}} + + echo "== update postgis extensions" + POSTGIS_SHIPPED=$(sed -n "s/^default_version *= *'\([^']*\)'.*/\1/p" "$(pg_config --sharedir)/extension/postgis.control") + postgis_offered() { + timeout 10 psql -t -A -c "SELECT default_version FROM pg_catalog.pg_available_extensions WHERE name = 'postgis'" 2>/dev/null + } + ALL_DBS=$(psql -v ON_ERROR_STOP=1 -t -A -c "SELECT datname FROM pg_database WHERE datallowconn AND NOT datistemplate") + POSTGIS_DBS="" + POSTGIS_FAILED="" + POSTGIS_LOST="" + for db in $ALL_DBS; do + status=0 + installed=$(psql -v ON_ERROR_STOP=1 -q -t -A --dbname "$db" -c "SET search_path = pg_catalog, pg_temp" -c "SELECT count(*) FROM pg_extension WHERE extname IN ('postgis', 'postgis_raster', 'postgis_topology', 'postgis_sfcgal', 'postgis_tiger_geocoder', 'address_standardizer', 'address_standardizer_data_us')") || status=$? + if [ "$status" != 0 ]; then + [ "$status" != 2 ] || POSTGIS_LOST=yes + echo "the PostGIS extensions in database $db were not checked (the error is above); the next upgrade of the release starts the repair again" >&2 + POSTGIS_FAILED="$POSTGIS_FAILED $db" + continue + fi + if [ "$installed" != 0 ]; then + POSTGIS_DBS="$POSTGIS_DBS $db" + fi + done + if [ -n "$POSTGIS_DBS" ] && [ -n "$POSTGIS_SHIPPED" ] && [ "$(postgis_offered)" != "$POSTGIS_SHIPPED" ]; then + echo "waiting for the server to offer PostGIS $POSTGIS_SHIPPED" + until [ "$(postgis_offered)" = "$POSTGIS_SHIPPED" ]; do + if [ "$SECONDS" -ge $((JOB_DEADLINE - 120)) ]; then + echo "the server did not move to PostGIS $POSTGIS_SHIPPED in time (check the rollout of the cnpg.io/Cluster); the PostGIS extensions are not updated yet - failing the collation repair Job, the next upgrade of the release starts it again" >&2 + exit 1 + fi + sleep 5 + done + fi + for db in $POSTGIS_DBS; do + LEFT=$((JOB_DEADLINE - SECONDS - 60)) + if [ "$LEFT" -lt 10 ]; then + echo "the PostGIS extensions in database $db were not updated: the collation repair Job is out of time, the next upgrade of the release starts it again" >&2 + POSTGIS_FAILED="$POSTGIS_FAILED $db" + continue + fi + if ! psql -v ON_ERROR_STOP=1 -q -t -A --dbname "$db" -v lock_wait="${LEFT}s" <<\EOT + SET client_min_messages = warning; + SET search_path = pg_catalog, pg_temp; + SET lock_timeout = :'lock_wait'; + SET session_replication_role = replica; + SELECT EXISTS (SELECT FROM pg_trigger t JOIN pg_depend d ON d.classid = 'pg_class'::regclass AND d.objid = t.tgrelid AND d.deptype = 'e' JOIN pg_extension x ON x.oid = d.refobjid WHERE NOT t.tgisinternal AND t.tgenabled IN ('A', 'R') AND x.extname IN ('postgis', 'postgis_raster', 'postgis_topology', 'postgis_sfcgal', 'postgis_tiger_geocoder', 'address_standardizer', 'address_standardizer_data_us')) AS armed \gset + \if :armed + SELECT format('DO %L', format('BEGIN RAISE EXCEPTION %L, %L; END', '%', format('the PostGIS extensions in database %s were not updated: a table of theirs carries a trigger enabled ALWAYS or REPLICA, which would run inside the superuser update; drop that trigger, and the next upgrade of the release starts the repair again', current_database()))) \gexec + \endif + SELECT clock_timestamp() + :'lock_wait'::interval AS deadline_at \gset + CREATE TEMP TABLE cozystack_postgis AS + SELECT e.extname, e.extversion, a.default_version, f.position, + EXISTS (SELECT FROM pg_extension_update_paths(e.extname) p WHERE p.source = e.extversion AND p.target = a.default_version AND p.path IS NOT NULL) AS reachable + FROM unnest(ARRAY['postgis', 'postgis_raster', 'postgis_topology', 'postgis_sfcgal', 'postgis_tiger_geocoder', 'address_standardizer', 'address_standardizer_data_us']::name[]) WITH ORDINALITY AS f(name, position) + JOIN pg_extension e ON e.extname = f.name + JOIN pg_available_extensions a ON a.name = e.extname + WHERE e.extversion <> a.default_version; + SELECT format('WARNING: extension %s in database %s stays at version %s: the image ships no update path from it to %s', extname, current_database(), extversion, default_version) FROM cozystack_postgis WHERE NOT reachable ORDER BY position; + SELECT format('updating extension %s in database %s from %s to %s', extname, current_database(), extversion, default_version) FROM cozystack_postgis WHERE reachable ORDER BY position; + SELECT format('DO %L', format('BEGIN PERFORM set_config(%L, greatest(1, floor(extract(epoch FROM %L::timestamptz - clock_timestamp()) * 1000))::bigint::text, false); PERFORM set_config(%L, current_setting(%L), false); END', 'statement_timeout', :'deadline_at', 'lock_timeout', 'statement_timeout')), + format('ALTER EXTENSION %I UPDATE TO %L', extname, default_version) + FROM cozystack_postgis WHERE reachable ORDER BY position \gexec + EOT + then + [ "${PIPESTATUS[0]}" != 2 ] || POSTGIS_LOST=yes + POSTGIS_FAILED="$POSTGIS_FAILED $db" + fi + done + if [ -n "$POSTGIS_LOST" ]; then + echo "lost the connection to the server during the PostGIS update in:$POSTGIS_FAILED" >&2 + exit 2 + fi + if [ -n "$POSTGIS_FAILED" ]; then + echo "PostGIS extension updates failed in:$POSTGIS_FAILED (the errors are above); the extensions there stay at their previous version. The next upgrade of the release starts the repair again" >&2 + exit 1 + fi + {{- end }} + [ -z "$COLLATION_FAILED" ] || exit 1 {{- end }} {{- if hasKey (.Values.users | default dict) "app" }} --- 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/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/tests/flavor_test.yaml b/packages/apps/postgres/tests/flavor_test.yaml index a5f740da4..80461d143 100644 --- a/packages/apps/postgres/tests/flavor_test.yaml +++ b/packages/apps/postgres/tests/flavor_test.yaml @@ -1,8 +1,8 @@ suite: postgres image flavor # The Cluster and the init Job must resolve the same image, and a live -# cluster must never be moved to the other flavor: the two image families -# ship different glibc versions, so CNPG would roll an image swap that -# corrupts collatable indexes. Tags are matched by pattern so that +# cluster must never be moved to the other flavor: only one image family +# carries the PostGIS libraries, and CNPG would roll the swap out as an +# ordinary image update. Tags are matched by pattern so that # hack/update-versions.sh can bump minors without touching this suite. release: name: pg-test @@ -20,7 +20,7 @@ tests: asserts: - matchRegex: path: spec.imageName - pattern: ^ghcr\.io/cloudnative-pg/postgresql:18\.[0-9]+$ + pattern: ^ghcr\.io/cloudnative-pg/postgresql:18\.[0-9]+-standard-trixie$ - it: postgis flavor switches the Cluster to the standard-trixie PostGIS image set: diff --git a/packages/apps/postgres/tests/locale_guard_test.yaml b/packages/apps/postgres/tests/locale_guard_test.yaml new file mode 100644 index 000000000..fe62dbb70 --- /dev/null +++ b/packages/apps/postgres/tests/locale_guard_test.yaml @@ -0,0 +1,526 @@ +suite: keep a bullseye cluster on its image until a clean locale check +release: + name: pg-test + namespace: tenant-test + upgrade: true +set: + _cluster: + scheduling: {} +kubernetesProvider: + scheme: + "postgresql.cnpg.io/v1/Cluster": + gvr: + group: postgresql.cnpg.io + version: v1 + resource: clusters + namespaced: true + objects: + - apiVersion: postgresql.cnpg.io/v1 + kind: Cluster + metadata: + name: pg-test + namespace: tenant-test + annotations: + postgres.cozystack.io/locale-data: affected + spec: + imageName: ghcr.io/cloudnative-pg/postgresql:18.1 + - apiVersion: postgresql.cnpg.io/v1 + kind: Cluster + metadata: + name: pg-clean + namespace: tenant-test + annotations: + postgres.cozystack.io/locale-data: clean + spec: + imageName: ghcr.io/cloudnative-pg/postgresql:18.1 + - apiVersion: postgresql.cnpg.io/v1 + kind: Cluster + metadata: + name: pg-unchecked + namespace: tenant-test + spec: + imageName: ghcr.io/cloudnative-pg/postgresql:18.1 + - apiVersion: postgresql.cnpg.io/v1 + kind: Cluster + metadata: + name: pg-unknown + namespace: tenant-test + annotations: + postgres.cozystack.io/locale-data: unknown + spec: + imageName: ghcr.io/cloudnative-pg/postgresql:18.1 + - apiVersion: postgresql.cnpg.io/v1 + kind: Cluster + metadata: + name: pg-trixie + namespace: tenant-test + annotations: + postgres.cozystack.io/locale-data: affected + spec: + imageName: ghcr.io/cloudnative-pg/postgresql:18.1-standard-trixie + - apiVersion: postgresql.cnpg.io/v1 + kind: Cluster + metadata: + name: pg-restored + namespace: tenant-test + spec: + imageName: ghcr.io/cloudnative-pg/postgresql:18.1 + bootstrap: + recovery: + source: pg-gone +tests: + - it: keeps a cluster the check found affected on its image + templates: + - templates/db.yaml + documentSelector: + path: kind + value: Cluster + asserts: + - equal: + path: spec.imageName + value: ghcr.io/cloudnative-pg/postgresql:18.1 + + - it: runs the init Job from the held image + templates: + - templates/init-job.yaml + documentSelector: + path: kind + value: Job + asserts: + - equal: + path: spec.template.spec.containers[0].image + value: ghcr.io/cloudnative-pg/postgresql:18.1 + + - it: keeps a cluster that was never checked on its image + release: + name: pg-unchecked + templates: + - templates/db.yaml + documentSelector: + path: kind + value: Cluster + asserts: + - equal: + path: spec.imageName + value: ghcr.io/cloudnative-pg/postgresql:18.1 + + - it: keeps a cluster the check could not finish on on its image + release: + name: pg-unknown + templates: + - templates/db.yaml + documentSelector: + path: kind + value: Cluster + asserts: + - equal: + path: spec.imageName + value: ghcr.io/cloudnative-pg/postgresql:18.1 + + - it: moves a cluster the check found clean + release: + name: pg-clean + templates: + - templates/db.yaml + documentSelector: + path: kind + value: Cluster + asserts: + - matchRegex: + path: spec.imageName + pattern: "^ghcr\\.io/cloudnative-pg/postgresql:18\\.[0-9]+-standard-trixie$" + + - it: moves an affected cluster once the change is allowed + set: + allowCollationChange: true + templates: + - templates/db.yaml + documentSelector: + path: kind + value: Cluster + asserts: + - matchRegex: + path: spec.imageName + pattern: "^ghcr\\.io/cloudnative-pg/postgresql:18\\.[0-9]+-standard-trixie$" + + - it: does not hold a cluster already on trixie + release: + name: pg-trixie + templates: + - templates/db.yaml + documentSelector: + path: kind + value: Cluster + asserts: + - matchRegex: + path: spec.imageName + pattern: "^ghcr\\.io/cloudnative-pg/postgresql:18\\.[0-9]+-standard-trixie$" + + - it: refuses a version change while held + set: + version: v17 + templates: + - templates/locale-check-hook.yaml + asserts: + - failedTemplate: + errorPattern: "version v17 cannot be applied: the cluster stays on ghcr.io/cloudnative-pg/postgresql:18.1" + + - it: allows a version change once the collation change is allowed + set: + version: v17 + allowCollationChange: true + templates: + - templates/db.yaml + documentSelector: + path: kind + value: Cluster + asserts: + - matchRegex: + path: spec.imageName + pattern: "^ghcr\\.io/cloudnative-pg/postgresql:17\\.[0-9]+-standard-trixie$" + + - it: restores a backup taken on a bullseye image onto that image + release: + name: pg-new + set: + bootstrap: + enabled: true + oldName: postgres-pg-0f1e2d3c + newServerName: pg-new-restore-0123456789abcdef + sourceImageName: ghcr.io/cloudnative-pg/postgresql:18.1 + backup: + s3AccessKey: access + s3SecretKey: secret + templates: + - templates/db.yaml + documentSelector: + path: kind + value: Cluster + asserts: + - equal: + path: spec.imageName + value: ghcr.io/cloudnative-pg/postgresql:18.1 + + - it: restores a backup taken on trixie onto the current image + release: + name: pg-new + set: + bootstrap: + enabled: true + oldName: postgres-pg-0f1e2d3c + newServerName: pg-new-restore-0123456789abcdef + sourceImageName: ghcr.io/cloudnative-pg/postgresql:18.1-standard-trixie + backup: + s3AccessKey: access + s3SecretKey: secret + templates: + - templates/db.yaml + documentSelector: + path: kind + value: Cluster + asserts: + - matchRegex: + path: spec.imageName + pattern: "^ghcr\\.io/cloudnative-pg/postgresql:18\\.[0-9]+-standard-trixie$" + + - it: never renders an image of another registry from bootstrap.sourceImageName + release: + name: pg-new + set: + bootstrap: + enabled: true + oldName: postgres-pg-0f1e2d3c + sourceImageName: "docker.io/attacker/payload:18" + backup: + s3AccessKey: access + s3SecretKey: secret + templates: + - templates/db.yaml + documentSelector: + path: kind + value: Cluster + asserts: + - matchRegex: + path: spec.imageName + pattern: "^ghcr\\.io/cloudnative-pg/postgresql:18\\.[0-9]+-standard-trixie$" + + - it: never renders a bare tag this chart never shipped from bootstrap.sourceImageName + release: + name: pg-new + set: + bootstrap: + enabled: true + oldName: postgres-pg-0f1e2d3c + sourceImageName: "ghcr.io/cloudnative-pg/postgresql:18.0" + backup: + s3AccessKey: access + s3SecretKey: secret + templates: + - templates/db.yaml + documentSelector: + path: kind + value: Cluster + asserts: + - matchRegex: + path: spec.imageName + pattern: "^ghcr\\.io/cloudnative-pg/postgresql:18\\.[0-9]+-standard-trixie$" + + - it: never renders a digest-pinned tag from bootstrap.sourceImageName + release: + name: pg-new + set: + bootstrap: + enabled: true + oldName: postgres-pg-0f1e2d3c + sourceImageName: "ghcr.io/cloudnative-pg/postgresql:18.1@sha256:0000000000000000000000000000000000000000000000000000000000000000" + backup: + s3AccessKey: access + s3SecretKey: secret + templates: + - templates/db.yaml + documentSelector: + path: kind + value: Cluster + asserts: + - matchRegex: + path: spec.imageName + pattern: "^ghcr\\.io/cloudnative-pg/postgresql:18\\.[0-9]+-standard-trixie$" + + - it: keeps a Cluster a recovery created on its image until it is checked + release: + name: pg-restored + set: + bootstrap: + enabled: true + oldName: pg-gone + backup: + s3AccessKey: access + s3SecretKey: secret + templates: + - templates/db.yaml + documentSelector: + path: kind + value: Cluster + asserts: + - equal: + path: spec.imageName + value: ghcr.io/cloudnative-pg/postgresql:18.1 + + - it: reads a live Cluster no recovery created on its own, whatever the bootstrap values say + release: + name: pg-clean + set: + bootstrap: + enabled: true + oldName: pg-test + sourceImageName: ghcr.io/cloudnative-pg/postgresql:18.1 + backup: + s3AccessKey: access + s3SecretKey: secret + templates: + - templates/db.yaml + documentSelector: + path: kind + value: Cluster + asserts: + - matchRegex: + path: spec.imageName + pattern: "^ghcr\\.io/cloudnative-pg/postgresql:18\\.[0-9]+-standard-trixie$" + + - it: restores a hand-set recovery onto the image of its source Cluster + release: + name: pg-new + set: + bootstrap: + enabled: true + oldName: pg-trixie + backup: + s3AccessKey: access + s3SecretKey: secret + templates: + - templates/db.yaml + documentSelector: + path: kind + value: Cluster + asserts: + - matchRegex: + path: spec.imageName + pattern: "^ghcr\\.io/cloudnative-pg/postgresql:18\\.[0-9]+-standard-trixie$" + + - it: holds a hand-set recovery of a bullseye source Cluster + release: + name: pg-new + set: + bootstrap: + enabled: true + oldName: pg-clean + backup: + s3AccessKey: access + s3SecretKey: secret + templates: + - templates/db.yaml + documentSelector: + path: kind + value: Cluster + asserts: + - equal: + path: spec.imageName + value: ghcr.io/cloudnative-pg/postgresql:18.1 + + - it: does not read a Cluster named like the server name of a RestoreJob + release: + name: pg-new + set: + bootstrap: + enabled: true + oldName: pg-test + newServerName: pg-new-restore-0123456789abcdef + backup: + s3AccessKey: access + s3SecretKey: secret + templates: + - templates/db.yaml + documentSelector: + path: kind + value: Cluster + asserts: + - matchRegex: + path: spec.imageName + pattern: "^ghcr\\.io/cloudnative-pg/postgresql:18\\.[0-9]+-standard-trixie$" + + - it: ignores a bootstrap.sourceImageName left over once the recovery is done + release: + name: pg-trixie + set: + bootstrap: + enabled: false + sourceImageName: ghcr.io/cloudnative-pg/postgresql:18.1 + templates: + - templates/db.yaml + documentSelector: + path: kind + value: Cluster + asserts: + - matchRegex: + path: spec.imageName + pattern: "^ghcr\\.io/cloudnative-pg/postgresql:18\\.[0-9]+-standard-trixie$" + + - it: never holds a postgis cluster on a postgresql image + release: + name: pg-new + set: + flavor: postgis + version: v17 + bootstrap: + enabled: true + oldName: postgres-pg-0f1e2d3c + sourceImageName: ghcr.io/cloudnative-pg/postgresql:17.7 + backup: + s3AccessKey: access + s3SecretKey: secret + templates: + - templates/db.yaml + documentSelector: + path: kind + value: Cluster + asserts: + - matchRegex: + path: spec.imageName + pattern: "^ghcr\\.io/cloudnative-pg/postgis:" + + - it: checks a bullseye cluster from its own image + release: + name: pg-unchecked + templates: + - templates/locale-check-hook.yaml + documentSelector: + path: kind + value: Job + asserts: + - equal: + path: spec.template.spec.initContainers[0].image + value: ghcr.io/cloudnative-pg/postgresql:18.1 + + - it: rechecks a held cluster from its held image + templates: + - templates/locale-check-hook.yaml + documentSelector: + path: kind + value: Job + asserts: + - equal: + path: spec.template.spec.initContainers[0].image + value: ghcr.io/cloudnative-pg/postgresql:18.1 + + - it: skips the check once the change is allowed + set: + allowCollationChange: true + templates: + - templates/locale-check-hook.yaml + asserts: + - hasDocuments: + count: 0 + + - it: skips the check for a cluster already on trixie + release: + name: pg-trixie + templates: + - templates/locale-check-hook.yaml + asserts: + - hasDocuments: + count: 0 + + - it: skips the check for a new cluster + release: + name: pg-new + templates: + - templates/locale-check-hook.yaml + asserts: + - hasDocuments: + count: 0 + + - it: does not check a cluster while its restore is in progress + release: + name: pg-unchecked + set: + bootstrap: + enabled: true + oldName: pg-test + backup: + s3AccessKey: access + s3SecretKey: secret + templates: + - templates/locale-check-hook.yaml + asserts: + - hasDocuments: + count: 0 + + - it: names the hook resources so that they cannot take the names CNPG gives another cluster + release: + name: pg-unchecked + templates: + - templates/locale-check-hook.yaml + documentSelector: + path: kind + value: Job + asserts: + - matchRegex: + path: metadata.name + pattern: ^locale-check-pg-unchecked-[0-9a-f]{8}$ + + - it: lets the role patch only its own Cluster + release: + name: pg-unchecked + templates: + - templates/locale-check-hook.yaml + documentSelector: + path: kind + value: Role + asserts: + - equal: + path: rules + value: + - apiGroups: ["postgresql.cnpg.io"] + resources: ["clusters"] + resourceNames: ["pg-unchecked"] + verbs: ["get", "patch"] diff --git a/packages/apps/postgres/values.schema.json b/packages/apps/postgres/values.schema.json index 4b5542d15..e9a4f7667 100644 --- a/packages/apps/postgres/values.schema.json +++ b/packages/apps/postgres/values.schema.json @@ -149,6 +149,11 @@ "postgis" ] }, + "allowCollationChange": { + "description": "Allow a cluster created on a Debian bullseye image (before the move to standard-trixie) to move to the new image without a clean locale check. Such a cluster is checked before each upgrade, except while `bootstrap.enabled` is set (set it back to false once a restore set up by hand has finished), and stays on its current image until the check finds nothing that depends on a collation other than C, POSIX or builtin: while this is false, a cluster the check found affected (an ICU or libc locale, or C.UTF-8) or could not finish on stays put, because glibc and ICU on the new image sort text differently and every index on such text must be rebuilt. A held cluster runs the bare bullseye tag it has, gets no further PostgreSQL minors and so none of their security fixes, and refuses a change of `version`, since new majors are built only on the new images. To leave that state, either remove the dependency (move such columns and indexes to C, or to the builtin `pg_c_utf8` on PostgreSQL 17 and later) and let the next upgrade check again, or set this to true in a maintenance window: the cluster moves on the next upgrade, replicas restart on the new image first and can return wrong results through `-ro`, and unique indexes can accept duplicates, until the indexes are rebuilt on the primary. The 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", @@ -476,6 +481,11 @@ "description": "Server name (S3 path prefix) used by the original cluster when writing backups; passed to the barman-cloud plugin via `externalClusters[].plugin.parameters.serverName`. Defaults to `bootstrap.oldName`. Set this only when the original cluster wrote backups under an explicit server name that differed from its Kubernetes resource name.", "type": "string", "default": "" + }, + "sourceImageName": { + "description": "Image of the cluster the backup was taken from. A restore of a backup taken on one of the bare Debian bullseye tags the chart used before standard-trixie comes back on that image (see `allowCollationChange`); any other value is ignored. The CNPG backup driver sets this on restore and clears it with `enabled`.", + "type": "string", + "default": "" } } } diff --git a/packages/apps/postgres/values.yaml b/packages/apps/postgres/values.yaml index a8d324dc8..b8f87a4ec 100644 --- a/packages/apps/postgres/values.yaml +++ b/packages/apps/postgres/values.yaml @@ -95,6 +95,9 @@ version: v18 ## @param {Flavor} flavor - PostgreSQL image flavor, fixed when the cluster is created. `postgresql` uses the CloudNativePG PostgreSQL image. `postgis` uses the CloudNativePG PostGIS image, which adds postgis, postgis_raster, postgis_topology, postgis_sfcgal, postgis_tiger_geocoder and address_standardizer; enable them per database in `databases..extensions`. Changing the flavor of an existing cluster is refused, and a backup restores only into a cluster of the flavor it was taken from: to change flavor, create a new cluster and move the data with a logical dump (pg_dump / pg_restore). flavor: postgresql +## @param {bool} allowCollationChange - Allow a cluster created on a Debian bullseye image (before the move to standard-trixie) to move to the new image without a clean locale check. Such a cluster is checked before each upgrade, except while `bootstrap.enabled` is set (set it back to false once a restore set up by hand has finished), and stays on its current image until the check finds nothing that depends on a collation other than C, POSIX or builtin: while this is false, a cluster the check found affected (an ICU or libc locale, or C.UTF-8) or could not finish on stays put, because glibc and ICU on the new image sort text differently and every index on such text must be rebuilt. A held cluster runs the bare bullseye tag it has, gets no further PostgreSQL minors and so none of their security fixes, and refuses a change of `version`, since new majors are built only on the new images. To leave that state, either remove the dependency (move such columns and indexes to C, or to the builtin `pg_c_utf8` on PostgreSQL 17 and later) and let the next upgrade check again, or set this to true in a maintenance window: the cluster moves on the next upgrade, replicas restart on the new image first and can return wrong results through `-ro`, and unique indexes can accept duplicates, until the indexes are rebuilt on the primary. The 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 + ## ## @section TLS configuration ## @@ -382,6 +385,7 @@ backup: ## @field {string} oldName - Previous cluster name before deletion. ## @field {string} [serverName] - Server name (S3 path prefix) used by the original cluster when writing backups; passed to the barman-cloud plugin via `externalClusters[].plugin.parameters.serverName`. Defaults to `bootstrap.oldName`. Set this only when the original cluster wrote backups under an explicit server name that differed from its Kubernetes resource name. ## @field {string} [newServerName] - WAL-archive server name (S3 path prefix) the RESTORED cluster writes to. Must differ from `serverName` (the recovery source) so a restored cluster archives to a fresh, empty prefix and barman-cloud-check-wal-archive passes while it recovers from the source's prefix. The CNPG backup driver sets this on restore; empty means the cluster archives under its own name. +## @field {string} [sourceImageName] - Image of the cluster the backup was taken from. A restore of a backup taken on one of the bare Debian bullseye tags the chart used before standard-trixie comes back on that image (see `allowCollationChange`); any other value is ignored. The CNPG backup driver sets this on restore and clears it with `enabled`. ## @param {Bootstrap} bootstrap - Bootstrap configuration. bootstrap: @@ -392,3 +396,4 @@ bootstrap: oldName: "" serverName: "" newServerName: "" + sourceImageName: "" diff --git a/packages/system/postgres-rd/cozyrds/postgres.yaml b/packages/system/postgres-rd/cozyrds/postgres.yaml index 052cb575d..3e66192ec 100644 --- a/packages/system/postgres-rd/cozyrds/postgres.yaml +++ b/packages/system/postgres-rd/cozyrds/postgres.yaml @@ -30,7 +30,7 @@ spec: singular: postgres plural: postgreses openAPISchema: |- - {"title":"Chart Values","type":"object","properties":{"replicas":{"description":"Number of Postgres replicas. Under active autoscaling this is the resting/seed count, not the live count — KEDA drives the live count via `/scale`. Disabling autoscaling does NOT automatically bring the live count back to `replicas`: the client-side merge writes `instances` only when the rendered value changes, so a cluster KEDA grew past `replicas` stays there with no autoscaler left to reduce it — lower `replicas` to the count you want and it rebases down (shedding the surplus replicas + PVCs). Lowering it below the live count, or disabling/dry-running while it sits below the live count, sheds in one step past the scaleDown pacing; stage it to the live count first (suspend the HelmRelease and `kubectl scale` if needed) to avoid a transient. Must stay greater than `quorum.maxSyncReplicas`.","type":"integer","default":2},"resources":{"description":"Explicit CPU and memory configuration for each PostgreSQL replica. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","default":{},"properties":{"cpu":{"description":"CPU available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Memory (RAM) available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted.","type":"string","default":"t1.micro","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]},"size":{"description":"Persistent Volume Claim size available for application data.","default":"10Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"storageClass":{"description":"StorageClass used to store the data.","type":"string","default":"","x-kubernetes-validations":[{"rule":"self == oldSelf","message":"storageClass is immutable"}],"x-cozystack-options":{"source":"storageclass"}},"external":{"description":"Enable external access from outside the cluster.","type":"boolean","default":false},"version":{"description":"PostgreSQL major version to deploy","type":"string","default":"v18","enum":["v18","v17","v16","v15","v14","v13"]},"flavor":{"description":"PostgreSQL image flavor, fixed when the cluster is created. `postgresql` uses the CloudNativePG PostgreSQL image. `postgis` uses the CloudNativePG PostGIS image, which adds postgis, postgis_raster, postgis_topology, postgis_sfcgal, postgis_tiger_geocoder and address_standardizer; enable them per database in `databases..extensions`. Changing the flavor of an existing cluster is refused, and a backup restores only into a cluster of the flavor it was taken from: to change flavor, create a new cluster and move the data with a logical dump (pg_dump / pg_restore).","type":"string","default":"postgresql","enum":["postgresql","postgis"]},"tls":{"description":"TLS configuration for server connections.","type":"object","default":{},"properties":{"enabled":{"description":"Tri-state switch controlling whether the chart injects the external hostnames into the operator-managed CNPG cert via spec.certificates.serverAltDNSNames. When omitted, the chart injects them if `external: true` and skips them otherwise. Set explicitly to `true` to inject regardless of `external` (no-op when `external: false` since there is no external hostname to add). Set to `false` to skip injection. Note that CNPG keeps its built-in TLS on the wire regardless of this flag — this toggle only controls the chart-side SAN injection; to disable PostgreSQL TLS entirely set `postgresql.parameters.ssl = \"off\"` at the CNPG layer.","type":"boolean"},"required":{"description":"Tri-state switch controlling whether the server refuses sessions that are not encrypted. When omitted, it is on if `external: true` and off otherwise. When on, the chart renders `spec.postgresql.pg_hba` with `hostssl all all all scram-sha-256` (`md5` on PostgreSQL 13, matching CloudNativePG's default rule) followed by `host all all all reject`, so a client that connects with `sslmode=disable` is refused instead of getting a plaintext session; in-cluster clients are held to the same rule, since the pod network cannot be told apart from an external client. Set to `false` to keep accepting plaintext sessions on an external instance, or to `true` to require TLS on an in-cluster one. Rendering fails if `postgresql.parameters.ssl` is off while this is in effect.","type":"boolean"}}},"postgresql":{"description":"PostgreSQL server configuration.","type":"object","default":{},"properties":{"parameters":{"description":"PostgreSQL server parameters. Values may be strings or integers; integers are coerced to strings by the template (e.g. both `max_connections: 100` and `max_connections: \"100\"` are accepted). BLOCKED (enable arbitrary code execution): archive_command, restore_command, ssl_passphrase_command, archive_cleanup_command, recovery_end_command, dynamic_library_path, local_preload_libraries, session_preload_libraries, shared_preload_libraries. Do NOT override CloudNativePG-managed parameters: archive_mode, primary_conninfo, wal_level, max_replication_slots.","type":"object","default":{"max_connections":"100"},"additionalProperties":{"anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}},"sharedPreloadLibraries":{"description":"Libraries loaded at server start, restricted to an allowlist of modules already shipped in the PostgreSQL image. CloudNativePG also preloads `pg_stat_statements`, `auto_explain` and `pgaudit` by itself whenever `parameters` sets a key under their prefix (e.g. `pg_stat_statements.track`), so removing one of them from this list does not unload it while such a key is set; `pg_prewarm` is preloaded only through this list. Changing the list restarts PostgreSQL on every instance, the primary included, so writes pause briefly.","type":"array","items":{"type":"string","enum":["pg_stat_statements","auto_explain","pgaudit","pg_prewarm"]}}}},"quorum":{"description":"Quorum configuration for synchronous replication.","type":"object","default":{},"required":["maxSyncReplicas","minSyncReplicas"],"properties":{"maxSyncReplicas":{"description":"Maximum number of synchronous replicas allowed (must be less than total replicas). Under autoscaling it also sets the scale-down floor (the effective minimum is `max(minReplicas, maxSyncReplicas+1, 2)`); the chart fails to render if that floor exceeds `autoscaling.maxReplicas`.","type":"integer","default":0},"minSyncReplicas":{"description":"Minimum number of synchronous replicas required for commit.","type":"integer","default":0}}},"autoscaling":{"description":"Read-replica autoscaling configuration.","type":"object","default":{},"required":["dryRun","enabled","maxReplicas","maxReplicationLagSeconds","metric","minReplicas","serverAddress","target","transition"],"properties":{"dryRun":{"description":"Recommendation mode: keep the static count and render the ScaledObject with both scaling directions paused, so KEDA keeps the HPA and keeps serving its trigger metric but actuates neither way. Note both scaling policies are disabled, so the HPA's desiredReplicas is frozen to the current count - read the recommendation from the matching read-load dashboard panel for your metric (connections or CPU): desired = 1 + ceil(read load / target), clamped to [effectiveMin..maxReplicas] where effectiveMin = max(minReplicas, maxSyncReplicas+1, 2), not from the desired-replicas line. Like disabling, flipping a LIVE autoscaled cluster into dryRun re-renders `instances: replicas` (the raw static value, which can be below the autoscaling floor); if `replicas` is below the live count, stage it to the live count first (see the enablement note) or the cluster sheds down to `replicas`. No shed occurs when the rendered value is unchanged (replicas already equals the active seed) — client-side merge is then a no-op and the live count is preserved. Permanent, unlike `transition`.","type":"boolean","default":false},"enabled":{"description":"Enable horizontal autoscaling of read replicas. Requires the platform `keda` package to be enabled by an administrator first; the chart fails to render (rather than break the release) if KEDA is not installed. Prerequisite: the queried vmselect must hold BOTH the CNPG metrics (cnpg_backends_total / container CPU) AND kube_pod_labels (kube-state-metrics). This holds for a tenant on the shared root monitoring stack (`monitoring: false`, both land in tenant-root). A tenant running its OWN Monitoring app (`monitoring: true`) has the CNPG metrics but not kube_pod_labels (KSM is root-only), so it must set `serverAddress` to a vmselect carrying both series or autoscaling never actuates.","type":"boolean","default":false},"maxReplicas":{"description":"Maximum total instances. Must be >= minReplicas and >= the synchronous-quorum floor (maxSyncReplicas+1); the chart fails to render (rather than silently run an unbounded instance count) if the effective floor exceeds it - raise maxReplicas. HAZARD: lowering maxReplicas below the live count makes the HPA cut straight to the new maximum in one step (the current>max branch bypasses the scale-down pacing), shedding the surplus replicas + PVCs at once; to lower it deliberately, suspend the HelmRelease and pin the live count with `kubectl scale` first.","type":"integer","default":6},"maxReplicationLagSeconds":{"description":"Freeze scaling while replication lag exceeds this (seconds) and the primary is writing. 0 disables the brake. Default 0: the freeze branch has only been validated on a live cluster in its non-braking (pass-through) form, so the lag brake is opt-in until the braking path is exercised under load; set a positive value (e.g. 30) to enable it.","type":"integer","default":0},"metric":{"description":"Read-load signal to scale on.","type":"string","default":"ReadConnections","enum":["ReadConnections","ReadCPUUtilization"]},"minReplicas":{"description":"Minimum total instances; raised to the synchronous-quorum floor (`maxSyncReplicas + 1`) and to 2 when either is higher.","type":"integer","default":2},"serverAddress":{"description":"Override the Prometheus/vmselect URL the ScaledObject queries. Empty (default) derives `http://vmselect-shortterm..svc:8481/select/0/prometheus`. Set it when the derived vmselect does not hold both the CNPG metrics and kube_pod_labels (e.g. `monitoring: true` tenants, or a non-default `metricsStorages` name). SSRF constraint: the host must be an in-cluster Service DNS name (`..svc[.]`) whose namespace is within the tenant's own subtree (its namespace, its parents, or `tenant-root`) — the cluster-privileged KEDA operator fetches this URL every poll, so it is refused a metadata endpoint, an external host, or a sibling/system namespace. Residual surface (accepted trade-off): `tenant-root` is always allowed because the derived default points there, so a tenant can still aim the operator at any Service in `tenant-root` on any port/path (a blind in-cluster reachability probe — the operator reads no response body back to the tenant); the egress NetworkPolicy does not narrow that.","type":"string","default":""},"target":{"description":"Target read load per read-serving replica (unit depends on `metric`: active connections, or CPU millicores). Dimensionless integer - a resource.Quantity here would accept `150m`, which PromQL reads as 150 minutes and KEDA cannot use as a threshold.","type":"integer","default":150},"transition":{"description":"Migration phase 1: render `.spec.instances` from `replicas` (which the operator stages to the current live count) AND pause the ScaledObject in both directions, so KEDA stands up with its HPA present but not actuating. Flip to false (phase 2) to hand the runtime count to KEDA. Because the both-direction pause keeps the HPA (not the HPA-deleting full pause), KEDA is genuinely warm at phase 2 — no HPA recreate — and because the active seed is max(replicas, effectiveMin), phase 2 re-renders the same instance count phase 1 did (when `replicas` is staged at/above the floor), so the flip is a merge no-op with no dip. The HPA's scaleUp stabilization window still smooths the first actuation.","type":"boolean","default":false}}},"users":{"description":"Users configuration map. Passwords are always auto-generated and stored in the `-credentials` Secret; they cannot be set from values — read a user's password from that Secret. A `password` left over in values from before the field was removed is ignored by the render and draws an admission warning, but it is not inert on an upgraded release: the chart preserves whatever password is already in the Secret, which on the first upgrade is the value that was set before removal, so that value stays the live credential until it is rotated (dedicated rotation is tracked in cozystack/community#72). The live password lives only in the Secret.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"bypassRls":{"description":"Whether the user can bypass row-level security policies (BYPASSRLS). A role can only create other roles carrying BYPASSRLS if it holds the attribute itself, so this is required alongside `createRole` to provision a privileged service role.","type":"boolean"},"createRole":{"description":"Whether the user can create and manage roles (CREATEROLE). Requires PostgreSQL 16 or newer. Setting it back to `false` withdraws the attribute only: the roles the user created, and its ADMIN and SET memberships in them, stay. Once any user has held it, the chart no longer adopts an existing role it did not create, so a user or database declared later under the name of such a role fails the init job until a platform administrator drops that role.","type":"boolean"},"replication":{"description":"Whether the user has replication privileges.","type":"boolean"}}}},"databases":{"description":"Databases configuration map. The PostgreSQL system databases `postgres`, `template0` and `template1` are refused.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"extensions":{"description":"List of enabled PostgreSQL extensions.","type":"array","items":{"type":"string"}},"roles":{"description":"Roles assigned to users.","type":"object","properties":{"admin":{"description":"List of users with admin privileges.","type":"array","items":{"type":"string"}},"readonly":{"description":"List of users with read-only privileges.","type":"array","items":{"type":"string"}}}}}}},"backup":{"description":"Backup configuration.","type":"object","default":{},"required":["enabled"],"properties":{"destinationPath":{"description":"DEPRECATED. Per-tenant S3 configuration is superseded by the platform-managed `cozy-default` BackupClass and the `cozy-backups` system bucket. Leave empty for new installations; the BackupClass driver picks up the system-managed coordinates. Kept for in-place upgrade compatibility.","type":"string","default":"s3://bucket/path/to/folder/"},"enabled":{"description":"Enable regular backups.","type":"boolean","default":false},"endpointCA":{"description":"DEPRECATED. Pre-existing Secret with the CA bundle the barman-cloud plugin should trust when reaching a self-signed S3 endpoint. Used for both backup and bootstrap recovery in the legacy chart-managed flow.","type":"object","default":{},"properties":{"key":{"description":"Key within the Secret containing the CA bundle. Defaults to `ca.crt`.","type":"string","default":""},"name":{"description":"Name of the Secret in the application namespace. Empty means no endpointCA is emitted (the plugin uses the system trust store).","type":"string","default":""}}},"endpointURL":{"description":"DEPRECATED. See `destinationPath`.","type":"string","default":"http://minio-gateway-service:9000"},"retentionPolicy":{"description":"Retention policy (e.g. \"30d\").","type":"string","default":"30d"},"s3AccessKey":{"description":"DEPRECATED. Tenants no longer supply S3 keys; the system Bucket Secret is projected into the tenant namespace by the backup controller. Ignored when `s3CredentialsSecret.name` is set or `useSystemBucket` is true. The chart skips materialising `-s3-creds` whenever this field is empty so a default install does not leak placeholder credentials into the tenant namespace.","type":"string","default":""},"s3CredentialsSecret":{"description":"DEPRECATED. Pre-existing Secret with S3 credentials. Use the platform-managed `cozy-default` BackupClass instead. When set, the chart references this Secret directly (legacy chart-managed flow). The CNPG backup driver writes this field on restore so credentials never land in the CR `.spec`.","type":"object","default":{},"properties":{"accessKeyIDKey":{"description":"Key in the Secret holding the access key ID. Defaults to `AWS_ACCESS_KEY_ID`.","type":"string","default":""},"name":{"description":"Name of the Secret in the application namespace. Empty means the chart materialises `-s3-creds` from `s3AccessKey`/`s3SecretKey`.","type":"string","default":""},"secretAccessKeyKey":{"description":"Key in the Secret holding the secret access key. Defaults to `AWS_SECRET_ACCESS_KEY`.","type":"string","default":""}}},"s3SecretKey":{"description":"DEPRECATED. See `s3AccessKey`.","type":"string","default":""},"schedule":{"description":"Legacy. Cron schedule for the chart-emitted ScheduledBackup, either a standard five-field cron such as `0 2 * * *` for every day at 02:00, or six fields with leading seconds such as `0 0 2 * * *` for the same time. Empty means no chart-managed schedule, which is the recommended setup when a `BackupClass` from `backups.cozystack.io` already drives backup orchestration. In the legacy chart-managed flow `spec.plugins` plus the barman-cloud ObjectStore is rendered when `backup.enabled=true` AND `useSystemBucket=false` AND `destinationPath` is non-empty AND inline-or-external creds are supplied; in the platform `useSystemBucket=true` flow the chart skips emitting `spec.plugins` and the CNPG driver SSA-applies the ObjectStore and patches `spec.plugins` onto the live Cluster at first BackupJob time.","type":"string","default":""},"useSystemBucket":{"description":"Opt-in: when true, the chart-emitted `-s3-creds` Secret is skipped AND `spec.plugins` (plus the barman-cloud ObjectStore) is left UNSET in the chart-rendered Cluster — the cozy-default BackupClass driver SSA-applies an ObjectStore (carrying destinationPath/endpointURL/credentials) and patches `spec.plugins` on the live Cluster when the first BackupJob runs. Consequence: plugin WAL archiving is NOT active until that first BackupJob fires; WAL accumulates on the PVC in the meantime, so fire an ad-hoc BackupJob immediately after enabling the flag on existing releases. Use together with the platform `cozy-default` BackupClass — tenants do not need to fill `s3AccessKey`/`s3SecretKey` or `destinationPath`/`endpointURL`. The destination path automatically scopes to `s3://cozy-backups///`.","type":"boolean","default":false}}},"bootstrap":{"description":"Bootstrap configuration.","type":"object","default":{},"required":["enabled","oldName"],"properties":{"backupID":{"description":"Barman ID of the base backup to recover from, passed as `recoveryTarget.backupID`. Empty lets the barman-cloud plugin pick one: the newest backup when `recoveryTime` is empty, otherwise the newest one ending at or before it, on any timeline. The CNPG backup driver sets this on restore.","type":"string","default":""},"enabled":{"description":"Whether to restore from a backup.","type":"boolean","default":false},"newServerName":{"description":"WAL-archive server name (S3 path prefix) the RESTORED cluster writes to. Must differ from `serverName` (the recovery source) so a restored cluster archives to a fresh, empty prefix and barman-cloud-check-wal-archive passes while it recovers from the source's prefix. The CNPG backup driver sets this on restore; empty means the cluster archives under its own name.","type":"string","default":""},"oldName":{"description":"Previous cluster name before deletion.","type":"string","default":""},"recoveryTime":{"description":"Timestamp (RFC3339) for point-in-time recovery; empty means latest.","type":"string","default":""},"serverName":{"description":"Server name (S3 path prefix) used by the original cluster when writing backups; passed to the barman-cloud plugin via `externalClusters[].plugin.parameters.serverName`. Defaults to `bootstrap.oldName`. Set this only when the original cluster wrote backups under an explicit server name that differed from its Kubernetes resource name.","type":"string","default":""}}}}} + {"title":"Chart Values","type":"object","properties":{"replicas":{"description":"Number of Postgres replicas. Under active autoscaling this is the resting/seed count, not the live count — KEDA drives the live count via `/scale`. Disabling autoscaling does NOT automatically bring the live count back to `replicas`: the client-side merge writes `instances` only when the rendered value changes, so a cluster KEDA grew past `replicas` stays there with no autoscaler left to reduce it — lower `replicas` to the count you want and it rebases down (shedding the surplus replicas + PVCs). Lowering it below the live count, or disabling/dry-running while it sits below the live count, sheds in one step past the scaleDown pacing; stage it to the live count first (suspend the HelmRelease and `kubectl scale` if needed) to avoid a transient. Must stay greater than `quorum.maxSyncReplicas`.","type":"integer","default":2},"resources":{"description":"Explicit CPU and memory configuration for each PostgreSQL replica. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","default":{},"properties":{"cpu":{"description":"CPU available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Memory (RAM) available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted.","type":"string","default":"t1.micro","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]},"size":{"description":"Persistent Volume Claim size available for application data.","default":"10Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"storageClass":{"description":"StorageClass used to store the data.","type":"string","default":"","x-kubernetes-validations":[{"rule":"self == oldSelf","message":"storageClass is immutable"}],"x-cozystack-options":{"source":"storageclass"}},"external":{"description":"Enable external access from outside the cluster.","type":"boolean","default":false},"version":{"description":"PostgreSQL major version to deploy","type":"string","default":"v18","enum":["v18","v17","v16","v15","v14","v13"]},"flavor":{"description":"PostgreSQL image flavor, fixed when the cluster is created. `postgresql` uses the CloudNativePG PostgreSQL image. `postgis` uses the CloudNativePG PostGIS image, which adds postgis, postgis_raster, postgis_topology, postgis_sfcgal, postgis_tiger_geocoder and address_standardizer; enable them per database in `databases..extensions`. Changing the flavor of an existing cluster is refused, and a backup restores only into a cluster of the flavor it was taken from: to change flavor, create a new cluster and move the data with a logical dump (pg_dump / pg_restore).","type":"string","default":"postgresql","enum":["postgresql","postgis"]},"allowCollationChange":{"description":"Allow a cluster created on a Debian bullseye image (before the move to standard-trixie) to move to the new image without a clean locale check. Such a cluster is checked before each upgrade, except while `bootstrap.enabled` is set (set it back to false once a restore set up by hand has finished), and stays on its current image until the check finds nothing that depends on a collation other than C, POSIX or builtin: while this is false, a cluster the check found affected (an ICU or libc locale, or C.UTF-8) or could not finish on stays put, because glibc and ICU on the new image sort text differently and every index on such text must be rebuilt. A held cluster runs the bare bullseye tag it has, gets no further PostgreSQL minors and so none of their security fixes, and refuses a change of `version`, since new majors are built only on the new images. To leave that state, either remove the dependency (move such columns and indexes to C, or to the builtin `pg_c_utf8` on PostgreSQL 17 and later) and let the next upgrade check again, or set this to true in a maintenance window: the cluster moves on the next upgrade, replicas restart on the new image first and can return wrong results through `-ro`, and unique indexes can accept duplicates, until the indexes are rebuilt on the primary. The collation repair Job, which a post-upgrade hook starts once the init Job is done, rebuilds the indexes on such text after the rollout, those on C.UTF-8 and other C.* locales included, and its log reports a rebuild that failed; check range partitions, CHECK constraints and materialized views on it, which a rebuild does not fix. A held cluster shows the hold only as an unchanged image; the result and the objects found are in the `postgres.cozystack.io/locale-data` and `postgres.cozystack.io/locale-data-objects` annotations of the cnpg.io Cluster, which an administrator can read. A restore of a backup taken on one of those bullseye images comes back on that image and is checked by the next upgrade.","type":"boolean","default":false},"tls":{"description":"TLS configuration for server connections.","type":"object","default":{},"properties":{"enabled":{"description":"Tri-state switch controlling whether the chart injects the external hostnames into the operator-managed CNPG cert via spec.certificates.serverAltDNSNames. When omitted, the chart injects them if `external: true` and skips them otherwise. Set explicitly to `true` to inject regardless of `external` (no-op when `external: false` since there is no external hostname to add). Set to `false` to skip injection. Note that CNPG keeps its built-in TLS on the wire regardless of this flag — this toggle only controls the chart-side SAN injection; to disable PostgreSQL TLS entirely set `postgresql.parameters.ssl = \"off\"` at the CNPG layer.","type":"boolean"},"required":{"description":"Tri-state switch controlling whether the server refuses sessions that are not encrypted. When omitted, it is on if `external: true` and off otherwise. When on, the chart renders `spec.postgresql.pg_hba` with `hostssl all all all scram-sha-256` (`md5` on PostgreSQL 13, matching CloudNativePG's default rule) followed by `host all all all reject`, so a client that connects with `sslmode=disable` is refused instead of getting a plaintext session; in-cluster clients are held to the same rule, since the pod network cannot be told apart from an external client. Set to `false` to keep accepting plaintext sessions on an external instance, or to `true` to require TLS on an in-cluster one. Rendering fails if `postgresql.parameters.ssl` is off while this is in effect.","type":"boolean"}}},"postgresql":{"description":"PostgreSQL server configuration.","type":"object","default":{},"properties":{"parameters":{"description":"PostgreSQL server parameters. Values may be strings or integers; integers are coerced to strings by the template (e.g. both `max_connections: 100` and `max_connections: \"100\"` are accepted). BLOCKED (enable arbitrary code execution): archive_command, restore_command, ssl_passphrase_command, archive_cleanup_command, recovery_end_command, dynamic_library_path, local_preload_libraries, session_preload_libraries, shared_preload_libraries. Do NOT override CloudNativePG-managed parameters: archive_mode, primary_conninfo, wal_level, max_replication_slots.","type":"object","default":{"max_connections":"100"},"additionalProperties":{"anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}},"sharedPreloadLibraries":{"description":"Libraries loaded at server start, restricted to an allowlist of modules already shipped in the PostgreSQL image. CloudNativePG also preloads `pg_stat_statements`, `auto_explain` and `pgaudit` by itself whenever `parameters` sets a key under their prefix (e.g. `pg_stat_statements.track`), so removing one of them from this list does not unload it while such a key is set; `pg_prewarm` is preloaded only through this list. Changing the list restarts PostgreSQL on every instance, the primary included, so writes pause briefly.","type":"array","items":{"type":"string","enum":["pg_stat_statements","auto_explain","pgaudit","pg_prewarm"]}}}},"quorum":{"description":"Quorum configuration for synchronous replication.","type":"object","default":{},"required":["maxSyncReplicas","minSyncReplicas"],"properties":{"maxSyncReplicas":{"description":"Maximum number of synchronous replicas allowed (must be less than total replicas). Under autoscaling it also sets the scale-down floor (the effective minimum is `max(minReplicas, maxSyncReplicas+1, 2)`); the chart fails to render if that floor exceeds `autoscaling.maxReplicas`.","type":"integer","default":0},"minSyncReplicas":{"description":"Minimum number of synchronous replicas required for commit.","type":"integer","default":0}}},"autoscaling":{"description":"Read-replica autoscaling configuration.","type":"object","default":{},"required":["dryRun","enabled","maxReplicas","maxReplicationLagSeconds","metric","minReplicas","serverAddress","target","transition"],"properties":{"dryRun":{"description":"Recommendation mode: keep the static count and render the ScaledObject with both scaling directions paused, so KEDA keeps the HPA and keeps serving its trigger metric but actuates neither way. Note both scaling policies are disabled, so the HPA's desiredReplicas is frozen to the current count - read the recommendation from the matching read-load dashboard panel for your metric (connections or CPU): desired = 1 + ceil(read load / target), clamped to [effectiveMin..maxReplicas] where effectiveMin = max(minReplicas, maxSyncReplicas+1, 2), not from the desired-replicas line. Like disabling, flipping a LIVE autoscaled cluster into dryRun re-renders `instances: replicas` (the raw static value, which can be below the autoscaling floor); if `replicas` is below the live count, stage it to the live count first (see the enablement note) or the cluster sheds down to `replicas`. No shed occurs when the rendered value is unchanged (replicas already equals the active seed) — client-side merge is then a no-op and the live count is preserved. Permanent, unlike `transition`.","type":"boolean","default":false},"enabled":{"description":"Enable horizontal autoscaling of read replicas. Requires the platform `keda` package to be enabled by an administrator first; the chart fails to render (rather than break the release) if KEDA is not installed. Prerequisite: the queried vmselect must hold BOTH the CNPG metrics (cnpg_backends_total / container CPU) AND kube_pod_labels (kube-state-metrics). This holds for a tenant on the shared root monitoring stack (`monitoring: false`, both land in tenant-root). A tenant running its OWN Monitoring app (`monitoring: true`) has the CNPG metrics but not kube_pod_labels (KSM is root-only), so it must set `serverAddress` to a vmselect carrying both series or autoscaling never actuates.","type":"boolean","default":false},"maxReplicas":{"description":"Maximum total instances. Must be >= minReplicas and >= the synchronous-quorum floor (maxSyncReplicas+1); the chart fails to render (rather than silently run an unbounded instance count) if the effective floor exceeds it - raise maxReplicas. HAZARD: lowering maxReplicas below the live count makes the HPA cut straight to the new maximum in one step (the current>max branch bypasses the scale-down pacing), shedding the surplus replicas + PVCs at once; to lower it deliberately, suspend the HelmRelease and pin the live count with `kubectl scale` first.","type":"integer","default":6},"maxReplicationLagSeconds":{"description":"Freeze scaling while replication lag exceeds this (seconds) and the primary is writing. 0 disables the brake. Default 0: the freeze branch has only been validated on a live cluster in its non-braking (pass-through) form, so the lag brake is opt-in until the braking path is exercised under load; set a positive value (e.g. 30) to enable it.","type":"integer","default":0},"metric":{"description":"Read-load signal to scale on.","type":"string","default":"ReadConnections","enum":["ReadConnections","ReadCPUUtilization"]},"minReplicas":{"description":"Minimum total instances; raised to the synchronous-quorum floor (`maxSyncReplicas + 1`) and to 2 when either is higher.","type":"integer","default":2},"serverAddress":{"description":"Override the Prometheus/vmselect URL the ScaledObject queries. Empty (default) derives `http://vmselect-shortterm..svc:8481/select/0/prometheus`. Set it when the derived vmselect does not hold both the CNPG metrics and kube_pod_labels (e.g. `monitoring: true` tenants, or a non-default `metricsStorages` name). SSRF constraint: the host must be an in-cluster Service DNS name (`..svc[.]`) whose namespace is within the tenant's own subtree (its namespace, its parents, or `tenant-root`) — the cluster-privileged KEDA operator fetches this URL every poll, so it is refused a metadata endpoint, an external host, or a sibling/system namespace. Residual surface (accepted trade-off): `tenant-root` is always allowed because the derived default points there, so a tenant can still aim the operator at any Service in `tenant-root` on any port/path (a blind in-cluster reachability probe — the operator reads no response body back to the tenant); the egress NetworkPolicy does not narrow that.","type":"string","default":""},"target":{"description":"Target read load per read-serving replica (unit depends on `metric`: active connections, or CPU millicores). Dimensionless integer - a resource.Quantity here would accept `150m`, which PromQL reads as 150 minutes and KEDA cannot use as a threshold.","type":"integer","default":150},"transition":{"description":"Migration phase 1: render `.spec.instances` from `replicas` (which the operator stages to the current live count) AND pause the ScaledObject in both directions, so KEDA stands up with its HPA present but not actuating. Flip to false (phase 2) to hand the runtime count to KEDA. Because the both-direction pause keeps the HPA (not the HPA-deleting full pause), KEDA is genuinely warm at phase 2 — no HPA recreate — and because the active seed is max(replicas, effectiveMin), phase 2 re-renders the same instance count phase 1 did (when `replicas` is staged at/above the floor), so the flip is a merge no-op with no dip. The HPA's scaleUp stabilization window still smooths the first actuation.","type":"boolean","default":false}}},"users":{"description":"Users configuration map. Passwords are always auto-generated and stored in the `-credentials` Secret; they cannot be set from values — read a user's password from that Secret. A `password` left over in values from before the field was removed is ignored by the render and draws an admission warning, but it is not inert on an upgraded release: the chart preserves whatever password is already in the Secret, which on the first upgrade is the value that was set before removal, so that value stays the live credential until it is rotated (dedicated rotation is tracked in cozystack/community#72). The live password lives only in the Secret.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"bypassRls":{"description":"Whether the user can bypass row-level security policies (BYPASSRLS). A role can only create other roles carrying BYPASSRLS if it holds the attribute itself, so this is required alongside `createRole` to provision a privileged service role.","type":"boolean"},"createRole":{"description":"Whether the user can create and manage roles (CREATEROLE). Requires PostgreSQL 16 or newer. Setting it back to `false` withdraws the attribute only: the roles the user created, and its ADMIN and SET memberships in them, stay. Once any user has held it, the chart no longer adopts an existing role it did not create, so a user or database declared later under the name of such a role fails the init job until a platform administrator drops that role.","type":"boolean"},"replication":{"description":"Whether the user has replication privileges.","type":"boolean"}}}},"databases":{"description":"Databases configuration map. The PostgreSQL system databases `postgres`, `template0` and `template1` are refused.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"extensions":{"description":"List of enabled PostgreSQL extensions.","type":"array","items":{"type":"string"}},"roles":{"description":"Roles assigned to users.","type":"object","properties":{"admin":{"description":"List of users with admin privileges.","type":"array","items":{"type":"string"}},"readonly":{"description":"List of users with read-only privileges.","type":"array","items":{"type":"string"}}}}}}},"backup":{"description":"Backup configuration.","type":"object","default":{},"required":["enabled"],"properties":{"destinationPath":{"description":"DEPRECATED. Per-tenant S3 configuration is superseded by the platform-managed `cozy-default` BackupClass and the `cozy-backups` system bucket. Leave empty for new installations; the BackupClass driver picks up the system-managed coordinates. Kept for in-place upgrade compatibility.","type":"string","default":"s3://bucket/path/to/folder/"},"enabled":{"description":"Enable regular backups.","type":"boolean","default":false},"endpointCA":{"description":"DEPRECATED. Pre-existing Secret with the CA bundle the barman-cloud plugin should trust when reaching a self-signed S3 endpoint. Used for both backup and bootstrap recovery in the legacy chart-managed flow.","type":"object","default":{},"properties":{"key":{"description":"Key within the Secret containing the CA bundle. Defaults to `ca.crt`.","type":"string","default":""},"name":{"description":"Name of the Secret in the application namespace. Empty means no endpointCA is emitted (the plugin uses the system trust store).","type":"string","default":""}}},"endpointURL":{"description":"DEPRECATED. See `destinationPath`.","type":"string","default":"http://minio-gateway-service:9000"},"retentionPolicy":{"description":"Retention policy (e.g. \"30d\").","type":"string","default":"30d"},"s3AccessKey":{"description":"DEPRECATED. Tenants no longer supply S3 keys; the system Bucket Secret is projected into the tenant namespace by the backup controller. Ignored when `s3CredentialsSecret.name` is set or `useSystemBucket` is true. The chart skips materialising `-s3-creds` whenever this field is empty so a default install does not leak placeholder credentials into the tenant namespace.","type":"string","default":""},"s3CredentialsSecret":{"description":"DEPRECATED. Pre-existing Secret with S3 credentials. Use the platform-managed `cozy-default` BackupClass instead. When set, the chart references this Secret directly (legacy chart-managed flow). The CNPG backup driver writes this field on restore so credentials never land in the CR `.spec`.","type":"object","default":{},"properties":{"accessKeyIDKey":{"description":"Key in the Secret holding the access key ID. Defaults to `AWS_ACCESS_KEY_ID`.","type":"string","default":""},"name":{"description":"Name of the Secret in the application namespace. Empty means the chart materialises `-s3-creds` from `s3AccessKey`/`s3SecretKey`.","type":"string","default":""},"secretAccessKeyKey":{"description":"Key in the Secret holding the secret access key. Defaults to `AWS_SECRET_ACCESS_KEY`.","type":"string","default":""}}},"s3SecretKey":{"description":"DEPRECATED. See `s3AccessKey`.","type":"string","default":""},"schedule":{"description":"Legacy. Cron schedule for the chart-emitted ScheduledBackup, either a standard five-field cron such as `0 2 * * *` for every day at 02:00, or six fields with leading seconds such as `0 0 2 * * *` for the same time. Empty means no chart-managed schedule, which is the recommended setup when a `BackupClass` from `backups.cozystack.io` already drives backup orchestration. In the legacy chart-managed flow `spec.plugins` plus the barman-cloud ObjectStore is rendered when `backup.enabled=true` AND `useSystemBucket=false` AND `destinationPath` is non-empty AND inline-or-external creds are supplied; in the platform `useSystemBucket=true` flow the chart skips emitting `spec.plugins` and the CNPG driver SSA-applies the ObjectStore and patches `spec.plugins` onto the live Cluster at first BackupJob time.","type":"string","default":""},"useSystemBucket":{"description":"Opt-in: when true, the chart-emitted `-s3-creds` Secret is skipped AND `spec.plugins` (plus the barman-cloud ObjectStore) is left UNSET in the chart-rendered Cluster — the cozy-default BackupClass driver SSA-applies an ObjectStore (carrying destinationPath/endpointURL/credentials) and patches `spec.plugins` on the live Cluster when the first BackupJob runs. Consequence: plugin WAL archiving is NOT active until that first BackupJob fires; WAL accumulates on the PVC in the meantime, so fire an ad-hoc BackupJob immediately after enabling the flag on existing releases. Use together with the platform `cozy-default` BackupClass — tenants do not need to fill `s3AccessKey`/`s3SecretKey` or `destinationPath`/`endpointURL`. The destination path automatically scopes to `s3://cozy-backups///`.","type":"boolean","default":false}}},"bootstrap":{"description":"Bootstrap configuration.","type":"object","default":{},"required":["enabled","oldName"],"properties":{"backupID":{"description":"Barman ID of the base backup to recover from, passed as `recoveryTarget.backupID`. Empty lets the barman-cloud plugin pick one: the newest backup when `recoveryTime` is empty, otherwise the newest one ending at or before it, on any timeline. The CNPG backup driver sets this on restore.","type":"string","default":""},"enabled":{"description":"Whether to restore from a backup.","type":"boolean","default":false},"newServerName":{"description":"WAL-archive server name (S3 path prefix) the RESTORED cluster writes to. Must differ from `serverName` (the recovery source) so a restored cluster archives to a fresh, empty prefix and barman-cloud-check-wal-archive passes while it recovers from the source's prefix. The CNPG backup driver sets this on restore; empty means the cluster archives under its own name.","type":"string","default":""},"oldName":{"description":"Previous cluster name before deletion.","type":"string","default":""},"recoveryTime":{"description":"Timestamp (RFC3339) for point-in-time recovery; empty means latest.","type":"string","default":""},"serverName":{"description":"Server name (S3 path prefix) used by the original cluster when writing backups; passed to the barman-cloud plugin via `externalClusters[].plugin.parameters.serverName`. Defaults to `bootstrap.oldName`. Set this only when the original cluster wrote backups under an explicit server name that differed from its Kubernetes resource name.","type":"string","default":""},"sourceImageName":{"description":"Image of the cluster the backup was taken from. A restore of a backup taken on one of the bare Debian bullseye tags the chart used before standard-trixie comes back on that image (see `allowCollationChange`); any other value is ignored. The CNPG backup driver sets this on restore and clears it with `enabled`.","type":"string","default":""}}}}} release: prefix: postgres- labels: @@ -74,7 +74,7 @@ spec: # labelSelector: # helm.toolkit.fluxcd.io/name: "{reqs[0]['metadata','name']}" - keysOrder: [["apiVersion"], ["appVersion"], ["kind"], ["metadata"], ["metadata", "name"], ["spec", "replicas"], ["spec", "resources"], ["spec", "resourcesPreset"], ["spec", "size"], ["spec", "storageClass"], ["spec", "external"], ["spec", "version"], ["spec", "flavor"], ["spec", "tls"], ["spec", "postgresql"], ["spec", "postgresql", "parameters"], ["spec", "postgresql", "parameters", "max_connections"], ["spec", "quorum"], ["spec", "quorum", "minSyncReplicas"], ["spec", "quorum", "maxSyncReplicas"], ["spec", "autoscaling"], ["spec", "autoscaling", "enabled"], ["spec", "autoscaling", "serverAddress"], ["spec", "autoscaling", "minReplicas"], ["spec", "autoscaling", "maxReplicas"], ["spec", "autoscaling", "metric"], ["spec", "autoscaling", "target"], ["spec", "autoscaling", "maxReplicationLagSeconds"], ["spec", "autoscaling", "dryRun"], ["spec", "autoscaling", "transition"], ["spec", "users"], ["spec", "databases"], ["spec", "backup"], ["spec", "backup", "enabled"], ["spec", "backup", "useSystemBucket"], ["spec", "backup", "retentionPolicy"], ["spec", "backup", "destinationPath"], ["spec", "backup", "endpointURL"], ["spec", "backup", "schedule"], ["spec", "backup", "s3AccessKey"], ["spec", "backup", "s3SecretKey"], ["spec", "backup", "s3CredentialsSecret"], ["spec", "backup", "s3CredentialsSecret", "name"], ["spec", "backup", "s3CredentialsSecret", "accessKeyIDKey"], ["spec", "backup", "s3CredentialsSecret", "secretAccessKeyKey"], ["spec", "backup", "endpointCA"], ["spec", "backup", "endpointCA", "name"], ["spec", "backup", "endpointCA", "key"], ["spec", "bootstrap"], ["spec", "bootstrap", "enabled"], ["spec", "bootstrap", "recoveryTime"], ["spec", "bootstrap", "backupID"], ["spec", "bootstrap", "oldName"], ["spec", "bootstrap", "serverName"], ["spec", "bootstrap", "newServerName"]] + keysOrder: [["apiVersion"], ["appVersion"], ["kind"], ["metadata"], ["metadata", "name"], ["spec", "replicas"], ["spec", "resources"], ["spec", "resourcesPreset"], ["spec", "size"], ["spec", "storageClass"], ["spec", "external"], ["spec", "version"], ["spec", "flavor"], ["spec", "allowCollationChange"], ["spec", "tls"], ["spec", "postgresql"], ["spec", "postgresql", "parameters"], ["spec", "postgresql", "parameters", "max_connections"], ["spec", "quorum"], ["spec", "quorum", "minSyncReplicas"], ["spec", "quorum", "maxSyncReplicas"], ["spec", "autoscaling"], ["spec", "autoscaling", "enabled"], ["spec", "autoscaling", "serverAddress"], ["spec", "autoscaling", "minReplicas"], ["spec", "autoscaling", "maxReplicas"], ["spec", "autoscaling", "metric"], ["spec", "autoscaling", "target"], ["spec", "autoscaling", "maxReplicationLagSeconds"], ["spec", "autoscaling", "dryRun"], ["spec", "autoscaling", "transition"], ["spec", "users"], ["spec", "databases"], ["spec", "backup"], ["spec", "backup", "enabled"], ["spec", "backup", "useSystemBucket"], ["spec", "backup", "retentionPolicy"], ["spec", "backup", "destinationPath"], ["spec", "backup", "endpointURL"], ["spec", "backup", "schedule"], ["spec", "backup", "s3AccessKey"], ["spec", "backup", "s3SecretKey"], ["spec", "backup", "s3CredentialsSecret"], ["spec", "backup", "s3CredentialsSecret", "name"], ["spec", "backup", "s3CredentialsSecret", "accessKeyIDKey"], ["spec", "backup", "s3CredentialsSecret", "secretAccessKeyKey"], ["spec", "backup", "endpointCA"], ["spec", "backup", "endpointCA", "name"], ["spec", "backup", "endpointCA", "key"], ["spec", "bootstrap"], ["spec", "bootstrap", "enabled"], ["spec", "bootstrap", "recoveryTime"], ["spec", "bootstrap", "backupID"], ["spec", "bootstrap", "oldName"], ["spec", "bootstrap", "serverName"], ["spec", "bootstrap", "newServerName"], ["spec", "bootstrap", "sourceImageName"]] secrets: exclude: [] include: diff --git a/pkg/registry/apps/application/rest_workloads_test.go b/pkg/registry/apps/application/rest_workloads_test.go index 1143e9c1d..5be5ee428 100644 --- a/pkg/registry/apps/application/rest_workloads_test.go +++ b/pkg/registry/apps/application/rest_workloads_test.go @@ -394,6 +394,14 @@ func TestConvertConditions_WorkloadsReadyCarriesMonitorMessages(t *testing.T) { "DataVolume b is Failed", cozyv1alpha1.WorkloadMonitorReasonDataVolumeNotReady, }, + { + "a failed Job", + []runtime.Object{ + monitor("mon-a", false, "Job mydb-repair failed: BackoffLimitExceeded: Job has reached the specified backoff limit", cozyv1alpha1.WorkloadMonitorReasonJobFailed), + }, + "Job mydb-repair failed: BackoffLimitExceeded: Job has reached the specified backoff limit", + cozyv1alpha1.WorkloadMonitorReasonJobFailed, + }, { "generic message when no monitor names a cause", []runtime.Object{monitor("mon-a", false, "", "")},