diff --git a/api/apps/v1alpha1/postgresql/types.go b/api/apps/v1alpha1/postgresql/types.go index 0378cbfd2..63dd5501e 100644 --- a/api/apps/v1alpha1/postgresql/types.go +++ b/api/apps/v1alpha1/postgresql/types.go @@ -47,6 +47,9 @@ type ConfigSpec struct { // PostgreSQL image flavor, fixed when the cluster is created. `postgresql` uses the CloudNativePG PostgreSQL image. `postgis` uses the CloudNativePG PostGIS image, which adds postgis, postgis_raster, postgis_topology, postgis_sfcgal, postgis_tiger_geocoder and address_standardizer; enable them per database in `databases..extensions`. Changing the flavor of an existing cluster is refused, and a backup restores only into a cluster of the flavor it was taken from: to change flavor, create a new cluster and move the data with a logical dump (pg_dump / pg_restore). // +kubebuilder:default:="postgresql" Flavor Flavor `json:"flavor"` + // Allow a cluster created on a Debian bullseye image (before the move to standard-trixie) to move to the new image without a clean locale check. Such a cluster is checked before each upgrade, except while `bootstrap.enabled` is set (set it back to false once a restore set up by hand has finished), and stays on its current image until the check finds nothing that depends on a collation other than C, POSIX or builtin: while this is false, a cluster the check found affected (an ICU or libc locale, or C.UTF-8) or could not finish on stays put, because glibc and ICU on the new image sort text differently and every index on such text must be rebuilt. A held cluster runs the bare bullseye tag it has, gets no further PostgreSQL minors and so none of their security fixes, and refuses a change of `version`, since new majors are built only on the new images. To leave that state, either remove the dependency (move such columns and indexes to C, or to the builtin `pg_c_utf8` on PostgreSQL 17 and later) and let the next upgrade check again, or set this to true in a maintenance window: the cluster moves on the next upgrade, replicas restart on the new image first and can return wrong results through `-ro`, and unique indexes can accept duplicates, until the indexes are rebuilt on the primary. The init Job rebuilds only indexes on collations that record a version (ICU, and libc locales other than C.*): rebuild indexes on C.UTF-8 or another C.* locale by hand with REINDEX, and check range partitions, CHECK constraints and materialized views on such text, which a rebuild does not fix. A held cluster shows the hold only as an unchanged image; the result and the objects found are in the `postgres.cozystack.io/locale-data` and `postgres.cozystack.io/locale-data-objects` annotations of the cnpg.io Cluster, which an administrator can read. A restore of a backup taken on one of those bullseye images comes back on that image and is checked by the next upgrade. + // +kubebuilder:default:=false + AllowCollationChange bool `json:"allowCollationChange"` // TLS configuration for server connections. // +kubebuilder:default:={} Tls TLS `json:"tls"` @@ -168,6 +171,9 @@ type Bootstrap struct { // Server name (S3 path prefix) used by the original cluster when writing backups; passed to the barman-cloud plugin via `externalClusters[].plugin.parameters.serverName`. Defaults to `bootstrap.oldName`. Set this only when the original cluster wrote backups under an explicit server name that differed from its Kubernetes resource name. // +kubebuilder:default:="" ServerName string `json:"serverName,omitempty"` + // Image of the cluster the backup was taken from. A restore of a backup taken on one of the bare Debian bullseye tags the chart used before standard-trixie comes back on that image (see `allowCollationChange`); any other value is ignored. The CNPG backup driver sets this on restore and clears it with `enabled`. + // +kubebuilder:default:="" + SourceImageName string `json:"sourceImageName,omitempty"` } type Database struct { diff --git a/internal/backupcontroller/cnpg_archive_access_test.go b/internal/backupcontroller/cnpg_archive_access_test.go index 5efdc4ff4..7a047b986 100644 --- a/internal/backupcontroller/cnpg_archive_access_test.go +++ b/internal/backupcontroller/cnpg_archive_access_test.go @@ -81,7 +81,7 @@ func artifactDriverMetadata(t *testing.T, store strategyv1alpha1.BarmanObjectSto }, } r := &BackupJobReconciler{Client: newCNPGStrategyTestClient(t)} - artifact, err := r.createCNPGBackupArtifact(context.Background(), j, &ResolvedBackupConfig{}, cnpgBk, "postgres-pg", "srv", "postgresql", destination, moved, newPostgresApp("pg", "tenant")) + artifact, err := r.createCNPGBackupArtifact(context.Background(), j, &ResolvedBackupConfig{}, cnpgBk, "postgres-pg", "srv", "postgresql", "", destination, moved, newPostgresApp("pg", "tenant")) if err != nil { t.Fatalf("createCNPGBackupArtifact: %v", err) } @@ -206,7 +206,7 @@ func TestCreateCNPGBackupArtifact_RecordWithoutAccessRecordsNone(t *testing.T) { written := cnpgDestination{DestinationPath: "s3://bkt-a/tenant/pg/", S3SecretRef: &secret} rendered := &strategyv1alpha1.CNPGTemplate{BarmanObjectStore: archiveStoreB()} r := &BackupJobReconciler{Client: newCNPGStrategyTestClient(t)} - artifact, err := r.createCNPGBackupArtifact(context.Background(), j, &ResolvedBackupConfig{}, &cnpgtypes.Backup{ObjectMeta: metav1.ObjectMeta{Name: "cnpg-bk"}}, "postgres-pg", "srv", "postgresql", written, rendered, newPostgresApp("pg", "tenant")) + artifact, err := r.createCNPGBackupArtifact(context.Background(), j, &ResolvedBackupConfig{}, &cnpgtypes.Backup{ObjectMeta: metav1.ObjectMeta{Name: "cnpg-bk"}}, "postgres-pg", "srv", "postgresql", "", written, rendered, newPostgresApp("pg", "tenant")) if err != nil { t.Fatalf("createCNPGBackupArtifact: %v", err) } @@ -270,7 +270,7 @@ func TestReconcileCNPGRestore_PatchesTheRecordedAccess(t *testing.T) { } restore := func(t *testing.T, md map[string]string, getErr error, objs ...client.Object) outcome { 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) } diff --git a/internal/backupcontroller/cnpg_artifact_size_test.go b/internal/backupcontroller/cnpg_artifact_size_test.go index 4afef7194..d90b76b54 100644 --- a/internal/backupcontroller/cnpg_artifact_size_test.go +++ b/internal/backupcontroller/cnpg_artifact_size_test.go @@ -284,7 +284,7 @@ func TestCreateCNPGBackupArtifact_SizeBytes(t *testing.T) { r := reconcilerWithLister(t, l) r.Client = newCNPGStrategyTestClient(t, s3CredsSecret("tenant", "creds")) - got, err := r.createCNPGBackupArtifact(context.Background(), j, resolved, cnpgBk, "postgres-pg", "srv", "postgresql", cnpgDestinationOf(rendered), rendered, newPostgresApp("pg", "tenant")) + got, err := r.createCNPGBackupArtifact(context.Background(), j, resolved, cnpgBk, "postgres-pg", "srv", "postgresql", "", cnpgDestinationOf(rendered), rendered, newPostgresApp("pg", "tenant")) if err != nil { t.Fatalf("createCNPGBackupArtifact: %v", err) } @@ -311,7 +311,7 @@ func TestCreateCNPGBackupArtifact_ExistingBackupSkipsProbe(t *testing.T) { cnpgBk := &cnpgtypes.Backup{ObjectMeta: metav1.ObjectMeta{Name: "cnpg-bk"}, Status: cnpgtypes.BackupStatus{BackupID: "20261021T100000"}} rendered := &strategyv1alpha1.CNPGTemplate{BarmanObjectStore: *newSizedBarmanObjectStore()} - if _, err := r.createCNPGBackupArtifact(context.Background(), j, &ResolvedBackupConfig{}, cnpgBk, "postgres-pg", "srv", "postgresql", cnpgDestinationOf(rendered), rendered, newPostgresApp("pg", "tenant")); err != nil { + if _, err := r.createCNPGBackupArtifact(context.Background(), j, &ResolvedBackupConfig{}, cnpgBk, "postgres-pg", "srv", "postgresql", "", cnpgDestinationOf(rendered), rendered, newPostgresApp("pg", "tenant")); err != nil { t.Fatalf("createCNPGBackupArtifact: %v", err) } if l.calls != 0 { @@ -331,7 +331,7 @@ func TestCreateCNPGBackupArtifact_AlreadyExistsRefetchReadsPastTheCache(t *testi store := newCNPGStrategyTestClient(t, backup) r := &BackupJobReconciler{Client: staleCache(t, store), APIReader: notFoundOnce(t, store)} rendered := &strategyv1alpha1.CNPGTemplate{BarmanObjectStore: strategyv1alpha1.BarmanObjectStoreTemplate{DestinationPath: "s3://b/"}} - got, err := r.createCNPGBackupArtifact(context.Background(), j, &ResolvedBackupConfig{}, &cnpgtypes.Backup{ObjectMeta: metav1.ObjectMeta{Name: "cnpg-bk"}}, "postgres-pg", "srv", "postgresql", cnpgDestinationOf(rendered), rendered, newPostgresApp("pg", "tenant")) + got, err := r.createCNPGBackupArtifact(context.Background(), j, &ResolvedBackupConfig{}, &cnpgtypes.Backup{ObjectMeta: metav1.ObjectMeta{Name: "cnpg-bk"}}, "postgres-pg", "srv", "postgresql", "", cnpgDestinationOf(rendered), rendered, newPostgresApp("pg", "tenant")) if err != nil || got == nil || got.Name != "bj-race" { t.Fatalf("createCNPGBackupArtifact = %v, %v; want the Backup that already exists", got, err) } @@ -349,7 +349,7 @@ func TestCreateCNPGBackupArtifact_UnreadableExistingBackupIsRetried(t *testing.T store := newCNPGStrategyTestClient(t, backup) r := &BackupJobReconciler{Client: staleCache(t, store), APIReader: failingReads(t, store)} rendered := &strategyv1alpha1.CNPGTemplate{BarmanObjectStore: strategyv1alpha1.BarmanObjectStoreTemplate{DestinationPath: "s3://b/"}} - _, err := r.createCNPGBackupArtifact(context.Background(), j, &ResolvedBackupConfig{}, &cnpgtypes.Backup{ObjectMeta: metav1.ObjectMeta{Name: "cnpg-bk"}}, "postgres-pg", "srv", "postgresql", cnpgDestinationOf(rendered), rendered, newPostgresApp("pg", "tenant")) + _, err := r.createCNPGBackupArtifact(context.Background(), j, &ResolvedBackupConfig{}, &cnpgtypes.Backup{ObjectMeta: metav1.ObjectMeta{Name: "cnpg-bk"}}, "postgres-pg", "srv", "postgresql", "", cnpgDestinationOf(rendered), rendered, newPostgresApp("pg", "tenant")) if !errors.Is(err, errBackupNotReadBack) { t.Errorf("err = %v, want errBackupNotReadBack", err) } @@ -409,7 +409,7 @@ func TestCreateCNPGBackupArtifact_FailedExistenceCheckSkipsProbe(t *testing.T) { cnpgBk := &cnpgtypes.Backup{ObjectMeta: metav1.ObjectMeta{Name: "cnpg-bk"}, Status: cnpgtypes.BackupStatus{BackupID: "20261021T100000"}} rendered := &strategyv1alpha1.CNPGTemplate{BarmanObjectStore: *newSizedBarmanObjectStore()} - got, err := r.createCNPGBackupArtifact(context.Background(), j, &ResolvedBackupConfig{}, cnpgBk, "postgres-pg", "srv", "postgresql", cnpgDestinationOf(rendered), rendered, newPostgresApp("pg", "tenant")) + got, err := r.createCNPGBackupArtifact(context.Background(), j, &ResolvedBackupConfig{}, cnpgBk, "postgres-pg", "srv", "postgresql", "", cnpgDestinationOf(rendered), rendered, newPostgresApp("pg", "tenant")) if err != nil || got == nil { t.Fatalf("createCNPGBackupArtifact = %v, %v; a transient read must not fail the backup", got, err) } @@ -471,7 +471,7 @@ func TestCreateCNPGBackupArtifact_SizeProbeReadsTheRecordedDestination(t *testin r := reconcilerWithLister(t, l) r.Client = newCNPGStrategyTestClient(t, s3CredsSecret("tenant", oldCreds)) - got, err := r.createCNPGBackupArtifact(context.Background(), j, &ResolvedBackupConfig{}, cnpgBk, "postgres-pg", "srv", "postgresql", written, rendered, newPostgresApp("pg", "tenant")) + got, err := r.createCNPGBackupArtifact(context.Background(), j, &ResolvedBackupConfig{}, cnpgBk, "postgres-pg", "srv", "postgresql", "", written, rendered, newPostgresApp("pg", "tenant")) if err != nil { t.Fatalf("createCNPGBackupArtifact: %v", err) } @@ -503,7 +503,7 @@ func TestCreateCNPGBackupArtifact_SizeProbeSkipsARecordWithoutCredentials(t *tes r := reconcilerWithLister(t, l) r.Client = newCNPGStrategyTestClient(t, s3CredsSecret("tenant", "creds")) - got, err := r.createCNPGBackupArtifact(context.Background(), j, &ResolvedBackupConfig{}, cnpgBk, "postgres-pg", "srv", "postgresql", written, rendered, newPostgresApp("pg", "tenant")) + got, err := r.createCNPGBackupArtifact(context.Background(), j, &ResolvedBackupConfig{}, cnpgBk, "postgres-pg", "srv", "postgresql", "", written, rendered, newPostgresApp("pg", "tenant")) if err != nil { t.Fatalf("createCNPGBackupArtifact: %v", err) } @@ -534,7 +534,7 @@ func probeRecordedBackup(t *testing.T, rendered *strategyv1alpha1.CNPGTemplate, r := reconcilerWithLister(t, l) r.Client = newCNPGStrategyTestClient(t, recordedSecret) - got, err := r.createCNPGBackupArtifact(context.Background(), j, &ResolvedBackupConfig{}, cnpgBk, "postgres-pg", "srv", "postgresql", written, rendered, newPostgresApp("pg", "tenant")) + got, err := r.createCNPGBackupArtifact(context.Background(), j, &ResolvedBackupConfig{}, cnpgBk, "postgres-pg", "srv", "postgresql", "", written, rendered, newPostgresApp("pg", "tenant")) if err != nil { t.Fatalf("createCNPGBackupArtifact: %v", err) } diff --git a/internal/backupcontroller/cnpg_source_image_test.go b/internal/backupcontroller/cnpg_source_image_test.go new file mode 100644 index 000000000..9b09c539d --- /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, true, "bj") + 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 04ee6935f..ab5b8ba3f 100644 --- a/internal/backupcontroller/cnpgstrategy_controller.go +++ b/internal/backupcontroller/cnpgstrategy_controller.go @@ -700,7 +700,7 @@ func (r *BackupJobReconciler) reconcileCNPG(ctx context.Context, j *backupsv1alp if destination.ServerName != "" { serverName = destination.ServerName } - artifact, err := r.createCNPGBackupArtifact(ctx, j, resolved, cnpgBackup, clusterName, serverName, attachment.flavor, destination, rendered, app) + artifact, err := r.createCNPGBackupArtifact(ctx, j, resolved, cnpgBackup, clusterName, serverName, attachment.flavor, attachment.imageName, destination, rendered, app) if err != nil { return r.failBackupArtifact(ctx, j, err) } @@ -1099,6 +1099,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, } attachment.attachedAt = existing.Annotations[cnpgPluginAttachedAtAnnotation] @@ -1258,6 +1259,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 // attachedAt is the cnpgPluginAttachedAtAnnotation the Cluster carried, @@ -1767,7 +1771,7 @@ func (r *BackupJobReconciler) createCNPGBackupArtifact( j *backupsv1alpha1.BackupJob, resolved *ResolvedBackupConfig, cnpgBackup *cnpgtypes.Backup, - clusterName, serverName, flavor string, + clusterName, serverName, flavor, imageName string, destination cnpgDestination, rendered *strategyv1alpha1.CNPGTemplate, sourceApp *postgresapp.Postgres, @@ -1804,7 +1808,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) } @@ -2025,6 +2029,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: @@ -2157,7 +2167,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, sourceCredentials, sourceEndpointCA, sourceDatabases, sourceUsers); err != nil { + if err := r.patchPostgresAppForRestore(ctx, targetApp, sourceServerName, newServerName, sourceDestinationPath, sourceEndpointURL, options.RecoveryTime, backupID, sourceCredentials, sourceEndpointCA, 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) @@ -2468,8 +2478,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)) } @@ -2496,6 +2507,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)) } @@ -2530,6 +2544,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 @@ -2540,6 +2555,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 @@ -2607,6 +2625,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"` @@ -2614,6 +2636,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" @@ -2628,7 +2675,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 } @@ -2639,6 +2686,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 cea45b69c..187b82cb3 100644 --- a/internal/backupcontroller/cnpgstrategy_controller_test.go +++ b/internal/backupcontroller/cnpgstrategy_controller_test.go @@ -230,7 +230,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) } @@ -535,6 +535,7 @@ func TestBuildPostgresAppRestorePatch_ForwardsSecretRef_NotCleartext(t *testing. creds, nil, nil, nil, + "", ) if got := patched.Spec.Backup.S3CredentialsSecret.Name; got != "pg-target-cnpg-backup-creds" { @@ -562,7 +563,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", @@ -580,7 +581,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) } @@ -778,7 +779,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") @@ -815,7 +816,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) @@ -854,7 +855,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 { @@ -870,7 +871,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) @@ -925,7 +926,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) } @@ -1077,7 +1078,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", cnpgDestinationOf(rendered), rendered, sourceApp) + got, err := r.createCNPGBackupArtifact(context.Background(), j, resolved, cnpgBk, "postgres-pg", "postgres-pg", "postgresql", "", cnpgDestinationOf(rendered), rendered, sourceApp) if err != nil { t.Fatalf("expected AlreadyExists to be swallowed, got error %v", err) } @@ -4786,7 +4787,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) } @@ -5048,16 +5049,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) } @@ -5076,6 +5081,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"}, @@ -5116,12 +5122,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 { @@ -5157,7 +5166,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) } @@ -5276,7 +5285,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) } @@ -5365,7 +5374,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) } @@ -5478,7 +5487,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) } @@ -5605,7 +5614,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) } @@ -5717,7 +5726,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) } @@ -5813,7 +5822,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) } @@ -6125,10 +6134,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) } } @@ -6155,7 +6164,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) } @@ -6293,7 +6302,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", cnpgDestinationOf(rendered), rendered, newPostgresApp("pg", "tenant")) + got, err := r.createCNPGBackupArtifact(context.Background(), j, resolved, cnpgBk, "postgres-pg", "postgres-pg", "postgresql", "", cnpgDestinationOf(rendered), rendered, newPostgresApp("pg", "tenant")) if err != nil { t.Fatalf("createCNPGBackupArtifact: %v", err) } @@ -6356,7 +6365,7 @@ func TestReconcileCNPGRestore_RefusesCrossMajorRestore(t *testing.T) { } targetCluster := cnpgClusterNameForApp(targetApp) - snap, err := marshalCNPGBackupSnapshot(newPostgresApp(sourceApp, ns), nil, "") + snap, err := marshalCNPGBackupSnapshot(newPostgresApp(sourceApp, ns), nil, "", "") if err != nil { t.Fatalf("marshal snapshot: %v", err) } diff --git a/internal/backupcontroller/postgresapp/types.go b/internal/backupcontroller/postgresapp/types.go index 914f522fa..9de1b7ac1 100644 --- a/internal/backupcontroller/postgresapp/types.go +++ b/internal/backupcontroller/postgresapp/types.go @@ -81,12 +81,13 @@ type Bootstrap struct { // recovery converges, and a bool+omitempty would drop false from the patch // (it deletes the key instead), leaving the server to fall back to a default // rather than being explicitly cleared. Same rule as Backup.UseSystemBucket. - Enabled bool `json:"enabled"` - OldName string `json:"oldName,omitempty"` - ServerName string `json:"serverName,omitempty"` - NewServerName string `json:"newServerName,omitempty"` - RecoveryTime string `json:"recoveryTime,omitempty"` - BackupID string `json:"backupID,omitempty"` + Enabled bool `json:"enabled"` + OldName string `json:"oldName,omitempty"` + ServerName string `json:"serverName,omitempty"` + NewServerName string `json:"newServerName,omitempty"` + RecoveryTime string `json:"recoveryTime,omitempty"` + BackupID string `json:"backupID,omitempty"` + SourceImageName string `json:"sourceImageName,omitempty"` } type Backup struct { diff --git a/packages/apps/postgres/README.md b/packages/apps/postgres/README.md index 50aeb4729..e3d486cda 100644 --- a/packages/apps/postgres/README.md +++ b/packages/apps/postgres/README.md @@ -207,19 +207,20 @@ 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` | -| `schedulingClass` | Name of a SchedulingClass CR (cluster-scoped, group cozystack.io) used in place of the tenant's for this application's pods. A pod gets its class when it is created, so running pods keep theirs until they are recreated. Must be the tenant's own class or one listed in the tenant's `allowedSchedulingClasses`. Setting any other value is refused, and the pods of an application whose class is not, or no longer, in that list get the tenant's class. Empty means inherit from the tenant. | `string` | `""` | -| `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` | +| `schedulingClass` | Name of a SchedulingClass CR (cluster-scoped, group cozystack.io) used in place of the tenant's for this application's pods. A pod gets its class when it is created, so running pods keep theirs until they are recreated. Must be the tenant's own class or one listed in the tenant's `allowedSchedulingClasses`. Setting any other value is refused, and the pods of an application whose class is not, or no longer, in that list get the tenant's class. Empty means inherit from the tenant. | `string` | `""` | +| `version` | PostgreSQL major version to deploy | `string` | `v18` | +| `flavor` | PostgreSQL image flavor, fixed when the cluster is created. `postgresql` uses the CloudNativePG PostgreSQL image. `postgis` uses the CloudNativePG PostGIS image, which adds postgis, postgis_raster, postgis_topology, postgis_sfcgal, postgis_tiger_geocoder and address_standardizer; enable them per database in `databases..extensions`. Changing the flavor of an existing cluster is refused, and a backup restores only into a cluster of the flavor it was taken from: to change flavor, create a new cluster and move the data with a logical dump (pg_dump / pg_restore). | `string` | `postgresql` | +| `allowCollationChange` | Allow a cluster created on a Debian bullseye image (before the move to standard-trixie) to move to the new image without a clean locale check. Such a cluster is checked before each upgrade, except while `bootstrap.enabled` is set (set it back to false once a restore set up by hand has finished), and stays on its current image until the check finds nothing that depends on a collation other than C, POSIX or builtin: while this is false, a cluster the check found affected (an ICU or libc locale, or C.UTF-8) or could not finish on stays put, because glibc and ICU on the new image sort text differently and every index on such text must be rebuilt. A held cluster runs the bare bullseye tag it has, gets no further PostgreSQL minors and so none of their security fixes, and refuses a change of `version`, since new majors are built only on the new images. To leave that state, either remove the dependency (move such columns and indexes to C, or to the builtin `pg_c_utf8` on PostgreSQL 17 and later) and let the next upgrade check again, or set this to true in a maintenance window: the cluster moves on the next upgrade, replicas restart on the new image first and can return wrong results through `-ro`, and unique indexes can accept duplicates, until the indexes are rebuilt on the primary. The init Job rebuilds only indexes on collations that record a version (ICU, and libc locales other than C.*): rebuild indexes on C.UTF-8 or another C.* locale by hand with REINDEX, and check range partitions, CHECK constraints and materialized views on such text, which a rebuild does not fix. A held cluster shows the hold only as an unchanged image; the result and the objects found are in the `postgres.cozystack.io/locale-data` and `postgres.cozystack.io/locale-data-objects` annotations of the cnpg.io Cluster, which an administrator can read. A restore of a backup taken on one of those bullseye images comes back on that image and is checked by the next upgrade. | `bool` | `false` | ### TLS configuration @@ -319,15 +320,16 @@ For `sslmode=verify-full` to work, the CA bundle retrieved above must be saved t ### Bootstrap (recovery) parameters -| Name | Description | Type | Value | -| ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | ------- | -| `bootstrap` | Bootstrap configuration. | `object` | `{}` | -| `bootstrap.enabled` | Whether to restore from a backup. | `bool` | `false` | -| `bootstrap.recoveryTime` | Timestamp (RFC3339) for point-in-time recovery; empty means latest. | `string` | `""` | -| `bootstrap.backupID` | Barman ID of the base backup to recover from, passed as `recoveryTarget.backupID`. Empty lets the barman-cloud plugin pick one: the newest backup when `recoveryTime` is empty, otherwise the newest one ending at or before it, on any timeline. The CNPG backup driver sets this on restore. | `string` | `""` | -| `bootstrap.oldName` | Previous cluster name before deletion. | `string` | `""` | -| `bootstrap.serverName` | Server name (S3 path prefix) used by the original cluster when writing backups; passed to the barman-cloud plugin via `externalClusters[].plugin.parameters.serverName`. Defaults to `bootstrap.oldName`. Set this only when the original cluster wrote backups under an explicit server name that differed from its Kubernetes resource name. | `string` | `""` | -| `bootstrap.newServerName` | WAL-archive server name (S3 path prefix) the RESTORED cluster writes to. Must differ from `serverName` (the recovery source) so a restored cluster archives to a fresh, empty prefix and barman-cloud-check-wal-archive passes while it recovers from the source's prefix. The CNPG backup driver sets this on restore; empty means the cluster archives under its own name. | `string` | `""` | +| Name | Description | Type | Value | +| --------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | ------- | +| `bootstrap` | Bootstrap configuration. | `object` | `{}` | +| `bootstrap.enabled` | Whether to restore from a backup. | `bool` | `false` | +| `bootstrap.recoveryTime` | Timestamp (RFC3339) for point-in-time recovery; empty means latest. | `string` | `""` | +| `bootstrap.backupID` | Barman ID of the base backup to recover from, passed as `recoveryTarget.backupID`. Empty lets the barman-cloud plugin pick one: the newest backup when `recoveryTime` is empty, otherwise the newest one ending at or before it, on any timeline. The CNPG backup driver sets this on restore. | `string` | `""` | +| `bootstrap.oldName` | Previous cluster name before deletion. | `string` | `""` | +| `bootstrap.serverName` | Server name (S3 path prefix) used by the original cluster when writing backups; passed to the barman-cloud plugin via `externalClusters[].plugin.parameters.serverName`. Defaults to `bootstrap.oldName`. Set this only when the original cluster wrote backups under an explicit server name that differed from its Kubernetes resource name. | `string` | `""` | +| `bootstrap.newServerName` | WAL-archive server name (S3 path prefix) the RESTORED cluster writes to. Must differ from `serverName` (the recovery source) so a restored cluster archives to a fresh, empty prefix and barman-cloud-check-wal-archive passes while it recovers from the source's prefix. The CNPG backup driver sets this on restore; empty means the cluster archives under its own name. | `string` | `""` | +| `bootstrap.sourceImageName` | Image of the cluster the backup was taken from. A restore of a backup taken on one of the bare Debian bullseye tags the chart used before standard-trixie comes back on that image (see `allowCollationChange`); any other value is ignored. The CNPG backup driver sets this on restore and clears it with `enabled`. | `string` | `""` | ## Parameter examples and reference diff --git a/packages/apps/postgres/templates/_versions.tpl b/packages/apps/postgres/templates/_versions.tpl index 688c16b49..ea46a11c2 100644 --- a/packages/apps/postgres/templates/_versions.tpl +++ b/packages/apps/postgres/templates/_versions.tpl @@ -26,6 +26,10 @@ flavor is on it already, so both image families share one Debian release. */}} {{- define "postgres.imageName" -}} +{{- include "postgres.heldImageName" . | default (include "postgres.targetImageName" .) -}} +{{- end -}} + +{{- define "postgres.targetImageName" -}} {{- if eq (default "postgresql" .Values.flavor) "postgis" -}} ghcr.io/cloudnative-pg/postgis:{{ include "postgres.postgisVersionMap" . | trim }} {{- else -}} @@ -33,6 +37,92 @@ ghcr.io/cloudnative-pg/postgresql:{{ include "postgres.versionMap" . | trim | tr {{- end -}} {{- end -}} +{{/* + The image a cluster on Debian bullseye keeps, or nothing. Clusters created + before the move to trixie run one of the bare tags postgres.bullseyeImage + lists, and moving them changes glibc and ICU under an initialised data + directory. Such a cluster stays on its image until the pre-upgrade locale + check has recorded "clean" on its Cluster, or until allowCollationChange is + set: a cluster not checked yet, one the check could not finish on and one + it found affected all stay. New majors are built only on the new images, so + a held cluster refuses a change of version instead of dropping it. +*/}} +{{- define "postgres.heldImageName" -}} +{{- if and (ne (default "postgresql" .Values.flavor) "postgis") (not .Values.allowCollationChange) -}} +{{- $hold := include "postgres.localeHold" . | fromJson -}} +{{- if and $hold.image (ne $hold.verdict "clean") -}} +{{- $heldMajor := regexFind "^[0-9]+" (last (splitList ":" $hold.image)) -}} +{{- $wantMajor := trimPrefix "v" .Values.version -}} +{{- if ne $heldMajor $wantMajor -}} +{{- fail (printf "postgres: version %s cannot be applied: the cluster stays on %s until the pre-upgrade check finds nothing in it that depends on a collation sorting differently on the images PostgreSQL %s is built on (the postgres.cozystack.io/locale-data annotation of the cnpg.io Cluster). Keep version v%s, or set allowCollationChange: true and rebuild the affected indexes in a maintenance window." .Values.version $hold.image $wantMajor $heldMajor) -}} +{{- end -}} +{{- $hold.image -}} +{{- end -}} +{{- end -}} +{{- end -}} + +{{/* + The bullseye image that applies to this cluster and its check result, as + JSON; the image is empty when the cluster runs any other one. The result is + the postgres.cozystack.io/locale-data annotation the pre-upgrade check + writes on the live Cluster. A physical recovery with no live Cluster yet + (the CNPG backup driver deletes it before the recovery renders) restores + onto the image the backup was taken on, so that the data keeps the library + that built it: bootstrap.sourceImageName, which the driver copies from the + source Cluster, or for a recovery set up by hand the bootstrap.oldName + Cluster while it exists. A recovery has no result of its own and is held + until the first upgrade after it checks the restored data. + + bootstrap.sourceImageName is in the application spec, so anyone who may + edit the application may set it; it only ever selects one of the images + postgres.bullseyeImage lists. +*/}} +{{- define "postgres.localeHold" -}} +{{- $live := lookup "postgresql.cnpg.io/v1" "Cluster" .Release.Namespace .Release.Name -}} +{{- $image := dig "spec" "imageName" "" $live -}} +{{- $verdict := dig "metadata" "annotations" "postgres.cozystack.io/locale-data" "" $live -}} +{{- if and .Values.bootstrap.enabled (not $image) -}} +{{- $image = .Values.bootstrap.sourceImageName | default (dig "spec" "imageName" "" (include "postgres.recoverySource" . | fromJson)) -}} +{{- $verdict = "" -}} +{{- end -}} +{{- if ne (include "postgres.bullseyeImage" $image) "true" -}} +{{- $image = "" -}} +{{- end -}} +{{- dict "image" $image "verdict" $verdict | toJson -}} +{{- end -}} + +{{- define "postgres.recoverySource" -}} +{{- if and .Values.bootstrap.enabled .Values.bootstrap.oldName (not .Values.bootstrap.newServerName) -}} +{{- lookup "postgresql.cnpg.io/v1" "Cluster" .Release.Namespace .Values.bootstrap.oldName | toJson -}} +{{- else -}} +{} +{{- end -}} +{{- end -}} + +{{/* + The images this chart ran clusters on before the move to trixie: the bare + version tags of the CloudNativePG image, which are its system variant on + Debian bullseye, as files/versions.yaml listed them in every release before + standard-trixie. Exact on purpose: a held image reaches spec.imageName. +*/}} +{{- define "postgres.bullseyeImage" -}} +{{- has . (list "ghcr.io/cloudnative-pg/postgresql:13.22" "ghcr.io/cloudnative-pg/postgresql:14.20" "ghcr.io/cloudnative-pg/postgresql:15.15" "ghcr.io/cloudnative-pg/postgresql:16.11" "ghcr.io/cloudnative-pg/postgresql:17.7" "ghcr.io/cloudnative-pg/postgresql:18.1") -}} +{{- end -}} + +{{/* + The live image of a cluster still on bullseye whose owner has not allowed + the collation change, or nothing. The pre-upgrade locale check runs only + then, from that image, against the server it is checking. +*/}} +{{- define "postgres.localeCheckImage" -}} +{{- if and (ne (default "postgresql" .Values.flavor) "postgis") (not .Values.allowCollationChange) (not .Values.bootstrap.enabled) -}} +{{- $live := lookup "postgresql.cnpg.io/v1" "Cluster" .Release.Namespace .Release.Name -}} +{{- if and $live $live.spec $live.spec.imageName (eq (include "postgres.bullseyeImage" $live.spec.imageName) "true") -}} +{{- $live.spec.imageName -}} +{{- end -}} +{{- end -}} +{{- end -}} + {{/* The flavor is fixed at bootstrap. Only the postgis image carries the shared libraries behind PostGIS objects, so the postgis-to-postgresql direction diff --git a/packages/apps/postgres/templates/locale-check-hook.yaml b/packages/apps/postgres/templates/locale-check-hook.yaml new file mode 100644 index 000000000..adbe922e1 --- /dev/null +++ b/packages/apps/postgres/templates/locale-check-hook.yaml @@ -0,0 +1,263 @@ +{{- /* + Runs before every upgrade of a cluster still on Debian bullseye, from the + image the cluster runs now. It looks for anything stored that depends on a + collation other than C, POSIX or builtin and records the answer on the + Cluster as the postgres.cozystack.io/locale-data annotation: clean, + affected, or unknown when the check could not finish. postgres.heldImageName + reads it, and only clean lets the cluster move. Helm renders the manifests + before this hook runs, so when the answer disagrees with what this attempt + rendered, the hook fails the attempt before the Cluster is patched and the + retry renders according to the new answer. +*/ -}} +{{- $liveImage := include "postgres.localeCheckImage" . }} +{{- if $liveImage }} +{{- $held := include "postgres.heldImageName" . }} +{{- /* Prefixed, not suffixed: CNPG names its ServiceAccount and Role after the + Cluster, and before-hook-creation would delete those of a release named + -locale-check. */}} +{{- $name := printf "locale-check-%s-%s" (.Release.Name | trunc 40 | trimSuffix "-") (.Release.Name | sha256sum | trunc 8) }} +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: {{ $name }} + annotations: + helm.sh/hook: pre-upgrade + helm.sh/hook-weight: "1" + helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: {{ $name }} + annotations: + helm.sh/hook: pre-upgrade + helm.sh/hook-weight: "1" + helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded +rules: +- apiGroups: ["postgresql.cnpg.io"] + resources: ["clusters"] + resourceNames: [{{ .Release.Name | quote }}] + verbs: ["get", "patch"] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: {{ $name }} + annotations: + helm.sh/hook: pre-upgrade + helm.sh/hook-weight: "1" + helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: {{ $name }} +subjects: +- kind: ServiceAccount + name: {{ $name }} + namespace: {{ .Release.Namespace | quote }} +--- +apiVersion: v1 +kind: Secret +metadata: + name: {{ $name }} + annotations: + helm.sh/hook: pre-upgrade + helm.sh/hook-weight: "1" + helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded +stringData: + {{- /* + Anything found is an answer, even when another database could not be + checked. The session settings override what a database owner may have set + with ALTER DATABASE, and the time budget ends the check before the Job + deadline, so that a slow check records unknown, which holds the cluster, + rather than failing every retry of the upgrade. + */}} + check.sh: | + set -u + export PGOPTIONS="-c default_transaction_read_only=off -c statement_timeout=60s -c lock_timeout=10s" + export PGCONNECT_TIMEOUT=10 + echo unknown > /work/verdict + : > /work/found + until pg_isready -q; do + if [ "$SECONDS" -ge 60 ]; then + echo "the server did not answer within 60s; the locale data of its databases is not checked" >&2 + exit 0 + fi + sleep 2 + done + psql -v ON_ERROR_STOP=1 -t -A -c "SELECT datname FROM pg_database WHERE datallowconn" > /work/databases || exit 0 + INCOMPLETE="" + CLOSED=$(psql -v ON_ERROR_STOP=1 -t -A -c "SELECT string_agg(datname, ', ') FROM pg_database WHERE NOT datallowconn AND datname <> 'template0'") || exit 0 + if [ -n "$CLOSED" ]; then + echo "databases that accept no connections are not checked: $CLOSED" >&2 + INCOMPLETE=yes + fi + while IFS= read -r db; do + if [ "$SECONDS" -ge 180 ]; then + echo "out of time before database $db was checked" >&2 + INCOMPLETE=yes + break + fi + PGDATABASE="$db" psql -v ON_ERROR_STOP=1 -q -t -A -f /scripts/check.sql >> /work/found || INCOMPLETE=yes + done < /work/databases + if [ -s /work/found ]; then + head -n 50 /work/found + echo affected > /work/verdict + elif [ -z "$INCOMPLETE" ]; then + echo clean > /work/verdict + fi + {{- /* + A collation is safe when its order and character classes cannot change + with the C library or ICU: C and POSIX, the builtin provider of PostgreSQL + 17, and the database default when that is one of them. C.UTF-8 is not: + Debian bullseye patches its order, glibc 2.35 and later sort by code point. + Objects below the first normal OID belong to the system catalogs, which + use C. + */}} + check.sql: | + SET search_path = pg_catalog, pg_temp; + SELECT current_setting('server_version_num')::int >= 150000 AS has_provider \gset + \if :has_provider + SELECT datlocprovider = 'b' OR (datlocprovider = 'c' AND datcollate IN ('C', 'POSIX') AND datctype IN ('C', 'POSIX')) AS default_safe FROM pg_database WHERE datname = current_database() \gset + \else + SELECT datcollate IN ('C', 'POSIX') AND datctype IN ('C', 'POSIX') AS default_safe FROM pg_database WHERE datname = current_database() \gset + \endif + WITH unsafe AS ( + SELECT c.oid FROM pg_collation c + WHERE NOT (c.collprovider = 'b' + OR (c.collprovider = 'c' AND c.collcollate IN ('C', 'POSIX') AND c.collctype IN ('C', 'POSIX')) + OR (c.collprovider = 'd' AND :'default_safe'::boolean)) + ) + SELECT DISTINCT format('%s: %s uses collation %s', current_database(), + pg_describe_object('pg_class'::regclass, a.attrelid, a.attnum), u.oid::regcollation) + FROM pg_attribute a + JOIN pg_class r ON r.oid = a.attrelid + JOIN unsafe u ON u.oid = a.attcollation + WHERE r.oid >= 16384 AND r.relkind IN ('r', 'p', 'm', 'i', 'c') AND r.relpersistence <> 't' + AND a.attnum > 0 AND NOT a.attisdropped + UNION + SELECT format('%s: %s depends on collation %s', current_database(), + pg_describe_object(d.classid, d.objid, d.objsubid), u.oid::regcollation) + FROM pg_depend d + JOIN unsafe u ON u.oid = d.refobjid + WHERE d.refclassid = 'pg_collation'::regclass AND d.objid >= 16384 + UNION + SELECT format('%s: range type %s uses collation %s', current_database(), + g.rngtypid::regtype, u.oid::regcollation) + FROM pg_range g + JOIN unsafe u ON u.oid = g.rngcollation + WHERE g.rngtypid >= 16384 + UNION + SELECT format('%s: %s orders jsonb strings by the database collation', current_database(), + pg_describe_object('pg_class'::regclass, a.attrelid, a.attnum)) + FROM pg_attribute a + JOIN pg_class r ON r.oid = a.attrelid + WHERE NOT :'default_safe'::boolean AND r.oid >= 16384 AND r.relkind = 'i' + AND a.attnum > 0 AND a.atttypid = 'jsonb'::regtype; +--- +apiVersion: batch/v1 +kind: Job +metadata: + name: {{ $name }} + annotations: + helm.sh/hook: pre-upgrade + helm.sh/hook-weight: "2" + {{- /* A failed Job stays, with its pod log, until the next attempt. */}} + helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded +spec: + activeDeadlineSeconds: 420 + backoffLimit: 0 + template: + metadata: + labels: + policy.cozystack.io/allow-to-apiserver: "true" + spec: + serviceAccountName: {{ $name }} + restartPolicy: Never + securityContext: + fsGroup: 26 + runAsGroup: 26 + runAsNonRoot: true + runAsUser: 26 + seccompProfile: + type: RuntimeDefault + initContainers: + - name: check + image: {{ $liveImage }} + command: [bash, /scripts/check.sh] + env: + - name: PGUSER + valueFrom: + secretKeyRef: + name: {{ .Release.Name }}-superuser + key: username + - name: PGPASSWORD + valueFrom: + secretKeyRef: + name: {{ .Release.Name }}-superuser + key: password + - name: PGHOST + value: {{ .Release.Name }}-rw + - name: PGPORT + value: "5432" + - name: PGDATABASE + value: postgres + securityContext: + allowPrivilegeEscalation: false + capabilities: + drop: + - ALL + readOnlyRootFilesystem: true + runAsNonRoot: true + volumeMounts: + - mountPath: /scripts + name: scripts + - mountPath: /work + name: work + {{- include "postgresjobs.resources" . | nindent 8 }} + containers: + - name: record + image: {{ include "cozy-lib.image" (list "clastix/kubectl:v1.32@sha256:b9ef7d8dbe65bcc81a46c09b8dc7543103055021c4f43287bf59e92a8f4fe05c" $) }} + command: [sh, -ec] + args: + - | + verdict=$(cat /work/verdict) + case "$verdict" in + affected) set -- "postgres.cozystack.io/locale-data-objects=$(head -n 20 /work/found | tr '\n' ';' | cut -c 1-4000)" ;; + clean) set -- "postgres.cozystack.io/locale-data-objects-" ;; + *) set -- ;; + esac + kubectl annotate --overwrite cluster.postgresql.cnpg.io/{{ .Release.Name }} postgres.cozystack.io/locale-data="$verdict" "$@" + {{- if not $held }} + if [ "$verdict" != clean ]; then + echo "postgres {{ .Release.Name }} stays on {{ $liveImage }}: the check found data that depends on a collation sorting differently on the new image, or could not finish (the check container log says which). The next attempt of this upgrade keeps the current image. Set allowCollationChange: true to move it, with the index rebuild, in a maintenance window." >&2 + exit 1 + fi + {{- else }} + if [ "$verdict" = clean ]; then + echo "postgres {{ .Release.Name }}: nothing in it depends on a changing collation any more, but this attempt was rendered with the held image {{ $liveImage }}; failing it so that the next attempt moves the cluster to the new image." >&2 + exit 1 + fi + {{- end }} + env: + - name: HOME + value: /work + securityContext: + allowPrivilegeEscalation: false + capabilities: + drop: + - ALL + readOnlyRootFilesystem: true + runAsNonRoot: true + volumeMounts: + - mountPath: /work + name: work + {{- include "postgresjobs.resources" . | nindent 8 }} + volumes: + - name: scripts + secret: + secretName: {{ $name }} + - name: work + emptyDir: {} +{{- end }} diff --git a/packages/apps/postgres/tests/locale_guard_test.yaml b/packages/apps/postgres/tests/locale_guard_test.yaml new file mode 100644 index 000000000..fe62dbb70 --- /dev/null +++ b/packages/apps/postgres/tests/locale_guard_test.yaml @@ -0,0 +1,526 @@ +suite: keep a bullseye cluster on its image until a clean locale check +release: + name: pg-test + namespace: tenant-test + upgrade: true +set: + _cluster: + scheduling: {} +kubernetesProvider: + scheme: + "postgresql.cnpg.io/v1/Cluster": + gvr: + group: postgresql.cnpg.io + version: v1 + resource: clusters + namespaced: true + objects: + - apiVersion: postgresql.cnpg.io/v1 + kind: Cluster + metadata: + name: pg-test + namespace: tenant-test + annotations: + postgres.cozystack.io/locale-data: affected + spec: + imageName: ghcr.io/cloudnative-pg/postgresql:18.1 + - apiVersion: postgresql.cnpg.io/v1 + kind: Cluster + metadata: + name: pg-clean + namespace: tenant-test + annotations: + postgres.cozystack.io/locale-data: clean + spec: + imageName: ghcr.io/cloudnative-pg/postgresql:18.1 + - apiVersion: postgresql.cnpg.io/v1 + kind: Cluster + metadata: + name: pg-unchecked + namespace: tenant-test + spec: + imageName: ghcr.io/cloudnative-pg/postgresql:18.1 + - apiVersion: postgresql.cnpg.io/v1 + kind: Cluster + metadata: + name: pg-unknown + namespace: tenant-test + annotations: + postgres.cozystack.io/locale-data: unknown + spec: + imageName: ghcr.io/cloudnative-pg/postgresql:18.1 + - apiVersion: postgresql.cnpg.io/v1 + kind: Cluster + metadata: + name: pg-trixie + namespace: tenant-test + annotations: + postgres.cozystack.io/locale-data: affected + spec: + imageName: ghcr.io/cloudnative-pg/postgresql:18.1-standard-trixie + - apiVersion: postgresql.cnpg.io/v1 + kind: Cluster + metadata: + name: pg-restored + namespace: tenant-test + spec: + imageName: ghcr.io/cloudnative-pg/postgresql:18.1 + bootstrap: + recovery: + source: pg-gone +tests: + - it: keeps a cluster the check found affected on its image + templates: + - templates/db.yaml + documentSelector: + path: kind + value: Cluster + asserts: + - equal: + path: spec.imageName + value: ghcr.io/cloudnative-pg/postgresql:18.1 + + - it: runs the init Job from the held image + templates: + - templates/init-job.yaml + documentSelector: + path: kind + value: Job + asserts: + - equal: + path: spec.template.spec.containers[0].image + value: ghcr.io/cloudnative-pg/postgresql:18.1 + + - it: keeps a cluster that was never checked on its image + release: + name: pg-unchecked + templates: + - templates/db.yaml + documentSelector: + path: kind + value: Cluster + asserts: + - equal: + path: spec.imageName + value: ghcr.io/cloudnative-pg/postgresql:18.1 + + - it: keeps a cluster the check could not finish on on its image + release: + name: pg-unknown + templates: + - templates/db.yaml + documentSelector: + path: kind + value: Cluster + asserts: + - equal: + path: spec.imageName + value: ghcr.io/cloudnative-pg/postgresql:18.1 + + - it: moves a cluster the check found clean + release: + name: pg-clean + templates: + - templates/db.yaml + documentSelector: + path: kind + value: Cluster + asserts: + - matchRegex: + path: spec.imageName + pattern: "^ghcr\\.io/cloudnative-pg/postgresql:18\\.[0-9]+-standard-trixie$" + + - it: moves an affected cluster once the change is allowed + set: + allowCollationChange: true + templates: + - templates/db.yaml + documentSelector: + path: kind + value: Cluster + asserts: + - matchRegex: + path: spec.imageName + pattern: "^ghcr\\.io/cloudnative-pg/postgresql:18\\.[0-9]+-standard-trixie$" + + - it: does not hold a cluster already on trixie + release: + name: pg-trixie + templates: + - templates/db.yaml + documentSelector: + path: kind + value: Cluster + asserts: + - matchRegex: + path: spec.imageName + pattern: "^ghcr\\.io/cloudnative-pg/postgresql:18\\.[0-9]+-standard-trixie$" + + - it: refuses a version change while held + set: + version: v17 + templates: + - templates/locale-check-hook.yaml + asserts: + - failedTemplate: + errorPattern: "version v17 cannot be applied: the cluster stays on ghcr.io/cloudnative-pg/postgresql:18.1" + + - it: allows a version change once the collation change is allowed + set: + version: v17 + allowCollationChange: true + templates: + - templates/db.yaml + documentSelector: + path: kind + value: Cluster + asserts: + - matchRegex: + path: spec.imageName + pattern: "^ghcr\\.io/cloudnative-pg/postgresql:17\\.[0-9]+-standard-trixie$" + + - it: restores a backup taken on a bullseye image onto that image + release: + name: pg-new + set: + bootstrap: + enabled: true + oldName: postgres-pg-0f1e2d3c + newServerName: pg-new-restore-0123456789abcdef + sourceImageName: ghcr.io/cloudnative-pg/postgresql:18.1 + backup: + s3AccessKey: access + s3SecretKey: secret + templates: + - templates/db.yaml + documentSelector: + path: kind + value: Cluster + asserts: + - equal: + path: spec.imageName + value: ghcr.io/cloudnative-pg/postgresql:18.1 + + - it: restores a backup taken on trixie onto the current image + release: + name: pg-new + set: + bootstrap: + enabled: true + oldName: postgres-pg-0f1e2d3c + newServerName: pg-new-restore-0123456789abcdef + sourceImageName: ghcr.io/cloudnative-pg/postgresql:18.1-standard-trixie + backup: + s3AccessKey: access + s3SecretKey: secret + templates: + - templates/db.yaml + documentSelector: + path: kind + value: Cluster + asserts: + - matchRegex: + path: spec.imageName + pattern: "^ghcr\\.io/cloudnative-pg/postgresql:18\\.[0-9]+-standard-trixie$" + + - it: never renders an image of another registry from bootstrap.sourceImageName + release: + name: pg-new + set: + bootstrap: + enabled: true + oldName: postgres-pg-0f1e2d3c + sourceImageName: "docker.io/attacker/payload:18" + backup: + s3AccessKey: access + s3SecretKey: secret + templates: + - templates/db.yaml + documentSelector: + path: kind + value: Cluster + asserts: + - matchRegex: + path: spec.imageName + pattern: "^ghcr\\.io/cloudnative-pg/postgresql:18\\.[0-9]+-standard-trixie$" + + - it: never renders a bare tag this chart never shipped from bootstrap.sourceImageName + release: + name: pg-new + set: + bootstrap: + enabled: true + oldName: postgres-pg-0f1e2d3c + sourceImageName: "ghcr.io/cloudnative-pg/postgresql:18.0" + backup: + s3AccessKey: access + s3SecretKey: secret + templates: + - templates/db.yaml + documentSelector: + path: kind + value: Cluster + asserts: + - matchRegex: + path: spec.imageName + pattern: "^ghcr\\.io/cloudnative-pg/postgresql:18\\.[0-9]+-standard-trixie$" + + - it: never renders a digest-pinned tag from bootstrap.sourceImageName + release: + name: pg-new + set: + bootstrap: + enabled: true + oldName: postgres-pg-0f1e2d3c + sourceImageName: "ghcr.io/cloudnative-pg/postgresql:18.1@sha256:0000000000000000000000000000000000000000000000000000000000000000" + backup: + s3AccessKey: access + s3SecretKey: secret + templates: + - templates/db.yaml + documentSelector: + path: kind + value: Cluster + asserts: + - matchRegex: + path: spec.imageName + pattern: "^ghcr\\.io/cloudnative-pg/postgresql:18\\.[0-9]+-standard-trixie$" + + - it: keeps a Cluster a recovery created on its image until it is checked + release: + name: pg-restored + set: + bootstrap: + enabled: true + oldName: pg-gone + backup: + s3AccessKey: access + s3SecretKey: secret + templates: + - templates/db.yaml + documentSelector: + path: kind + value: Cluster + asserts: + - equal: + path: spec.imageName + value: ghcr.io/cloudnative-pg/postgresql:18.1 + + - it: reads a live Cluster no recovery created on its own, whatever the bootstrap values say + release: + name: pg-clean + set: + bootstrap: + enabled: true + oldName: pg-test + sourceImageName: ghcr.io/cloudnative-pg/postgresql:18.1 + backup: + s3AccessKey: access + s3SecretKey: secret + templates: + - templates/db.yaml + documentSelector: + path: kind + value: Cluster + asserts: + - matchRegex: + path: spec.imageName + pattern: "^ghcr\\.io/cloudnative-pg/postgresql:18\\.[0-9]+-standard-trixie$" + + - it: restores a hand-set recovery onto the image of its source Cluster + release: + name: pg-new + set: + bootstrap: + enabled: true + oldName: pg-trixie + backup: + s3AccessKey: access + s3SecretKey: secret + templates: + - templates/db.yaml + documentSelector: + path: kind + value: Cluster + asserts: + - matchRegex: + path: spec.imageName + pattern: "^ghcr\\.io/cloudnative-pg/postgresql:18\\.[0-9]+-standard-trixie$" + + - it: holds a hand-set recovery of a bullseye source Cluster + release: + name: pg-new + set: + bootstrap: + enabled: true + oldName: pg-clean + backup: + s3AccessKey: access + s3SecretKey: secret + templates: + - templates/db.yaml + documentSelector: + path: kind + value: Cluster + asserts: + - equal: + path: spec.imageName + value: ghcr.io/cloudnative-pg/postgresql:18.1 + + - it: does not read a Cluster named like the server name of a RestoreJob + release: + name: pg-new + set: + bootstrap: + enabled: true + oldName: pg-test + newServerName: pg-new-restore-0123456789abcdef + backup: + s3AccessKey: access + s3SecretKey: secret + templates: + - templates/db.yaml + documentSelector: + path: kind + value: Cluster + asserts: + - matchRegex: + path: spec.imageName + pattern: "^ghcr\\.io/cloudnative-pg/postgresql:18\\.[0-9]+-standard-trixie$" + + - it: ignores a bootstrap.sourceImageName left over once the recovery is done + release: + name: pg-trixie + set: + bootstrap: + enabled: false + sourceImageName: ghcr.io/cloudnative-pg/postgresql:18.1 + templates: + - templates/db.yaml + documentSelector: + path: kind + value: Cluster + asserts: + - matchRegex: + path: spec.imageName + pattern: "^ghcr\\.io/cloudnative-pg/postgresql:18\\.[0-9]+-standard-trixie$" + + - it: never holds a postgis cluster on a postgresql image + release: + name: pg-new + set: + flavor: postgis + version: v17 + bootstrap: + enabled: true + oldName: postgres-pg-0f1e2d3c + sourceImageName: ghcr.io/cloudnative-pg/postgresql:17.7 + backup: + s3AccessKey: access + s3SecretKey: secret + templates: + - templates/db.yaml + documentSelector: + path: kind + value: Cluster + asserts: + - matchRegex: + path: spec.imageName + pattern: "^ghcr\\.io/cloudnative-pg/postgis:" + + - it: checks a bullseye cluster from its own image + release: + name: pg-unchecked + templates: + - templates/locale-check-hook.yaml + documentSelector: + path: kind + value: Job + asserts: + - equal: + path: spec.template.spec.initContainers[0].image + value: ghcr.io/cloudnative-pg/postgresql:18.1 + + - it: rechecks a held cluster from its held image + templates: + - templates/locale-check-hook.yaml + documentSelector: + path: kind + value: Job + asserts: + - equal: + path: spec.template.spec.initContainers[0].image + value: ghcr.io/cloudnative-pg/postgresql:18.1 + + - it: skips the check once the change is allowed + set: + allowCollationChange: true + templates: + - templates/locale-check-hook.yaml + asserts: + - hasDocuments: + count: 0 + + - it: skips the check for a cluster already on trixie + release: + name: pg-trixie + templates: + - templates/locale-check-hook.yaml + asserts: + - hasDocuments: + count: 0 + + - it: skips the check for a new cluster + release: + name: pg-new + templates: + - templates/locale-check-hook.yaml + asserts: + - hasDocuments: + count: 0 + + - it: does not check a cluster while its restore is in progress + release: + name: pg-unchecked + set: + bootstrap: + enabled: true + oldName: pg-test + backup: + s3AccessKey: access + s3SecretKey: secret + templates: + - templates/locale-check-hook.yaml + asserts: + - hasDocuments: + count: 0 + + - it: names the hook resources so that they cannot take the names CNPG gives another cluster + release: + name: pg-unchecked + templates: + - templates/locale-check-hook.yaml + documentSelector: + path: kind + value: Job + asserts: + - matchRegex: + path: metadata.name + pattern: ^locale-check-pg-unchecked-[0-9a-f]{8}$ + + - it: lets the role patch only its own Cluster + release: + name: pg-unchecked + templates: + - templates/locale-check-hook.yaml + documentSelector: + path: kind + value: Role + asserts: + - equal: + path: rules + value: + - apiGroups: ["postgresql.cnpg.io"] + resources: ["clusters"] + resourceNames: ["pg-unchecked"] + verbs: ["get", "patch"] diff --git a/packages/apps/postgres/values.schema.json b/packages/apps/postgres/values.schema.json index 4ec823fd4..ddf6ff5a0 100644 --- a/packages/apps/postgres/values.schema.json +++ b/packages/apps/postgres/values.schema.json @@ -155,6 +155,11 @@ "postgis" ] }, + "allowCollationChange": { + "description": "Allow a cluster created on a Debian bullseye image (before the move to standard-trixie) to move to the new image without a clean locale check. Such a cluster is checked before each upgrade, except while `bootstrap.enabled` is set (set it back to false once a restore set up by hand has finished), and stays on its current image until the check finds nothing that depends on a collation other than C, POSIX or builtin: while this is false, a cluster the check found affected (an ICU or libc locale, or C.UTF-8) or could not finish on stays put, because glibc and ICU on the new image sort text differently and every index on such text must be rebuilt. A held cluster runs the bare bullseye tag it has, gets no further PostgreSQL minors and so none of their security fixes, and refuses a change of `version`, since new majors are built only on the new images. To leave that state, either remove the dependency (move such columns and indexes to C, or to the builtin `pg_c_utf8` on PostgreSQL 17 and later) and let the next upgrade check again, or set this to true in a maintenance window: the cluster moves on the next upgrade, replicas restart on the new image first and can return wrong results through `-ro`, and unique indexes can accept duplicates, until the indexes are rebuilt on the primary. The init Job rebuilds only indexes on collations that record a version (ICU, and libc locales other than C.*): rebuild indexes on C.UTF-8 or another C.* locale by hand with REINDEX, and check range partitions, CHECK constraints and materialized views on such text, which a rebuild does not fix. A held cluster shows the hold only as an unchanged image; the result and the objects found are in the `postgres.cozystack.io/locale-data` and `postgres.cozystack.io/locale-data-objects` annotations of the cnpg.io Cluster, which an administrator can read. A restore of a backup taken on one of those bullseye images comes back on that image and is checked by the next upgrade.", + "type": "boolean", + "default": false + }, "tls": { "description": "TLS configuration for server connections.", "type": "object", @@ -500,6 +505,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 26a60ba2b..e0f8b2f96 100644 --- a/packages/apps/postgres/values.yaml +++ b/packages/apps/postgres/values.yaml @@ -99,6 +99,9 @@ version: v18 ## @param {Flavor} flavor - PostgreSQL image flavor, fixed when the cluster is created. `postgresql` uses the CloudNativePG PostgreSQL image. `postgis` uses the CloudNativePG PostGIS image, which adds postgis, postgis_raster, postgis_topology, postgis_sfcgal, postgis_tiger_geocoder and address_standardizer; enable them per database in `databases..extensions`. Changing the flavor of an existing cluster is refused, and a backup restores only into a cluster of the flavor it was taken from: to change flavor, create a new cluster and move the data with a logical dump (pg_dump / pg_restore). flavor: postgresql +## @param {bool} allowCollationChange - Allow a cluster created on a Debian bullseye image (before the move to standard-trixie) to move to the new image without a clean locale check. Such a cluster is checked before each upgrade, except while `bootstrap.enabled` is set (set it back to false once a restore set up by hand has finished), and stays on its current image until the check finds nothing that depends on a collation other than C, POSIX or builtin: while this is false, a cluster the check found affected (an ICU or libc locale, or C.UTF-8) or could not finish on stays put, because glibc and ICU on the new image sort text differently and every index on such text must be rebuilt. A held cluster runs the bare bullseye tag it has, gets no further PostgreSQL minors and so none of their security fixes, and refuses a change of `version`, since new majors are built only on the new images. To leave that state, either remove the dependency (move such columns and indexes to C, or to the builtin `pg_c_utf8` on PostgreSQL 17 and later) and let the next upgrade check again, or set this to true in a maintenance window: the cluster moves on the next upgrade, replicas restart on the new image first and can return wrong results through `-ro`, and unique indexes can accept duplicates, until the indexes are rebuilt on the primary. The init Job rebuilds only indexes on collations that record a version (ICU, and libc locales other than C.*): rebuild indexes on C.UTF-8 or another C.* locale by hand with REINDEX, and check range partitions, CHECK constraints and materialized views on such text, which a rebuild does not fix. A held cluster shows the hold only as an unchanged image; the result and the objects found are in the `postgres.cozystack.io/locale-data` and `postgres.cozystack.io/locale-data-objects` annotations of the cnpg.io Cluster, which an administrator can read. A restore of a backup taken on one of those bullseye images comes back on that image and is checked by the next upgrade. +allowCollationChange: false + ## ## @section TLS configuration ## @@ -400,6 +403,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: @@ -410,3 +414,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 dc60ee20a..616783e48 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},"schedulingClass":{"description":"Name of a SchedulingClass CR (cluster-scoped, group cozystack.io) used in place of the tenant's for this application's pods. A pod gets its class when it is created, so running pods keep theirs until they are recreated. Must be the tenant's own class or one listed in the tenant's `allowedSchedulingClasses`. Setting any other value is refused, and the pods of an application whose class is not, or no longer, in that list get the tenant's class. Empty means inherit from the tenant.","type":"string","default":"","maxLength":63},"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"]}}}},"audit":{"description":"PostgreSQL audit configuration.","type":"object","default":{},"properties":{"enabled":{"description":"Enable PostgreSQL auditing. Loads the pgaudit extension through the `sharedPreloadLibraries` allowlist and turns on `log_connections`/`log_disconnections`, so who connected and the classes of statement they ran are written to the instance log and collected by the platform log stack. The audited statement classes are set by `log`. Off by default. Enabling or disabling it restarts PostgreSQL, since pgaudit is a preloaded library. Note that `write` and `all` record statement text with literal values, so anyone who can read the tenant's log stack can read audited data; keep that in mind on a shared Monitoring.","type":"boolean","default":false},"log":{"description":"pgaudit session audit classes recorded when `enabled`, as the comma-separated value of `pgaudit.log`. Valid classes are `read`, `write`, `function`, `role`, `ddl`, `misc`, `misc_set`, `all` and `none`; a class may be prefixed with `-` to subtract it from `all` (for example `ddl, role`, `write, ddl, role`, or `all, -misc`). `all` logs every statement including reads and is heavy. Defaults to `write, ddl, role`. A `pgaudit.log` set in `postgresql.parameters` overrides this. The pattern rejects an unrecognised class at admission, which otherwise makes pgaudit fall back to `none` at the next start and silently disables auditing.","type":"string","default":"write, ddl, role","pattern":"^(\\s*-?(read|write|function|role|ddl|misc_set|misc|all|none)\\s*(,\\s*-?(read|write|function|role|ddl|misc_set|misc|all|none)\\s*)*)?$"}}},"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},"schedulingClass":{"description":"Name of a SchedulingClass CR (cluster-scoped, group cozystack.io) used in place of the tenant's for this application's pods. A pod gets its class when it is created, so running pods keep theirs until they are recreated. Must be the tenant's own class or one listed in the tenant's `allowedSchedulingClasses`. Setting any other value is refused, and the pods of an application whose class is not, or no longer, in that list get the tenant's class. Empty means inherit from the tenant.","type":"string","default":"","maxLength":63},"version":{"description":"PostgreSQL major version to deploy","type":"string","default":"v18","enum":["v18","v17","v16","v15","v14","v13"]},"flavor":{"description":"PostgreSQL image flavor, fixed when the cluster is created. `postgresql` uses the CloudNativePG PostgreSQL image. `postgis` uses the CloudNativePG PostGIS image, which adds postgis, postgis_raster, postgis_topology, postgis_sfcgal, postgis_tiger_geocoder and address_standardizer; enable them per database in `databases..extensions`. Changing the flavor of an existing cluster is refused, and a backup restores only into a cluster of the flavor it was taken from: to change flavor, create a new cluster and move the data with a logical dump (pg_dump / pg_restore).","type":"string","default":"postgresql","enum":["postgresql","postgis"]},"allowCollationChange":{"description":"Allow a cluster created on a Debian bullseye image (before the move to standard-trixie) to move to the new image without a clean locale check. Such a cluster is checked before each upgrade, except while `bootstrap.enabled` is set (set it back to false once a restore set up by hand has finished), and stays on its current image until the check finds nothing that depends on a collation other than C, POSIX or builtin: while this is false, a cluster the check found affected (an ICU or libc locale, or C.UTF-8) or could not finish on stays put, because glibc and ICU on the new image sort text differently and every index on such text must be rebuilt. A held cluster runs the bare bullseye tag it has, gets no further PostgreSQL minors and so none of their security fixes, and refuses a change of `version`, since new majors are built only on the new images. To leave that state, either remove the dependency (move such columns and indexes to C, or to the builtin `pg_c_utf8` on PostgreSQL 17 and later) and let the next upgrade check again, or set this to true in a maintenance window: the cluster moves on the next upgrade, replicas restart on the new image first and can return wrong results through `-ro`, and unique indexes can accept duplicates, until the indexes are rebuilt on the primary. The init Job rebuilds only indexes on collations that record a version (ICU, and libc locales other than C.*): rebuild indexes on C.UTF-8 or another C.* locale by hand with REINDEX, and check range partitions, CHECK constraints and materialized views on such text, which a rebuild does not fix. A held cluster shows the hold only as an unchanged image; the result and the objects found are in the `postgres.cozystack.io/locale-data` and `postgres.cozystack.io/locale-data-objects` annotations of the cnpg.io Cluster, which an administrator can read. A restore of a backup taken on one of those bullseye images comes back on that image and is checked by the next upgrade.","type":"boolean","default":false},"tls":{"description":"TLS configuration for server connections.","type":"object","default":{},"properties":{"enabled":{"description":"Tri-state switch controlling whether the chart injects the external hostnames into the operator-managed CNPG cert via spec.certificates.serverAltDNSNames. When omitted, the chart injects them if `external: true` and skips them otherwise. Set explicitly to `true` to inject regardless of `external` (no-op when `external: false` since there is no external hostname to add). Set to `false` to skip injection. Note that CNPG keeps its built-in TLS on the wire regardless of this flag — this toggle only controls the chart-side SAN injection; to disable PostgreSQL TLS entirely set `postgresql.parameters.ssl = \"off\"` at the CNPG layer.","type":"boolean"},"required":{"description":"Tri-state switch controlling whether the server refuses sessions that are not encrypted. When omitted, it is on if `external: true` and off otherwise. When on, the chart renders `spec.postgresql.pg_hba` with `hostssl all all all scram-sha-256` (`md5` on PostgreSQL 13, matching CloudNativePG's default rule) followed by `host all all all reject`, so a client that connects with `sslmode=disable` is refused instead of getting a plaintext session; in-cluster clients are held to the same rule, since the pod network cannot be told apart from an external client. Set to `false` to keep accepting plaintext sessions on an external instance, or to `true` to require TLS on an in-cluster one. Rendering fails if `postgresql.parameters.ssl` is off while this is in effect.","type":"boolean"}}},"postgresql":{"description":"PostgreSQL server configuration.","type":"object","default":{},"properties":{"parameters":{"description":"PostgreSQL server parameters. Values may be strings or integers; integers are coerced to strings by the template (e.g. both `max_connections: 100` and `max_connections: \"100\"` are accepted). BLOCKED (enable arbitrary code execution): archive_command, restore_command, ssl_passphrase_command, archive_cleanup_command, recovery_end_command, dynamic_library_path, local_preload_libraries, session_preload_libraries, shared_preload_libraries. Do NOT override CloudNativePG-managed parameters: archive_mode, primary_conninfo, wal_level, max_replication_slots.","type":"object","default":{"max_connections":"100"},"additionalProperties":{"anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}},"sharedPreloadLibraries":{"description":"Libraries loaded at server start, restricted to an allowlist of modules already shipped in the PostgreSQL image. CloudNativePG also preloads `pg_stat_statements`, `auto_explain` and `pgaudit` by itself whenever `parameters` sets a key under their prefix (e.g. `pg_stat_statements.track`), so removing one of them from this list does not unload it while such a key is set; `pg_prewarm` is preloaded only through this list. Changing the list restarts PostgreSQL on every instance, the primary included, so writes pause briefly.","type":"array","items":{"type":"string","enum":["pg_stat_statements","auto_explain","pgaudit","pg_prewarm"]}}}},"audit":{"description":"PostgreSQL audit configuration.","type":"object","default":{},"properties":{"enabled":{"description":"Enable PostgreSQL auditing. Loads the pgaudit extension through the `sharedPreloadLibraries` allowlist and turns on `log_connections`/`log_disconnections`, so who connected and the classes of statement they ran are written to the instance log and collected by the platform log stack. The audited statement classes are set by `log`. Off by default. Enabling or disabling it restarts PostgreSQL, since pgaudit is a preloaded library. Note that `write` and `all` record statement text with literal values, so anyone who can read the tenant's log stack can read audited data; keep that in mind on a shared Monitoring.","type":"boolean","default":false},"log":{"description":"pgaudit session audit classes recorded when `enabled`, as the comma-separated value of `pgaudit.log`. Valid classes are `read`, `write`, `function`, `role`, `ddl`, `misc`, `misc_set`, `all` and `none`; a class may be prefixed with `-` to subtract it from `all` (for example `ddl, role`, `write, ddl, role`, or `all, -misc`). `all` logs every statement including reads and is heavy. Defaults to `write, ddl, role`. A `pgaudit.log` set in `postgresql.parameters` overrides this. The pattern rejects an unrecognised class at admission, which otherwise makes pgaudit fall back to `none` at the next start and silently disables auditing.","type":"string","default":"write, ddl, role","pattern":"^(\\s*-?(read|write|function|role|ddl|misc_set|misc|all|none)\\s*(,\\s*-?(read|write|function|role|ddl|misc_set|misc|all|none)\\s*)*)?$"}}},"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", "schedulingClass"], ["spec", "version"], ["spec", "flavor"], ["spec", "tls"], ["spec", "postgresql"], ["spec", "postgresql", "parameters"], ["spec", "postgresql", "parameters", "max_connections"], ["spec", "audit"], ["spec", "audit", "enabled"], ["spec", "audit", "log"], ["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", "schedulingClass"], ["spec", "version"], ["spec", "flavor"], ["spec", "allowCollationChange"], ["spec", "tls"], ["spec", "postgresql"], ["spec", "postgresql", "parameters"], ["spec", "postgresql", "parameters", "max_connections"], ["spec", "audit"], ["spec", "audit", "enabled"], ["spec", "audit", "log"], ["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: