fix(postgres): keep bullseye clusters on their image until a clean locale check

Clusters created before the move to standard-trixie run the bare tag, the
system variant on Debian bullseye. Moving them changes glibc and ICU under
the data directory, and the collation repair pass cannot see every case
(C.UTF-8 carries no collation version), so text indexes can return wrong
results and unique indexes can accept duplicates.

Such a cluster now stays on its image until a pre-upgrade hook, run from
that image, finds nothing stored that depends on a collation other than C,
POSIX or builtin. The hook records clean, affected or unknown on the
Cluster; anything but clean holds the cluster, so a check that cannot
finish keeps it where it is rather than letting it move unchecked. Helm
renders before hooks run, so the hook fails an attempt only when its
answer contradicts what that attempt rendered, and the retry follows the
answer. allowCollationChange moves a held cluster on the owner's terms, and
a held cluster refuses a change of version, since new majors are built only
on the new images.

A physical restore replaces the Cluster that carries the answer. The CNPG
backup driver records the source Cluster's image in the backup snapshot and
passes it on as bootstrap.sourceImageName without interpreting it; the
chart restores onto it only when it is one of the bullseye tags it shipped,
and the next upgrade checks the restored data.

Assisted-By: LLM
Signed-off-by: Andrey Kolkov <androndo@gmail.com>
This commit is contained in:
Andrey Kolkov committed 2026-11-27 18:21:43 +07:00
1 parent 9af6594342
commit 21d66c4cce
14 files changed
+1134 -71

No files matched your search

+6
View File
@@ -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.<name>.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 {
@@ -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)
}
@@ -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)
}
@@ -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)
}
}
}
@@ -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 {
@@ -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)
}
@@ -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 {
+24 -22
View File
@@ -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.<name>.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.<name>.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
@@ -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
@@ -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
<this release>-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 }}
@@ -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"]
+10
View File
@@ -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": ""
}
}
}
+5
View File
@@ -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.<name>.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: ""
+2 -2
View File
@@ -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.<name>.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 Line truncated
{"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.<name>.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 iLine truncated
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: