diff --git a/api/apps/v1alpha1/postgresql/types.go b/api/apps/v1alpha1/postgresql/types.go index 51698e558..ae86282cc 100644 --- a/api/apps/v1alpha1/postgresql/types.go +++ b/api/apps/v1alpha1/postgresql/types.go @@ -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 collation repair Job, which a post-upgrade hook starts once the init Job is done, rebuilds the indexes on such text after the rollout, those on C.UTF-8 and other C.* locales included, and its log reports a rebuild that failed; check range partitions, CHECK constraints and materialized views on it, which a rebuild does not fix. A held cluster shows the hold only as an unchanged image; the result and the objects found are in the `postgres.cozystack.io/locale-data` and `postgres.cozystack.io/locale-data-objects` annotations of the cnpg.io Cluster, which an administrator can read. A restore of a backup taken on one of those bullseye images comes back on that image and is checked by the next upgrade. + // +kubebuilder:default:=false + AllowCollationChange bool `json:"allowCollationChange"` // TLS configuration for server connections. // +kubebuilder:default:={} Tls TLS `json:"tls"` @@ -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 { diff --git a/api/v1alpha1/workloadmonitor_types.go b/api/v1alpha1/workloadmonitor_types.go index e7639edb4..64e94a789 100644 --- a/api/v1alpha1/workloadmonitor_types.go +++ b/api/v1alpha1/workloadmonitor_types.go @@ -34,6 +34,12 @@ type WorkloadMonitorSpec struct { Replicas *int32 `json:"replicas,omitempty"` } +// WorkloadMonitorReportFailureLabel set to "true" on a Job that also carries a +// monitor's selector labels makes a failure of that Job a failure of the +// workload. Other Jobs, such as those an operator labels by inheritance from +// the workload, never affect the monitor. +const WorkloadMonitorReportFailureLabel = "workloads.cozystack.io/report-failure" + // WorkloadMonitorStatus defines the observed state of WorkloadMonitor type WorkloadMonitorStatus struct { // Operational indicates if the workload meets all operational requirements diff --git a/cmd/cozystack-controller/main.go b/cmd/cozystack-controller/main.go index 3a4077463..445d98798 100644 --- a/cmd/cozystack-controller/main.go +++ b/cmd/cozystack-controller/main.go @@ -26,6 +26,7 @@ import ( // to ensure that exec-entrypoint and run can make use of them. _ "k8s.io/client-go/plugin/pkg/client/auth" + batchv1 "k8s.io/api/batch/v1" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/runtime" utilruntime "k8s.io/apimachinery/pkg/util/runtime" @@ -200,6 +201,7 @@ func main() { Cache: cache.Options{ ByObject: map[client.Object]cache.ByObject{ &corev1.Secret{}: wildcardsecret.SecretCacheByObject(), + &batchv1.Job{}: controller.JobCacheByObject(), }, }, // LeaderElectionReleaseOnCancel defines if the leader should step down voluntarily diff --git a/hack/e2e-chainsaw/_lib/remediation-guard.sh b/hack/e2e-chainsaw/_lib/remediation-guard.sh index 7ad66371e..6fec4a5d2 100644 --- a/hack/e2e-chainsaw/_lib/remediation-guard.sh +++ b/hack/e2e-chainsaw/_lib/remediation-guard.sh @@ -22,6 +22,13 @@ # "uninstalled", 1 otherwise. Empty input is treated as "no history yet, # no cycle observed". +# The jsonpath a caller hands to kubectl to read those statuses, one per +# line. Defined here so the postgres e2e step reads it as it does on main. +# On this branch nothing checks it against the Flux HelmRelease type: a +# renamed field makes it return nothing and the guard report no cycle. +# shellcheck disable=SC2034 # used by callers that source this file +HELMRELEASE_HISTORY_JSONPATH='{range .status.history[*]}{.status}{"\n"}{end}' + helmrelease_has_remediation_cycle() { statuses="$1" if [ -z "${statuses}" ]; then diff --git a/hack/e2e-chainsaw/postgres/chainsaw-test.yaml b/hack/e2e-chainsaw/postgres/chainsaw-test.yaml index 2ab873ad6..9cade81a7 100644 --- a/hack/e2e-chainsaw/postgres/chainsaw-test.yaml +++ b/hack/e2e-chainsaw/postgres/chainsaw-test.yaml @@ -126,6 +126,230 @@ spec: name: postgres-test-init-job # The Postgres CR itself was applied by chainsaw and is deleted (and waited # on) automatically during cleanup — no explicit teardown step needed. + + # The collation repair Job rebuilds an index whose collation changed library + # version. The pass is SQL run by a Job a Helm hook starts, so only a real + # server can say whether it works. A collation created with an explicit version reads as stale + # without swapping the operand image, and so does a C. collation + # once the database records another Debian release as the one it was + # repaired for, which makes one more upgrade of the release enough to run + # the pass over both. A database created after the last run records no + # release, the state every existing cluster starts from; there a stale libc + # collation is what tells the pass that glibc moved. + - name: rebuild-index-after-collation-version-change + try: + - script: + timeout: 2m + content: | + set -eu + pod=$(kubectl -n "$NAMESPACE" get pod \ + -l cnpg.io/cluster=postgres-test,cnpg.io/instanceRole=primary \ + -o name | head -n1) + kubectl -n "$NAMESPACE" exec -i "$pod" -c postgres -- \ + psql -U postgres -d testdb -v ON_ERROR_STOP=1 <<'EOF' + CREATE COLLATION stale_icu (provider = icu, locale = 'en', version = '0'); + CREATE TABLE collation_probe (s text COLLATE stale_icu); + INSERT INTO collation_probe SELECT 'v' || g FROM generate_series(1, 1000) g; + CREATE UNIQUE INDEX collation_probe_s ON collation_probe (s); + CREATE EXTENSION IF NOT EXISTS btree_gist; + CREATE TABLE collation_probe_excl (s text COLLATE stale_icu, EXCLUDE USING gist (s WITH =)); + INSERT INTO collation_probe_excl SELECT 'k' || g FROM generate_series(1, 200) g; + CREATE TABLE collation_probe_c (s text COLLATE "C.utf8" UNIQUE); + INSERT INTO collation_probe_c SELECT 'c' || g FROM generate_series(1, 1000) g; + ALTER DATABASE testdb SET cozystack.collation_release = 'pgdg11'; + CREATE TABLE collation_probe_before AS + SELECT 'collation_probe_s'::regclass::oid AS index, + (SELECT relfilenode FROM pg_class WHERE oid = 'collation_probe_excl_s_excl'::regclass) AS in_place_file, + 'collation_probe_c_s_key'::regclass::oid AS c_index; + CREATE DATABASE collation_probe_unrecorded; + \c collation_probe_unrecorded + CREATE COLLATION stale_libc (provider = libc, locale = 'en_US.utf8', version = '0'); + CREATE TABLE collation_probe_c (s text COLLATE "C.utf8" UNIQUE); + INSERT INTO collation_probe_c SELECT 'c' || g FROM generate_series(1, 1000) g; + CREATE TABLE collation_probe_before AS SELECT 'collation_probe_c_s_key'::regclass::oid AS c_index; + EOF + check: + ($error == null): true + # A repair Job left by the install has completed already; it goes + # first, so that the Job awaited below is the one this upgrade starts. + - script: + timeout: 2m + content: | + set -eu + kubectl -n "$NAMESPACE" delete job postgres-test-collation-repair --ignore-not-found --wait=true + check: + ($error == null): true + # A declared user is the smallest change that makes Helm upgrade the + # release, and so run the hook, without restarting PostgreSQL. + - patch: + resource: + apiVersion: apps.cozystack.io/v1alpha1 + kind: Postgres + metadata: + name: test + spec: + users: + collationprobe: {} + # 11m: above the 600s upgrade timeout cozystack-api gives this release. + # The step above that waited for this Job deleted it, so the Job found + # here is the one the upgrade created. + - assert: + timeout: 11m + resource: + apiVersion: batch/v1 + kind: Job + metadata: + name: postgres-test-init-job + status: + (conditions[?type == 'Complete']): + - status: "True" + # The repair runs in a Job a post-upgrade hook starts outside the + # release, after the init Job. The label is what makes the + # WorkloadMonitor report a failed repair on the Application. + - assert: + timeout: 15m + resource: + apiVersion: batch/v1 + kind: Job + metadata: + name: postgres-test-collation-repair + labels: + app.kubernetes.io/name: postgres.apps.cozystack.io + app.kubernetes.io/instance: postgres-test + workloads.cozystack.io/report-failure: "true" + status: + (conditions[?type == 'Complete']): + - status: "True" + # The next upgrade finds that Job complete on the same image and replaces + # it with a new run under the same name. + - script: + timeout: 1m + content: | + set -eu + # A failed repair must stay visible until the next upgrade replaces it. + ttl=$(kubectl -n "$NAMESPACE" get job postgres-test-collation-repair -o jsonpath='{.spec.ttlSecondsAfterFinished}') + if [ -n "$ttl" ]; then + echo "the collation repair Job has ttlSecondsAfterFinished=$ttl, so a failed repair would disappear" >&2 + exit 1 + fi + kubectl -n "$NAMESPACE" annotate job postgres-test-collation-repair e2e.cozystack.io/previous-run=true + check: + ($error == null): true + - patch: + resource: + apiVersion: apps.cozystack.io/v1alpha1 + kind: Postgres + metadata: + name: test + spec: + users: + collationprobe: {} + collationprobe2: {} + - script: + timeout: 15m + content: | + set -eu + until [ "$(kubectl -n "$NAMESPACE" get job postgres-test-collation-repair --ignore-not-found \ + -o jsonpath='{.metadata.annotations.e2e\.cozystack\.io/previous-run}|{.status.conditions[?(@.type=="Complete")].status}')" = "|True" ]; do + sleep 5 + done + check: + ($error == null): true + - script: + timeout: 2m + content: | + set -eu + pod=$(kubectl -n "$NAMESPACE" get pod \ + -l cnpg.io/cluster=postgres-test,cnpg.io/instanceRole=primary \ + -o name | head -n1) + q() { + kubectl -n "$NAMESPACE" exec "$pod" -c postgres -- \ + psql -U postgres -d testdb -v ON_ERROR_STOP=1 -tAc "$1" + } + refreshed=$(q "SELECT collversion = pg_collation_actual_version(oid) FROM pg_collation WHERE collname = 'stale_icu'") + if [ "$refreshed" != t ]; then + echo "the collation repair Job left the collation version stale" >&2 + exit 1 + fi + # REINDEX CONCURRENTLY gives the index a new OID, so an unchanged + # one means the version was refreshed over an index nobody rebuilt. + rebuilt=$(q "SELECT 'collation_probe_s'::regclass::oid <> index FROM collation_probe_before") + if [ "$rebuilt" != t ]; then + echo "the collation repair Job refreshed the collation version without rebuilding the index" >&2 + exit 1 + fi + q "CREATE EXTENSION IF NOT EXISTS amcheck" + q "SELECT bt_index_check('collation_probe_s', true)" + # An exclusion constraint's index is rebuilt in place: it keeps its + # OID and gets a new storage file. + rebuilt_in_place=$(q "SELECT c.relfilenode <> b.in_place_file FROM pg_class c, collation_probe_before b WHERE c.oid = 'collation_probe_excl_s_excl'::regclass") + if [ "$rebuilt_in_place" != t ]; then + echo "the collation repair Job did not rebuild the exclusion constraint's index" >&2 + exit 1 + fi + rebuilt_c=$(q "SELECT 'collation_probe_c_s_key'::regclass::oid <> c_index FROM collation_probe_before") + if [ "$rebuilt_c" != t ]; then + echo "the collation repair Job did not rebuild the index on a C. collation after the Debian release changed" >&2 + exit 1 + fi + q "SELECT bt_index_check('collation_probe_c_s_key', true)" + release=$(q "SELECT current_setting('cozystack.collation_release', true) = substring(current_setting('server_version') from 'pgdg[0-9]+')") + if [ "$release" != t ]; then + echo "the collation repair Job did not record the Debian release it repaired the database for" >&2 + exit 1 + fi + qu() { + kubectl -n "$NAMESPACE" exec "$pod" -c postgres -- \ + psql -U postgres -d collation_probe_unrecorded -v ON_ERROR_STOP=1 -tAc "$1" + } + rebuilt_unrecorded=$(qu "SELECT 'collation_probe_c_s_key'::regclass::oid <> c_index FROM collation_probe_before") + if [ "$rebuilt_unrecorded" != t ]; then + echo "the collation repair Job did not rebuild the index on a C. collation in a database that recorded no release and holds a stale libc collation" >&2 + exit 1 + fi + qu "CREATE EXTENSION IF NOT EXISTS amcheck" + qu "SELECT bt_index_check('collation_probe_c_s_key', true)" + release=$(qu "SELECT current_setting('cozystack.collation_release', true) = substring(current_setting('server_version') from 'pgdg[0-9]+')") + if [ "$release" != t ]; then + echo "the collation repair Job did not record the Debian release it repaired the unrecorded database for" >&2 + exit 1 + fi + # The pass keeps its progress in a setting of the database and + # removes it once nothing is left to repair. + progress=$(q "SELECT count(*) FROM pg_db_role_setting s JOIN pg_database d ON d.oid = s.setdatabase, unnest(s.setconfig) AS c WHERE d.datname = current_database() AND c LIKE 'cozystack.collation_repair=%'") + if [ "$progress" != 0 ]; then + echo "the collation repair Job left its repair setting on a database it finished repairing" >&2 + exit 1 + fi + leftovers=$(q "SELECT count(*) FROM pg_index WHERE NOT indisvalid") + if [ "$leftovers" != 0 ]; then + echo "the rebuild left $leftovers invalid index(es) behind" >&2 + exit 1 + fi + # The Job above also completes on a retry, so a hook that failed + # first would pass unseen without this. + cd ../../.. + . hack/e2e-chainsaw/_lib/remediation-guard.sh + statuses=$(kubectl -n "$NAMESPACE" get helmrelease postgres-test \ + -o jsonpath="$HELMRELEASE_HISTORY_JSONPATH") + printf 'HelmRelease postgres-test history statuses:\n%s\n' "${statuses:-}" + if helmrelease_has_remediation_cycle "$statuses"; then + echo "HelmRelease postgres-test failed an action while the index was rebuilt" >&2 + exit 1 + fi + check: + ($error == null): true + finally: + - delete: + ref: + apiVersion: batch/v1 + kind: Job + name: postgres-test-init-job + - delete: + ref: + apiVersion: batch/v1 + kind: Job + name: postgres-test-collation-repair --- # Full barman-cloud backup -> to-copy RestoreJob round-trip, driving the # validated example scripts (examples/backups/postgres) as the harness so the diff --git a/internal/backupcontroller/cnpg_source_image_test.go b/internal/backupcontroller/cnpg_source_image_test.go new file mode 100644 index 000000000..10abcef43 --- /dev/null +++ b/internal/backupcontroller/cnpg_source_image_test.go @@ -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) + } +} diff --git a/internal/backupcontroller/cnpgstrategy_controller.go b/internal/backupcontroller/cnpgstrategy_controller.go index 499336730..ad3662d79 100644 --- a/internal/backupcontroller/cnpgstrategy_controller.go +++ b/internal/backupcontroller/cnpgstrategy_controller.go @@ -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 `` 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 diff --git a/internal/backupcontroller/cnpgstrategy_controller_test.go b/internal/backupcontroller/cnpgstrategy_controller_test.go index 4b7a1b3b4..78b1a6b6d 100644 --- a/internal/backupcontroller/cnpgstrategy_controller_test.go +++ b/internal/backupcontroller/cnpgstrategy_controller_test.go @@ -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, diff --git a/internal/backupcontroller/cnpgtypes/types.go b/internal/backupcontroller/cnpgtypes/types.go index 4a7c4e58c..e47a9d014 100644 --- a/internal/backupcontroller/cnpgtypes/types.go +++ b/internal/backupcontroller/cnpgtypes/types.go @@ -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 diff --git a/internal/backupcontroller/postgresapp/types.go b/internal/backupcontroller/postgresapp/types.go index 1b5036ec0..07db293f7 100644 --- a/internal/backupcontroller/postgresapp/types.go +++ b/internal/backupcontroller/postgresapp/types.go @@ -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 { diff --git a/internal/controller/workloadmonitor_controller.go b/internal/controller/workloadmonitor_controller.go index daf3a682a..b1e647b65 100644 --- a/internal/controller/workloadmonitor_controller.go +++ b/internal/controller/workloadmonitor_controller.go @@ -13,17 +13,20 @@ import ( "time" apierrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" "k8s.io/client-go/tools/record" "k8s.io/client-go/util/retry" "k8s.io/utils/pointer" ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/cache" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/handler" "sigs.k8s.io/controller-runtime/pkg/log" "sigs.k8s.io/controller-runtime/pkg/reconcile" + batchv1 "k8s.io/api/batch/v1" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -77,12 +80,114 @@ type WorkloadMonitorReconciler struct { // +kubebuilder:rbac:groups=core,resources=namespaces,verbs=get // +kubebuilder:rbac:groups=core,resources=events,verbs=create;patch // +kubebuilder:rbac:groups=objectstorage.k8s.io,resources=bucketclaims,verbs=get;list;watch +// +kubebuilder:rbac:groups=batch,resources=jobs,verbs=get;list;watch // isBucketClaimReady checks if the BucketClaim has been provisioned. func (r *WorkloadMonitorReconciler) isBucketClaimReady(bc *cosiv1alpha1.BucketClaim) bool { return bc.Status.BucketReady } +// maxFailedJobsInMessage bounds how many failed Jobs a monitor's message names. +const maxFailedJobsInMessage = 3 + +// jobFailedCondition returns the Failed=True condition of a Job, or nil. +func jobFailedCondition(job *batchv1.Job) *batchv1.JobCondition { + for i := range job.Status.Conditions { + c := &job.Status.Conditions[i] + if c.Type == batchv1.JobFailed && c.Status == corev1.ConditionTrue { + return c + } + } + return nil +} + +func jobIsNewer(a, b *batchv1.Job) bool { + if !a.CreationTimestamp.Equal(&b.CreationTimestamp) { + return b.CreationTimestamp.Before(&a.CreationTimestamp) + } + return a.Name > b.Name +} + +// failedJobsMessage names the failed Jobs with the reason and message of their +// Failed condition, and is empty when there is none. Of the Jobs one controller +// owns, only the newest counts: a CronJob keeps failed runs in its history +// after a later run succeeds. +func failedJobsMessage(jobs []batchv1.Job) string { + var current []*batchv1.Job + newestByOwner := map[types.UID]*batchv1.Job{} + for i := range jobs { + job := &jobs[i] + if job.DeletionTimestamp != nil { + continue + } + owner := metav1.GetControllerOfNoCopy(job) + if owner == nil { + current = append(current, job) + continue + } + if prev, ok := newestByOwner[owner.UID]; !ok || jobIsNewer(job, prev) { + newestByOwner[owner.UID] = job + } + } + for _, job := range newestByOwner { + current = append(current, job) + } + sort.Slice(current, func(i, j int) bool { return current[i].Name < current[j].Name }) + + var failed []string + for _, job := range current { + cond := jobFailedCondition(job) + if cond == nil { + continue + } + entry := fmt.Sprintf("Job %s failed", job.Name) + if cond.Reason != "" { + entry += ": " + cond.Reason + } + if cond.Message != "" { + entry += ": " + cond.Message + } + failed = append(failed, entry) + } + if extra := len(failed) - maxFailedJobsInMessage; extra > 0 { + failed = append(failed[:maxFailedJobsInMessage], fmt.Sprintf("%d more Jobs failed", extra)) + } + return strings.Join(failed, "; ") +} + +// JobCacheByObject returns the cache options the cozystack-controller manager +// applies to Jobs. The WorkloadMonitor reconciler, their only reader there, +// reads only Jobs that opted in with WorkloadMonitorReportFailureLabel, and of +// them only labels, owners and conditions. +func JobCacheByObject() cache.ByObject { + return cache.ByObject{ + Label: labels.SelectorFromSet(labels.Set{cozyv1alpha1.WorkloadMonitorReportFailureLabel: "true"}), + Transform: stripJob, + } +} + +func stripJob(obj any) (any, error) { + job, ok := obj.(*batchv1.Job) + if !ok { + return obj, nil + } + return &batchv1.Job{ + TypeMeta: job.TypeMeta, + ObjectMeta: metav1.ObjectMeta{ + Name: job.Name, + Namespace: job.Namespace, + UID: job.UID, + ResourceVersion: job.ResourceVersion, + Generation: job.Generation, + CreationTimestamp: job.CreationTimestamp, + DeletionTimestamp: job.DeletionTimestamp, + Labels: job.Labels, + OwnerReferences: job.OwnerReferences, + }, + Status: batchv1.JobStatus{Conditions: job.Status.Conditions}, + }, nil +} + // isServiceReady checks if the service has an external IP bound func (r *WorkloadMonitorReconciler) isServiceReady(svc *corev1.Service) bool { return len(svc.Status.LoadBalancer.Ingress) > 0 @@ -708,6 +813,27 @@ func (r *WorkloadMonitorReconciler) Reconcile(ctx context.Context, req ctrl.Requ } } + reportedJobs := client.MatchingLabels{cozyv1alpha1.WorkloadMonitorReportFailureLabel: "true"} + for k, v := range monitor.Spec.Selector { + reportedJobs[k] = v + } + jobList := &batchv1.JobList{} + if err := r.List( + ctx, + jobList, + client.InNamespace(monitor.Namespace), + reportedJobs, + ); err != nil { + logger.Error(err, "Unable to list Jobs for WorkloadMonitor", "monitor", monitor.Name) + return ctrl.Result{}, err + } + // The status has no field for the cause on this line, so the failed Jobs + // are named in the log only. + jobsMessage := failedJobsMessage(jobList.Items) + if jobsMessage != "" { + logger.Info("WorkloadMonitor is not operational: a Job that reports failure has failed", "monitor", monitor.Name, "jobs", jobsMessage) + } + // Update WorkloadMonitor status based on observed pods monitor.Status.ObservedReplicas = observedReplicas monitor.Status.AvailableReplicas = availableReplicas @@ -728,6 +854,9 @@ func (r *WorkloadMonitorReconciler) Reconcile(ctx context.Context, req ctrl.Requ if fresh.Spec.MinReplicas != nil && availableReplicas < *fresh.Spec.MinReplicas { fresh.Status.Operational = pointer.Bool(false) } + if jobsMessage != "" { + fresh.Status.Operational = pointer.Bool(false) + } return r.Status().Update(ctx, fresh) }) if err != nil { @@ -771,6 +900,11 @@ func (r *WorkloadMonitorReconciler) SetupWithManager(mgr ctrl.Manager) error { &cosiv1alpha1.BucketClaim{}, handler.EnqueueRequestsFromMapFunc(mapObjectToMonitor(&cosiv1alpha1.BucketClaim{}, r.Client)), ). + // Cached Jobs carry only what JobCacheByObject keeps. + Watches( + &batchv1.Job{}, + handler.EnqueueRequestsFromMapFunc(mapObjectToMonitor(&batchv1.Job{}, r.Client)), + ). // Watch for changes to Workload objects we create (owned by WorkloadMonitor) Owns(&cozyv1alpha1.Workload{}). Complete(r) diff --git a/internal/controller/workloadmonitor_controller_test.go b/internal/controller/workloadmonitor_controller_test.go index ee85f422c..7d7a47bd0 100644 --- a/internal/controller/workloadmonitor_controller_test.go +++ b/internal/controller/workloadmonitor_controller_test.go @@ -7,8 +7,10 @@ import ( "net/http/httptest" "strings" "testing" + "time" cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1" + batchv1 "k8s.io/api/batch/v1" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -16,6 +18,7 @@ import ( "k8s.io/apimachinery/pkg/types" "k8s.io/utils/ptr" cosiv1alpha1 "sigs.k8s.io/container-object-storage-interface-api/apis/objectstorage/v1alpha1" + "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client/fake" "sigs.k8s.io/controller-runtime/pkg/reconcile" ) @@ -24,6 +27,7 @@ func TestReconcile_OperationalStatusPersisted(t *testing.T) { scheme := runtime.NewScheme() _ = cozyv1alpha1.AddToScheme(scheme) _ = corev1.AddToScheme(scheme) + _ = batchv1.AddToScheme(scheme) _ = cosiv1alpha1.AddToScheme(scheme) minReplicas := int32(2) @@ -90,6 +94,7 @@ func TestReconcile_OperationalTrue_WhenEnoughReplicas(t *testing.T) { scheme := runtime.NewScheme() _ = cozyv1alpha1.AddToScheme(scheme) _ = corev1.AddToScheme(scheme) + _ = batchv1.AddToScheme(scheme) _ = cosiv1alpha1.AddToScheme(scheme) minReplicas := int32(1) @@ -219,6 +224,7 @@ func TestReconcile_MonitorLabelsPropagatedToPodWorkload(t *testing.T) { scheme := runtime.NewScheme() _ = cozyv1alpha1.AddToScheme(scheme) _ = corev1.AddToScheme(scheme) + _ = batchv1.AddToScheme(scheme) _ = cosiv1alpha1.AddToScheme(scheme) monitor := &cozyv1alpha1.WorkloadMonitor{ @@ -291,6 +297,7 @@ func TestReconcile_BackwardCompat_NoMonitorLabels(t *testing.T) { scheme := runtime.NewScheme() _ = cozyv1alpha1.AddToScheme(scheme) _ = corev1.AddToScheme(scheme) + _ = batchv1.AddToScheme(scheme) _ = cosiv1alpha1.AddToScheme(scheme) monitor := &cozyv1alpha1.WorkloadMonitor{ @@ -343,6 +350,7 @@ func TestReconcile_OperationalTrue_WhenNoMinReplicas(t *testing.T) { scheme := runtime.NewScheme() _ = cozyv1alpha1.AddToScheme(scheme) _ = corev1.AddToScheme(scheme) + _ = batchv1.AddToScheme(scheme) _ = cosiv1alpha1.AddToScheme(scheme) monitor := &cozyv1alpha1.WorkloadMonitor{ @@ -387,6 +395,7 @@ func newTestScheme() *runtime.Scheme { s := runtime.NewScheme() _ = cozyv1alpha1.AddToScheme(s) _ = corev1.AddToScheme(s) + _ = batchv1.AddToScheme(s) _ = cosiv1alpha1.AddToScheme(s) return s } @@ -1300,3 +1309,197 @@ func TestReconcile_PVCStorageClassResourceKey(t *testing.T) { }) } } + +func newJob(name string, labels map[string]string, conditions ...batchv1.JobCondition) *batchv1.Job { + return &batchv1.Job{ + ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: "default", Labels: labels}, + Status: batchv1.JobStatus{Conditions: conditions}, + } +} + +func jobFailed(reason, message string) batchv1.JobCondition { + return batchv1.JobCondition{Type: batchv1.JobFailed, Status: corev1.ConditionTrue, Reason: reason, Message: message} +} + +func newJobMonitorClient(s *runtime.Scheme, minReplicas int32, objs ...client.Object) client.Client { + monitor := &cozyv1alpha1.WorkloadMonitor{ + ObjectMeta: metav1.ObjectMeta{Name: "db", Namespace: "default"}, + Spec: cozyv1alpha1.WorkloadMonitorSpec{ + Selector: map[string]string{"app.kubernetes.io/instance": "db"}, + MinReplicas: ptr.To(minReplicas), + }, + } + return fake.NewClientBuilder(). + WithScheme(s). + WithObjects(append([]client.Object{monitor}, objs...)...). + WithStatusSubresource(monitor). + Build() +} + +func reconcileJobMonitor(t *testing.T, c client.Client, s *runtime.Scheme) *cozyv1alpha1.WorkloadMonitor { + t.Helper() + reconciler := &WorkloadMonitorReconciler{Client: c, Scheme: s} + req := reconcile.Request{NamespacedName: types.NamespacedName{Name: "db", Namespace: "default"}} + if _, err := reconciler.Reconcile(context.TODO(), req); err != nil { + t.Fatalf("Reconcile returned error: %v", err) + } + updated := &cozyv1alpha1.WorkloadMonitor{} + if err := c.Get(context.TODO(), req.NamespacedName, updated); err != nil { + t.Fatalf("Failed to get updated WorkloadMonitor: %v", err) + } + if updated.Status.Operational == nil { + t.Fatal("Expected Operational to be set, got nil") + } + return updated +} + +func TestReconcile_FailedJobDecidesOperational(t *testing.T) { + selected := map[string]string{"app.kubernetes.io/instance": "db", cozyv1alpha1.WorkloadMonitorReportFailureLabel: "true"} + cases := []struct { + name string + job *batchv1.Job + operational bool + }{ + {"failed", newJob("db-repair", selected, jobFailed("BackoffLimitExceeded", "Job has reached the specified backoff limit")), false}, + {"failed without a reason", newJob("db-repair", selected, jobFailed("", "")), false}, + {"succeeded", newJob("db-repair", selected, batchv1.JobCondition{Type: batchv1.JobComplete, Status: corev1.ConditionTrue}), true}, + {"running", newJob("db-repair", selected), true}, + {"Failed condition not true", newJob("db-repair", selected, batchv1.JobCondition{Type: batchv1.JobFailed, Status: corev1.ConditionFalse}), true}, + {"outside the selector", newJob("other", map[string]string{"app.kubernetes.io/instance": "other", cozyv1alpha1.WorkloadMonitorReportFailureLabel: "true"}, jobFailed("BackoffLimitExceeded", "")), true}, + {"not opted in", newJob("db-1-initdb", map[string]string{"app.kubernetes.io/instance": "db"}, jobFailed("BackoffLimitExceeded", "")), true}, + {"opted out", newJob("db-repair", map[string]string{"app.kubernetes.io/instance": "db", cozyv1alpha1.WorkloadMonitorReportFailureLabel: "false"}, jobFailed("BackoffLimitExceeded", "")), true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + s := newTestScheme() + got := reconcileJobMonitor(t, newJobMonitorClient(s, 0, tc.job), s) + if *got.Status.Operational != tc.operational { + t.Errorf("Operational = %v, want %v", *got.Status.Operational, tc.operational) + } + }) + } +} + +func TestReconcile_FailedJobVerdictClears(t *testing.T) { + selected := map[string]string{"app.kubernetes.io/instance": "db", cozyv1alpha1.WorkloadMonitorReportFailureLabel: "true"} + for _, tc := range []struct { + name string + clear func(c client.Client, job *batchv1.Job) error + }{ + {"deleted", func(c client.Client, job *batchv1.Job) error { return c.Delete(context.TODO(), job) }}, + {"replaced by a run that succeeded", func(c client.Client, job *batchv1.Job) error { + if err := c.Delete(context.TODO(), job); err != nil { + return err + } + return c.Create(context.TODO(), newJob("db-repair", selected, batchv1.JobCondition{Type: batchv1.JobComplete, Status: corev1.ConditionTrue})) + }}, + } { + t.Run(tc.name, func(t *testing.T) { + s := newTestScheme() + job := newJob("db-repair", selected, jobFailed("BackoffLimitExceeded", "")) + c := newJobMonitorClient(s, 0, job) + if got := reconcileJobMonitor(t, c, s); *got.Status.Operational { + t.Fatal("before: Operational = true, want false") + } + if err := tc.clear(c, job); err != nil { + t.Fatal(err) + } + if got := reconcileJobMonitor(t, c, s); !*got.Status.Operational { + t.Error("after: Operational = false, want true") + } + }) + } +} + +func TestReconcile_FailedJobWithEnoughReplicas(t *testing.T) { + selected := map[string]string{"app.kubernetes.io/instance": "db", cozyv1alpha1.WorkloadMonitorReportFailureLabel: "true"} + s := newTestScheme() + pod := &corev1.Pod{ + ObjectMeta: metav1.ObjectMeta{Name: "db-1", Namespace: "default", Labels: map[string]string{"app.kubernetes.io/instance": "db"}}, + Status: corev1.PodStatus{ + Phase: corev1.PodRunning, + Conditions: []corev1.PodCondition{{Type: corev1.PodReady, Status: corev1.ConditionTrue}}, + }, + } + got := reconcileJobMonitor(t, newJobMonitorClient(s, 1, pod, newJob("db-repair", selected, jobFailed("BackoffLimitExceeded", ""))), s) + if got.Status.AvailableReplicas != 1 { + t.Fatalf("AvailableReplicas = %d, want 1", got.Status.AvailableReplicas) + } + if *got.Status.Operational { + t.Error("Operational = true, want false: a failed Job outranks enough ready replicas") + } +} + +func TestFailedJobsMessage(t *testing.T) { + failed := jobFailed("BackoffLimitExceeded", "") + complete := batchv1.JobCondition{Type: batchv1.JobComplete, Status: corev1.ConditionTrue} + ownedBy := func(job *batchv1.Job, uid types.UID, created time.Time) batchv1.Job { + job.OwnerReferences = []metav1.OwnerReference{{APIVersion: "batch/v1", Kind: "CronJob", Name: "backup", UID: uid, Controller: ptr.To(true)}} + job.CreationTimestamp = metav1.NewTime(created) + return *job + } + now := time.Now() + cases := []struct { + name string + jobs []batchv1.Job + want string + }{ + { + "sorted by name", + []batchv1.Job{*newJob("b", nil, failed), *newJob("a", nil, failed)}, + "Job a failed: BackoffLimitExceeded; Job b failed: BackoffLimitExceeded", + }, + { + "bounded", + []batchv1.Job{*newJob("e", nil, failed), *newJob("d", nil, failed), *newJob("c", nil, failed), *newJob("b", nil, failed), *newJob("a", nil, failed)}, + "Job a failed: BackoffLimitExceeded; Job b failed: BackoffLimitExceeded; Job c failed: BackoffLimitExceeded; 2 more Jobs failed", + }, + { + "a later run of the same controller succeeded", + []batchv1.Job{ownedBy(newJob("backup-1", nil, failed), "cron", now.Add(-time.Hour)), ownedBy(newJob("backup-2", nil, complete), "cron", now)}, + "", + }, + { + "the latest run of the controller failed", + []batchv1.Job{ownedBy(newJob("backup-1", nil, complete), "cron", now.Add(-time.Hour)), ownedBy(newJob("backup-2", nil, failed), "cron", now)}, + "Job backup-2 failed: BackoffLimitExceeded", + }, + { + "being deleted", + []batchv1.Job{func() batchv1.Job { + j := newJob("a", nil, failed) + j.DeletionTimestamp = ptr.To(metav1.NewTime(now)) + return *j + }()}, + "", + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := failedJobsMessage(tc.jobs); got != tc.want { + t.Errorf("failedJobsMessage = %q, want %q", got, tc.want) + } + }) + } +} + +func TestStripJobKeepsWhatTheMonitorReads(t *testing.T) { + job := newJob("db-repair", map[string]string{"app.kubernetes.io/instance": "db"}, jobFailed("BackoffLimitExceeded", "limit")) + job.OwnerReferences = []metav1.OwnerReference{{Name: "owner", UID: "u", Controller: ptr.To(true)}} + job.ResourceVersion = "7" + job.ManagedFields = []metav1.ManagedFieldsEntry{{Manager: "kube-controller-manager"}} + job.Spec.Template.Spec.Containers = []corev1.Container{{Name: "repair", Image: "postgres"}} + + out, err := stripJob(job) + if err != nil { + t.Fatal(err) + } + got := out.(*batchv1.Job) + if got.Name != job.Name || got.Namespace != job.Namespace || got.ResourceVersion != "7" || + len(got.Labels) != 1 || len(got.OwnerReferences) != 1 || failedJobsMessage([]batchv1.Job{*got}) != "Job db-repair failed: BackoffLimitExceeded: limit" { + t.Errorf("stripped Job lost what the monitor reads: %+v", got) + } + if len(got.ManagedFields) != 0 || len(got.Spec.Template.Spec.Containers) != 0 { + t.Errorf("stripped Job kept its spec or managed fields: %+v", got) + } +} diff --git a/packages/apps/postgres/README.md b/packages/apps/postgres/README.md index 649e2e177..62bac38c0 100644 --- a/packages/apps/postgres/README.md +++ b/packages/apps/postgres/README.md @@ -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 collation repair Job, which a post-upgrade hook starts once the init Job is done, rebuilds the indexes on such text after the rollout, those on C.UTF-8 and other C.* locales included, and its log reports a rebuild that failed; check range partitions, CHECK constraints and materialized views on it, which a rebuild does not fix. A held cluster shows the hold only as an unchanged image; the result and the objects found are in the `postgres.cozystack.io/locale-data` and `postgres.cozystack.io/locale-data-objects` annotations of the cnpg.io Cluster, which an administrator can read. A restore of a backup taken on one of those bullseye images comes back on that image and is checked by the next upgrade. | `bool` | `false` | ### TLS configuration @@ -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 diff --git a/packages/apps/postgres/files/versions.yaml b/packages/apps/postgres/files/versions.yaml index e4fe13ead..2624066e3 100644 --- a/packages/apps/postgres/files/versions.yaml +++ b/packages/apps/postgres/files/versions.yaml @@ -1,6 +1,6 @@ -"v18": "v18.1" -"v17": "v17.7" -"v16": "v16.11" -"v15": "v15.15" -"v14": "v14.20" +"v18": "v18.7" +"v17": "v17.12" +"v16": "v16.16" +"v15": "v15.20" +"v14": "v14.25" "v13": "v13.22" diff --git a/packages/apps/postgres/hack/update-versions.sh b/packages/apps/postgres/hack/update-versions.sh index c92b3895b..8567402a8 100755 --- a/packages/apps/postgres/hack/update-versions.sh +++ b/packages/apps/postgres/hack/update-versions.sh @@ -32,9 +32,10 @@ if ! command -v jq &> /dev/null; then exit 1 fi -# Get available image tags +# Get available image tags. Only standard-trixie builds count: the chart +# appends that suffix to the minor it reads from versions.yaml. echo "Fetching available image tags from registry..." -AVAILABLE_TAGS=$(skopeo list-tags docker://ghcr.io/cloudnative-pg/postgresql | jq -r '.Tags[] | select(test("^[0-9]+\\.[0-9]+$"))' | sort -V) +AVAILABLE_TAGS=$(skopeo list-tags docker://ghcr.io/cloudnative-pg/postgresql | jq -r '.Tags[] | select(test("^[0-9]+\\.[0-9]+-standard-trixie$")) | sub("-standard-trixie$"; "")' | sort -V) if [ -z "$AVAILABLE_TAGS" ]; then echo "Error: Could not fetch available image tags" >&2 diff --git a/packages/apps/postgres/templates/_versions.tpl b/packages/apps/postgres/templates/_versions.tpl index ca0ff2a27..06fdbb96e 100644 --- a/packages/apps/postgres/templates/_versions.tpl +++ b/packages/apps/postgres/templates/_versions.tpl @@ -6,3 +6,106 @@ {{- index $versionMap .Values.version }} {{- end }} +{{/* + Single source for the operand image: the init Job runs psql against the + Cluster, so both must resolve the same image, and the Job compares its own + PostgreSQL build with the server's to tell when a new image has rolled out. + + standard-trixie, not the bare tag: a bare tag is the system variant on + Debian bullseye, which upstream stopped building. The standard variant, + because backups go through the barman-cloud plugin and need none of the + barman binaries the system variant adds. +*/}} +{{- 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 -}} diff --git a/packages/apps/postgres/templates/collation-repair.yaml b/packages/apps/postgres/templates/collation-repair.yaml new file mode 100644 index 000000000..2729c93d0 --- /dev/null +++ b/packages/apps/postgres/templates/collation-repair.yaml @@ -0,0 +1,223 @@ +{{- /* + The collation repair (repair.sh in the init-script Secret) must not run as + a Helm hook: it waits for CNPG to move the primary to the new image and then + rebuilds indexes, and both take as long as the data and the clients make + them. Nor can it be an ordinary manifest: helm-controller waits for every + Job of a release to complete within the same upgrade timeout. So this hook + creates it through the API, outside the release, and returns. + + The repair Job has one fixed name, so no two of them run against the + Cluster at once. One still running on the image this release renders, + and not being deleted, is left to finish; any other is deleted, and its pod is gone, before the new + one is created, which also retries a repair that failed. It is owned by + the Cluster, so it goes with it. The hook's Role reaches only those two + objects by name, except for create, which RBAC cannot narrow to a name, + and is removed again once the hooks succeed. Skipped with the init-job + while bootstrap is on: the repair runs from its Secret, and the init-job + must have converged the release first. It runs on install too, where it + only records the Debian release each database starts on: a later image + move is told apart by that record, and the repair of that move may start + only after the primary has moved. +*/}} +{{- if not .Values.bootstrap.enabled }} +{{- /* One base for both names, short enough for the longer suffix: cut + separately, a long release name would give both the same name, and + the starter would take its own Job for a previous repair. */}} +{{- $base := .Release.Name }} +{{- if gt (len $base) 40 }} +{{- $base = printf "%s-%s" ($base | trunc 31 | trimSuffix "-") ($base | sha256sum | trunc 8) }} +{{- end }} +{{- $name := printf "%s-collation-repair" $base }} +{{- $starter := printf "%s-collation-repair-start" $base }} +{{- /* + The repair keeps what is left of an hour for rebuilding once the primary + runs the new image, and it bounds its lock waits by the same clock, so a + longer deadline is not free: an index rebuilt in place waits for its lock + in the queue that writes to its table join. +*/}} +{{- $deadline := 3600 }} +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: {{ $starter }} + annotations: + helm.sh/hook: post-install,post-upgrade + helm.sh/hook-weight: "0" + helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: {{ $starter }} + annotations: + helm.sh/hook: post-install,post-upgrade + helm.sh/hook-weight: "0" + helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded +rules: +- apiGroups: ["batch"] + resources: ["jobs"] + resourceNames: [{{ $name | quote }}] + verbs: ["get", "delete"] +- apiGroups: ["batch"] + resources: ["jobs"] + verbs: ["create"] +- apiGroups: ["postgresql.cnpg.io"] + resources: ["clusters"] + resourceNames: [{{ .Release.Name | quote }}] + verbs: ["get"] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: {{ $starter }} + annotations: + helm.sh/hook: post-install,post-upgrade + helm.sh/hook-weight: "0" + helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: {{ $starter }} +subjects: +- kind: ServiceAccount + name: {{ $starter }} + namespace: {{ .Release.Namespace | quote }} +--- +apiVersion: batch/v1 +kind: Job +metadata: + name: {{ $starter }} + annotations: + helm.sh/hook: post-install,post-upgrade + helm.sh/hook-weight: "1" + helm.sh/hook-delete-policy: before-hook-creation +spec: + activeDeadlineSeconds: 180 + backoffLimit: 0 + ttlSecondsAfterFinished: 3600 + template: + metadata: + labels: + policy.cozystack.io/allow-to-apiserver: "true" + spec: + serviceAccountName: {{ $starter }} + restartPolicy: Never + securityContext: + runAsGroup: 26 + runAsNonRoot: true + runAsUser: 26 + seccompProfile: + type: RuntimeDefault + containers: + - name: kubectl + image: {{ include "cozy-lib.image" (list "clastix/kubectl:v1.32@sha256:b9ef7d8dbe65bcc81a46c09b8dc7543103055021c4f43287bf59e92a8f4fe05c" $) }} + command: [sh, -ec] + args: + - | + name={{ $name | quote }} + image={{ include "postgres.imageName" $ | quote }} + + state=$(kubectl get job "$name" --ignore-not-found -o jsonpath='{.spec.template.spec.containers[0].image}|{.status.conditions[?(@.status=="True")].type}|{.metadata.deletionTimestamp}') + if [ "$state" = "$image||" ]; then + echo "the collation repair for $image is still running; leaving it to finish" + exit 0 + fi + if [ -n "$state" ]; then + echo "replacing the previous collation repair ($state)" + kubectl delete job "$name" --cascade=foreground --wait=false + echo "waiting for the pod of the previous collation repair to terminate; one on an unreachable node keeps it, and fails this upgrade, until the node is back or the pod is force-deleted" + until left=$(kubectl get job "$name" --ignore-not-found -o name) && [ -z "$left" ]; do + sleep 2 + done + fi + + uid=$(kubectl get clusters.postgresql.cnpg.io {{ .Release.Name | quote }} -o jsonpath='{.metadata.uid}') + kubectl create -f - <&2 + sleep "$delay" + delay=$((delay * 2 > 60 ? 60 : delay * 2)) + done init.sh: | #!/bin/bash set -e @@ -229,6 +251,317 @@ stringData: EOT {{- end }} {{- end }} + repair.sh: | + #!/bin/bash + set -e + {{- /* + An operand image built on another Debian release ships another glibc and + ICU, and an index ordered by a collation of either library is then + ordered by rules the server no longer applies: lookups miss rows and a + unique index stops seeing duplicates. PostgreSQL records the library + version each collation was created with, so a collation whose recorded + version differs from the one the server reports marks the indexes to + rebuild. The C and POSIX collations carry no version and never qualify, + which is every index of a database this chart created with its defaults. + + PostgreSQL records a collation for an index only where it orders a key. + A collation can also decide what an index holds without ordering it, in + a predicate or inside an expression, and for those the catalog names + the columns the index reads and nothing else. The collations of those + columns therefore count as well. That rebuilds an index or two that did + not need it, and still misses a collation that an expression applies to + a column of another one. + + This pass runs in a Job of its own, which a post-upgrade hook starts + once the init-job has managed roles and databases, and which Helm does + not wait for. The hook runs as soon as the Cluster is patched, while + CNPG is still rolling the instances, the primary last, and an instance + whose clients keep their sessions open waits out smartShutdownTimeout + before it restarts: the rollout alone can take longer than Helm gives a + hook, and the rebuild of a large index as long again, so inside the + hook either one failed the upgrade. Here a rebuild that fails costs + nothing else, and the next upgrade starts the Job again. + + The primary may therefore answer from the previous image for minutes. + The Job runs the image the Cluster is moving to, so + the server is on it once both report the same PostgreSQL version and + the same Debian release. The rebuild counter that follows them is left + out: a tag is rebuilt in place, so the Job and an instance can run + different rebuilds of one release for good. The pass waits for that + whenever the image changes, even when no index depends on a collation + yet: a plan made on the previous image misses an index created in the + meantime, which the release recorded at the end would then claim as + repaired. The wait ends 120 seconds before the Job's deadline, which is + what a first run keeps for rebuilding. + + Rebuilds survive a retry: REINDEX CONCURRENTLY gives the index a new + OID, so the highest OID seen when the repair began separates the + indexes still to rebuild from the ones already done. That mark is kept + as a setting of the database, next to a fingerprint of the stale + collations and their new versions, so another library change starts a + new repair. An exclusion constraint's index cannot be rebuilt + concurrently: its table is neither read nor written while it is rebuilt + in place, and it keeps its OID. The same setting therefore records each + attempt at one together with the index's storage file: a file that has + changed since means the index was rebuilt, by a run or by hand, and two + attempts on the same file mean two runs did not finish, after which the + index is left to an operator. The rebuild is given what is left of the + Job and no more, so that the table is not kept locked by a backend the + Job no longer waits for. + + A transaction that stays open on the table makes a rebuild wait for a + lock. That wait is bounded by what is left of the Job as well, so that + no backend is left waiting for a lock after the Job is gone. A + concurrent rebuild that is already running is not cut short: it blocks + nobody, and the index it finishes counts as done. Both bounds keep a + minute in reserve: the deadline counts from the start of the Job, + $SECONDS from the start of this script. + + Such a rebuild outlives the run that started it: its backend does not + notice that the Job is gone until the rebuild ends. REINDEX finds an + index by name, and once it has waited behind that rebuild the name + belongs to the index the rebuild put in place, which would then be + rebuilt a second time. An index is therefore skipped, and reported like + a failed rebuild, while another session builds an index of its table; + the next run finds the new index above the mark. That check comes + first in the session, before the index is looked up: a rebuild that + ended before it has removed the index the session looks for, and an + orphaned one cannot start another after it. + + One index must be rebuilt within one run of the Job, and a retry would + otherwise start a rebuild that cannot finish over and over. An + interrupted or failed REINDEX CONCURRENTLY leaves an invalid index with + a _ccnew suffix on the table, so two of those mean two runs already + failed there: the pass then leaves the table's stale indexes alone + until an operator has dropped the leftovers. A rebuild that succeeds + drops them itself. A failed or + skipped rebuild does not stop the others: the pass reports them, and + the Job exits non-zero at its end, with the recorded versions of that + database left as they are. + + A collation that a range partition key depends on is never refreshed: + rebuilding an index does not move a row to the partition the new + ordering assigns it, and the version mismatch PostgreSQL keeps logging + is the only lasting sign of that. Its indexes are still rebuilt, and + again only when another collation of the database goes stale. + Before PostgreSQL 15 the server records no version for a database's + default collation. The version recorded for the libc collation of the + same locale stands in for it there, and is refreshed in its place; the + two are matched as glibc matches them, without regard to the case of + the codeset or a hyphen in it. A locale with no such collation cannot + be checked, which a run that saw the image change says in a warning. + + PostgreSQL records no version for a libc locale named C. + either, yet the one Debian patched into the glibc of bullseye and the + one glibc ships since 2.35 order some characters differently. Such a + collation, and a database whose default collation is such a locale, + therefore take the Debian release of the server's build as their + version. The release a database was last repaired for is another + setting of it, written once a run repairs the database without a + failure. A database without that setting gets the release of the + server the pass first finds it on: that is the previous image whenever + the pass sees the image change, since it looks before it waits for the + rollout, so a retry after the primary has restarted still rebuilds + those indexes. A database that already runs on a new glibc by then is + recognised by a libc collation, or a libc database default, whose + recorded version differs from the server's, and is taken as repaired + for no release. Anything else, a new cluster included, is taken as + repaired for the release it runs. That includes a database a pass + without this rule already repaired on the new glibc: it refreshed the + libc versions and left no sign of the move behind, so its indexes on a + C. collation have to be rebuilt by hand with REINDEX. + With no version for PostgreSQL to complain about, a range partition key + of such a collation is reported only by the run that rebuilds its + indexes. + + Every session of the pass pins search_path to pg_catalog: the Job + connects as the superuser, and a function or operator a tenant defined + in public would otherwise be picked wherever its argument types match + a call more exactly than the built-in does. + */}} + + echo "== refresh collation versions" + collation_sql() { + cat <<\EOT + SET client_min_messages = error; + SET search_path = pg_catalog, pg_temp; + SELECT current_setting('server_version_num')::int >= 150000 AS tracks_database \gset + \if :tracks_database + SELECT datcollversion IS NOT NULL AS db_versioned, coalesce(pg_database_collation_actual_version(oid), '') AS db_actual, datcollversion IS NOT NULL AND datcollversion IS DISTINCT FROM pg_database_collation_actual_version(oid) AS db_stale, false AS db_unmatched, datlocprovider = 'c' AND datcollate ~* '^C\.' AS db_c, datlocprovider = 'c' AND datcollversion IS NOT NULL AND datcollversion IS DISTINCT FROM pg_database_collation_actual_version(oid) AS db_libc_stale FROM pg_database WHERE datname = current_database() \gset + \else + SELECT d.datcollate NOT IN ('C', 'POSIX') AND d.datcollate !~* '^C\.' AS db_versioned, + coalesce(max(pg_collation_actual_version(c.oid)), '') AS db_actual, + coalesce(bool_or(c.collversion IS DISTINCT FROM pg_collation_actual_version(c.oid)), false) AS db_stale, + d.datcollate NOT IN ('C', 'POSIX') AND d.datcollate !~* '^C\.' AND count(c.oid) = 0 AS db_unmatched, + d.datcollate ~* '^C\.' AS db_c, + false AS db_libc_stale + FROM pg_database d + LEFT JOIN pg_collation c ON c.collprovider = 'c' AND lower(replace(c.collcollate, '-', '')) = lower(replace(d.datcollate, '-', '')) AND c.collversion IS NOT NULL AND c.collencoding IN (-1, d.encoding) + WHERE d.datname = current_database() + GROUP BY d.datcollate \gset + \endif + SELECT coalesce(substring(current_setting('server_version') from 'pgdg[0-9]+'), '') AS release, coalesce(current_setting('cozystack.collation_release', true), '') AS repaired \gset + SELECT :'repaired' = '' AND :'release' <> '' AS unrecorded \gset + \if :unrecorded + SELECT CASE WHEN :'db_libc_stale'::boolean OR EXISTS (SELECT FROM pg_collation c WHERE c.collprovider = 'c' AND c.collversion IS NOT NULL AND c.collversion IS DISTINCT FROM pg_collation_actual_version(c.oid)) THEN 'unknown' ELSE :'release' END AS repaired \gset + SELECT format('ALTER DATABASE %I SET cozystack.collation_release = %L', current_database(), :'repaired') \gexec + \endif + CREATE TEMP TABLE cozystack_collation AS + SELECT v.oid, v.actual, v.stale, + EXISTS (SELECT FROM pg_partitioned_table p WHERE p.partstrat = 'r' AND v.oid = ANY (p.partcollation::oid[])) AS held + FROM ( + SELECT c.oid, coalesce(pg_collation_actual_version(c.oid), '') AS actual, c.collversion IS DISTINCT FROM pg_collation_actual_version(c.oid) AS stale + FROM pg_collation c + WHERE c.collversion IS NOT NULL + AND c.collencoding IN (-1, (SELECT encoding FROM pg_database WHERE datname = current_database())) + UNION ALL + SELECT 100, :'db_actual', :'db_stale'::boolean WHERE :'db_versioned'::boolean + ) v + UNION ALL + SELECT c.oid, :'release', :'repaired' <> :'release', false + FROM pg_collation c + WHERE :'release' <> '' AND c.collprovider = 'c' AND c.collversion IS NULL AND c.collcollate ~* '^C\.' + AND c.collencoding IN (-1, (SELECT encoding FROM pg_database WHERE datname = current_database())) + UNION ALL + SELECT 100, :'release', :'repaired' <> :'release', false WHERE :'release' <> '' AND :'db_c'::boolean; + CREATE TEMP TABLE cozystack_collation_index AS + SELECT i.indexrelid AS index, bool_or(c.stale) AS stale + FROM ( + SELECT x.indexrelid, k.used FROM pg_index x, unnest(x.indcollation::oid[]) AS k(used) + UNION + SELECT d.objid, d.refobjid FROM pg_depend d WHERE d.classid = 'pg_class'::regclass AND d.refclassid = 'pg_collation'::regclass + UNION + SELECT d.objid, a.attcollation FROM pg_depend d JOIN pg_attribute a ON a.attrelid = d.refobjid AND a.attnum = d.refobjsubid + WHERE d.classid = 'pg_class'::regclass AND d.refclassid = 'pg_class'::regclass AND d.refobjsubid > 0 AND a.attcollation <> 0 + ) u + JOIN cozystack_collation c ON c.oid = u.used + JOIN pg_index i ON i.indexrelid = u.indexrelid + JOIN pg_class r ON r.oid = i.indexrelid + WHERE r.relkind = 'i' AND r.relpersistence <> 't' AND i.indisvalid + GROUP BY 1; + EOT + } + collation_run() { + { collation_sql; cat; } | psql -v ON_ERROR_STOP=1 -q -t -A --dbname "$1" -v moved="$IMAGE_MOVED" + } + IMAGE_MOVED=false + pg_release() { + sed -E 's/^([0-9.]+) \(Debian [^)]*(pgdg[0-9]+)\+[0-9]+\)$/\1 \2/' + } + server_release() { + psql -t -A -c 'SHOW server_version' 2>/dev/null | pg_release + } + JOB_RELEASE=$(psql -V | sed 's/^psql (PostgreSQL) //' | pg_release) + COLLATION_DBS=$(psql -v ON_ERROR_STOP=1 -t -A -c "SELECT datname FROM pg_database WHERE datallowconn AND NOT datistemplate") + if [ "$(server_release)" != "$JOB_RELEASE" ]; then + IMAGE_MOVED=true + for db in $COLLATION_DBS; do + collation_run "$db" /dev/null + done + echo "waiting for the server to run PostgreSQL $JOB_RELEASE" + until [ "$(server_release)" = "$JOB_RELEASE" ]; do + if [ "$SECONDS" -ge $((JOB_DEADLINE - 120)) ]; then + echo "the server did not move to PostgreSQL $JOB_RELEASE in time (check the rollout of the cnpg.io/Cluster); no index is rebuilt yet - failing the collation repair Job, the next upgrade of the release starts it again" >&2 + exit 1 + fi + sleep 5 + done + fi + COLLATION_FAILED="" + for db in $COLLATION_DBS; do + PLAN=$(collation_run "$db" <<\EOT + SELECT coalesce(md5(string_agg(oid || '=' || actual, ',' ORDER BY oid)), '') AS fingerprint FROM cozystack_collation WHERE stale \gset + SELECT coalesce(current_setting('cozystack.collation_repair', true), '') AS recorded \gset + SELECT :'fingerprint' <> '' AND split_part(:'recorded', ':', 1) = :'fingerprint' AS resumed \gset + \if :resumed + SELECT split_part(:'recorded', ':', 2) AS mark, split_part(:'recorded', ':', 3) AS inplace \gset + \else + SELECT max(oid)::bigint AS mark, '' AS inplace FROM pg_class \gset + SELECT format('ALTER DATABASE %I SET cozystack.collation_repair = %L', current_database(), :'fingerprint' || ':' || :'mark') WHERE :'fingerprint' <> '' \gexec + \endif + SELECT index::bigint FROM cozystack_collation_index WHERE stale AND index::bigint <= :'mark'::bigint AND NOT EXISTS (SELECT FROM unnest(string_to_array(:'inplace', ',')) AS e JOIN pg_class r ON r.oid = index WHERE split_part(e, '/', 1) = index::text AND split_part(e, '/', 2) <> r.relfilenode::text) ORDER BY pg_relation_size(index); + EOT + ) + DB_FAILED="" + for index in $PLAN; do + LEFT=$((JOB_DEADLINE - SECONDS - 60)) + if [ "$LEFT" -lt 10 ]; then + echo "index $index in database $db was not rebuilt: the collation repair Job is out of time, the next upgrade of the release starts it again" >&2 + DB_FAILED=yes + continue + fi + if ! psql -v ON_ERROR_STOP=1 -q -t -A --dbname "$db" -v index="$index" -v lock_wait="${LEFT}s" <<\EOT + SET client_min_messages = error; + SET search_path = pg_catalog, pg_temp; + SET lock_timeout = :'lock_wait'; + SELECT EXISTS (SELECT FROM pg_index i JOIN pg_stat_progress_create_index p ON p.relid = i.indrelid JOIN pg_database d ON d.oid = p.datid WHERE i.indexrelid = :'index'::oid AND d.datname = current_database() AND p.pid <> pg_backend_pid()) AS building \gset + \if :building + SELECT format('DO %L', format('BEGIN RAISE EXCEPTION %L, %L; END', '%', format('index %s in database %s was skipped: another session is building an index of its table, as a rebuild left by an earlier repair does; the next upgrade of the release starts the repair again', :'index'::oid::regclass, current_database()))) \gexec + \endif + SELECT count(*) = 1 AS present FROM pg_index WHERE indexrelid = :'index'::oid \gset + \if :present + SELECT coalesce(current_setting('cozystack.collation_repair', true), '') AS recorded \gset + SELECT i.indrelid AS relation, i.indisexclusion AS exclusion, i.indexrelid::regclass AS name, :'index' || '/' || r.relfilenode AS attempt, + (SELECT count(*) FROM pg_index l JOIN pg_class n ON n.oid = l.indexrelid WHERE l.indrelid = i.indrelid AND NOT l.indisvalid AND n.relname ~ '_ccnew[0-9]*$') >= 2 AS abandoned, + (SELECT count(*) FROM unnest(string_to_array(split_part(:'recorded', ':', 3), ',')) AS e WHERE e = :'index' || '/' || r.relfilenode) >= 2 AS abandoned_in_place + FROM pg_index i JOIN pg_class r ON r.oid = i.indexrelid WHERE i.indexrelid = :'index'::oid \gset + \if :abandoned + SELECT format('DO %L', format('BEGIN RAISE EXCEPTION %L, %L; END', '%', format('index %s in database %s was left alone: two earlier runs failed to rebuild an index of its table, and each left an invalid _ccnew index there. Fix what made them fail, then drop those _ccnew indexes; the repair started by the next upgrade of the release rebuilds this one', :'name', current_database()))) \gexec + \endif + \if :exclusion + \if :abandoned_in_place + SELECT format('DO %L', format('BEGIN RAISE EXCEPTION %L, %L; END', '%', format('index %s in database %s was left alone: two earlier runs began rebuilding it in place and did not finish. Rebuild it by hand with REINDEX INDEX, which blocks its table meanwhile; the repair started by the next upgrade of the release sees that it was rebuilt', :'name', current_database()))) \gexec + \endif + SELECT format('rebuilding index %s in database %s in place: its collation changed version', :'name', current_database()); + SELECT format('ALTER DATABASE %I SET cozystack.collation_repair = %L', current_database(), split_part(:'recorded', ':', 1) || ':' || split_part(:'recorded', ':', 2) || ':' || concat_ws(',', nullif(split_part(:'recorded', ':', 3), ''), :'attempt')) WHERE :'recorded' <> '' \gexec + SET statement_timeout = :'lock_wait'; + SELECT format('REINDEX INDEX %s', :'name') \gexec + RESET statement_timeout; + \else + SELECT format('rebuilding index %s in database %s: its collation changed version', :'name', current_database()); + SELECT format('REINDEX INDEX CONCURRENTLY %s', :'name') \gexec + \endif + SELECT format('DROP INDEX CONCURRENTLY IF EXISTS %s', l.indexrelid::regclass) FROM pg_index l JOIN pg_class n ON n.oid = l.indexrelid WHERE l.indrelid = :'relation'::oid AND NOT l.indisvalid AND n.relname ~ '_ccnew[0-9]*$' \gexec + \endif + EOT + then + [ "${PIPESTATUS[0]}" != 2 ] || COLLATION_LOST=yes + DB_FAILED=yes + fi + done + if [ -n "$DB_FAILED" ]; then + COLLATION_FAILED="$COLLATION_FAILED $db" + else + collation_run "$db" <<\EOT + SELECT format('WARNING: database %s uses the locale %s, for which this PostgreSQL major records no collation version and the catalog has no collation to stand in; the indexes on its default collation were not checked. If this upgrade moved the image to another Debian release, rebuild them with REINDEX DATABASE', datname, datcollate) FROM pg_database WHERE datname = current_database() AND :'db_unmatched'::boolean AND :'moved'::boolean; + SELECT format('WARNING: %s in database %s is range-partitioned on a key whose collation changed version; rows stored before the change may now belong to another partition, %s', p.partrelid::regclass, current_database(), CASE WHEN bool_or(c.held) THEN 'and the collation version is left as recorded until that is checked' ELSE 'and no later run says so again: PostgreSQL records no version for that collation' END) FROM pg_partitioned_table p JOIN cozystack_collation c ON c.stale AND c.oid = ANY (p.partcollation::oid[]) WHERE p.partstrat = 'r' GROUP BY p.partrelid; + DO $$ + DECLARE + entry record; + BEGIN + FOR entry IN SELECT c.oid::regcollation AS name FROM cozystack_collation c WHERE c.stale AND NOT c.held AND c.oid <> 100 + AND NOT (current_setting('server_version_num')::int < 150000 + AND EXISTS (SELECT FROM cozystack_collation d WHERE d.oid = 100 AND d.held) + AND c.oid IN (SELECT n.oid FROM pg_collation n JOIN pg_database d ON d.datname = current_database() WHERE n.collprovider = 'c' AND lower(replace(n.collcollate, '-', '')) = lower(replace(d.datcollate, '-', '')))) LOOP + EXECUTE format('ALTER COLLATION %s REFRESH VERSION', entry.name); + END LOOP; + END$$; + SELECT format('ALTER DATABASE %I REFRESH COLLATION VERSION', current_database()) FROM cozystack_collation WHERE oid = 100 AND stale AND NOT held AND current_setting('server_version_num')::int >= 150000 \gexec + SELECT format('ALTER DATABASE %I SET cozystack.collation_release = %L', current_database(), :'release') WHERE :'release' NOT IN ('', :'repaired') \gexec + SELECT coalesce(md5(string_agg(oid || '=' || actual, ',' ORDER BY oid)), '') AS remaining FROM cozystack_collation WHERE stale AND held \gset + SELECT CASE WHEN :'remaining' = '' THEN '' ELSE :'remaining' || ':0' END AS settled \gset + SELECT CASE WHEN :'settled' = '' THEN format('ALTER DATABASE %I RESET cozystack.collation_repair', current_database()) ELSE format('ALTER DATABASE %I SET cozystack.collation_repair = %L', current_database(), :'settled') END WHERE coalesce(current_setting('cozystack.collation_repair', true), '') <> :'settled' \gexec + EOT + fi + done + if [ -n "$COLLATION_LOST" ]; then + echo "lost the connection to the server during index rebuilds in:$COLLATION_FAILED" >&2 + exit 2 + fi + if [ -n "$COLLATION_FAILED" ]; then + echo "index rebuilds failed in:$COLLATION_FAILED (the errors are above); the other indexes were rebuilt. A unique index cannot be rebuilt over rows that the previous ordering kept apart and the new one treats as equal, so remove such duplicates. The next upgrade of the release starts the repair again, except for an index an error above reports as left alone" >&2 + fi + [ -z "$COLLATION_FAILED" ] || exit 1 {{- end }} {{- if hasKey (.Values.users | default dict) "app" }} --- diff --git a/packages/apps/postgres/templates/locale-check-hook.yaml b/packages/apps/postgres/templates/locale-check-hook.yaml new file mode 100644 index 000000000..adbe922e1 --- /dev/null +++ b/packages/apps/postgres/templates/locale-check-hook.yaml @@ -0,0 +1,263 @@ +{{- /* + Runs before every upgrade of a cluster still on Debian bullseye, from the + image the cluster runs now. It looks for anything stored that depends on a + collation other than C, POSIX or builtin and records the answer on the + Cluster as the postgres.cozystack.io/locale-data annotation: clean, + affected, or unknown when the check could not finish. postgres.heldImageName + reads it, and only clean lets the cluster move. Helm renders the manifests + before this hook runs, so when the answer disagrees with what this attempt + rendered, the hook fails the attempt before the Cluster is patched and the + retry renders according to the new answer. +*/ -}} +{{- $liveImage := include "postgres.localeCheckImage" . }} +{{- if $liveImage }} +{{- $held := include "postgres.heldImageName" . }} +{{- /* Prefixed, not suffixed: CNPG names its ServiceAccount and Role after the + Cluster, and before-hook-creation would delete those of a release named + -locale-check. */}} +{{- $name := printf "locale-check-%s-%s" (.Release.Name | trunc 40 | trimSuffix "-") (.Release.Name | sha256sum | trunc 8) }} +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: {{ $name }} + annotations: + helm.sh/hook: pre-upgrade + helm.sh/hook-weight: "1" + helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: {{ $name }} + annotations: + helm.sh/hook: pre-upgrade + helm.sh/hook-weight: "1" + helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded +rules: +- apiGroups: ["postgresql.cnpg.io"] + resources: ["clusters"] + resourceNames: [{{ .Release.Name | quote }}] + verbs: ["get", "patch"] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: {{ $name }} + annotations: + helm.sh/hook: pre-upgrade + helm.sh/hook-weight: "1" + helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: {{ $name }} +subjects: +- kind: ServiceAccount + name: {{ $name }} + namespace: {{ .Release.Namespace | quote }} +--- +apiVersion: v1 +kind: Secret +metadata: + name: {{ $name }} + annotations: + helm.sh/hook: pre-upgrade + helm.sh/hook-weight: "1" + helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded +stringData: + {{- /* + Anything found is an answer, even when another database could not be + checked. The session settings override what a database owner may have set + with ALTER DATABASE, and the time budget ends the check before the Job + deadline, so that a slow check records unknown, which holds the cluster, + rather than failing every retry of the upgrade. + */}} + check.sh: | + set -u + export PGOPTIONS="-c default_transaction_read_only=off -c statement_timeout=60s -c lock_timeout=10s" + export PGCONNECT_TIMEOUT=10 + echo unknown > /work/verdict + : > /work/found + until pg_isready -q; do + if [ "$SECONDS" -ge 60 ]; then + echo "the server did not answer within 60s; the locale data of its databases is not checked" >&2 + exit 0 + fi + sleep 2 + done + psql -v ON_ERROR_STOP=1 -t -A -c "SELECT datname FROM pg_database WHERE datallowconn" > /work/databases || exit 0 + INCOMPLETE="" + CLOSED=$(psql -v ON_ERROR_STOP=1 -t -A -c "SELECT string_agg(datname, ', ') FROM pg_database WHERE NOT datallowconn AND datname <> 'template0'") || exit 0 + if [ -n "$CLOSED" ]; then + echo "databases that accept no connections are not checked: $CLOSED" >&2 + INCOMPLETE=yes + fi + while IFS= read -r db; do + if [ "$SECONDS" -ge 180 ]; then + echo "out of time before database $db was checked" >&2 + INCOMPLETE=yes + break + fi + PGDATABASE="$db" psql -v ON_ERROR_STOP=1 -q -t -A -f /scripts/check.sql >> /work/found || INCOMPLETE=yes + done < /work/databases + if [ -s /work/found ]; then + head -n 50 /work/found + echo affected > /work/verdict + elif [ -z "$INCOMPLETE" ]; then + echo clean > /work/verdict + fi + {{- /* + A collation is safe when its order and character classes cannot change + with the C library or ICU: C and POSIX, the builtin provider of PostgreSQL + 17, and the database default when that is one of them. C.UTF-8 is not: + Debian bullseye patches its order, glibc 2.35 and later sort by code point. + Objects below the first normal OID belong to the system catalogs, which + use C. + */}} + check.sql: | + SET search_path = pg_catalog, pg_temp; + SELECT current_setting('server_version_num')::int >= 150000 AS has_provider \gset + \if :has_provider + SELECT datlocprovider = 'b' OR (datlocprovider = 'c' AND datcollate IN ('C', 'POSIX') AND datctype IN ('C', 'POSIX')) AS default_safe FROM pg_database WHERE datname = current_database() \gset + \else + SELECT datcollate IN ('C', 'POSIX') AND datctype IN ('C', 'POSIX') AS default_safe FROM pg_database WHERE datname = current_database() \gset + \endif + WITH unsafe AS ( + SELECT c.oid FROM pg_collation c + WHERE NOT (c.collprovider = 'b' + OR (c.collprovider = 'c' AND c.collcollate IN ('C', 'POSIX') AND c.collctype IN ('C', 'POSIX')) + OR (c.collprovider = 'd' AND :'default_safe'::boolean)) + ) + SELECT DISTINCT format('%s: %s uses collation %s', current_database(), + pg_describe_object('pg_class'::regclass, a.attrelid, a.attnum), u.oid::regcollation) + FROM pg_attribute a + JOIN pg_class r ON r.oid = a.attrelid + JOIN unsafe u ON u.oid = a.attcollation + WHERE r.oid >= 16384 AND r.relkind IN ('r', 'p', 'm', 'i', 'c') AND r.relpersistence <> 't' + AND a.attnum > 0 AND NOT a.attisdropped + UNION + SELECT format('%s: %s depends on collation %s', current_database(), + pg_describe_object(d.classid, d.objid, d.objsubid), u.oid::regcollation) + FROM pg_depend d + JOIN unsafe u ON u.oid = d.refobjid + WHERE d.refclassid = 'pg_collation'::regclass AND d.objid >= 16384 + UNION + SELECT format('%s: range type %s uses collation %s', current_database(), + g.rngtypid::regtype, u.oid::regcollation) + FROM pg_range g + JOIN unsafe u ON u.oid = g.rngcollation + WHERE g.rngtypid >= 16384 + UNION + SELECT format('%s: %s orders jsonb strings by the database collation', current_database(), + pg_describe_object('pg_class'::regclass, a.attrelid, a.attnum)) + FROM pg_attribute a + JOIN pg_class r ON r.oid = a.attrelid + WHERE NOT :'default_safe'::boolean AND r.oid >= 16384 AND r.relkind = 'i' + AND a.attnum > 0 AND a.atttypid = 'jsonb'::regtype; +--- +apiVersion: batch/v1 +kind: Job +metadata: + name: {{ $name }} + annotations: + helm.sh/hook: pre-upgrade + helm.sh/hook-weight: "2" + {{- /* A failed Job stays, with its pod log, until the next attempt. */}} + helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded +spec: + activeDeadlineSeconds: 420 + backoffLimit: 0 + template: + metadata: + labels: + policy.cozystack.io/allow-to-apiserver: "true" + spec: + serviceAccountName: {{ $name }} + restartPolicy: Never + securityContext: + fsGroup: 26 + runAsGroup: 26 + runAsNonRoot: true + runAsUser: 26 + seccompProfile: + type: RuntimeDefault + initContainers: + - name: check + image: {{ $liveImage }} + command: [bash, /scripts/check.sh] + env: + - name: PGUSER + valueFrom: + secretKeyRef: + name: {{ .Release.Name }}-superuser + key: username + - name: PGPASSWORD + valueFrom: + secretKeyRef: + name: {{ .Release.Name }}-superuser + key: password + - name: PGHOST + value: {{ .Release.Name }}-rw + - name: PGPORT + value: "5432" + - name: PGDATABASE + value: postgres + securityContext: + allowPrivilegeEscalation: false + capabilities: + drop: + - ALL + readOnlyRootFilesystem: true + runAsNonRoot: true + volumeMounts: + - mountPath: /scripts + name: scripts + - mountPath: /work + name: work + {{- include "postgresjobs.resources" . | nindent 8 }} + containers: + - name: record + image: {{ include "cozy-lib.image" (list "clastix/kubectl:v1.32@sha256:b9ef7d8dbe65bcc81a46c09b8dc7543103055021c4f43287bf59e92a8f4fe05c" $) }} + command: [sh, -ec] + args: + - | + verdict=$(cat /work/verdict) + case "$verdict" in + affected) set -- "postgres.cozystack.io/locale-data-objects=$(head -n 20 /work/found | tr '\n' ';' | cut -c 1-4000)" ;; + clean) set -- "postgres.cozystack.io/locale-data-objects-" ;; + *) set -- ;; + esac + kubectl annotate --overwrite cluster.postgresql.cnpg.io/{{ .Release.Name }} postgres.cozystack.io/locale-data="$verdict" "$@" + {{- if not $held }} + if [ "$verdict" != clean ]; then + echo "postgres {{ .Release.Name }} stays on {{ $liveImage }}: the check found data that depends on a collation sorting differently on the new image, or could not finish (the check container log says which). The next attempt of this upgrade keeps the current image. Set allowCollationChange: true to move it, with the index rebuild, in a maintenance window." >&2 + exit 1 + fi + {{- else }} + if [ "$verdict" = clean ]; then + echo "postgres {{ .Release.Name }}: nothing in it depends on a changing collation any more, but this attempt was rendered with the held image {{ $liveImage }}; failing it so that the next attempt moves the cluster to the new image." >&2 + exit 1 + fi + {{- end }} + env: + - name: HOME + value: /work + securityContext: + allowPrivilegeEscalation: false + capabilities: + drop: + - ALL + readOnlyRootFilesystem: true + runAsNonRoot: true + volumeMounts: + - mountPath: /work + name: work + {{- include "postgresjobs.resources" . | nindent 8 }} + volumes: + - name: scripts + secret: + secretName: {{ $name }} + - name: work + emptyDir: {} +{{- end }} diff --git a/packages/apps/postgres/tests/collation_repair_test.yaml b/packages/apps/postgres/tests/collation_repair_test.yaml new file mode 100644 index 000000000..cdc3b95e2 --- /dev/null +++ b/packages/apps/postgres/tests/collation_repair_test.yaml @@ -0,0 +1,167 @@ +suite: the collation repair is started by a hook and runs outside the release + +# The repair waits for CNPG to roll the new image out and then rebuilds +# indexes; inside the init-job hook that wait alone outlasted the upgrade +# timeout. A post-install/post-upgrade hook now only starts a Job of its own +# through the API, so the hook must never render while bootstrap is on, must +# run after the init-job, and reach nothing but the repair Job and the Cluster. + +templates: + - templates/collation-repair.yaml + - templates/init-job.yaml + - templates/init-script.yaml + +release: + name: pg-test + namespace: tenant-test + +set: + _cluster: + scheduling: {} + users: + app: {} + +tests: + - it: renders the starter and its RBAC on install, to record the release the data starts on + template: templates/collation-repair.yaml + asserts: + - hasDocuments: + count: 4 + + - it: renders nothing while bootstrap is on, like the init-job it follows + template: templates/collation-repair.yaml + release: + upgrade: true + set: + bootstrap: + enabled: true + oldName: pg-old + asserts: + - hasDocuments: + count: 0 + + - it: renders the starter and its RBAC on upgrade + template: templates/collation-repair.yaml + release: + upgrade: true + asserts: + - hasDocuments: + count: 4 + + - it: runs the starter after the init-job, as a post-install and post-upgrade hook + template: templates/collation-repair.yaml + release: + upgrade: true + documentSelector: + path: kind + value: Job + asserts: + - equal: + path: metadata.annotations["helm.sh/hook"] + value: post-install,post-upgrade + - equal: + path: metadata.annotations["helm.sh/hook-weight"] + value: "1" + - equal: + path: spec.backoffLimit + value: 0 + - equal: + path: spec.activeDeadlineSeconds + value: 180 + - equal: + path: spec.template.spec.serviceAccountName + value: pg-test-collation-repair-start + - equal: + path: spec.template.metadata.labels["policy.cozystack.io/allow-to-apiserver"] + value: "true" + + - it: the init-job runs before the starter + template: templates/init-job.yaml + asserts: + - equal: + path: metadata.annotations["helm.sh/hook-weight"] + value: "-5" + + - it: limits the Role to the repair Job and the release's own Cluster + template: templates/collation-repair.yaml + release: + upgrade: true + documentSelector: + path: kind + value: Role + asserts: + - equal: + path: rules + value: + - apiGroups: ["batch"] + resources: ["jobs"] + resourceNames: ["pg-test-collation-repair"] + verbs: ["get", "delete"] + - apiGroups: ["batch"] + resources: ["jobs"] + verbs: ["create"] + - apiGroups: ["postgresql.cnpg.io"] + resources: ["clusters"] + resourceNames: ["pg-test"] + verbs: ["get"] + + - it: removes the RBAC once the hooks succeed + template: templates/collation-repair.yaml + release: + upgrade: true + documentSelector: + path: kind + value: RoleBinding + asserts: + - equal: + path: metadata.annotations["helm.sh/hook-delete-policy"] + value: before-hook-creation,hook-succeeded + - equal: + path: subjects[0].name + value: pg-test-collation-repair-start + + - it: keeps the starter and the repair Job apart for a long release name + template: templates/collation-repair.yaml + release: + name: postgres-a-name-at-the-53-character-release-name-limi + upgrade: true + documentSelector: + path: kind + value: Job + asserts: + - matchRegex: + path: metadata.name + pattern: ^.{1,40}-collation-repair-start$ + + - it: names the repair Job within 63 characters for a long release name + template: templates/collation-repair.yaml + release: + name: postgres-a-name-at-the-53-character-release-name-limi + upgrade: true + documentSelector: + path: kind + value: Role + asserts: + - matchRegex: + path: rules[0].resourceNames[0] + pattern: ^.{1,46}-collation-repair$ + + - it: the init-job runs its script through the reconnecting wrapper + template: templates/init-job.yaml + asserts: + - equal: + path: spec.template.spec.containers[0].command + value: [bash, /scripts/run.sh, /scripts/init.sh] + + - it: the init-script Secret carries the repair apart from the init script + template: templates/init-script.yaml + documentSelector: + path: metadata.name + value: pg-test-init-script + asserts: + - exists: + path: stringData["run.sh"] + - exists: + path: stringData["init.sh"] + - exists: + path: stringData["repair.sh"] diff --git a/packages/apps/postgres/tests/locale_guard_test.yaml b/packages/apps/postgres/tests/locale_guard_test.yaml new file mode 100644 index 000000000..4413760c2 --- /dev/null +++ b/packages/apps/postgres/tests/locale_guard_test.yaml @@ -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"] diff --git a/packages/apps/postgres/values.schema.json b/packages/apps/postgres/values.schema.json index bd5331788..c00ac7409 100644 --- a/packages/apps/postgres/values.schema.json +++ b/packages/apps/postgres/values.schema.json @@ -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 collation repair Job, which a post-upgrade hook starts once the init Job is done, rebuilds the indexes on such text after the rollout, those on C.UTF-8 and other C.* locales included, and its log reports a rebuild that failed; check range partitions, CHECK constraints and materialized views on it, which a rebuild does not fix. A held cluster shows the hold only as an unchanged image; the result and the objects found are in the `postgres.cozystack.io/locale-data` and `postgres.cozystack.io/locale-data-objects` annotations of the cnpg.io Cluster, which an administrator can read. A restore of a backup taken on one of those bullseye images comes back on that image and is checked by the next upgrade.", + "type": "boolean", + "default": false + }, "tls": { "description": "TLS configuration for server connections.", "type": "object", @@ -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": "" } } } diff --git a/packages/apps/postgres/values.yaml b/packages/apps/postgres/values.yaml index 3c6d68f59..2feb9d890 100644 --- a/packages/apps/postgres/values.yaml +++ b/packages/apps/postgres/values.yaml @@ -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 collation repair Job, which a post-upgrade hook starts once the init Job is done, rebuilds the indexes on such text after the rollout, those on C.UTF-8 and other C.* locales included, and its log reports a rebuild that failed; check range partitions, CHECK constraints and materialized views on it, which a rebuild does not fix. A held cluster shows the hold only as an unchanged image; the result and the objects found are in the `postgres.cozystack.io/locale-data` and `postgres.cozystack.io/locale-data-objects` annotations of the cnpg.io Cluster, which an administrator can read. A restore of a backup taken on one of those bullseye images comes back on that image and is checked by the next upgrade. +allowCollationChange: false + ## ## @section TLS configuration ## @@ -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: "" diff --git a/packages/system/postgres-rd/cozyrds/postgres.yaml b/packages/system/postgres-rd/cozyrds/postgres.yaml index ef67e44cd..b424650f8 100644 --- a/packages/system/postgres-rd/cozyrds/postgres.yaml +++ b/packages/system/postgres-rd/cozyrds/postgres.yaml @@ -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":"string"}},"roles":{"description":"Roles assigned to users.","type":"object","properties":{"admin":{"description":"List of users with admin privileges.","type":"array","items":{"type":"string"}},"readonly":{"description":"List of users with read-only privileges.","type":"array","items":{"type":"string"}}}}}}},"backup":{"description":"Backup configuration.","type":"object","default":{},"required":["enabled"],"properties":{"destinationPath":{"description":"DEPRECATED. Per-tenant S3 configuration is superseded by the platform-managed `cozy-default` BackupClass and the `cozy-backups` system bucket. Leave empty for new installations; the BackupClass driver picks up the system-managed coordinates. Kept for in-place upgrade compatibility.","type":"string","default":"s3://bucket/path/to/folder/"},"enabled":{"description":"Enable regular backups.","type":"boolean","default":false},"endpointCA":{"description":"DEPRECATED. Pre-existing Secret with the CA bundle the barman-cloud plugin should trust when reaching a self-signed S3 endpoint. Used for both backup and bootstrap recovery in the legacy chart-managed flow.","type":"object","default":{},"properties":{"key":{"description":"Key within the Secret containing the CA bundle. Defaults to `ca.crt`.","type":"string","default":""},"name":{"description":"Name of the Secret in the application namespace. Empty means no endpointCA is emitted (the plugin uses the system trust store).","type":"string","default":""}}},"endpointURL":{"description":"DEPRECATED. See `destinationPath`.","type":"string","default":"http://minio-gateway-service:9000"},"retentionPolicy":{"description":"Retention policy (e.g. \"30d\").","type":"string","default":"30d"},"s3AccessKey":{"description":"DEPRECATED. Tenants no longer supply S3 keys; the system Bucket Secret is projected into the tenant namespace by the backup controller. Ignored when `s3CredentialsSecret.name` is set or `useSystemBucket` is true. The chart skips materialising `-s3-creds` whenever this field is empty so a default install does not leak placeholder credentials into the tenant namespace.","type":"string","default":""},"s3CredentialsSecret":{"description":"DEPRECATED. Pre-existing Secret with S3 credentials. Use the platform-managed `cozy-default` BackupClass instead. When set, the chart references this Secret directly (legacy chart-managed flow). The CNPG backup driver writes this field on restore so credentials never land in the CR `.spec`.","type":"object","default":{},"properties":{"accessKeyIDKey":{"description":"Key in the Secret holding the access key ID. Defaults to `AWS_ACCESS_KEY_ID`.","type":"string","default":""},"name":{"description":"Name of the Secret in the application namespace. Empty means the chart materialises `-s3-creds` from `s3AccessKey`/`s3SecretKey`.","type":"string","default":""},"secretAccessKeyKey":{"description":"Key in the Secret holding the secret access key. Defaults to `AWS_SECRET_ACCESS_KEY`.","type":"string","default":""}}},"s3SecretKey":{"description":"DEPRECATED. See `s3AccessKey`.","type":"string","default":""},"schedule":{"description":"Legacy. Cron schedule for the chart-emitted ScheduledBackup, either a standard five-field cron such as `0 2 * * *` for every day at 02:00, or six fields with leading seconds such as `0 0 2 * * *` for the same time. Empty means no chart-managed schedule, which is the recommended setup when a `BackupClass` from `backups.cozystack.io` already drives backup orchestration. In the legacy chart-managed flow `spec.plugins` plus the barman-cloud ObjectStore is rendered when `backup.enabled=true` AND `useSystemBucket=false` AND `destinationPath` is non-empty AND inline-or-external creds are supplied; in the platform `useSystemBucket=true` flow the chart skips emitting `spec.plugins` and the CNPG driver SSA-applies the ObjectStore and patches `spec.plugins` onto the live Cluster at first BackupJob time.","type":"string","default":""},"useSystemBucket":{"description":"Opt-in: when true, the chart-emitted `-s3-creds` Secret is skipped AND `spec.plugins` (plus the barman-cloud ObjectStore) is left UNSET in the chart-rendered Cluster — the cozy-default BackupClass driver SSA-applies an ObjectStore (carrying destinationPath/endpointURL/credentials) and patches `spec.plugins` on the live Cluster when the first BackupJob runs. Consequence: plugin WAL archiving is NOT active until that first BackupJob fires; WAL accumulates on the PVC in the meantime, so fire an ad-hoc BackupJob immediately after enabling the flag on existing releases. Use together with the platform `cozy-default` BackupClass — tenants do not need to fill `s3AccessKey`/`s3SecretKey` or `destinationPath`/`endpointURL`. The destination path automatically scopes to `s3://cozy-backups///`.","type":"boolean","default":false}}},"bootstrap":{"description":"Bootstrap configuration.","type":"object","default":{},"required":["enabled","oldName"],"properties":{"enabled":{"description":"Whether to restore from a backup.","type":"boolean","default":false},"newServerName":{"description":"WAL-archive server name (S3 path prefix) the RESTORED cluster writes to. Must differ from `serverName` (the recovery source) so a restored cluster archives to a fresh, empty prefix and barman-cloud-check-wal-archive passes while it recovers from the source's prefix. The CNPG backup driver sets this on restore; empty means the cluster archives under its own name.","type":"string","default":""},"oldName":{"description":"Previous cluster name before deletion.","type":"string","default":""},"recoveryTime":{"description":"Timestamp (RFC3339) for point-in-time recovery; empty means latest.","type":"string","default":""},"serverName":{"description":"Server name (S3 path prefix) used by the original cluster when writing backups; passed to the barman-cloud plugin via `externalClusters[].plugin.parameters.serverName`. Defaults to `bootstrap.oldName`. Set this only when the original cluster wrote backups under an explicit server name that differed from its Kubernetes resource name.","type":"string","default":""}}}}} + {"title":"Chart Values","type":"object","properties":{"replicas":{"description":"Number of Postgres replicas.","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 collation repair Job, which a post-upgrade hook starts once the init Job is done, rebuilds the indexes on such text after the rollout, those on C.UTF-8 and other C.* locales included, and its log reports a rebuild that failed; check range partitions, CHECK constraints and materialized views on it, which a rebuild does not fix. A held cluster shows the hold only as an unchanged image; the result and the objects found are in the `postgres.cozystack.io/locale-data` and `postgres.cozystack.io/locale-data-objects` annotations of the cnpg.io Cluster, which an administrator can read. A restore of a backup taken on one of those bullseye images comes back on that image and is checked by the next upgrade.","type":"boolean","default":false},"tls":{"description":"TLS configuration for server connections.","type":"object","default":{},"properties":{"enabled":{"description":"Tri-state switch controlling whether the chart injects the external 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":"string"}},"roles":{"description":"Roles assigned to users.","type":"object","properties":{"admin":{"description":"List of users with admin privileges.","type":"array","items":{"type":"string"}},"readonly":{"description":"List of users with read-only privileges.","type":"array","items":{"type":"string"}}}}}}},"backup":{"description":"Backup configuration.","type":"object","default":{},"required":["enabled"],"properties":{"destinationPath":{"description":"DEPRECATED. Per-tenant S3 configuration is superseded by the platform-managed `cozy-default` BackupClass and the `cozy-backups` system bucket. Leave empty for new installations; the BackupClass driver picks up the system-managed coordinates. Kept for in-place upgrade compatibility.","type":"string","default":"s3://bucket/path/to/folder/"},"enabled":{"description":"Enable regular backups.","type":"boolean","default":false},"endpointCA":{"description":"DEPRECATED. Pre-existing Secret with the CA bundle the barman-cloud plugin should trust when reaching a self-signed S3 endpoint. Used for both backup and bootstrap recovery in the legacy chart-managed flow.","type":"object","default":{},"properties":{"key":{"description":"Key within the Secret containing the CA bundle. Defaults to `ca.crt`.","type":"string","default":""},"name":{"description":"Name of the Secret in the application namespace. Empty means no endpointCA is emitted (the plugin uses the system trust store).","type":"string","default":""}}},"endpointURL":{"description":"DEPRECATED. See `destinationPath`.","type":"string","default":"http://minio-gateway-service:9000"},"retentionPolicy":{"description":"Retention policy (e.g. \"30d\").","type":"string","default":"30d"},"s3AccessKey":{"description":"DEPRECATED. Tenants no longer supply S3 keys; the system Bucket Secret is projected into the tenant namespace by the backup controller. Ignored when `s3CredentialsSecret.name` is set or `useSystemBucket` is true. The chart skips materialising `-s3-creds` whenever this field is empty so a default install does not leak placeholder credentials into the tenant namespace.","type":"string","default":""},"s3CredentialsSecret":{"description":"DEPRECATED. Pre-existing Secret with S3 credentials. Use the platform-managed `cozy-default` BackupClass instead. When set, the chart references this Secret directly (legacy chart-managed flow). The CNPG backup driver writes this field on restore so credentials never land in the CR `.spec`.","type":"object","default":{},"properties":{"accessKeyIDKey":{"description":"Key in the Secret holding the access key ID. Defaults to `AWS_ACCESS_KEY_ID`.","type":"string","default":""},"name":{"description":"Name of the Secret in the application namespace. Empty means the chart materialises `-s3-creds` from `s3AccessKey`/`s3SecretKey`.","type":"string","default":""},"secretAccessKeyKey":{"description":"Key in the Secret holding the secret access key. Defaults to `AWS_SECRET_ACCESS_KEY`.","type":"string","default":""}}},"s3SecretKey":{"description":"DEPRECATED. See `s3AccessKey`.","type":"string","default":""},"schedule":{"description":"Legacy. Cron schedule for the chart-emitted ScheduledBackup, either a standard five-field cron such as `0 2 * * *` for every day at 02:00, or six fields with leading seconds such as `0 0 2 * * *` for the same time. Empty means no chart-managed schedule, which is the recommended setup when a `BackupClass` from `backups.cozystack.io` already drives backup orchestration. In the legacy chart-managed flow `spec.plugins` plus the barman-cloud ObjectStore is rendered when `backup.enabled=true` AND `useSystemBucket=false` AND `destinationPath` is non-empty AND inline-or-external creds are supplied; in the platform `useSystemBucket=true` flow the chart skips emitting `spec.plugins` and the CNPG driver SSA-applies the ObjectStore and patches `spec.plugins` onto the live Cluster at first BackupJob time.","type":"string","default":""},"useSystemBucket":{"description":"Opt-in: when true, the chart-emitted `-s3-creds` Secret is skipped AND `spec.plugins` (plus the barman-cloud ObjectStore) is left UNSET in the chart-rendered Cluster — the cozy-default BackupClass driver SSA-applies an ObjectStore (carrying destinationPath/endpointURL/credentials) and patches `spec.plugins` on the live Cluster when the first BackupJob runs. Consequence: plugin WAL archiving is NOT active until that first BackupJob fires; WAL accumulates on the PVC in the meantime, so fire an ad-hoc BackupJob immediately after enabling the flag on existing releases. Use together with the platform `cozy-default` BackupClass — tenants do not need to fill `s3AccessKey`/`s3SecretKey` or `destinationPath`/`endpointURL`. The destination path automatically scopes to `s3://cozy-backups///`.","type":"boolean","default":false}}},"bootstrap":{"description":"Bootstrap configuration.","type":"object","default":{},"required":["enabled","oldName"],"properties":{"enabled":{"description":"Whether to restore from a backup.","type":"boolean","default":false},"newServerName":{"description":"WAL-archive server name (S3 path prefix) the RESTORED cluster writes to. Must differ from `serverName` (the recovery source) so a restored cluster archives to a fresh, empty prefix and barman-cloud-check-wal-archive passes while it recovers from the source's prefix. The CNPG backup driver sets this on restore; empty means the cluster archives under its own name.","type":"string","default":""},"oldName":{"description":"Previous cluster name before deletion.","type":"string","default":""},"recoveryTime":{"description":"Timestamp (RFC3339) for point-in-time recovery; empty means latest.","type":"string","default":""},"serverName":{"description":"Server name (S3 path prefix) used by the original cluster when writing backups; passed to the barman-cloud plugin via `externalClusters[].plugin.parameters.serverName`. Defaults to `bootstrap.oldName`. Set this only when the original cluster wrote backups under an explicit server name that differed from its Kubernetes resource name.","type":"string","default":""},"sourceImageName":{"description":"Image of the cluster the backup was taken from. A restore of a backup taken on one of the bare Debian bullseye tags the chart used before standard-trixie comes back on that image (see `allowCollationChange`); any other value is ignored. The CNPG backup driver sets this on every restore, and clears it when the backup carries no image.","type":"string","default":""}}}}} 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: