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

## What this PR does

Refs #5459. Part of bringing #5405 (standard-trixie images) back to
release-1.7, which #5461 reverted. This PR covers the `C.UTF-8` item of
#5459 by keeping such clusters off the new image. The other items are
fixed separately: the repair racing the rollout and the Job budget, the
repair skipping `C.UTF-8`, the double REINDEX, and the postgis extension
update.

### Why

Clusters created before #5405 run a bare tag, the system variant on
Debian bullseye. Moving them to `standard-trixie` changes glibc and ICU
under the data directory. The collation repair pass from #5405 cannot
see every case. A libc `C.*` locale such as `C.UTF-8` carries no
collation version in any PostgreSQL major, yet Debian bullseye's
`C.UTF-8` and the one in glibc 2.35+ sort differently. Until the indexes
are rebuilt, replicas return wrong results through `-ro` and unique
indexes accept duplicates. PostgreSQL ([Locale data
changes](https://wiki.postgresql.org/wiki/Locale_data_changes)) and
CloudNativePG
([postgres-containers](https://github.com/cloudnative-pg/postgres-containers):
switching the Debian base "is a manual operation because of PostgreSQL
locale-data implications") both treat this as a deliberate, owner-driven
step.

### What it does

A cluster on one of the bare bullseye tags the chart shipped (13.22,
14.20, 15.15, 16.11, 17.7, 18.1) stays on its image until a check finds
it clean. The check fails closed: a cluster not checked yet, one the
check could not finish on, and one it found affected all stay.

- **The check.** A `pre-upgrade` hook (`locale-check-<release>-<hash>`)
runs before every upgrade of such a cluster, from the cluster's current
image.
- It looks in every database for columns, indexes, composite or range
types, and `jsonb` indexes that depend on a collation other than C,
POSIX or builtin, and for a database default (collate or ctype) outside
those.
- It records `clean`, `affected` or `unknown` in the
`postgres.cozystack.io/locale-data` annotation of the Cluster, and the
first objects found in `postgres.cozystack.io/locale-data-objects`.
  - Its Role can only `get`/`patch` that one Cluster.
- **What the chart renders.** The chart reads the recorded answer
through `lookup`. Helm renders before hooks run, so the hook fails an
attempt only when the new answer contradicts that render, before the
Cluster is patched. The HelmRelease retry then renders according to the
new answer:
- A cluster not checked before, or found `affected` or `unknown`, is
rendered on its current image. The upgrade passes, and every other value
of the app still applies.
- A cluster found `clean` fails that attempt once, and the retry moves
it to `standard-trixie` with the existing repair.
- **Opt-in.** `allowCollationChange: true` moves a held cluster on the
next upgrade, in a window the owner picks.
- **Version changes.** A held cluster refuses a change of `version` with
an explicit render error, since new majors are built only on the new
images.
- **Restore.** The CNPG backup driver copies the source Cluster's
`spec.imageName` into the backup snapshot verbatim, passes it to the
restore as `bootstrap.sourceImageName`, and clears it with
`bootstrap.enabled`. The core controller knows nothing about the chart's
hold rules.
- The chart decides: a backup taken on one of the bullseye tags restores
onto that image, so the data keeps the library that built it.
- The next upgrade then checks the restored data like any other bullseye
cluster.
- Any other value is ignored, so a tenant cannot choose an image through
it.
- The driver also reads the major from that image tag when the backup
recorded none, and refuses a mismatch with `spec.version` before the
purge.

### What a held cluster is left with

- It keeps running its bare bullseye tag. Upstream builds new PostgreSQL
minors only on bookworm and trixie, so a held cluster gets **no further
minors and none of their security fixes; CVE-2026-116331 stays open on
it** for as long as it is held.
- The tenant sees only that the image did not change. The answer and the
objects found are on the cnpg.io Cluster, which only an administrator
can read.
- There is no deadline. The hold lasts until the owner takes one of the
ways out below.

### How a held cluster leaves that state

1. **Remove the dependency.** Move the listed columns and indexes to
`C`, or to the builtin `pg_c_utf8` on PostgreSQL 17 and later, or drop
them. The next upgrade checks again, finds the cluster `clean` and moves
it.
2. **Move explicitly.** In a maintenance window, set
`allowCollationChange: true`. The next upgrade moves the cluster and the
init Job's repair rebuilds indexes on versioned collations (ICU, libc
locales other than `C.*`). Until the separate `C.UTF-8` repair fix
lands, rebuild indexes on `C.UTF-8` or another `C.*` locale by hand with
`REINDEX INDEX CONCURRENTLY`. Range partitions, CHECK constraints and
materialized views on such text are not fixed by a rebuild and need a
logical move (pg_dump/restore or logical replication). During the move,
replicas restart on the new image first, so reads through `-ro` can be
wrong and unique indexes can accept duplicates until the primary's
rebuild is done.

### Testing

- `helm unittest packages/apps/postgres`: 276 passed, including
`tests/locale_guard_test.yaml`. It covers:
- holding on `affected`, `unknown` and a missing result, and moving on
`clean`;
  - the opt-in and the version refusal;
- restores from bullseye and trixie backups, hand-set recoveries, and
leftover values;
- ignoring foreign images, postgis, hook gating, naming and the Role
scope.
- `go test ./internal/backupcontroller/...` passes, including
`cnpg_source_image_test.go` and the restore reconcile cases for passing
the image on and refusing the held major before the purge.
- The check script was run in Docker against `postgres:13-bullseye` and
`postgres:18-bookworm`:
- It flags `C.UTF-8`/`C.utf8` columns and defaults, ICU indexes, `en_US`
defaults with text, a `C`-collate / `en_US`-ctype database with a
`lower()` index, composite and range types over text, and `jsonb`
indexes under a non-C default.
- It reports `clean` for `C`, `POSIX`, `pg_c_utf8` and `ucs_basic`, and
when another database is `default_transaction_read_only`.
- It reports `unknown` on an authentication failure or when a database
accepts no connections.
- The record step was run with a stub `kubectl` for each render (held or
moving) and answer:
- held + `clean` fails the attempt; held + `affected`/`unknown` passes;
- moving + `clean` passes; moving + `affected`/`unknown` fails the
attempt;
  - every answer is recorded.
- Dev cluster: apps installed from the v1.7.1 chart (`postgresql:17.7`,
bullseye) and upgraded to this branch (results in the PR thread).

### Screenshots

### Downstream repositories

The trigger map hits `cozystack/terraform-provider-cozystack`, because
this adds `allowCollationChange` and `bootstrap.sourceImageName` to the
postgres `values.schema.json`. The follow-up is
cozystack/terraform-provider-cozystack#91.

- [ ] No downstream repository is affected by this change
- [ ] [cozystack/website](https://github.com/cozystack/website) -
follow-up:
- [x]
[cozystack/terraform-provider-cozystack](https://github.com/cozystack/terraform-provider-cozystack)
- follow-up: cozystack/terraform-provider-cozystack#91
- [ ]
[cozystack/ansible-cozystack](https://github.com/cozystack/ansible-cozystack)
- follow-up:
- [ ] [cozystack/ccp](https://github.com/cozystack/ccp) - follow-up:
- [ ] [cozystack/talm](https://github.com/cozystack/talm) - follow-up:
- [ ] [cozystack/cozyhr](https://github.com/cozystack/cozyhr) -
follow-up:
- [ ] [cozystack/cozy-proxy](https://github.com/cozystack/cozy-proxy) -
follow-up:
- [ ]
[cozystack/cozystack-telemetry-server](https://github.com/cozystack/cozystack-telemetry-server)
- follow-up:
- [ ]
[cozystack/external-apps-example](https://github.com/cozystack/external-apps-example)
- follow-up:
- [ ] [cozystack/examples](https://github.com/cozystack/examples) -
follow-up:
- [ ] [cozystack/community](https://github.com/cozystack/community) -
follow-up:

### Release note

```release-note
[postgres] A cluster still on a Debian bullseye image now stays on that image until a pre-upgrade check finds nothing in it that depends on a collation other than C, POSIX or builtin (an ICU or libc locale, or C.UTF-8), or until `allowCollationChange` is set. A held cluster gets no further PostgreSQL minors or their security fixes. The `postgres.cozystack.io/locale-data` annotation of the cnpg.io Cluster shows the result of the check.
```

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

- **New Features**
- PostgreSQL upgrades from older Debian Bullseye images now check for
collation-dependent data and hold the current image when results are
affected or unknown.
- Added an opt-in setting to allow the image change despite the
collation check. Review collation and index-rebuild considerations
before enabling it.
- PostgreSQL restores retain source-image information to support image
selection and compatibility checks.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

On release-1.6 the CNPG backup driver predates the backup destination,
artifact-size, flavor and major-version changes this builds on on main,
so only the image handling is ported: the live Cluster's spec.imageName
goes into the backup snapshot and the restore passes it to the chart as
bootstrap.sourceImageName. The 1.6 driver never patches bootstrap.enabled
back to false after a restore and has no check of the backup's major
against spec.version, so there is nowhere to clear the value or to read
the major from the image; the next restore sets or clears it, and the
chart uses it only while no live Cluster exists. The cnpgtypes Cluster
spec gains the read-only imageName field, which main added with the
flavor record, and the unmarshal helper returns the snapshot struct, as
on main, so the restore can read the image. The tests for the destination and artifact size, and those for
the bootstrap clearing and the major, are not part of this line.

release-1.6 has no postgis flavor, so the flavor conditions in the hold
rules, the flavor guard, the postgis branch of the target image, the
flavor value and the postgis test case are not carried over.

(cherry picked from commit 9cf93b8535)
Assisted-By: LLM
Signed-off-by: Andrey Kolkov <androndo@gmail.com>
This commit is contained in:
Aleksei Sviridkin authored and Andrey Kolkov committed 2026-12-02 15:31:37 +07:00
1 parent 4ea048e466
commit df12079583
13 files changed
+1056 -68

No files matched your search

+6
View File
@@ -40,6 +40,9 @@ type ConfigSpec struct {
// PostgreSQL major version to deploy
// +kubebuilder:default:="v18"
Version Version `json:"version"`
// Allow a cluster created on a Debian bullseye image (before the move to standard-trixie) to move to the new image without a clean locale check. Such a cluster is checked before each upgrade, except while `bootstrap.enabled` is set (set it back to false once a restore has finished), and stays on its current image until the check finds nothing that depends on a collation other than C, POSIX or builtin: while this is false, a cluster the check found affected (an ICU or libc locale, or C.UTF-8) or could not finish on stays put, because glibc and ICU on the new image sort text differently and every index on such text must be rebuilt. A held cluster runs the bare bullseye tag it has, gets no further PostgreSQL minors and so none of their security fixes, and refuses a change of `version`, since new majors are built only on the new images. To leave that state, either remove the dependency (move such columns and indexes to C, or to the builtin `pg_c_utf8` on PostgreSQL 17 and later) and let the next upgrade check again, or set this to true in a maintenance window: the cluster moves on the next upgrade, replicas restart on the new image first and can return wrong results through `-ro`, and unique indexes can accept duplicates, until the indexes are rebuilt on the primary. The init Job rebuilds only indexes on collations that record a version (ICU, and libc locales other than C.*): rebuild indexes on C.UTF-8 or another C.* locale by hand with REINDEX, and check range partitions, CHECK constraints and materialized views on such text, which a rebuild does not fix. A held cluster shows the hold only as an unchanged image; the result and the objects found are in the `postgres.cozystack.io/locale-data` and `postgres.cozystack.io/locale-data-objects` annotations of the cnpg.io Cluster, which an administrator can read. A restore of a backup taken on one of those bullseye images comes back on that image and is checked by the next upgrade.
// +kubebuilder:default:=false
AllowCollationChange bool `json:"allowCollationChange"`
// TLS configuration for server connections.
// +kubebuilder:default:={}
Tls TLS `json:"tls"`
@@ -112,6 +115,9 @@ type Bootstrap struct {
// Server name (S3 path prefix) used by the original cluster when writing backups; passed to the barman-cloud plugin via `externalClusters[].plugin.parameters.serverName`. Defaults to `bootstrap.oldName`. Set this only when the original cluster wrote backups under an explicit server name that differed from its Kubernetes resource name.
// +kubebuilder:default:=""
ServerName string `json:"serverName,omitempty"`
// Image of the cluster the backup was taken from. A restore of a backup taken on one of the bare Debian bullseye tags the chart used before standard-trixie comes back on that image (see `allowCollationChange`); any other value is ignored. The CNPG backup driver sets this on every restore, and clears it when the backup carries no image.
// +kubebuilder:default:=""
SourceImageName string `json:"sourceImageName,omitempty"`
}
type Database struct {
@@ -0,0 +1,62 @@
package backupcontroller
import (
"context"
"testing"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
strategyv1alpha1 "github.com/cozystack/cozystack/api/backups/strategy/v1alpha1"
backupsv1alpha1 "github.com/cozystack/cozystack/api/backups/v1alpha1"
cnpgtypes "github.com/cozystack/cozystack/internal/backupcontroller/cnpgtypes"
)
func TestApplyClusterPluginBackup_RecordsImageName(t *testing.T) {
for _, image := range []string{"ghcr.io/cloudnative-pg/postgresql:17.7", "ghcr.io/cloudnative-pg/postgresql:17.12-standard-trixie"} {
t.Run(image, func(t *testing.T) {
cluster := &cnpgtypes.Cluster{
ObjectMeta: metav1.ObjectMeta{Namespace: "tenant", Name: "postgres-app", UID: "cluster-uid-123"},
}
cluster.Spec.ImageName = image
c := newCNPGStrategyTestClient(t, cluster)
r := &BackupJobReconciler{Client: c, Interface: cnpgDynamicFor(t, cluster)}
tmpl := &strategyv1alpha1.CNPGTemplate{
BarmanObjectStore: strategyv1alpha1.BarmanObjectStoreTemplate{DestinationPath: "s3://bucket/x/"},
}
_, got, err := r.applyClusterPluginBackup(context.Background(), "tenant", "postgres-app", tmpl, "strategy-name")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if got != image {
t.Fatalf("imageName = %q, want %q", got, image)
}
})
}
}
func TestCNPGBackupSnapshot_CarriesImageName(t *testing.T) {
raw, err := marshalCNPGBackupSnapshot(newPostgresApp("pg", "tenant"), nil, "ghcr.io/cloudnative-pg/postgresql:17.7")
if err != nil {
t.Fatalf("marshal snapshot: %v", err)
}
snap, err := unmarshalCNPGBackupSnapshot(&backupsv1alpha1.Backup{Status: backupsv1alpha1.BackupStatus{UnderlyingResources: raw}})
if err != nil {
t.Fatalf("unmarshal snapshot: %v", err)
}
if snap.ImageName != "ghcr.io/cloudnative-pg/postgresql:17.7" {
t.Fatalf("ImageName = %q", snap.ImageName)
}
}
func TestBuildPostgresAppRestorePatch_SetsAndClearsSourceImage(t *testing.T) {
app := newPostgresApp("pg", "tenant")
app.Spec.Bootstrap.SourceImageName = "ghcr.io/cloudnative-pg/postgresql:16.11"
if got := buildPostgresAppRestorePatch(app, "src", "pg-new", "s3://b/", "", "", nil, nil, nil, nil, "ghcr.io/cloudnative-pg/postgresql:17.7").Spec.Bootstrap.SourceImageName; got != "ghcr.io/cloudnative-pg/postgresql:17.7" {
t.Errorf("bootstrap.sourceImageName: got %q", got)
}
if got := buildPostgresAppRestorePatch(app, "src", "pg-new", "s3://b/", "", "", nil, nil, nil, nil, "").Spec.Bootstrap.SourceImageName; got != "" {
t.Errorf("bootstrap.sourceImageName from a previous restore must be cleared; got %q", got)
}
}
@@ -213,7 +213,7 @@ func (r *BackupJobReconciler) reconcileCNPG(ctx context.Context, j *backupsv1alp
serverName = clusterName
}
effectiveServerName, err := r.applyClusterPluginBackup(ctx, j.Namespace, clusterName, rendered, serverName)
effectiveServerName, imageName, err := r.applyClusterPluginBackup(ctx, j.Namespace, clusterName, rendered, serverName)
if err != nil {
if apierrors.IsNotFound(err) {
// HelmRelease has not yet rendered the Cluster (fresh app, or
@@ -260,7 +260,7 @@ func (r *BackupJobReconciler) reconcileCNPG(ctx context.Context, j *backupsv1alp
if j.Status.BackupRef != nil {
return ctrl.Result{}, nil
}
artifact, err := r.createCNPGBackupArtifact(ctx, j, resolved, cnpgBackup, clusterName, serverName, rendered, app)
artifact, err := r.createCNPGBackupArtifact(ctx, j, resolved, cnpgBackup, clusterName, serverName, imageName, rendered, app)
if err != nil {
return r.markBackupJobFailed(ctx, j, fmt.Sprintf("failed to create Backup artifact: %v", err))
}
@@ -418,16 +418,19 @@ var cnpgClusterGVR = schema.GroupVersionResource{
// mid-stream splits the archive across two prefixes — WALs around the flip
// land under the old prefix while the base backup indexes under the new one,
// and the eventual restore fails with "WAL not found".
func (r *BackupJobReconciler) applyClusterPluginBackup(ctx context.Context, namespace, clusterName string, t *strategyv1alpha1.CNPGTemplate, serverName string) (string, error) {
//
// It also returns the live Cluster's spec.imageName, see
// cnpgBackupSnapshot.ImageName.
func (r *BackupJobReconciler) applyClusterPluginBackup(ctx context.Context, namespace, clusterName string, t *strategyv1alpha1.CNPGTemplate, serverName string) (string, string, error) {
// Live read: the cached Cluster can predate a restore re-render, and both
// the serverName and the UID below must come from the current object.
existing := &cnpgtypes.Cluster{}
live, err := r.Resource(cnpgClusterGVR).Namespace(namespace).Get(ctx, clusterName, metav1.GetOptions{})
if err != nil {
return "", err
return "", "", err
}
if err := runtime.DefaultUnstructuredConverter.FromUnstructured(live.Object, existing); err != nil {
return "", fmt.Errorf("decode Cluster %s/%s: %w", namespace, clusterName, err)
return "", "", fmt.Errorf("decode Cluster %s/%s: %w", namespace, clusterName, err)
}
if live := currentBarmanServerName(existing); live != "" {
serverName = live
@@ -459,15 +462,15 @@ func (r *BackupJobReconciler) applyClusterPluginBackup(ctx context.Context, name
InstanceSidecarConfiguration: barmanSidecarConfiguration(),
}
if err := r.Patch(ctx, objStore, client.Apply, client.FieldOwner(cnpgFieldManager), client.ForceOwnership); err != nil {
return "", fmt.Errorf("apply ObjectStore %s/%s: %w", namespace, objStoreName, err)
return "", "", fmt.Errorf("apply ObjectStore %s/%s: %w", namespace, objStoreName, err)
}
patch := newCNPGClusterPatch(namespace, clusterName)
patch.Spec.Plugins = []cnpgtypes.PluginConfiguration{buildBarmanPlugin(objStoreName, serverName)}
if err := r.Patch(ctx, patch, client.Apply, client.FieldOwner(cnpgFieldManager), client.ForceOwnership); err != nil {
return "", err
return "", "", err
}
return serverName, nil
return serverName, existing.Spec.ImageName, nil
}
// currentBarmanServerName returns the serverName the Cluster's barman-cloud
@@ -552,7 +555,7 @@ func (r *BackupJobReconciler) createCNPGBackupArtifact(
j *backupsv1alpha1.BackupJob,
resolved *ResolvedBackupConfig,
cnpgBackup *cnpgtypes.Backup,
clusterName, serverName string,
clusterName, serverName, imageName string,
rendered *strategyv1alpha1.CNPGTemplate,
sourceApp *postgresapp.Postgres,
) (*backupsv1alpha1.Backup, error) {
@@ -572,7 +575,7 @@ func (r *BackupJobReconciler) createCNPGBackupArtifact(
driverMD[cnpgS3SecretRefKey] = rendered.BarmanObjectStore.S3Credentials.SecretRef.Name
}
underlyingResources, err := marshalCNPGBackupSnapshot(sourceApp, resolved.Parameters)
underlyingResources, err := marshalCNPGBackupSnapshot(sourceApp, resolved.Parameters, imageName)
if err != nil {
return nil, fmt.Errorf("encode source snapshot for Backup.status.underlyingResources: %w", err)
}
@@ -718,13 +721,14 @@ func (r *RestoreJobReconciler) reconcileCNPGRestore(ctx context.Context, restore
// time. Without this, restore-time rendering with parameters=nil
// silently produced `<no value>` and patched the target Postgres app
// with broken Secret references.
sourceDatabases, sourceUsers, sourceParameters, err := unmarshalCNPGBackupSnapshot(backup)
snapshot, err := unmarshalCNPGBackupSnapshot(backup)
if err != nil {
return r.markRestoreJobFailed(ctx, restoreJob, fmt.Sprintf(
"Backup %s/%s carries no usable source-spec snapshot in status.underlyingResources: %v "+
"(re-take the backup with a controller version that persists source spec)",
backup.Namespace, backup.Name, err))
}
sourceDatabases, sourceUsers, sourceParameters := snapshot.Databases, snapshot.Users, snapshot.Parameters
rendered, err := renderCNPGTemplate(strategy.Spec.Template, targetApp, sourceParameters)
if err != nil {
@@ -847,7 +851,7 @@ func (r *RestoreJobReconciler) reconcileCNPGRestore(ctx context.Context, restore
logger.Info("restored WAL-archive serverName collided with the recovery source",
"cluster", clusterName, "serverName", newServerName)
}
if err := r.patchPostgresAppForRestore(ctx, targetApp, sourceServerName, newServerName, sourceDestinationPath, sourceEndpointURL, options.RecoveryTime, rendered.BarmanObjectStore.S3Credentials, rendered.BarmanObjectStore.EndpointCA, sourceDatabases, sourceUsers); err != nil {
if err := r.patchPostgresAppForRestore(ctx, targetApp, sourceServerName, newServerName, sourceDestinationPath, sourceEndpointURL, options.RecoveryTime, rendered.BarmanObjectStore.S3Credentials, rendered.BarmanObjectStore.EndpointCA, sourceDatabases, sourceUsers, snapshot.ImageName); err != nil {
// Resume HR before terminal failure so an operator deleting
// the failed RestoreJob does not leave the HR stuck.
_ = r.setCNPGRestoreHRSuspended(ctx, target.Namespace, hrName, false)
@@ -988,8 +992,9 @@ func (r *RestoreJobReconciler) patchPostgresAppForRestore(
caRef *strategyv1alpha1.EndpointCARef,
sourceDatabases map[string]postgresapp.Database,
sourceUsers map[string]postgresapp.User,
sourceImageName string,
) error {
patched := buildPostgresAppRestorePatch(app, sourceServerName, newServerName, sourceDestinationPath, sourceEndpointURL, recoveryTime, credsRef, caRef, sourceDatabases, sourceUsers)
patched := buildPostgresAppRestorePatch(app, sourceServerName, newServerName, sourceDestinationPath, sourceEndpointURL, recoveryTime, credsRef, caRef, sourceDatabases, sourceUsers, sourceImageName)
return r.Patch(ctx, patched, client.MergeFrom(app), client.FieldOwner(cnpgFieldManager))
}
@@ -1024,6 +1029,7 @@ func buildPostgresAppRestorePatch(
caRef *strategyv1alpha1.EndpointCARef,
sourceDatabases map[string]postgresapp.Database,
sourceUsers map[string]postgresapp.User,
sourceImageName string,
) *postgresapp.Postgres {
patched := app.DeepCopy()
patched.Spec.Bootstrap.Enabled = true
@@ -1033,6 +1039,9 @@ func buildPostgresAppRestorePatch(
// in-place restore fails barman-cloud-check-wal-archive ("Expected empty archive").
patched.Spec.Bootstrap.NewServerName = newServerName
patched.Spec.Bootstrap.RecoveryTime = recoveryTime
// Set or cleared on every restore: a value left by an earlier restore of
// another backup would name an image this one was not taken on.
patched.Spec.Bootstrap.SourceImageName = sourceImageName
patched.Spec.Backup.DestinationPath = sourceDestinationPath
patched.Spec.Backup.EndpointURL = sourceEndpointURL
@@ -1095,12 +1104,17 @@ func buildPostgresAppRestorePatch(
// names, prefixes, secret references), never cleartext credentials -
// credentials are always referenced through `secretRef`, not inlined, and
// the Secret content stays in etcd's encryption-at-rest store.
//
// ImageName is the source Cluster's spec.imageName, handed to the chart on
// restore as bootstrap.sourceImageName: the chart decides whether recovered
// data has to stay on the image that built it.
type cnpgBackupSnapshot struct {
Kind string `json:"kind"`
APIVersion string `json:"apiVersion"`
Databases map[string]postgresapp.Database `json:"databases,omitempty"`
Users map[string]postgresapp.User `json:"users,omitempty"`
Parameters map[string]string `json:"parameters,omitempty"`
ImageName string `json:"imageName,omitempty"`
}
const cnpgBackupSnapshotKind = "CNPGBackupSnapshot"
@@ -1113,7 +1127,7 @@ var cnpgBackupSnapshotAPIVersion = backupsv1alpha1.GroupVersion.String()
// marshalCNPGBackupSnapshot serializes the source app's spec.databases /
// spec.users plus the BackupClassStrategy parameters into a
// runtime.RawExtension suitable for Backup.Status.UnderlyingResources.
func marshalCNPGBackupSnapshot(app *postgresapp.Postgres, parameters map[string]string) (*runtime.RawExtension, error) {
func marshalCNPGBackupSnapshot(app *postgresapp.Postgres, parameters map[string]string, imageName string) (*runtime.RawExtension, error) {
if app == nil {
return nil, nil
}
@@ -1123,6 +1137,7 @@ func marshalCNPGBackupSnapshot(app *postgresapp.Postgres, parameters map[string]
Databases: app.Spec.Databases,
Users: app.Spec.Users,
Parameters: parameters,
ImageName: imageName,
}
raw, err := json.Marshal(snap)
if err != nil {
@@ -1142,18 +1157,18 @@ func marshalCNPGBackupSnapshot(app *postgresapp.Postgres, parameters map[string]
// by a controller version that pre-dates parameter persistence has no
// parameters block at all). The caller must treat a nil/empty map the
// same as "no parameter overrides" rather than failing.
func unmarshalCNPGBackupSnapshot(backup *backupsv1alpha1.Backup) (map[string]postgresapp.Database, map[string]postgresapp.User, map[string]string, error) {
func unmarshalCNPGBackupSnapshot(backup *backupsv1alpha1.Backup) (*cnpgBackupSnapshot, error) {
if backup == nil || backup.Status.UnderlyingResources == nil || len(backup.Status.UnderlyingResources.Raw) == 0 {
return nil, nil, nil, fmt.Errorf("status.underlyingResources is empty")
return nil, fmt.Errorf("status.underlyingResources is empty")
}
var snap cnpgBackupSnapshot
if err := json.Unmarshal(backup.Status.UnderlyingResources.Raw, &snap); err != nil {
return nil, nil, nil, fmt.Errorf("decode snapshot: %w", err)
return nil, fmt.Errorf("decode snapshot: %w", err)
}
if snap.Kind != cnpgBackupSnapshotKind {
return nil, nil, nil, fmt.Errorf("unexpected snapshot kind %q (want %q)", snap.Kind, cnpgBackupSnapshotKind)
return nil, fmt.Errorf("unexpected snapshot kind %q (want %q)", snap.Kind, cnpgBackupSnapshotKind)
}
return snap.Databases, snap.Users, snap.Parameters, nil
return &snap, nil
}
// purgeExistingCluster deletes the live cnpg.io Cluster and its PVCs so the
@@ -222,15 +222,16 @@ func TestRenderCNPGTemplate_RoundTripsParametersThroughSnapshot(t *testing.T) {
}
// Round-trip parameters through Backup.status.underlyingResources.
raw, err := marshalCNPGBackupSnapshot(app, parameters)
raw, err := marshalCNPGBackupSnapshot(app, parameters, "")
if err != nil {
t.Fatalf("marshal snapshot: %v", err)
}
bk := &backupsv1alpha1.Backup{Status: backupsv1alpha1.BackupStatus{UnderlyingResources: raw}}
_, _, gotParams, err := unmarshalCNPGBackupSnapshot(bk)
snap, err := unmarshalCNPGBackupSnapshot(bk)
if err != nil {
t.Fatalf("unmarshal snapshot: %v", err)
}
gotParams := snap.Parameters
// Restore-time render with retrieved parameters: same values out.
rendRestore, err := renderCNPGTemplate(tmpl, app, gotParams)
@@ -496,7 +497,7 @@ func TestBuildPostgresAppRestorePatch_ForwardsSecretRef_NotCleartext(t *testing.
creds,
nil,
nil, nil,
)
"")
if got := patched.Spec.Backup.S3CredentialsSecret.Name; got != "pg-target-cnpg-backup-creds" {
t.Errorf("s3CredentialsSecret.name: got %q want %q", got, "pg-target-cnpg-backup-creds")
@@ -523,7 +524,7 @@ func TestBuildPostgresAppRestorePatch_ForwardsCustomKeyOverrides(t *testing.T) {
SecretAccessKeyKey: "SECRET_KEY",
}
patched := buildPostgresAppRestorePatch(app, "src", "pg-new", "s3://b/", "", "", creds, nil, nil, nil)
patched := buildPostgresAppRestorePatch(app, "src", "pg-new", "s3://b/", "", "", creds, nil, nil, nil, "")
want := postgresapp.S3CredentialsSecret{
Name: "creds",
@@ -541,7 +542,7 @@ func TestBuildPostgresAppRestorePatch_ForwardsCustomKeyOverrides(t *testing.T) {
// Secret name and helm install would fail.
func TestBuildPostgresAppRestorePatch_NoSecretRefIsSkipped(t *testing.T) {
app := newPostgresApp("pg", "tenant")
patched := buildPostgresAppRestorePatch(app, "src", "pg-new", "s3://b/", "", "", nil, nil, nil, nil)
patched := buildPostgresAppRestorePatch(app, "src", "pg-new", "s3://b/", "", "", nil, nil, nil, nil, "")
if got := patched.Spec.Backup.S3CredentialsSecret; got != (postgresapp.S3CredentialsSecret{}) {
t.Errorf("spec.backup.s3CredentialsSecret must be zero when credsRef is nil; got %#v", got)
}
@@ -699,7 +700,7 @@ func TestBuildPostgresAppRestorePatch_ReplacesTargetUsersAndDatabases(t *testing
"appdb": {Extensions: []string{"hstore"}},
}
patched := buildPostgresAppRestorePatch(app, "src", "pg-new", "s3://b/", "", "", nil, nil, sourceDatabases, sourceUsers)
patched := buildPostgresAppRestorePatch(app, "src", "pg-new", "s3://b/", "", "", nil, nil, sourceDatabases, sourceUsers, "")
if _, ok := patched.Spec.Users["stale-target-user"]; ok {
t.Errorf("stale target user survived restore; replace semantics regressed")
@@ -736,7 +737,7 @@ func TestBuildPostgresAppRestorePatch_ScrubsStaleBackupSettings(t *testing.T) {
// Restore with no recoveryTime, no endpointURL, no creds, no CA -
// everything stale on the target must be wiped.
patched := buildPostgresAppRestorePatch(app, "src", "pg-new", "s3://b/", "", "", nil, nil, nil, nil)
patched := buildPostgresAppRestorePatch(app, "src", "pg-new", "s3://b/", "", "", nil, nil, nil, nil, "")
if got := patched.Spec.Bootstrap.RecoveryTime; got != "" {
t.Errorf("stale recoveryTime survived; got %q", got)
@@ -775,7 +776,7 @@ func TestBuildPostgresAppRestorePatch_ForwardsEndpointCA(t *testing.T) {
SecretRef: corev1.LocalObjectReference{Name: "pg-cnpg-backup-ca"},
Key: "ca.crt",
}
patched := buildPostgresAppRestorePatch(app, "src", "pg-new", "s3://b/", "", "", nil, caRef, nil, nil)
patched := buildPostgresAppRestorePatch(app, "src", "pg-new", "s3://b/", "", "", nil, caRef, nil, nil, "")
want := postgresapp.EndpointCA{Name: "pg-cnpg-backup-ca", Key: "ca.crt"}
if got := patched.Spec.Backup.EndpointCA; got != want {
@@ -791,7 +792,7 @@ func TestBuildPostgresAppRestorePatch_ArchiveServerNameDiffersFromSource(t *test
// An in-place restore is the worst case: source serverName equals the
// target cluster's own name.
const source = "postgres-pg"
patched := buildPostgresAppRestorePatch(app, source, "postgres-pg-restore-deadbeef", "s3://b/", "", "", nil, nil, nil, nil)
patched := buildPostgresAppRestorePatch(app, source, "postgres-pg-restore-deadbeef", "s3://b/", "", "", nil, nil, nil, nil, "")
if got := patched.Spec.Bootstrap.ServerName; got != source {
t.Errorf("recovery serverName must stay the source; got %q want %q", got, source)
@@ -846,7 +847,7 @@ func TestMarshalUnmarshalCNPGBackupSnapshot(t *testing.T) {
"region": "eu-west-1",
}
raw, err := marshalCNPGBackupSnapshot(src, parameters)
raw, err := marshalCNPGBackupSnapshot(src, parameters, "")
if err != nil {
t.Fatalf("marshal: %v", err)
}
@@ -855,10 +856,11 @@ func TestMarshalUnmarshalCNPGBackupSnapshot(t *testing.T) {
}
bk := &backupsv1alpha1.Backup{Status: backupsv1alpha1.BackupStatus{UnderlyingResources: raw}}
dbs, users, params, err := unmarshalCNPGBackupSnapshot(bk)
snap, err := unmarshalCNPGBackupSnapshot(bk)
if err != nil {
t.Fatalf("unmarshal: %v", err)
}
dbs, users, params := snap.Databases, snap.Users, snap.Parameters
if dbs["app"].Extensions[0] != "pgcrypto" {
t.Errorf("databases round-trip mismatch: %#v", dbs)
}
@@ -883,11 +885,11 @@ func TestMarshalUnmarshalCNPGBackupSnapshot(t *testing.T) {
func TestMarshalUnmarshalCNPGBackupSnapshot_BackwardCompat(t *testing.T) {
legacyRaw := []byte(`{"kind":"CNPGBackupSnapshot","apiVersion":"backups.cozystack.io/v1alpha1","databases":{"app":{}},"users":{"app":{}}}`)
bk := &backupsv1alpha1.Backup{Status: backupsv1alpha1.BackupStatus{UnderlyingResources: &runtime.RawExtension{Raw: legacyRaw}}}
_, _, params, err := unmarshalCNPGBackupSnapshot(bk)
snap, err := unmarshalCNPGBackupSnapshot(bk)
if err != nil {
t.Fatalf("unmarshal legacy snapshot: %v", err)
}
if len(params) != 0 {
if params := snap.Parameters; len(params) != 0 {
t.Errorf("legacy snapshot must yield empty parameters, got %#v", params)
}
}
@@ -909,7 +911,7 @@ func TestUnmarshalCNPGBackupSnapshot_RejectsMissingOrWrongKind(t *testing.T) {
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
bk := &backupsv1alpha1.Backup{Status: backupsv1alpha1.BackupStatus{UnderlyingResources: tc.ur}}
_, _, _, err := unmarshalCNPGBackupSnapshot(bk)
_, err := unmarshalCNPGBackupSnapshot(bk)
if err == nil {
t.Fatalf("expected error, got nil")
}
@@ -993,7 +995,7 @@ func TestCreateCNPGBackupArtifact_AlreadyExistsReturnsExisting(t *testing.T) {
}
sourceApp := newPostgresApp("pg", "tenant")
got, err := r.createCNPGBackupArtifact(context.Background(), j, resolved, cnpgBk, "postgres-pg", "postgres-pg", rendered, sourceApp)
got, err := r.createCNPGBackupArtifact(context.Background(), j, resolved, cnpgBk, "postgres-pg", "postgres-pg", "", rendered, sourceApp)
if err != nil {
t.Fatalf("expected AlreadyExists to be swallowed, got error %v", err)
}
@@ -1019,7 +1021,7 @@ func TestApplyClusterPluginBackup_NotFoundOnMissingCluster(t *testing.T) {
},
}
_, err := r.applyClusterPluginBackup(context.Background(), "tenant", "postgres-missing", tmpl, "postgres-missing")
_, _, err := r.applyClusterPluginBackup(context.Background(), "tenant", "postgres-missing", tmpl, "postgres-missing")
if err == nil {
t.Fatalf("expected NotFound error, got nil")
}
@@ -1424,7 +1426,7 @@ func TestApplyClusterPluginBackup_ReadsTheLiveClusterNotTheCache(t *testing.T) {
BarmanObjectStore: strategyv1alpha1.BarmanObjectStoreTemplate{DestinationPath: "s3://bucket/x/"},
}
got, err := r.applyClusterPluginBackup(context.Background(), "tenant", "postgres-app", tmpl, "strategy-name")
got, _, err := r.applyClusterPluginBackup(context.Background(), "tenant", "postgres-app", tmpl, "strategy-name")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
@@ -1532,7 +1534,7 @@ func TestApplyClusterPluginBackup_PreservesLiveServerName(t *testing.T) {
BarmanObjectStore: strategyv1alpha1.BarmanObjectStoreTemplate{DestinationPath: "s3://bucket/x/"},
}
got, err := r.applyClusterPluginBackup(context.Background(), "tenant", "postgres-app", tmpl, "strategy-name")
got, _, err := r.applyClusterPluginBackup(context.Background(), "tenant", "postgres-app", tmpl, "strategy-name")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
@@ -1571,7 +1573,7 @@ func TestApplyClusterPluginBackup_PatchesExistingCluster(t *testing.T) {
},
}
if _, err := r.applyClusterPluginBackup(context.Background(), "tenant", "postgres-app", tmpl, "tenant-app"); err != nil {
if _, _, err := r.applyClusterPluginBackup(context.Background(), "tenant", "postgres-app", tmpl, "tenant-app"); err != nil {
t.Fatalf("unexpected error: %v", err)
}
@@ -1905,9 +1907,9 @@ func TestReconcileCNPGRestore_RepeatInPlacePurgesStaleRecoveryCluster(t *testing
// it, a freshly-recovered one postdates it.
startedAt := metav1.NewTime(time.Now())
mkBackupArtifact := func(t *testing.T) *backupsv1alpha1.Backup {
mkBackupArtifact := func(t *testing.T, sourceImage string) *backupsv1alpha1.Backup {
t.Helper()
snap, err := marshalCNPGBackupSnapshot(newPostgresApp(appName, ns), nil)
snap, err := marshalCNPGBackupSnapshot(newPostgresApp(appName, ns), nil, sourceImage)
if err != nil {
t.Fatalf("marshal snapshot: %v", err)
}
@@ -1965,7 +1967,7 @@ func TestReconcileCNPGRestore_RepeatInPlacePurgesStaleRecoveryCluster(t *testing
}
t.Run("stale leftover recovery cluster from a prior restore is purged", func(t *testing.T) {
backup := mkBackupArtifact(t)
backup := mkBackupArtifact(t, "")
// creationTimestamp an hour before StartedAt: leftover from a prior restore.
stale := metav1.NewTime(startedAt.Add(-time.Hour))
c := newCNPGStrategyTestClient(t, backup, mkRestoreJob(), strategy, cnpgBackup,
@@ -1994,8 +1996,33 @@ func TestReconcileCNPGRestore_RepeatInPlacePurgesStaleRecoveryCluster(t *testing
}
})
t.Run("backup hands its source image to the app", func(t *testing.T) {
const sourceImage = "ghcr.io/cloudnative-pg/postgresql:17.7"
backup := mkBackupArtifact(t, sourceImage)
stale := metav1.NewTime(startedAt.Add(-time.Hour))
c := newCNPGStrategyTestClient(t, backup, mkRestoreJob(), strategy, cnpgBackup,
newPostgresApp(appName, ns), mkRecoveryCluster(stale), mkClusterPVC())
r := &RestoreJobReconciler{Client: c, Interface: dynamicfake.NewSimpleDynamicClient(testCNPGScheme(t))}
rj := &backupsv1alpha1.RestoreJob{}
if err := c.Get(ctx, client.ObjectKey{Namespace: ns, Name: "rj"}, rj); err != nil {
t.Fatalf("get seeded RestoreJob: %v", err)
}
if _, err := r.reconcileCNPGRestore(ctx, rj, backup); err != nil {
t.Fatalf("reconcileCNPGRestore: %v", err)
}
app, err := r.getPostgresApp(ctx, ns, appName)
if err != nil {
t.Fatalf("get app: %v", err)
}
if !app.Spec.Bootstrap.Enabled || app.Spec.Bootstrap.SourceImageName != sourceImage {
t.Fatalf("bootstrap after restore patch: enabled=%v sourceImageName=%q, want true/%q",
app.Spec.Bootstrap.Enabled, app.Spec.Bootstrap.SourceImageName, sourceImage)
}
})
t.Run("freshly-recovered cluster from this restore is not re-purged", func(t *testing.T) {
backup := mkBackupArtifact(t)
backup := mkBackupArtifact(t, "")
// creationTimestamp a minute after StartedAt: this restore's own re-render.
fresh := metav1.NewTime(startedAt.Add(time.Minute))
c := newCNPGStrategyTestClient(t, backup, mkRestoreJob(), strategy, cnpgBackup,
@@ -75,6 +75,9 @@ type ClusterList struct {
}
type ClusterSpec struct {
// ImageName is read, never patched: the backup driver records the image
// the data directory runs on. Empty means CNPG's default postgresql image.
ImageName string `json:"imageName,omitempty"`
Backup *BackupConfiguration `json:"backup,omitempty"`
Bootstrap *BootstrapConfiguration `json:"bootstrap,omitempty"`
// Plugins wires CNPG-I plugins (here barman-cloud) onto the Cluster. The
@@ -71,11 +71,12 @@ type PostgresSpec struct {
}
type Bootstrap struct {
Enabled bool `json:"enabled,omitempty"`
OldName string `json:"oldName,omitempty"`
ServerName string `json:"serverName,omitempty"`
NewServerName string `json:"newServerName,omitempty"`
RecoveryTime string `json:"recoveryTime,omitempty"`
Enabled bool `json:"enabled,omitempty"`
OldName string `json:"oldName,omitempty"`
ServerName string `json:"serverName,omitempty"`
NewServerName string `json:"newServerName,omitempty"`
RecoveryTime string `json:"recoveryTime,omitempty"`
SourceImageName string `json:"sourceImageName,omitempty"`
}
type Backup struct {
+21 -19
View File
@@ -195,17 +195,18 @@ For `sslmode=verify-full` to work, the CA bundle retrieved above must be saved t
### Common parameters
| Name | Description | Type | Value |
| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------ | ---------- | ---------- |
| `replicas` | Number of Postgres replicas. | `int` | `2` |
| `resources` | Explicit CPU and memory configuration for each PostgreSQL replica. When omitted, the preset defined in `resourcesPreset` is applied. | `object` | `{}` |
| `resources.cpu` | CPU available to each replica. | `quantity` | `""` |
| `resources.memory` | Memory (RAM) available to each replica. | `quantity` | `""` |
| `resourcesPreset` | Default sizing preset used when `resources` is omitted. | `string` | `t1.micro` |
| `size` | Persistent Volume Claim size available for application data. | `quantity` | `10Gi` |
| `storageClass` | StorageClass used to store the data. | `string` | `""` |
| `external` | Enable external access from outside the cluster. | `bool` | `false` |
| `version` | PostgreSQL major version to deploy | `string` | `v18` |
| Name | Description | Type | Value |
| ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | ---------- |
| `replicas` | Number of Postgres replicas. | `int` | `2` |
| `resources` | Explicit CPU and memory configuration for each PostgreSQL replica. When omitted, the preset defined in `resourcesPreset` is applied. | `object` | `{}` |
| `resources.cpu` | CPU available to each replica. | `quantity` | `""` |
| `resources.memory` | Memory (RAM) available to each replica. | `quantity` | `""` |
| `resourcesPreset` | Default sizing preset used when `resources` is omitted. | `string` | `t1.micro` |
| `size` | Persistent Volume Claim size available for application data. | `quantity` | `10Gi` |
| `storageClass` | StorageClass used to store the data. | `string` | `""` |
| `external` | Enable external access from outside the cluster. | `bool` | `false` |
| `version` | PostgreSQL major version to deploy | `string` | `v18` |
| `allowCollationChange` | Allow a cluster created on a Debian bullseye image (before the move to standard-trixie) to move to the new image without a clean locale check. Such a cluster is checked before each upgrade, except while `bootstrap.enabled` is set (set it back to false once a restore has finished), and stays on its current image until the check finds nothing that depends on a collation other than C, POSIX or builtin: while this is false, a cluster the check found affected (an ICU or libc locale, or C.UTF-8) or could not finish on stays put, because glibc and ICU on the new image sort text differently and every index on such text must be rebuilt. A held cluster runs the bare bullseye tag it has, gets no further PostgreSQL minors and so none of their security fixes, and refuses a change of `version`, since new majors are built only on the new images. To leave that state, either remove the dependency (move such columns and indexes to C, or to the builtin `pg_c_utf8` on PostgreSQL 17 and later) and let the next upgrade check again, or set this to true in a maintenance window: the cluster moves on the next upgrade, replicas restart on the new image first and can return wrong results through `-ro`, and unique indexes can accept duplicates, until the indexes are rebuilt on the primary. The init Job rebuilds only indexes on collations that record a version (ICU, and libc locales other than C.*): rebuild indexes on C.UTF-8 or another C.* locale by hand with REINDEX, and check range partitions, CHECK constraints and materialized views on such text, which a rebuild does not fix. A held cluster shows the hold only as an unchanged image; the result and the objects found are in the `postgres.cozystack.io/locale-data` and `postgres.cozystack.io/locale-data-objects` annotations of the cnpg.io Cluster, which an administrator can read. A restore of a backup taken on one of those bullseye images comes back on that image and is checked by the next upgrade. | `bool` | `false` |
### TLS configuration
@@ -277,14 +278,15 @@ For `sslmode=verify-full` to work, the CA bundle retrieved above must be saved t
### Bootstrap (recovery) parameters
| Name | Description | Type | Value |
| ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | ------- |
| `bootstrap` | Bootstrap configuration. | `object` | `{}` |
| `bootstrap.enabled` | Whether to restore from a backup. | `bool` | `false` |
| `bootstrap.recoveryTime` | Timestamp (RFC3339) for point-in-time recovery; empty means latest. | `string` | `""` |
| `bootstrap.oldName` | Previous cluster name before deletion. | `string` | `""` |
| `bootstrap.serverName` | Server name (S3 path prefix) used by the original cluster when writing backups; passed to the barman-cloud plugin via `externalClusters[].plugin.parameters.serverName`. Defaults to `bootstrap.oldName`. Set this only when the original cluster wrote backups under an explicit server name that differed from its Kubernetes resource name. | `string` | `""` |
| `bootstrap.newServerName` | WAL-archive server name (S3 path prefix) the RESTORED cluster writes to. Must differ from `serverName` (the recovery source) so a restored cluster archives to a fresh, empty prefix and barman-cloud-check-wal-archive passes while it recovers from the source's prefix. The CNPG backup driver sets this on restore; empty means the cluster archives under its own name. | `string` | `""` |
| Name | Description | Type | Value |
| --------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | ------- |
| `bootstrap` | Bootstrap configuration. | `object` | `{}` |
| `bootstrap.enabled` | Whether to restore from a backup. | `bool` | `false` |
| `bootstrap.recoveryTime` | Timestamp (RFC3339) for point-in-time recovery; empty means latest. | `string` | `""` |
| `bootstrap.oldName` | Previous cluster name before deletion. | `string` | `""` |
| `bootstrap.serverName` | Server name (S3 path prefix) used by the original cluster when writing backups; passed to the barman-cloud plugin via `externalClusters[].plugin.parameters.serverName`. Defaults to `bootstrap.oldName`. Set this only when the original cluster wrote backups under an explicit server name that differed from its Kubernetes resource name. | `string` | `""` |
| `bootstrap.newServerName` | WAL-archive server name (S3 path prefix) the RESTORED cluster writes to. Must differ from `serverName` (the recovery source) so a restored cluster archives to a fresh, empty prefix and barman-cloud-check-wal-archive passes while it recovers from the source's prefix. The CNPG backup driver sets this on restore; empty means the cluster archives under its own name. | `string` | `""` |
| `bootstrap.sourceImageName` | Image of the cluster the backup was taken from. A restore of a backup taken on one of the bare Debian bullseye tags the chart used before standard-trixie comes back on that image (see `allowCollationChange`); any other value is ignored. The CNPG backup driver sets this on every restore, and clears it when the backup carries no image. | `string` | `""` |
## Parameter examples and reference
@@ -17,5 +17,95 @@
barman binaries the system variant adds.
*/}}
{{- define "postgres.imageName" -}}
{{- include "postgres.heldImageName" . | default (include "postgres.targetImageName" .) -}}
{{- end -}}
{{- define "postgres.targetImageName" -}}
ghcr.io/cloudnative-pg/postgresql:{{ include "postgres.versionMap" . | trim | trimPrefix "v" }}-standard-trixie
{{- end -}}
{{/*
The image a cluster on Debian bullseye keeps, or nothing. Clusters created
before the move to trixie run one of the bare tags postgres.bullseyeImage
lists, and moving them changes glibc and ICU under an initialised data
directory. Such a cluster stays on its image until the pre-upgrade locale
check has recorded "clean" on its Cluster, or until allowCollationChange is
set: a cluster not checked yet, one the check could not finish on and one
it found affected all stay. New majors are built only on the new images, so
a held cluster refuses a change of version instead of dropping it.
*/}}
{{- define "postgres.heldImageName" -}}
{{- if not .Values.allowCollationChange -}}
{{- $hold := include "postgres.localeHold" . | fromJson -}}
{{- if and $hold.image (ne $hold.verdict "clean") -}}
{{- $heldMajor := regexFind "^[0-9]+" (last (splitList ":" $hold.image)) -}}
{{- $wantMajor := trimPrefix "v" .Values.version -}}
{{- if ne $heldMajor $wantMajor -}}
{{- fail (printf "postgres: version %s cannot be applied: the cluster stays on %s until the pre-upgrade check finds nothing in it that depends on a collation sorting differently on the images PostgreSQL %s is built on (the postgres.cozystack.io/locale-data annotation of the cnpg.io Cluster). Keep version v%s, or set allowCollationChange: true and rebuild the affected indexes in a maintenance window." .Values.version $hold.image $wantMajor $heldMajor) -}}
{{- end -}}
{{- $hold.image -}}
{{- end -}}
{{- end -}}
{{- end -}}
{{/*
The bullseye image that applies to this cluster and its check result, as
JSON; the image is empty when the cluster runs any other one. The result is
the postgres.cozystack.io/locale-data annotation the pre-upgrade check
writes on the live Cluster. A physical recovery with no live Cluster yet
(the CNPG backup driver deletes it before the recovery renders) restores
onto the image the backup was taken on, so that the data keeps the library
that built it: bootstrap.sourceImageName, which the driver copies from the
source Cluster, or for a recovery set up by hand the bootstrap.oldName
Cluster while it exists. A recovery has no result of its own and is held
until the first upgrade after it checks the restored data.
bootstrap.sourceImageName is in the application spec, so anyone who may
edit the application may set it; it only ever selects one of the images
postgres.bullseyeImage lists.
*/}}
{{- define "postgres.localeHold" -}}
{{- $live := lookup "postgresql.cnpg.io/v1" "Cluster" .Release.Namespace .Release.Name -}}
{{- $image := dig "spec" "imageName" "" $live -}}
{{- $verdict := dig "metadata" "annotations" "postgres.cozystack.io/locale-data" "" $live -}}
{{- if and .Values.bootstrap.enabled (not $image) -}}
{{- $image = .Values.bootstrap.sourceImageName | default (dig "spec" "imageName" "" (include "postgres.recoverySource" . | fromJson)) -}}
{{- $verdict = "" -}}
{{- end -}}
{{- if ne (include "postgres.bullseyeImage" $image) "true" -}}
{{- $image = "" -}}
{{- end -}}
{{- dict "image" $image "verdict" $verdict | toJson -}}
{{- end -}}
{{- define "postgres.recoverySource" -}}
{{- if and .Values.bootstrap.enabled .Values.bootstrap.oldName (not .Values.bootstrap.newServerName) -}}
{{- lookup "postgresql.cnpg.io/v1" "Cluster" .Release.Namespace .Values.bootstrap.oldName | toJson -}}
{{- else -}}
{}
{{- end -}}
{{- end -}}
{{/*
The images this chart ran clusters on before the move to trixie: the bare
version tags of the CloudNativePG image, which are its system variant on
Debian bullseye, as files/versions.yaml listed them in every release before
standard-trixie. Exact on purpose: a held image reaches spec.imageName.
*/}}
{{- define "postgres.bullseyeImage" -}}
{{- has . (list "ghcr.io/cloudnative-pg/postgresql:13.22" "ghcr.io/cloudnative-pg/postgresql:14.20" "ghcr.io/cloudnative-pg/postgresql:15.15" "ghcr.io/cloudnative-pg/postgresql:16.11" "ghcr.io/cloudnative-pg/postgresql:17.7" "ghcr.io/cloudnative-pg/postgresql:18.1") -}}
{{- end -}}
{{/*
The live image of a cluster still on bullseye whose owner has not allowed
the collation change, or nothing. The pre-upgrade locale check runs only
then, from that image, against the server it is checking.
*/}}
{{- define "postgres.localeCheckImage" -}}
{{- if and (not .Values.allowCollationChange) (not .Values.bootstrap.enabled) -}}
{{- $live := lookup "postgresql.cnpg.io/v1" "Cluster" .Release.Namespace .Release.Name -}}
{{- if and $live $live.spec $live.spec.imageName (eq (include "postgres.bullseyeImage" $live.spec.imageName) "true") -}}
{{- $live.spec.imageName -}}
{{- end -}}
{{- end -}}
{{- end -}}
@@ -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,503 @@
suite: keep a bullseye cluster on its image until a clean locale check
release:
name: pg-test
namespace: tenant-test
upgrade: true
set:
_cluster:
scheduling: {}
kubernetesProvider:
scheme:
"postgresql.cnpg.io/v1/Cluster":
gvr:
group: postgresql.cnpg.io
version: v1
resource: clusters
namespaced: true
objects:
- apiVersion: postgresql.cnpg.io/v1
kind: Cluster
metadata:
name: pg-test
namespace: tenant-test
annotations:
postgres.cozystack.io/locale-data: affected
spec:
imageName: ghcr.io/cloudnative-pg/postgresql:18.1
- apiVersion: postgresql.cnpg.io/v1
kind: Cluster
metadata:
name: pg-clean
namespace: tenant-test
annotations:
postgres.cozystack.io/locale-data: clean
spec:
imageName: ghcr.io/cloudnative-pg/postgresql:18.1
- apiVersion: postgresql.cnpg.io/v1
kind: Cluster
metadata:
name: pg-unchecked
namespace: tenant-test
spec:
imageName: ghcr.io/cloudnative-pg/postgresql:18.1
- apiVersion: postgresql.cnpg.io/v1
kind: Cluster
metadata:
name: pg-unknown
namespace: tenant-test
annotations:
postgres.cozystack.io/locale-data: unknown
spec:
imageName: ghcr.io/cloudnative-pg/postgresql:18.1
- apiVersion: postgresql.cnpg.io/v1
kind: Cluster
metadata:
name: pg-trixie
namespace: tenant-test
annotations:
postgres.cozystack.io/locale-data: affected
spec:
imageName: ghcr.io/cloudnative-pg/postgresql:18.1-standard-trixie
- apiVersion: postgresql.cnpg.io/v1
kind: Cluster
metadata:
name: pg-restored
namespace: tenant-test
spec:
imageName: ghcr.io/cloudnative-pg/postgresql:18.1
bootstrap:
recovery:
source: pg-gone
tests:
- it: keeps a cluster the check found affected on its image
templates:
- templates/db.yaml
documentSelector:
path: kind
value: Cluster
asserts:
- equal:
path: spec.imageName
value: ghcr.io/cloudnative-pg/postgresql:18.1
- it: runs the init Job from the held image
templates:
- templates/init-job.yaml
documentSelector:
path: kind
value: Job
asserts:
- equal:
path: spec.template.spec.containers[0].image
value: ghcr.io/cloudnative-pg/postgresql:18.1
- it: keeps a cluster that was never checked on its image
release:
name: pg-unchecked
templates:
- templates/db.yaml
documentSelector:
path: kind
value: Cluster
asserts:
- equal:
path: spec.imageName
value: ghcr.io/cloudnative-pg/postgresql:18.1
- it: keeps a cluster the check could not finish on on its image
release:
name: pg-unknown
templates:
- templates/db.yaml
documentSelector:
path: kind
value: Cluster
asserts:
- equal:
path: spec.imageName
value: ghcr.io/cloudnative-pg/postgresql:18.1
- it: moves a cluster the check found clean
release:
name: pg-clean
templates:
- templates/db.yaml
documentSelector:
path: kind
value: Cluster
asserts:
- matchRegex:
path: spec.imageName
pattern: "^ghcr\\.io/cloudnative-pg/postgresql:18\\.[0-9]+-standard-trixie$"
- it: moves an affected cluster once the change is allowed
set:
allowCollationChange: true
templates:
- templates/db.yaml
documentSelector:
path: kind
value: Cluster
asserts:
- matchRegex:
path: spec.imageName
pattern: "^ghcr\\.io/cloudnative-pg/postgresql:18\\.[0-9]+-standard-trixie$"
- it: does not hold a cluster already on trixie
release:
name: pg-trixie
templates:
- templates/db.yaml
documentSelector:
path: kind
value: Cluster
asserts:
- matchRegex:
path: spec.imageName
pattern: "^ghcr\\.io/cloudnative-pg/postgresql:18\\.[0-9]+-standard-trixie$"
- it: refuses a version change while held
set:
version: v17
templates:
- templates/locale-check-hook.yaml
asserts:
- failedTemplate:
errorPattern: "version v17 cannot be applied: the cluster stays on ghcr.io/cloudnative-pg/postgresql:18.1"
- it: allows a version change once the collation change is allowed
set:
version: v17
allowCollationChange: true
templates:
- templates/db.yaml
documentSelector:
path: kind
value: Cluster
asserts:
- matchRegex:
path: spec.imageName
pattern: "^ghcr\\.io/cloudnative-pg/postgresql:17\\.[0-9]+-standard-trixie$"
- it: restores a backup taken on a bullseye image onto that image
release:
name: pg-new
set:
bootstrap:
enabled: true
oldName: postgres-pg-0f1e2d3c
newServerName: pg-new-restore-0123456789abcdef
sourceImageName: ghcr.io/cloudnative-pg/postgresql:18.1
backup:
s3AccessKey: access
s3SecretKey: secret
templates:
- templates/db.yaml
documentSelector:
path: kind
value: Cluster
asserts:
- equal:
path: spec.imageName
value: ghcr.io/cloudnative-pg/postgresql:18.1
- it: restores a backup taken on trixie onto the current image
release:
name: pg-new
set:
bootstrap:
enabled: true
oldName: postgres-pg-0f1e2d3c
newServerName: pg-new-restore-0123456789abcdef
sourceImageName: ghcr.io/cloudnative-pg/postgresql:18.1-standard-trixie
backup:
s3AccessKey: access
s3SecretKey: secret
templates:
- templates/db.yaml
documentSelector:
path: kind
value: Cluster
asserts:
- matchRegex:
path: spec.imageName
pattern: "^ghcr\\.io/cloudnative-pg/postgresql:18\\.[0-9]+-standard-trixie$"
- it: never renders an image of another registry from bootstrap.sourceImageName
release:
name: pg-new
set:
bootstrap:
enabled: true
oldName: postgres-pg-0f1e2d3c
sourceImageName: "docker.io/attacker/payload:18"
backup:
s3AccessKey: access
s3SecretKey: secret
templates:
- templates/db.yaml
documentSelector:
path: kind
value: Cluster
asserts:
- matchRegex:
path: spec.imageName
pattern: "^ghcr\\.io/cloudnative-pg/postgresql:18\\.[0-9]+-standard-trixie$"
- it: never renders a bare tag this chart never shipped from bootstrap.sourceImageName
release:
name: pg-new
set:
bootstrap:
enabled: true
oldName: postgres-pg-0f1e2d3c
sourceImageName: "ghcr.io/cloudnative-pg/postgresql:18.0"
backup:
s3AccessKey: access
s3SecretKey: secret
templates:
- templates/db.yaml
documentSelector:
path: kind
value: Cluster
asserts:
- matchRegex:
path: spec.imageName
pattern: "^ghcr\\.io/cloudnative-pg/postgresql:18\\.[0-9]+-standard-trixie$"
- it: never renders a digest-pinned tag from bootstrap.sourceImageName
release:
name: pg-new
set:
bootstrap:
enabled: true
oldName: postgres-pg-0f1e2d3c
sourceImageName: "ghcr.io/cloudnative-pg/postgresql:18.1@sha256:0000000000000000000000000000000000000000000000000000000000000000"
backup:
s3AccessKey: access
s3SecretKey: secret
templates:
- templates/db.yaml
documentSelector:
path: kind
value: Cluster
asserts:
- matchRegex:
path: spec.imageName
pattern: "^ghcr\\.io/cloudnative-pg/postgresql:18\\.[0-9]+-standard-trixie$"
- it: keeps a Cluster a recovery created on its image until it is checked
release:
name: pg-restored
set:
bootstrap:
enabled: true
oldName: pg-gone
backup:
s3AccessKey: access
s3SecretKey: secret
templates:
- templates/db.yaml
documentSelector:
path: kind
value: Cluster
asserts:
- equal:
path: spec.imageName
value: ghcr.io/cloudnative-pg/postgresql:18.1
- it: reads a live Cluster no recovery created on its own, whatever the bootstrap values say
release:
name: pg-clean
set:
bootstrap:
enabled: true
oldName: pg-test
sourceImageName: ghcr.io/cloudnative-pg/postgresql:18.1
backup:
s3AccessKey: access
s3SecretKey: secret
templates:
- templates/db.yaml
documentSelector:
path: kind
value: Cluster
asserts:
- matchRegex:
path: spec.imageName
pattern: "^ghcr\\.io/cloudnative-pg/postgresql:18\\.[0-9]+-standard-trixie$"
- it: restores a hand-set recovery onto the image of its source Cluster
release:
name: pg-new
set:
bootstrap:
enabled: true
oldName: pg-trixie
backup:
s3AccessKey: access
s3SecretKey: secret
templates:
- templates/db.yaml
documentSelector:
path: kind
value: Cluster
asserts:
- matchRegex:
path: spec.imageName
pattern: "^ghcr\\.io/cloudnative-pg/postgresql:18\\.[0-9]+-standard-trixie$"
- it: holds a hand-set recovery of a bullseye source Cluster
release:
name: pg-new
set:
bootstrap:
enabled: true
oldName: pg-clean
backup:
s3AccessKey: access
s3SecretKey: secret
templates:
- templates/db.yaml
documentSelector:
path: kind
value: Cluster
asserts:
- equal:
path: spec.imageName
value: ghcr.io/cloudnative-pg/postgresql:18.1
- it: does not read a Cluster named like the server name of a RestoreJob
release:
name: pg-new
set:
bootstrap:
enabled: true
oldName: pg-test
newServerName: pg-new-restore-0123456789abcdef
backup:
s3AccessKey: access
s3SecretKey: secret
templates:
- templates/db.yaml
documentSelector:
path: kind
value: Cluster
asserts:
- matchRegex:
path: spec.imageName
pattern: "^ghcr\\.io/cloudnative-pg/postgresql:18\\.[0-9]+-standard-trixie$"
- it: ignores a bootstrap.sourceImageName left over once the recovery is done
release:
name: pg-trixie
set:
bootstrap:
enabled: false
sourceImageName: ghcr.io/cloudnative-pg/postgresql:18.1
templates:
- templates/db.yaml
documentSelector:
path: kind
value: Cluster
asserts:
- matchRegex:
path: spec.imageName
pattern: "^ghcr\\.io/cloudnative-pg/postgresql:18\\.[0-9]+-standard-trixie$"
- it: checks a bullseye cluster from its own image
release:
name: pg-unchecked
templates:
- templates/locale-check-hook.yaml
documentSelector:
path: kind
value: Job
asserts:
- equal:
path: spec.template.spec.initContainers[0].image
value: ghcr.io/cloudnative-pg/postgresql:18.1
- it: rechecks a held cluster from its held image
templates:
- templates/locale-check-hook.yaml
documentSelector:
path: kind
value: Job
asserts:
- equal:
path: spec.template.spec.initContainers[0].image
value: ghcr.io/cloudnative-pg/postgresql:18.1
- it: skips the check once the change is allowed
set:
allowCollationChange: true
templates:
- templates/locale-check-hook.yaml
asserts:
- hasDocuments:
count: 0
- it: skips the check for a cluster already on trixie
release:
name: pg-trixie
templates:
- templates/locale-check-hook.yaml
asserts:
- hasDocuments:
count: 0
- it: skips the check for a new cluster
release:
name: pg-new
templates:
- templates/locale-check-hook.yaml
asserts:
- hasDocuments:
count: 0
- it: does not check a cluster while its restore is in progress
release:
name: pg-unchecked
set:
bootstrap:
enabled: true
oldName: pg-test
backup:
s3AccessKey: access
s3SecretKey: secret
templates:
- templates/locale-check-hook.yaml
asserts:
- hasDocuments:
count: 0
- it: names the hook resources so that they cannot take the names CNPG gives another cluster
release:
name: pg-unchecked
templates:
- templates/locale-check-hook.yaml
documentSelector:
path: kind
value: Job
asserts:
- matchRegex:
path: metadata.name
pattern: ^locale-check-pg-unchecked-[0-9a-f]{8}$
- it: lets the role patch only its own Cluster
release:
name: pg-unchecked
templates:
- templates/locale-check-hook.yaml
documentSelector:
path: kind
value: Role
asserts:
- equal:
path: rules
value:
- apiGroups: ["postgresql.cnpg.io"]
resources: ["clusters"]
resourceNames: ["pg-unchecked"]
verbs: ["get", "patch"]
+10
View File
@@ -140,6 +140,11 @@
"v13"
]
},
"allowCollationChange": {
"description": "Allow a cluster created on a Debian bullseye image (before the move to standard-trixie) to move to the new image without a clean locale check. Such a cluster is checked before each upgrade, except while `bootstrap.enabled` is set (set it back to false once a restore has finished), and stays on its current image until the check finds nothing that depends on a collation other than C, POSIX or builtin: while this is false, a cluster the check found affected (an ICU or libc locale, or C.UTF-8) or could not finish on stays put, because glibc and ICU on the new image sort text differently and every index on such text must be rebuilt. A held cluster runs the bare bullseye tag it has, gets no further PostgreSQL minors and so none of their security fixes, and refuses a change of `version`, since new majors are built only on the new images. To leave that state, either remove the dependency (move such columns and indexes to C, or to the builtin `pg_c_utf8` on PostgreSQL 17 and later) and let the next upgrade check again, or set this to true in a maintenance window: the cluster moves on the next upgrade, replicas restart on the new image first and can return wrong results through `-ro`, and unique indexes can accept duplicates, until the indexes are rebuilt on the primary. The init Job rebuilds only indexes on collations that record a version (ICU, and libc locales other than C.*): rebuild indexes on C.UTF-8 or another C.* locale by hand with REINDEX, and check range partitions, CHECK constraints and materialized views on such text, which a rebuild does not fix. A held cluster shows the hold only as an unchanged image; the result and the objects found are in the `postgres.cozystack.io/locale-data` and `postgres.cozystack.io/locale-data-objects` annotations of the cnpg.io Cluster, which an administrator can read. A restore of a backup taken on one of those bullseye images comes back on that image and is checked by the next upgrade.",
"type": "boolean",
"default": false
},
"tls": {
"description": "TLS configuration for server connections.",
"type": "object",
@@ -374,6 +379,11 @@
"description": "Server name (S3 path prefix) used by the original cluster when writing backups; passed to the barman-cloud plugin via `externalClusters[].plugin.parameters.serverName`. Defaults to `bootstrap.oldName`. Set this only when the original cluster wrote backups under an explicit server name that differed from its Kubernetes resource name.",
"type": "string",
"default": ""
},
"sourceImageName": {
"description": "Image of the cluster the backup was taken from. A restore of a backup taken on one of the bare Debian bullseye tags the chart used before standard-trixie comes back on that image (see `allowCollationChange`); any other value is ignored. The CNPG backup driver sets this on every restore, and clears it when the backup carries no image.",
"type": "string",
"default": ""
}
}
}
+6
View File
@@ -87,6 +87,10 @@ external: false
## @param {Version} version - PostgreSQL major version to deploy
version: v18
##
## @param {bool} allowCollationChange - Allow a cluster created on a Debian bullseye image (before the move to standard-trixie) to move to the new image without a clean locale check. Such a cluster is checked before each upgrade, except while `bootstrap.enabled` is set (set it back to false once a restore has finished), and stays on its current image until the check finds nothing that depends on a collation other than C, POSIX or builtin: while this is false, a cluster the check found affected (an ICU or libc locale, or C.UTF-8) or could not finish on stays put, because glibc and ICU on the new image sort text differently and every index on such text must be rebuilt. A held cluster runs the bare bullseye tag it has, gets no further PostgreSQL minors and so none of their security fixes, and refuses a change of `version`, since new majors are built only on the new images. To leave that state, either remove the dependency (move such columns and indexes to C, or to the builtin `pg_c_utf8` on PostgreSQL 17 and later) and let the next upgrade check again, or set this to true in a maintenance window: the cluster moves on the next upgrade, replicas restart on the new image first and can return wrong results through `-ro`, and unique indexes can accept duplicates, until the indexes are rebuilt on the primary. The init Job rebuilds only indexes on collations that record a version (ICU, and libc locales other than C.*): rebuild indexes on C.UTF-8 or another C.* locale by hand with REINDEX, and check range partitions, CHECK constraints and materialized views on such text, which a rebuild does not fix. A held cluster shows the hold only as an unchanged image; the result and the objects found are in the `postgres.cozystack.io/locale-data` and `postgres.cozystack.io/locale-data-objects` annotations of the cnpg.io Cluster, which an administrator can read. A restore of a backup taken on one of those bullseye images comes back on that image and is checked by the next upgrade.
allowCollationChange: false
##
## @section TLS configuration
##
@@ -272,6 +276,7 @@ backup:
## @field {string} oldName - Previous cluster name before deletion.
## @field {string} [serverName] - Server name (S3 path prefix) used by the original cluster when writing backups; passed to the barman-cloud plugin via `externalClusters[].plugin.parameters.serverName`. Defaults to `bootstrap.oldName`. Set this only when the original cluster wrote backups under an explicit server name that differed from its Kubernetes resource name.
## @field {string} [newServerName] - WAL-archive server name (S3 path prefix) the RESTORED cluster writes to. Must differ from `serverName` (the recovery source) so a restored cluster archives to a fresh, empty prefix and barman-cloud-check-wal-archive passes while it recovers from the source's prefix. The CNPG backup driver sets this on restore; empty means the cluster archives under its own name.
## @field {string} [sourceImageName] - Image of the cluster the backup was taken from. A restore of a backup taken on one of the bare Debian bullseye tags the chart used before standard-trixie comes back on that image (see `allowCollationChange`); any other value is ignored. The CNPG backup driver sets this on every restore, and clears it when the backup carries no image.
## @param {Bootstrap} bootstrap - Bootstrap configuration.
bootstrap:
@@ -281,3 +286,4 @@ bootstrap:
oldName: ""
serverName: ""
newServerName: ""
sourceImageName: ""
@@ -8,7 +8,7 @@ spec:
singular: postgres
plural: postgreses
openAPISchema: |-
{"title":"Chart Values","type":"object","properties":{"replicas":{"description":"Number of Postgres replicas.","type":"integer","default":2},"resources":{"description":"Explicit CPU and memory configuration for each PostgreSQL replica. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","default":{},"properties":{"cpu":{"description":"CPU available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Memory (RAM) available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted.","type":"string","default":"t1.micro","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]},"size":{"description":"Persistent Volume Claim size available for application data.","default":"10Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"storageClass":{"description":"StorageClass used to store the data.","type":"string","default":"","x-kubernetes-validations":[{"rule":"self == oldSelf","message":"storageClass is immutable"}],"x-cozystack-options":{"source":"storageclass"}},"external":{"description":"Enable external access from outside the cluster.","type":"boolean","default":false},"version":{"description":"PostgreSQL major version to deploy","type":"string","default":"v18","enum":["v18","v17","v16","v15","v14","v13"]},"tls":{"description":"TLS configuration for server connections.","type":"object","default":{},"properties":{"enabled":{"description":"Tri-state switch controlling whether the chart injects the external hostname into the operator-managed CNPG cert via spec.certificates.serverAltDNSNames. When omitted, the chart injects the SAN if `external: true` and skips it otherwise. Set explicitly to `true` to inject regardless of `external` (no-op when `external: false` since there is no external hostname to add). Set to `false` to skip injection. Note that CNPG keeps its built-in TLS on the wire regardless of this flag — this toggle only controls the chart-side SAN injection; to disable PostgreSQL TLS entirely set `postgresql.parameters.ssl = \"off\"` at the CNPG layer.","type":"boolean"}}},"postgresql":{"description":"PostgreSQL server configuration.","type":"object","default":{},"properties":{"parameters":{"description":"PostgreSQL server parameters. Values may be strings or integers; integers are coerced to strings by the template (e.g. both `max_connections: 100` and `max_connections: \"100\"` are accepted). BLOCKED (enable arbitrary code execution): archive_command, restore_command, ssl_passphrase_command, archive_cleanup_command, recovery_end_command, dynamic_library_path, local_preload_libraries, session_preload_libraries, shared_preload_libraries. Do NOT override CloudNativePG-managed parameters: archive_mode, primary_conninfo, wal_level, max_replication_slots.","type":"object","default":{"max_connections":"100"},"additionalProperties":{"anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}}},"quorum":{"description":"Quorum configuration for synchronous replication.","type":"object","default":{},"required":["maxSyncReplicas","minSyncReplicas"],"properties":{"maxSyncReplicas":{"description":"Maximum number of synchronous replicas allowed (must be less than total replicas).","type":"integer","default":0},"minSyncReplicas":{"description":"Minimum number of synchronous replicas required for commit.","type":"integer","default":0}}},"users":{"description":"Users configuration map.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"password":{"description":"Password for the user.","type":"string"},"replication":{"description":"Whether the user has replication privileges.","type":"boolean"}}}},"databases":{"description":"Databases configuration map.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"extensions":{"description":"List of enabled PostgreSQL extensions.","type":"array","items":{"type"Line truncated
{"title":"Chart Values","type":"object","properties":{"replicas":{"description":"Number of Postgres replicas.","type":"integer","default":2},"resources":{"description":"Explicit CPU and memory configuration for each PostgreSQL replica. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","default":{},"properties":{"cpu":{"description":"CPU available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Memory (RAM) available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted.","type":"string","default":"t1.micro","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]},"size":{"description":"Persistent Volume Claim size available for application data.","default":"10Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"storageClass":{"description":"StorageClass used to store the data.","type":"string","default":"","x-kubernetes-validations":[{"rule":"self == oldSelf","message":"storageClass is immutable"}],"x-cozystack-options":{"source":"storageclass"}},"external":{"description":"Enable external access from outside the cluster.","type":"boolean","default":false},"version":{"description":"PostgreSQL major version to deploy","type":"string","default":"v18","enum":["v18","v17","v16","v15","v14","v13"]},"allowCollationChange":{"description":"Allow a cluster created on a Debian bullseye image (before the move to standard-trixie) to move to the new image without a clean locale check. Such a cluster is checked before each upgrade, except while `bootstrap.enabled` is set (set it back to false once a restore has finished), and stays on its current image until the check finds nothing that depends on a collation other than C, POSIX or builtin: while this is false, a cluster the check found affected (an ICU or libc locale, or C.UTF-8) or could not finish on stays put, because glibc and ICU on the new image sort text differently and every index on such text must be rebuilt. A held cluster runs the bare bullseye tag it has, gets no further PostgreSQL minors and so none of their security fixes, and refuses a change of `version`, since new majors are built only on the new images. To leave that state, either remove the dependency (move such columns and indexes to C, or to the builtin `pg_c_utf8` on PostgreSQL 17 and later) and let the next upgrade check again, or set this to true in a maintenance window: the cluster moves on the next upgrade, replicas restart on the new image first and can return wrong results through `-ro`, and unique indexes can accept duplicates, until the indexes are rebuilt on the primary. The init Job rebuilds only indexes on collations that record a version (ICU, and libc locales other than C.*): rebuild indexes on C.UTF-8 or another C.* locale by hand with REINDEX, and check range partitions, CHECK constraints and materialized views on such text, which a rebuild does not fix. A held cluster shows the hold only as an unchanged image; the result and the objects found are in the `postgres.cozystack.io/locale-data` and `postgres.cozystack.io/locale-data-objects` annotations of the cnpg.io Cluster, which an administrator can read. A restore of a backup taken on one of those bullseye images comes back on that image and is checked by the next upgrade.","type":"boolean","default":false},"tls":{"description":"TLS configuration for server connections.","type":"object","default":{},"properties":{"enabled":{"description":"Tri-state switch controlling whether the chart injects the external hostname into the operator-managed CNPG cert via spec.certificates.serverAltDNSNames. When omitted, the chart injects the SAN if `external: true` and skips it otherwise. Set explicitly to `true` to inject regardless of `external` (no-op when `external: false` since there is no external hostname to add). Set to `false` to skip injection. Note that CNPG keeps its built-in TLS on the wire regardlesLine truncated
release:
prefix: postgres-
labels:
@@ -33,7 +33,7 @@ spec:
# labelSelector:
# helm.toolkit.fluxcd.io/name: "{reqs[0]['metadata','name']}"
keysOrder: [["apiVersion"], ["appVersion"], ["kind"], ["metadata"], ["metadata", "name"], ["spec", "replicas"], ["spec", "resources"], ["spec", "resourcesPreset"], ["spec", "size"], ["spec", "storageClass"], ["spec", "external"], ["spec", "version"], ["spec", "tls"], ["spec", "postgresql"], ["spec", "postgresql", "parameters"], ["spec", "postgresql", "parameters", "max_connections"], ["spec", "quorum"], ["spec", "quorum", "minSyncReplicas"], ["spec", "quorum", "maxSyncReplicas"], ["spec", "users"], ["spec", "databases"], ["spec", "backup"], ["spec", "backup", "enabled"], ["spec", "backup", "useSystemBucket"], ["spec", "backup", "retentionPolicy"], ["spec", "backup", "destinationPath"], ["spec", "backup", "endpointURL"], ["spec", "backup", "schedule"], ["spec", "backup", "s3AccessKey"], ["spec", "backup", "s3SecretKey"], ["spec", "backup", "s3CredentialsSecret"], ["spec", "backup", "s3CredentialsSecret", "name"], ["spec", "backup", "s3CredentialsSecret", "accessKeyIDKey"], ["spec", "backup", "s3CredentialsSecret", "secretAccessKeyKey"], ["spec", "backup", "endpointCA"], ["spec", "backup", "endpointCA", "name"], ["spec", "backup", "endpointCA", "key"], ["spec", "bootstrap"], ["spec", "bootstrap", "enabled"], ["spec", "bootstrap", "recoveryTime"], ["spec", "bootstrap", "oldName"], ["spec", "bootstrap", "serverName"], ["spec", "bootstrap", "newServerName"]]
keysOrder: [["apiVersion"], ["appVersion"], ["kind"], ["metadata"], ["metadata", "name"], ["spec", "replicas"], ["spec", "resources"], ["spec", "resourcesPreset"], ["spec", "size"], ["spec", "storageClass"], ["spec", "external"], ["spec", "version"], ["spec", "allowCollationChange"], ["spec", "tls"], ["spec", "postgresql"], ["spec", "postgresql", "parameters"], ["spec", "postgresql", "parameters", "max_connections"], ["spec", "quorum"], ["spec", "quorum", "minSyncReplicas"], ["spec", "quorum", "maxSyncReplicas"], ["spec", "users"], ["spec", "databases"], ["spec", "backup"], ["spec", "backup", "enabled"], ["spec", "backup", "useSystemBucket"], ["spec", "backup", "retentionPolicy"], ["spec", "backup", "destinationPath"], ["spec", "backup", "endpointURL"], ["spec", "backup", "schedule"], ["spec", "backup", "s3AccessKey"], ["spec", "backup", "s3SecretKey"], ["spec", "backup", "s3CredentialsSecret"], ["spec", "backup", "s3CredentialsSecret", "name"], ["spec", "backup", "s3CredentialsSecret", "accessKeyIDKey"], ["spec", "backup", "s3CredentialsSecret", "secretAccessKeyKey"], ["spec", "backup", "endpointCA"], ["spec", "backup", "endpointCA", "name"], ["spec", "backup", "endpointCA", "key"], ["spec", "bootstrap"], ["spec", "bootstrap", "enabled"], ["spec", "bootstrap", "recoveryTime"], ["spec", "bootstrap", "oldName"], ["spec", "bootstrap", "serverName"], ["spec", "bootstrap", "newServerName"], ["spec", "bootstrap", "sourceImageName"]]
secrets:
exclude: []
include: