diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 42861b6..f5fa0b7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -128,8 +128,11 @@ jobs: - shard: kube-nginx-joins # the NPM joins suite behind the nginx edge run: ^TestKubernetesNginxEdgeJoins$ pkgs: ./test/e2e/ + - shard: kube-cluster-upgrade # CloudNativePG 17 to 18, copies and the rollback from them + run: ^TestKubernetesIdentityDatabaseClusterUpgrade$ + pkgs: ./test/e2e/ - shard: rest # 3.5 min - skip: ^(TestKubernetesNPMEdge|TestKubernetesNPMEdgeJoins|TestKubernetesNginxEdge|TestKubernetesNginxEdgeJoins|TestKubernetesNginxEdgeFailover|TestKubernetesKyMessage|TestKubernetesApply|TestKubernetesRestore|TestKubernetesKyYard)$ + skip: ^(TestKubernetesIdentityDatabaseClusterUpgrade|TestKubernetesNPMEdge|TestKubernetesNPMEdgeJoins|TestKubernetesNginxEdge|TestKubernetesNginxEdgeJoins|TestKubernetesNginxEdgeFailover|TestKubernetesKyMessage|TestKubernetesApply|TestKubernetesRestore|TestKubernetesKyYard)$ pkgs: ./test/e2e/ ./internal/edge/ runs-on: ubuntu-latest timeout-minutes: 45 diff --git a/AGENTS.md b/AGENTS.md index 105de89..a5cc87b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -613,8 +613,7 @@ edge compatibility: `docs/redirect.md`. `database_instances: 3-5` beside `replicas`, never with `database_secret`, replaces Deployment `database` with a CloudNativePG `Cluster` of that name (`postgresql.cnpg.io/v1`, written through the dynamic client with strict field validation): the catalog's - `replicas.cluster_image` (a CloudNativePG operand image; PostgreSQL 17, since the installer - has no backup of a Cluster to take before CloudNativePG's major upgrade), required + `replicas.cluster_image` (a CloudNativePG operand image, PostgreSQL 18 on trixie), required anti-affinity by node, synchronous replication `ANY 1`, the same UTF8/C database and non-superuser owner, taken from `kyq-database` (basic-auth here: `username`, `password`, `url`). The operator is the catalog's `cloudnative-pg` (next) or the cluster owner's: `DatabaseOperatorCheck` (preflight @@ -628,6 +627,28 @@ edge compatibility: `docs/redirect.md`. `stop` and `uninstall` hibernate the `Cluster` (`cnpg.io/hibernation`) and never delete it: it owns its claims. Between the single pod and the `Cluster` is a database move, refused like any other (`kyquickstart/database` is `cluster`). + A `Cluster` whose data is an older major (17, from earlier releases; owner decision + 2026-11-25, `internal/kube/dbupgrade.go`) moves only in step `.database-upgrade`, before + deploy: create claim `pre-upgrade-pg--` for every claim the Cluster + owns, a new set per attempt, and start each instance's copy pod once on its node while it runs + (a refused or unprovisioned claim stops nothing), hibernate, copy and verify each + (`copyCommand`, uid 26, one pod per instance; only `PG_DATA` claims: a WAL or tablespace claim, + never the installer's, refuses first), then one patch sets the new `imageName` and wakes it for CloudNativePG's in-place + `pg_upgrade --link` (operator 1.26+); then wait healthy and `vacuumdb --analyze-only + --missing-stats-only`. Cluster patches never carry a resourceVersion (the operator writes its + status constantly); the switch and the wake carry the Cluster's `metadata.uid`, and the switch + first re-reads it (same uid, still hibernated on the old image). Anything failing after the hibernation is requested (its write may land + unanswered) gets one patch: hibernation off and the old `imageName`, except a switch whose + answer is lost: re-read, it is left to the wait when the new image is set, and reported without + any write when the Cluster cannot be read. Copies' `instance-role` is taken from the claims as + the Cluster stopped (a failover before then moves the primary), and a changed claim set + refuses; an + upgrade still on old data after `clusterTimeout` gets the old image back (CloudNativePG's + rollback). Deploy's `applyCluster` refuses any major change itself. The copies (labels + `kyquickstart/postgres`, `copy-of`, `instance`, `instance-role`; annotations `copied-at`, + `cluster-uid`) are never deleted or replaced, by `prune-copies` either. Rollback is by hand from the primary's copy + (`docs/guided-setup.md`, "Going back to PostgreSQL 17"). The plan's permissions add list on + claims. - The database operator (owner amendment, 2026-11-14; `internal/kube/operator.go`, `docs/guided-setup.md`): the catalog app `cloudnative-pg`, category `operator`, Kubernetes only, written in `stack.yaml` and never asked by `plan`. `kubernetes.operator` names its @@ -742,6 +763,11 @@ calls and kind nodes must carry their own explicit bounds. restored with the manifest's command); `scripts/test-postgres-17-to-18-pod.sh` runs the previous and current database pod specs in Docker as a kubelet would, with the same rollback cases (not Kubernetes itself). +- CI's `e2e (kube-cluster-upgrade)` shard: `TestKubernetesIdentityDatabaseClusterUpgrade` + (three kind workers, the catalog's KyIdentity and CloudNativePG) installs on a 17 `Cluster`, + seeds rows and a password role, applies this release (rows, the role's password over the + network and a wrong one refused, a session made on 17, three verified copies, an idle second + apply), then goes back to 17 from the primary's copy by the documented steps. - `make workflow-lint`: needs Docker (CI runs it in `vulncheck`); actionlint v1.7.12 on every workflow and offline, digest-pinned zizmor (medium and up) on `release-image.yml` and `dependency-release.yml`. diff --git a/CHANGELOG.md b/CHANGELOG.md index 7b9d912..e95ef37 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,7 +22,17 @@ state directory, target data and target-held credentials; do not reset them as a data free. Removing the 17 data afterwards is a manual step (`docs/guided-setup.md`). After a rollback that ran 17, deploying 18 again refuses until you choose to move 17 again or keep 18 (same doc). A one-shot service that fails (the 17 dump) fails `apply`, `start` and health at - once, with its logs. CloudNativePG clusters stay on 17. + once, with its logs. +- PostgreSQL 18 for the highly available KyIdentity database (`database_instances`). A + CloudNativePG `Cluster` on 17 is hibernated, every instance's claim is copied and verified, + and only then does CloudNativePG upgrade it in place; fresh Clusters start on 18. + **Upgrade impact:** sign-in is down for the copy and the upgrade; the copies need as much + storage as the Cluster's claims and are never deleted for you; CloudNativePG 1.26 or later is + required, and the plan's kubeconfig needs list on persistentvolumeclaims. Storage that cannot + hold the copies is refused before the Cluster stops; anything that fails once it is + hibernated starts it again on 17, unchanged. Each attempt makes its own timestamped copies, + beside any an earlier attempt left. Going back to 17 is by hand from the copies + (`docs/guided-setup.md`, "Going back to PostgreSQL 17"). - Follow KyPost, KyCalendar and KyYard `0.6.1.1` with verified release image digests. KyPost includes the receiving accelerator and file-lock/fsync fixes; KyCalendar and KyYard refresh their Alpine base. **Upgrade impact:** the selected apps restart on diff --git a/docs/guided-setup.md b/docs/guided-setup.md index 7949256..2990a10 100644 --- a/docs/guided-setup.md +++ b/docs/guided-setup.md @@ -830,20 +830,22 @@ reach it, and it can reach nothing. Read this before choosing it: **The installer's, highly available (`database_instances`).** Owner amendment, 2026-11-13. `database_instances: 3` (3 to 5) replaces that one pod with a -[CloudNativePG](https://cloudnative-pg.io/) `Cluster` named `database`: that many Postgres 17 +[CloudNativePG](https://cloudnative-pg.io/) `Cluster` named `database`: that many PostgreSQL 18 instances, each on its own claim (2 GiB) and never two on one node. One is the primary. A write is acknowledged once a second instance has it, so a failover loses nothing KyIdentity was told is saved, and the operator promotes a standby when the primary's node is lost. With three instances, sign-in survives the loss of any one node. It needs: -- **The CloudNativePG operator** (1.24 or later; tested against 1.30.1): the catalog's +- **The CloudNativePG operator** (1.24 or later, 1.26 or later to move a Cluster from + PostgreSQL 17; tested against 1.30.1): the catalog's `cloudnative-pg` app in the same plan ([below](#the-cloudnative-pg-operator)), or one the cluster's owner installed. Preflight and apply refuse the plan on a cluster that does not serve `postgresql.cnpg.io/v1` Clusters. - **As many schedulable nodes as instances.** An instance with no node of its own stays pending, and apply reports how many are ready. - **Permission on Clusters**: get, create, update and patch on `postgresql.cnpg.io` - `clusters`, asked only of a plan with `database_instances`. + `clusters`, and list on `persistentvolumeclaims` (the move from 17 finds the Cluster's + claims), asked only of a plan with `database_instances`. What differs from the single pod: @@ -866,9 +868,129 @@ What differs from the single pod: The first apply takes several minutes: the instances start one after another, each copying the one before, and KyIdentity's pods start once all are ready (15 minutes at most, then apply stops and names the `kubectl describe` to read). The installer still does not back the -database up: KyIdentity's own backups (below) are its only backup. It does not upgrade -Postgres across major versions: a `Cluster` stays on PostgreSQL 17 (17.12), supported until -November 2029, until the installer has a backup of it to take first. +database up: KyIdentity's own backups (below) are its only backup. + +#### PostgreSQL 17 to 18 + +Owner decision, 2026-11-25. A `Cluster` made by an earlier release runs PostgreSQL 17 (operand +`ghcr.io/cloudnative-pg/postgresql:17.12-minimal-trixie`). This release's is 18.7 on the same +Debian trixie base (`18.7-minimal-trixie`, digest `c8caac98…88cc`). A fresh `Cluster` starts on +18. An existing one moves on the next `apply` or `upgrade`, in step `kyidentity.database-upgrade`, +before anything else of KyIdentity changes: + +1. **Copies first, while it runs.** For every claim the `Cluster` owns (`database-1`, + `database-2`, …; a `Cluster` the installer made keeps its WAL inside them, and a separate + WAL or tablespace claim refuses the upgrade before anything stops) the installer creates claim + `pre-upgrade-pg17--`: the same size and StorageClass. Every + attempt makes its own; a copy an earlier attempt left is never replaced or deleted. Then one + pod per instance, on that instance's node, mounts its copies while the `Cluster` still + runs, so the storage provisions them before sign-in stops. If the cluster refuses a claim + (quota, class) or cannot provide it, apply stops there: nothing was stopped, and the message + names every earlier copy taking space, which you may delete. Storage that provisions more + than it has (thin, or node-local such as `local-path`) can still pass this and fill up + during step 3. +2. **Hibernate.** The `Cluster` is hibernated (CloudNativePG's declarative hibernation, a clean + shutdown) and apply waits until no instance pod runs. Sign-in stops from here until step 4. +3. **Copy and verify.** One pod per instance, as the instances' own user (uid 26), copies + `pgdata/` of each claim into its copy and compares contents, modes, owners, + sizes and times with the original, as other apps' pre-upgrade copies do + ([Managing apps](#managing-apps)). Anything that fails from step 2 on, a copy that fails or + does not fit included, wakes the `Cluster` on its PostgreSQL 17 image, unchanged, and apply + fails with the reason and the list of copies. Fix the cause and apply again; the next run + makes new copies beside the earlier ones, which stay until you delete them. Each copy's + `kyquickstart/instance-role` is the instance's role as the `Cluster` stopped, so a + failover just before is accounted for. +4. **Upgrade.** One write sets the 18 image and wakes the `Cluster`. CloudNativePG runs its + [offline in-place major upgrade](https://cloudnative-pg.io/documentation/current/postgres_upgrades/) + (`pg_upgrade --link` in a job on the primary's claim). On success it deletes the replicas' + claims and clones them again from the primary. An operator older than 1.26 refuses the + image: the `Cluster` is woken on 17 and apply says so. If that write's answer is lost, + apply reads the `Cluster` again: with the 18 image set, the upgrade is under way and apply + waits for it as below (never setting 17 back); if the `Cluster` cannot be read, apply writes + nothing more and tells you how to check `imageName` yourself. +5. **Healthy, then `ANALYZE`.** Apply waits for every instance to be ready on 18 (15 minutes + at most), then runs `vacuumdb --all --analyze-only --missing-stats-only` on the primary for + the statistics `pg_upgrade` does not carry. If that fails, apply prints the command to run. + +If the upgrade has not finished after 15 minutes and the data is still 17, apply does what +CloudNativePG documents for a failed upgrade: it sets the 17 image back, the operator deletes +the upgrade's job and the `Cluster` starts on its unchanged 17 data. Apply fails and says so. +If the data is already 18 and only the replicas are still cloning, apply fails asking you to +apply again, which waits for them. + +**Space and time.** The copies need as much storage as the `Cluster`'s claims (with three +instances, three times the database), from the same StorageClass. On node-local storage each +copy is made on its instance's node. Sign-in is down for the copy plus the upgrade: for +KyIdentity's database, usually a few minutes. + +**The copies stay.** Apply's note for the step names them, verified or not, with the +`kubectl delete pvc` command that removes them. They carry the labels +`kyquickstart/postgres=17`, `kyquickstart/copy-of=`, `kyquickstart/instance=` +and `kyquickstart/instance-role=primary|replica`, and the annotations `kyquickstart/copied-at` +(UTC) and `kyquickstart/pre-upgrade: verified`. List them with +`kubectl -n kyq-kyidentity get pvc -l kyquickstart/postgres=17 -L kyquickstart/instance-role`. +Nothing deletes them, `prune-copies` included. Once you are satisfied with 18, deleting them is +your choice: `kubectl -n kyq-kyidentity delete pvc -l kyquickstart/postgres=17`. + +#### Going back to PostgreSQL 17 + +CloudNativePG cannot move a `Cluster` back to an older major. Going back means recreating the +`Cluster` from the primary's copy, which holds the data as it was when the move began; anything +written on 18 since is lost. This was run end to end in +`TestKubernetesIdentityDatabaseClusterUpgrade` (`test/e2e`). With `kubectl` on namespace +`kyq-kyidentity`: + +1. Find the primary's copy, its volume, class and size: + + ```sh + kubectl -n kyq-kyidentity get pvc -l kyquickstart/postgres=17,kyquickstart/instance-role=primary + COPY=pre-upgrade-pg17-database-1-20261125-231556 # the verified name printed above + PV=$(kubectl -n kyq-kyidentity get pvc $COPY -o jsonpath='{.spec.volumeName}') + kubectl -n kyq-kyidentity get pvc $COPY -o jsonpath='{.spec.storageClassName} {.spec.resources.requests.storage}{"\n"}' + ``` + +2. Keep that volume when its claim goes: `kubectl patch pv $PV -p '{"spec":{"persistentVolumeReclaimPolicy":"Retain"}}'`. +3. Delete the 18 `Cluster`. **This deletes its claims, the 18 data.** Copy them first if you + may want them. `kubectl -n kyq-kyidentity delete cluster database --wait`, then wait until + `kubectl -n kyq-kyidentity get pvc -l cnpg.io/cluster=database` lists none. +4. Free the volume: `kubectl -n kyq-kyidentity delete pvc $COPY`, then + `kubectl patch pv $PV --type json -p '[{"op":"remove","path":"/spec/claimRef"}]'`. +5. Give it to the new `Cluster`'s first instance, as CloudNativePG labels its claims (fill in + the class, size and volume from step 1): + + ```yaml + apiVersion: v1 + kind: PersistentVolumeClaim + metadata: + name: database-1 + namespace: kyq-kyidentity + labels: + cnpg.io/cluster: database + cnpg.io/instanceName: database-1 + cnpg.io/instanceRole: primary + role: primary + cnpg.io/pvcRole: PG_DATA + annotations: + cnpg.io/nodeSerial: "1" + cnpg.io/pvcStatus: ready + spec: + accessModes: [ReadWriteOnce] + storageClassName: + volumeName: + resources: + requests: + storage: + ``` + + `kubectl apply -f` it. +6. `apply` with the previous KyQuickStart release, whose image is 17.12. It creates the + `Cluster` again; CloudNativePG finds the claim without an owner and starts the primary on it + (its restore of a `Cluster` from existing claims), then clones the other instances. + KyIdentity's Secrets were never removed, so its pods sign in with the same password. + +The other copies stay until you delete them. An apply with this release afterwards moves the +`Cluster` to 18 again with new copies; the earlier `Cluster`'s (annotation +`kyquickstart/cluster-uid`) are left alone and only named when space runs short. ### The CloudNativePG operator @@ -953,7 +1075,9 @@ choose who can open a backup: Apply prints this as an outstanding step after every run, and says plainly when no key is set that KyIdentity has no backup. Pre-upgrade copies of claims do not cover a replicated -KyIdentity, and `kyquickstart backup` covers Docker apps only. +KyIdentity's upgrades, and `kyquickstart backup` covers Docker apps only. The copies of a +`Cluster`'s claims made for [its move to PostgreSQL 18](#postgresql-17-to-18) are no backup +either: they hold the data as it was then. ### What it does not do diff --git a/internal/catalog/apps/kyidentity/manifest.yaml b/internal/catalog/apps/kyidentity/manifest.yaml index b2d96ef..36431a0 100644 --- a/internal/catalog/apps/kyidentity/manifest.yaml +++ b/internal/catalog/apps/kyidentity/manifest.yaml @@ -18,9 +18,10 @@ images: # and the 17 its init container runs once to dump a 17 database for 18 to restore. postgres: postgres:18.7-alpine3.24@sha256:0115267ab5a509022df9319c77be365cef335adb71556c75f60f5360ee247e71 postgres_17: postgres:17.12-alpine3.24@sha256:f9cf3e1f0066f0eb0c48707d864f0ac5941e9ff454a072077d97a4d278d07d73 - # The same, with database_instances in the plan: the CloudNativePG community's Postgres 17 - # operand image (17.12 on Debian trixie, no extras), which the cluster's operator runs. - postgres_cluster: ghcr.io/cloudnative-pg/postgresql:17.12-minimal-trixie@sha256:4ae89311e5031155a139a5c6d31a80f6deb135443711e61ff7df41cb549fdcaa + # The same, with database_instances in the plan: the CloudNativePG community's PostgreSQL 18 + # operand image (18.7 on Debian trixie, no extras, like the 17.12 earlier releases ran), which + # the cluster's operator runs. A Cluster on 17 is copied, then upgraded in place. + postgres_cluster: ghcr.io/cloudnative-pg/postgresql:18.7-minimal-trixie@sha256:c8caac9817d2b5e5e66297a3ccf86d9fcbd68f097aa6cc00161d83f9635e88cc health: timeout_seconds: 300 # Its signing, session and encryption keys are generated in the data directory on first start. diff --git a/internal/kube/app.go b/internal/kube/app.go index 2313d50..7ee1351 100644 --- a/internal/kube/app.go +++ b/internal/kube/app.go @@ -46,7 +46,8 @@ func hashOf(parts ...string) string { return hex.EncodeToString(h.Sum(nil)) } -// Steps returns the app's install steps: secrets, deploy, health, and for NPM its bootstrap. +// Steps returns the app's install steps: secrets, a Cluster's major upgrade, deploy, health, +// and for NPM its bootstrap. func Steps(a App) []engine.Step { if a.operator() { step := operatorStep{a} @@ -57,6 +58,9 @@ func Steps(a App) []engine.Step { if a.replicated() { steps = append(steps, replicaSecretsStep{a}) } + if a.clustered() { + steps = append(steps, clusterUpgradeStep{a: a, note: new(string)}) + } steps = append(steps, deployStep{a: a, hash: hash}, healthStep{a: a, hash: hash}) if a.Name == "npm" && a.Catalog.Category == "edge" { steps = append(steps, npmBootstrapStep{a}) diff --git a/internal/kube/dbcluster.go b/internal/kube/dbcluster.go index d130302..bd3135a 100644 --- a/internal/kube/dbcluster.go +++ b/internal/kube/dbcluster.go @@ -60,7 +60,8 @@ var clusterAccess = func() []authorizationv1.ResourceAttributes { for _, v := range []string{"get", "create", "update", "patch"} { out = append(out, authorizationv1.ResourceAttributes{Group: clusterGroup, Resource: clusterResource.Resource, Verb: v}) } - return out + // The major upgrade finds the claims the Cluster owns. + return append(out, authorizationv1.ResourceAttributes{Resource: "persistentvolumeclaims", Verb: "list"}) }() // clustered reports whether the installer's Postgres is a CloudNativePG Cluster. @@ -218,6 +219,13 @@ func (c *Client) applyCluster(ctx context.Context, a App, spec map[string]any, h want.SetNamespace(namespaceOf(a.Name)) want.SetLabels(workloadLabels(a.ReleaseSet)) want.SetAnnotations(map[string]string{hashAnnotation: hash}) + // Only the database-upgrade step, after its copies, moves the data to another major. + if have != nil { + image, _, _ := unstructured.NestedString(have.Object, "spec", "imageName") + if from, to := imageMajor(image), imageMajor(spec["imageName"].(string)); from != to { + return fmt.Errorf("cluster %s runs PostgreSQL %d, and this release's is %d: step %s.database-upgrade moves it first", databaseName, from, to, a.Name) + } + } api := c.dyn.Resource(clusterResource).Namespace(namespaceOf(a.Name)) // Strict: a field this operator does not know is refused, never silently dropped. if have == nil { @@ -250,7 +258,9 @@ func clusterState(o *unstructured.Unstructured) string { } // hibernate stops the Cluster's pods and keeps its claims, or with on false starts them -// again. Deleting the Cluster instead would delete every claim it owns. +// again. Deleting the Cluster instead would delete every claim it owns. The patch carries no +// resourceVersion: the operator writes the Cluster's status all the time, and the annotation +// is the installer's alone. func (c *Client) hibernate(ctx context.Context, app string, on bool) error { o, err := c.clusterObject(ctx, app) if err != nil || o == nil || (o.GetAnnotations()[hibernation] == "on") == on { @@ -260,15 +270,16 @@ func (c *Client) hibernate(ctx context.Context, app string, on bool) error { if on { value = "on" } - patch := fmt.Sprintf(`{"metadata":{"resourceVersion":%q,"annotations":{%q:%q}}}`, o.GetResourceVersion(), hibernation, value) - if _, err := c.dyn.Resource(clusterResource).Namespace(namespaceOf(app)).Patch(ctx, databaseName, types.MergePatchType, []byte(patch), metav1.PatchOptions{}); err != nil { - return fmt.Errorf("cluster %s: %w", databaseName, err) - } - return nil + return c.patchCluster(ctx, app, map[string]any{"metadata": map[string]any{"annotations": map[string]string{hibernation: value}}}) } // waitCluster waits until every instance of the app's Cluster is ready. func (c *Client) waitCluster(ctx context.Context, app string) error { + return c.waitClusterFor(ctx, app, clusterState) +} + +// waitClusterFor waits until state, why the Cluster is not yet as wanted, returns "". +func (c *Client) waitClusterFor(ctx context.Context, app string, state func(*unstructured.Unstructured) string) error { deadline := time.Now().Add(clusterTimeout) for { o, err := c.clusterObject(ctx, app) @@ -277,7 +288,7 @@ func (c *Client) waitCluster(ctx context.Context, app string) error { } why := "no answer from the API server" if err == nil { - if why = clusterState(o); why == "" { + if why = state(o); why == "" { return nil } } diff --git a/internal/kube/dbcluster_test.go b/internal/kube/dbcluster_test.go index ea37b8c..f17d958 100644 --- a/internal/kube/dbcluster_test.go +++ b/internal/kube/dbcluster_test.go @@ -11,6 +11,7 @@ import ( "testing" "time" + "github.com/Busnes-app/kyquickstart/internal/engine" corev1 "k8s.io/api/core/v1" networkingv1 "k8s.io/api/networking/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -197,7 +198,7 @@ func TestDatabaseClusterLifecycle(t *testing.T) { ctx := context.Background() a, cs, dyn, healthy := clusteredApp(t, 3) steps := Steps(a) - for _, s := range steps[:3] { + for _, s := range steps[:4] { if err := s.Apply(ctx); err != nil { t.Fatalf("%s: %v", s.ID(), err) } @@ -238,7 +239,7 @@ func TestDatabaseClusterLifecycle(t *testing.T) { // Health and deploy wait for the instances, not only for the pods. markReady(t, cs) - health := steps[3] + health := steps[4] if err := health.Verify(ctx); err != nil { t.Fatal(err) } @@ -247,7 +248,7 @@ func TestDatabaseClusterLifecycle(t *testing.T) { t.Fatalf("health with no instance ready = %v", err) } clusterTimeout = 20 * time.Millisecond - if err := steps[2].Apply(ctx); err == nil || !strings.Contains(err.Error(), "describe cluster") { + if err := steps[3].Apply(ctx); err == nil || !strings.Contains(err.Error(), "describe cluster") { t.Fatalf("deploy with no instance ready = %v", err) } clusterTimeout = time.Minute @@ -258,7 +259,7 @@ func TestDatabaseClusterLifecycle(t *testing.T) { k := *a.Catalog.Kubernetes k.DatabaseInstances = 5 more.Catalog.Kubernetes = &k - grow := Steps(more)[2] + grow := Steps(more)[3] if done, _ := grow.Inspect(ctx); done { t.Fatal("deploy accepts three instances for five") } @@ -268,7 +269,7 @@ func TestDatabaseClusterLifecycle(t *testing.T) { if n, _, _ := unstructured.NestedInt64(clusterOf(t, dyn).Object, "spec", "instances"); n != 5 { t.Fatalf("instances = %d", n) } - if err := steps[2].Apply(ctx); err != nil { + if err := steps[3].Apply(ctx); err != nil { t.Fatal(err) } @@ -294,7 +295,7 @@ func TestDatabaseClusterLifecycle(t *testing.T) { if s, _ := a.Client.State(ctx, a.Name); s != "stopped" { t.Fatalf("state after stop = %s", s) } - if done, _ := steps[2].Inspect(ctx); done { + if done, _ := steps[3].Inspect(ctx); done { t.Fatal("deploy accepts a hibernated database") } go func() { @@ -337,7 +338,7 @@ func TestDatabaseClusterLifecycle(t *testing.T) { t.Fatalf("second uninstall: %v", err) } // A reinstall wakes it. - if err := steps[2].Apply(ctx); err != nil { + if err := steps[3].Apply(ctx); err != nil { t.Fatal(err) } if clusterOf(t, dyn).GetAnnotations()[hibernation] == "on" { @@ -372,7 +373,7 @@ func TestDatabaseClusterChangeRefused(t *testing.T) { t.Fatal(err) } } - for _, s := range Steps(a)[1:3] { + for _, s := range []engine.Step{Steps(a)[1], Steps(a)[3]} { if err := s.Apply(ctx); err == nil || !strings.Contains(err.Error(), "the installer's Postgres (Deployment database)") || !strings.Contains(err.Error(), "highly available") { t.Fatalf("%s = %v", s.ID(), err) } @@ -383,7 +384,7 @@ func TestDatabaseClusterChangeRefused(t *testing.T) { // A Cluster with no keys beside it is old data: no new keys are made. b, cs2, _, _ := clusteredApp(t, 3) - for _, s := range Steps(b)[:3] { + for _, s := range Steps(b)[:4] { if err := s.Apply(ctx); err != nil { t.Fatal(err) } diff --git a/internal/kube/dbupgrade.go b/internal/kube/dbupgrade.go new file mode 100644 index 0000000..365de65 --- /dev/null +++ b/internal/kube/dbupgrade.go @@ -0,0 +1,435 @@ +package kube + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "maps" + "slices" + "strconv" + "strings" + "time" + + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/types" + "k8s.io/utils/ptr" +) + +// A Cluster an earlier release made holds PostgreSQL 17 data. Owner decision 2026-11-25: it +// moves to the catalog's newer major only like this. Hibernate it; copy every claim it owns +// into a claim of the installer's and verify the copy; only then set the new image and wake +// it, so CloudNativePG runs its offline in-place pg_upgrade --link; wait until it is healthy +// and ANALYZE what pg_upgrade left without statistics. A copy that cannot be made wakes it on +// the old major, unchanged. The copies are never deleted by the installer. +const ( + cnpgUID = 26 // postgres in CloudNativePG's operand images, which runs the instances + cnpgPVCRole = "cnpg.io/pvcRole" + cnpgInstance = "cnpg.io/instanceName" + cnpgRole = "cnpg.io/instanceRole" + copyOfLabel = "kyquickstart/copy-of" // the claim copied + copyMajorLabel = "kyquickstart/postgres" // the PostgreSQL major it holds + copyInstance = "kyquickstart/instance" + copyRole = "kyquickstart/instance-role" // primary or replica, when copied + copiedAt = "kyquickstart/copied-at" + copyClusterUID = "kyquickstart/cluster-uid" + upgradeDocument = "docs/guided-setup.md, \"Going back to PostgreSQL 17\"" +) + +// cnpgDirs is the directory each of a Cluster's claims keeps, by its role. A claim of any +// other role is refused before anything stops: the installer never makes one. A WAL claim +// (walStorage) would leave pgdata/pg_wal a link to a path the copy pod does not mount. +var cnpgDirs = map[string]string{"PG_DATA": "pgdata"} + +// ClusterCopyClaim names the copy of a Cluster's claim taken before upgrading from major, by +// the attempt that made it at stamp. +func ClusterCopyClaim(major int, claim, stamp string) string { + return fmt.Sprintf("pre-upgrade-pg%d-%s-%s", major, claim, stamp) +} + +// imageMajor is the PostgreSQL major of an operand image reference, from its tag as +// CloudNativePG reads it; 0 when it has none. +func imageMajor(ref string) int { + ref, _, _ = strings.Cut(ref, "@") + _, tag, found := strings.Cut(ref[strings.LastIndex(ref, "/")+1:], ":") + if !found { + return 0 + } + end := strings.IndexFunc(tag, func(r rune) bool { return r < '0' || r > '9' }) + if end < 0 { + end = len(tag) + } + n, _ := strconv.Atoi(tag[:end]) + return n +} + +// dataMajor is the major of the Cluster's data: what the operator records (1.26 and later), +// else its image's. +func dataMajor(o *unstructured.Unstructured) int { + if n, found, _ := unstructured.NestedInt64(o.Object, "status", "pgDataImageInfo", "majorVersion"); found && n > 0 { + return int(n) + } + image, _, _ := unstructured.NestedString(o.Object, "spec", "imageName") + return imageMajor(image) +} + +type clusterUpgradeStep struct { + a App + note *string +} + +func (s clusterUpgradeStep) ID() string { return s.a.Name + ".database-upgrade" } +func (s clusterUpgradeStep) InputHash() string { return s.want() } +func (s clusterUpgradeStep) Note() string { return *s.note } + +func (s clusterUpgradeStep) want() string { + return s.a.Catalog.Images[s.a.Catalog.Kubernetes.Replicas.ClusterImage] +} + +// Inspect is done without a Cluster (a fresh one starts on the catalog's image) and once its +// data is the catalog's major. +func (s clusterUpgradeStep) Inspect(ctx context.Context) (bool, error) { + o, err := s.a.Client.clusterObject(ctx, s.a.Name) + if err != nil || o == nil { + return err == nil, err + } + to, from := imageMajor(s.want()), dataMajor(o) + if to == 0 || from == 0 { + return false, fmt.Errorf("cannot tell the PostgreSQL major of cluster %s (%d) or of image %s (%d)", databaseName, from, s.want(), to) + } + return from >= to, nil +} + +func (s clusterUpgradeStep) Verify(ctx context.Context) error { + done, err := s.Inspect(ctx) + if err == nil && !done { + err = fmt.Errorf("cluster %s still holds data older than PostgreSQL %d", databaseName, imageMajor(s.want())) + } + return err +} + +func (s clusterUpgradeStep) Apply(ctx context.Context) error { + a, c, want := s.a, s.a.Client, s.want() + o, err := c.clusterObject(ctx, a.Name) + if err != nil || o == nil { + return err + } + from, to, uid := dataMajor(o), imageMajor(want), o.GetUID() + if from >= to { + return nil + } + // A run that stopped after the switch below finds the new image set: the copies are made. + if image, _, _ := unstructured.NestedString(o.Object, "spec", "imageName"); imageMajor(image) == from { + claims, err := a.clusterClaims(ctx, o) + if err != nil { + return err + } + if err := a.copyAndSwitch(ctx, o, claims, from, image, want); err != nil { + return fmt.Errorf("%w. %s", err, a.keepCopies(ctx, uid)) + } + } + upgraded := func(o *unstructured.Unstructured) string { + if why := clusterState(o); why != "" { + return why + } + if dataMajor(o) < to { + return fmt.Sprintf("cluster %s holds PostgreSQL %d data", databaseName, dataMajor(o)) + } + return "" + } + if err := c.waitClusterFor(ctx, a.Name, upgraded); err != nil { + o, gerr := c.clusterObject(ctx, a.Name) + if gerr != nil || o == nil || dataMajor(o) >= to { + return fmt.Errorf("the upgrade to PostgreSQL %d ran but the Cluster is not healthy yet (%w); apply again to wait for it. %s", to, err, a.keepCopies(ctx, uid)) + } + // CloudNativePG's documented rollback of a failed upgrade: the previous image again, + // and the operator deletes the upgrade's job and starts the unchanged data. + previous, _, _ := unstructured.NestedString(o.Object, "status", "pgDataImageInfo", "image") + if previous == "" { + return fmt.Errorf("the upgrade to PostgreSQL %d did not finish (%w), and the Cluster records no previous image to go back to. %s", to, err, a.keepCopies(ctx, uid)) + } + rerr := c.patchCluster(ctx, a.Name, map[string]any{"spec": map[string]any{"imageName": previous}}) + if rerr == nil { + rerr = c.waitCluster(ctx, a.Name) + } + return errors.Join(fmt.Errorf("the upgrade to PostgreSQL %d did not finish (%w): the image was set back to %s, as CloudNativePG documents for a failed upgrade, and the Cluster runs PostgreSQL %d on its unchanged data. %s", to, err, previous, from, a.keepCopies(ctx, uid)), rerr) + } + *s.note = fmt.Sprintf("PostgreSQL %d to %d (copies verified against the originals before the upgrade). %s", from, to, a.keepCopies(ctx, uid)) + if msg := a.analyze(ctx); msg != "" { + *s.note += ". " + msg + } + return nil +} + +// analyze gathers the statistics pg_upgrade did not carry over, on the primary. A failure is +// reported, not fatal: the upgrade is done, and autovacuum gathers them in time. +func (a App) analyze(ctx context.Context) string { + o, err := a.Client.clusterObject(ctx, a.Name) + if err != nil || o == nil { + return fmt.Sprintf("ANALYZE was not run (%v)", err) + } + primary, _, _ := unstructured.NestedString(o.Object, "status", "currentPrimary") + cmd := []string{"vacuumdb", "--all", "--analyze-only", "--missing-stats-only"} + if out, err := a.Client.ExecReport(ctx, namespaceOf(a.Name), primary, "postgres", cmd); err != nil { + return fmt.Sprintf("ANALYZE failed (%v: %s); run it yourself: kubectl -n %s exec %s -c postgres -- %s", err, strings.TrimSpace(string(out)), namespaceOf(a.Name), primary, strings.Join(cmd, " ")) + } + return "ANALYZE ran on " + primary +} + +// patchCluster merge-patches the app's Cluster. +func (c *Client) patchCluster(ctx context.Context, app string, patch map[string]any) error { + b, err := json.Marshal(patch) + if err != nil { + return err + } + if _, err := c.dyn.Resource(clusterResource).Namespace(namespaceOf(app)).Patch(ctx, databaseName, types.MergePatchType, b, metav1.PatchOptions{}); err != nil { + return fmt.Errorf("cluster %s: %w", databaseName, err) + } + return nil +} + +// clusterClaims are the claims the Cluster owns, by name. Listing them needs list on claims, +// which a plan with database_instances asks for. +func (a App) clusterClaims(ctx context.Context, o *unstructured.Unstructured) ([]corev1.PersistentVolumeClaim, error) { + ns := namespaceOf(a.Name) + list, err := a.Client.cs.CoreV1().PersistentVolumeClaims(ns).List(ctx, metav1.ListOptions{LabelSelector: clusterLabel + "=" + databaseName}) + if err != nil { + return nil, fmt.Errorf("list the claims of cluster %s: %w", databaseName, err) + } + var out []corev1.PersistentVolumeClaim + for _, p := range list.Items { + if p.DeletionTimestamp != nil || !slices.ContainsFunc(p.OwnerReferences, func(r metav1.OwnerReference) bool { return r.UID == o.GetUID() }) { + continue + } + if cnpgDirs[p.Labels[cnpgPVCRole]] == "" { + return nil, fmt.Errorf("no upgrade: claim %s of cluster %s has role %q (a separate WAL or tablespace claim, which the installer never makes); the pre-upgrade copy does not cover it, and nothing was stopped", p.Name, databaseName, p.Labels[cnpgPVCRole]) + } + out = append(out, p) + } + if len(out) == 0 { + return nil, fmt.Errorf("cluster %s owns no claims to copy", databaseName) + } + slices.SortFunc(out, func(x, y corev1.PersistentVolumeClaim) int { return strings.Compare(x.Name, y.Name) }) + return out, nil +} + +// copyStamp is the UTC time in a copy's name: every attempt makes copies of its own. +var copyStamp = func() string { return time.Now().UTC().Format("20060102-150405") } + +// clusterCopies are the installer's copies in the app's namespace, by name: of the Cluster +// with uid, or of any Cluster when uid is "". +func (a App) clusterCopies(ctx context.Context, uid types.UID) ([]corev1.PersistentVolumeClaim, error) { + list, err := a.Client.cs.CoreV1().PersistentVolumeClaims(namespaceOf(a.Name)).List(ctx, metav1.ListOptions{LabelSelector: copyOfLabel}) + if err != nil { + return nil, fmt.Errorf("list the copies in %s: %w", namespaceOf(a.Name), err) + } + out := slices.DeleteFunc(list.Items, func(p corev1.PersistentVolumeClaim) bool { + return !owned(&p) || uid != "" && p.Annotations[copyClusterUID] != string(uid) + }) + slices.SortFunc(out, func(x, y corev1.PersistentVolumeClaim) int { return strings.Compare(x.Name, y.Name) }) + return out, nil +} + +// keepCopies lists the Cluster's copies and how to remove them, which only the operator does. +func (a App) keepCopies(ctx context.Context, uid types.UID) string { + ns := namespaceOf(a.Name) + copies, err := a.clusterCopies(ctx, uid) + if err != nil { + return fmt.Sprintf("Its copies could not be listed (%v): kubectl -n %s get pvc -l %s", err, ns, copyOfLabel) + } + if len(copies) == 0 { + return "No copies were made" + } + var names, list []string + for _, p := range copies { + state := "unverified" + if p.Annotations[copiedAnnotation] == "verified" { + state = "verified " + p.Annotations[copiedAt] + } + names = append(names, p.Name) + list = append(list, fmt.Sprintf("%s (of %s, %s)", p.Name, p.Labels[copyOfLabel], state)) + } + return fmt.Sprintf("Copies of cluster %s in namespace %s: %s. They stay until you delete them: kubectl -n %s delete pvc %s. Rollback from a verified one: %s", + databaseName, ns, strings.Join(list, ", "), ns, strings.Join(names, " "), upgradeDocument) +} + +// copyAndSwitch makes a verified copy of each of the Cluster's claims while it is hibernated, +// then sets image want and wakes it in one patch. Anything that fails once it is hibernated +// wakes it on its old image, unchanged. Each attempt makes new copies, beside any an earlier +// one left: none is ever replaced or deleted. +func (a App) copyAndSwitch(ctx context.Context, o *unstructured.Unstructured, claims []corev1.PersistentVolumeClaim, from int, image, want string) (err error) { + pvcs := a.Client.cs.CoreV1().PersistentVolumeClaims(namespaceOf(a.Name)) + stamp := copyStamp() + byInstance := map[string][]claimCopy{} + // The claims first, while the Cluster runs: a quota or class refusal stops nothing. + for _, p := range claims { + name := ClusterCopyClaim(from, p.Name, stamp) + labels := workloadLabels(a.ReleaseSet) + labels[copyOfLabel], labels[copyMajorLabel], labels[copyInstance], labels[copyRole] = p.Name, strconv.Itoa(from), p.Labels[cnpgInstance], instanceRole(p) + c := &corev1.PersistentVolumeClaim{ + ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: p.Namespace, Labels: labels, Annotations: map[string]string{copyClusterUID: string(o.GetUID())}}, + Spec: corev1.PersistentVolumeClaimSpec{ + AccessModes: []corev1.PersistentVolumeAccessMode{corev1.ReadWriteOnce}, + Resources: corev1.VolumeResourceRequirements{Requests: corev1.ResourceList{corev1.ResourceStorage: p.Spec.Resources.Requests[corev1.ResourceStorage]}}, + StorageClassName: p.Spec.StorageClassName, + }, + } + if _, err := pvcs.Create(ctx, c, metav1.CreateOptions{}); err != nil { + return a.clusterStorageRefusal(ctx, []string{name}, time.Now(), fmt.Errorf("create claim %s: %w", name, err)) + } + i := p.Labels[cnpgInstance] + byInstance[i] = append(byInstance[i], claimCopy{name: p.Name, src: p.Name, dir: cnpgDirs[p.Labels[cnpgPVCRole]], dst: name}) + } + instances := slices.Sorted(maps.Keys(byInstance)) + sc := &corev1.PodSecurityContext{ + RunAsNonRoot: ptr.To(true), FSGroup: ptr.To(int64(cnpgUID)), FSGroupChangePolicy: ptr.To(corev1.FSGroupChangeOnRootMismatch), + SeccompProfile: &corev1.SeccompProfile{Type: corev1.SeccompProfileTypeRuntimeDefault}, + } + // The storage check: each instance's copy pod, started once on that instance's node while + // it still runs, so the storage provisions every copy (beside its original on node-local + // storage) before sign-in stops. A copy the storage cannot provide refuses here. + for _, i := range instances { + check := a.copyPod(byInstance[i], cnpgUID, sc) + if pod, err := a.Client.cs.CoreV1().Pods(namespaceOf(a.Name)).Get(ctx, i, metav1.GetOptions{}); err == nil && pod.Spec.NodeName != "" { + pinTo(check, pod.Spec.NodeName) + } + start := time.Now() + if err := a.Client.podSession(ctx, check, "pre-upgrade storage check", func(string) error { return nil }); err != nil { + var names []string + for _, c := range byInstance[i] { + names = append(names, c.dst) + } + return a.clusterStorageRefusal(ctx, names, start, err) + } + } + // From here on every way out but success wakes the Cluster on its old image, unless the + // switch to the new one may have landed. Registered before the hibernation, whose write + // may land even when its answer is lost. + unknown := false + defer func() { + if err != nil && !unknown { + wake := context.WithoutCancel(ctx) + werr := a.Client.patchCluster(wake, a.Name, map[string]any{ + "metadata": map[string]any{"uid": o.GetUID(), "annotations": map[string]string{hibernation: "off"}}, + "spec": map[string]any{"imageName": image}, + }) + if werr == nil { + werr = a.Client.waitCluster(wake, a.Name) + } + if werr != nil { + err = fmt.Errorf("no upgrade: %w; then starting cluster %s again on PostgreSQL %d failed (%w): check with kubectl -n %s get cluster %s -o yaml that imageName is %s and annotation %s is off, and set them so", + err, databaseName, from, werr, namespaceOf(a.Name), databaseName, image, hibernation) + return + } + err = fmt.Errorf("no upgrade: %w; cluster %s was started again on PostgreSQL %d, unchanged", err, databaseName, from) + } + }() + if err := a.Client.hibernate(ctx, a.Name, true); err != nil { + return err + } + if err := waitGone(ctx, a, func(ctx context.Context) error { + left, err := a.Client.podsLeft(ctx, a.Name, clusterPods) + if err == nil && left { + err = fmt.Errorf("an instance of cluster %s is still running", databaseName) + } + return err + }); err != nil { + return err + } + // The claims and their roles as the Cluster stopped: a failover since the list above moves + // the primary, and the rollback restores the copy labelled primary. + stopped, err := a.clusterClaims(ctx, o) + if err != nil { + return err + } + role := map[string]string{} + for _, p := range stopped { + role[p.Name] = instanceRole(p) + } + if !slices.EqualFunc(stopped, claims, func(x, y corev1.PersistentVolumeClaim) bool { return x.Name == y.Name }) { + return fmt.Errorf("the claims of cluster %s changed while it stopped (an instance was added or removed)", databaseName) + } + // One pod per instance: on node-local storage each instance's claims are on its own node. + for _, i := range instances { + if err := a.copyClaims(ctx, a.copyPod(byInstance[i], cnpgUID, sc), byInstance[i]); err != nil { + return err + } + } + at := time.Now().UTC().Format(time.RFC3339) + for _, i := range instances { + for _, c := range byInstance[i] { + b, _ := json.Marshal(map[string]any{"metadata": map[string]any{ + "labels": map[string]string{copyRole: role[c.src]}, + "annotations": map[string]string{copiedAnnotation: "verified", copiedAt: at}, + }}) + if _, err := pvcs.Patch(ctx, c.dst, types.MergePatchType, b, metav1.PatchOptions{}); err != nil { + return fmt.Errorf("mark %s verified: %w", c.dst, err) + } + } + } + // Still the Cluster that was copied, as it was copied. The patches name its uid, so a + // Cluster recreated since is refused by the API server, never changed. + now, err := a.Client.clusterObject(ctx, a.Name) + if err != nil { + return err + } + if now == nil || now.GetUID() != o.GetUID() { + return fmt.Errorf("cluster %s was deleted or recreated during the copy", databaseName) + } + if have, _, _ := unstructured.NestedString(now.Object, "spec", "imageName"); have != image || now.GetAnnotations()[hibernation] != "on" { + return fmt.Errorf("cluster %s changed during the copy (image %s, hibernation %q)", databaseName, have, now.GetAnnotations()[hibernation]) + } + // One write sets the image and wakes the Cluster: the operator upgrades it on waking. + if err := a.Client.patchCluster(ctx, a.Name, map[string]any{ + "metadata": map[string]any{"uid": o.GetUID(), "annotations": map[string]string{hibernation: "off"}}, + "spec": map[string]any{"imageName": want}, + }); err != nil { + // A switch that landed with its answer lost already woke the Cluster, and the operator + // may be upgrading it: never set 17 back then; the caller's wait decides. + now, rerr := a.Client.clusterObject(context.WithoutCancel(ctx), a.Name) + if rerr != nil || now == nil { + unknown = true + return fmt.Errorf("cluster %s: the switch to PostgreSQL %d failed (%w) and its state cannot be read (%v): if kubectl -n %s get cluster %s shows imageName %s, apply again to wait for the upgrade; if %s, annotate it %s=off", + databaseName, imageMajor(want), err, rerr, namespaceOf(a.Name), databaseName, want, image, hibernation) + } + if have, _, _ := unstructured.NestedString(now.Object, "spec", "imageName"); have == want && now.GetUID() == o.GetUID() { + return nil + } + return fmt.Errorf("cluster %s refused PostgreSQL %d (%w; in-place major upgrades need CloudNativePG 1.26 or later)", databaseName, imageMajor(want), err) + } + return nil +} + +// instanceRole is a claim's instance role as the operator labels it: primary or replica. +func instanceRole(p corev1.PersistentVolumeClaim) string { + if p.Labels[cnpgRole] == "primary" { + return "primary" + } + return "replica" +} + +// clusterStorageRefusal explains copies the storage did not provide, before the Cluster was +// stopped, naming every earlier copy that takes space; the operator may delete those. +func (a App) clusterStorageRefusal(ctx context.Context, names []string, start time.Time, cause error) error { + ns := namespaceOf(a.Name) + msg := fmt.Sprintf("no upgrade: the storage did not provide the pre-upgrade copies %s (%v); cluster %s was not stopped%s", strings.Join(names, ", "), cause, databaseName, a.warnings(ctx, names, start)) + if copies, err := a.clusterCopies(ctx, ""); err == nil { + var older []string + for _, p := range copies { + if slices.Contains(names, p.Name) { + continue + } + q := p.Spec.Resources.Requests[corev1.ResourceStorage] + older = append(older, fmt.Sprintf("%s (%s, %s)", p.Name, q.String(), map[bool]string{true: "verified", false: "unverified"}[p.Annotations[copiedAnnotation] == "verified"])) + } + if len(older) > 0 { + msg += fmt.Sprintf("; earlier copies take space: %s. Delete those you no longer need yourself (kubectl -n %s delete pvc ) and apply again", strings.Join(older, ", "), ns) + } + } + if a.Redact != nil { + msg = a.Redact.Redact(msg) + } + return errors.New(msg) +} diff --git a/internal/kube/dbupgrade_test.go b/internal/kube/dbupgrade_test.go new file mode 100644 index 0000000..0c22da5 --- /dev/null +++ b/internal/kube/dbupgrade_test.go @@ -0,0 +1,805 @@ +package kube + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "maps" + "slices" + "strconv" + "strings" + "testing" + "time" + + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/api/resource" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/apimachinery/pkg/types" + dynamicfake "k8s.io/client-go/dynamic/fake" + "k8s.io/client-go/kubernetes/fake" + k8stesting "k8s.io/client-go/testing" + "k8s.io/utils/ptr" +) + +// cluster17 is the operand image earlier releases ran. +const cluster17 = "ghcr.io/cloudnative-pg/postgresql:17.12-minimal-trixie@sha256:4ae89311e5031155a139a5c6d31a80f6deb135443711e61ff7df41cb549fdcaa" + +// upgradeFixture is KyIdentity deployed by an earlier release on a Cluster of three 17 +// instances, database-1 the primary, on nodes node-1 to node-3, and an +// operator that upgrades the data in place once the Cluster wakes with an image of a higher +// major, unless fail is set. The operator writes the Cluster's status after every read, so a +// write that carries the resourceVersion it read conflicts, as in CI run 45719982937. +type upgradeFixture struct { + a App // this release's, on the catalog's 18 image + cs *fake.Clientset + dyn *dynamicfake.FakeDynamicClient + data string // the image of the Cluster's data, as the operator records it + fail bool + events []string // hibernation, image changes and copies, in order + execs [][]string + copyFn func(args []string) error + podFn func(*corev1.Pod) error + rv int // the Cluster's resourceVersion, which the operator bumps after every read +} + +func newUpgradeFixture(t *testing.T) *upgradeFixture { + t.Helper() + pollInterval = time.Millisecond + ctx := context.Background() + a, cs, dyn, _ := clusteredApp(t, 3) + f := &upgradeFixture{a: a, cs: cs, dyn: dyn, data: cluster17} + if imageMajor(f.want()) != 18 { + t.Fatalf("the catalog's Cluster image is %s", f.want()) + } + stamp, stamps := 0, copyStamp + copyStamp = func() string { stamp++; return fmt.Sprintf("2026112%d-000000", stamp) } + t.Cleanup(func() { copyStamp = stamps }) + dyn.PrependReactor("get", "clusters", func(action k8stesting.Action) (bool, runtime.Object, error) { + get := action.(k8stesting.GetAction) + o, err := dyn.Tracker().Get(clusterResource, get.GetNamespace(), get.GetName()) + if err != nil { + return true, nil, err + } + u := o.(*unstructured.Unstructured).DeepCopy() + image, _, _ := unstructured.NestedString(u.Object, "spec", "imageName") + awake := u.GetAnnotations()[hibernation] != "on" + if awake && (imageMajor(image) == imageMajor(f.data) || imageMajor(image) > imageMajor(f.data) && !f.fail) { + f.data = image + } + status := map[string]any{ + "pgDataImageInfo": map[string]any{"image": f.data, "majorVersion": int64(imageMajor(f.data))}, + "currentPrimary": "database-1", "phase": "Upgrading Postgres major version", "readyInstances": int64(0), + } + if awake && image == f.data { + status["phase"], status["readyInstances"] = clusterHealthy, int64(3) + } + u.Object["status"] = status + f.rv++ + u.SetResourceVersion(strconv.Itoa(f.rv)) + f.rv++ // the operator's status write, after this read + return true, u, nil + }) + record := func(action k8stesting.Action) (bool, runtime.Object, error) { + var o map[string]any + switch a := action.(type) { + case k8stesting.PatchAction: + _ = json.Unmarshal(a.GetPatch(), &o) + // The API server refuses a patch naming another uid: uid is immutable. + if uid, _, _ := unstructured.NestedString(o, "metadata", "uid"); uid != "" && uid != string(clusterOf(t, dyn).GetUID()) { + return true, nil, apierrors.NewInvalid(schema.GroupKind{Group: clusterGroup, Kind: "Cluster"}, databaseName, nil) + } + if rv, _, _ := unstructured.NestedString(o, "metadata", "resourceVersion"); rv != "" && rv != strconv.Itoa(f.rv) { + return true, nil, apierrors.NewConflict(clusterResource.GroupResource(), databaseName, errors.New("the object has been modified; please apply your changes to the latest version and try again")) + } + case k8stesting.UpdateAction: + o = a.GetObject().(*unstructured.Unstructured).Object + } + if v, found, _ := unstructured.NestedString(o, "metadata", "annotations", hibernation); found { + f.events = append(f.events, "hibernation "+v) + f.instances(v != "on") // the operator stops or starts the instances + + } + if v, found, _ := unstructured.NestedString(o, "spec", "imageName"); found { + f.events = append(f.events, fmt.Sprintf("image %d", imageMajor(v))) + } + return false, nil, nil + } + dyn.PrependReactor("patch", "clusters", record) + dyn.PrependReactor("update", "clusters", record) + + // The earlier release's install. + old := a + old.Catalog.Images = maps.Clone(a.Catalog.Images) + old.Catalog.Images[a.Catalog.Kubernetes.Replicas.ClusterImage] = cluster17 + for _, s := range Steps(old)[:4] { + if err := s.Apply(ctx); err != nil { + t.Fatalf("%s: %v", s.ID(), err) + } + } + f.events = nil + c := clusterOf(t, dyn) + c.SetUID("cluster-uid") + if err := dyn.Tracker().Update(clusterResource, c, c.GetNamespace()); err != nil { + t.Fatal(err) + } + claim := func(name, instance, role, pvcRole string) { + p := &corev1.PersistentVolumeClaim{ + ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: "kyq-kyidentity", + Labels: map[string]string{clusterLabel: databaseName, cnpgInstance: instance, cnpgRole: role, cnpgPVCRole: pvcRole}, + OwnerReferences: []metav1.OwnerReference{{APIVersion: clusterGroup + "/v1", Kind: "Cluster", Name: databaseName, UID: "cluster-uid"}}}, + Spec: corev1.PersistentVolumeClaimSpec{StorageClassName: ptr.To("longhorn"), + Resources: corev1.VolumeResourceRequirements{Requests: corev1.ResourceList{corev1.ResourceStorage: resource.MustParse("2Gi")}}}, + } + if _, err := cs.CoreV1().PersistentVolumeClaims("kyq-kyidentity").Create(ctx, p, metav1.CreateOptions{}); err != nil { + t.Fatal(err) + } + } + claim("database-1", "database-1", "primary", "PG_DATA") + claim("database-2", "database-2", "replica", "PG_DATA") + claim("database-3", "database-3", "replica", "PG_DATA") + f.instances(true) + // The installer's pods: each copy pod's claims, node and when it started. + cs.PrependReactor("create", "pods", func(action k8stesting.Action) (bool, runtime.Object, error) { + p := action.(k8stesting.CreateAction).GetObject().(*corev1.Pod) + if !strings.HasPrefix(p.GenerateName, "kyq-pre-upgrade-") { + return false, nil, nil + } + var claims []string + for _, v := range p.Spec.Volumes { + if v.PersistentVolumeClaim != nil && strings.HasPrefix(v.Name, "src-") { + claims = append(claims, v.PersistentVolumeClaim.ClaimName) + } + } + node := "any node" + if aff := p.Spec.Affinity; aff != nil { + node = aff.NodeAffinity.RequiredDuringSchedulingIgnoredDuringExecution.NodeSelectorTerms[0].MatchFields[0].Values[0] + } + o, _ := dyn.Tracker().Get(clusterResource, "kyq-kyidentity", databaseName) + f.events = append(f.events, fmt.Sprintf("pod %v on %s while hibernation %q", claims, node, o.(*unstructured.Unstructured).GetAnnotations()[hibernation])) + if f.podFn != nil { + if err := f.podFn(p); err != nil { + return true, nil, err + } + } + return false, nil, nil + }) + // Another Cluster's claim, which is never copied. + claim("other-1", "other-1", "primary", "PG_DATA") + o, _ := cs.CoreV1().PersistentVolumeClaims("kyq-kyidentity").Get(ctx, "other-1", metav1.GetOptions{}) + o.OwnerReferences[0].UID = "other-uid" + if _, err := cs.CoreV1().PersistentVolumeClaims("kyq-kyidentity").Update(ctx, o, metav1.UpdateOptions{}); err != nil { + t.Fatal(err) + } + + before := a.Client.execCommand + a.Client.execCommand = func(ctx context.Context, ns, pod, container string, args []string) ([]byte, error) { + switch container { + case "copy": + if len(args) < 4 || args[2] != copyCommand { + return nil, errors.New("not the copy command") + } + o, _ := dyn.Tracker().Get(clusterResource, "kyq-kyidentity", databaseName) + f.events = append(f.events, fmt.Sprintf("copy %v while hibernation %s", args[4:], o.(*unstructured.Unstructured).GetAnnotations()[hibernation])) + if f.copyFn != nil { + if err := f.copyFn(args[4:]); err != nil { + return []byte(err.Error()), err + } + } + return nil, nil + case "postgres": + f.execs = append(f.execs, append([]string{pod}, args...)) + return nil, nil + } + return before(ctx, ns, pod, container, args) + } + f.a = a + return f +} + +// instances starts, or stops, the Cluster's instance pods database-N on node-N. +func (f *upgradeFixture) instances(run bool) { + pods := corev1.SchemeGroupVersion.WithResource("pods") + for i := 1; i <= 3; i++ { + name := fmt.Sprintf("database-%d", i) + if !run { + _ = f.cs.Tracker().Delete(pods, "kyq-kyidentity", name) + continue + } + _ = f.cs.Tracker().Create(pods, &corev1.Pod{ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: "kyq-kyidentity", Labels: map[string]string{clusterLabel: databaseName}}, + Spec: corev1.PodSpec{NodeName: fmt.Sprintf("node-%d", i)}}, "kyq-kyidentity") + } +} + +func (f *upgradeFixture) want() string { + return f.a.Catalog.Images[f.a.Catalog.Kubernetes.Replicas.ClusterImage] +} + +func (f *upgradeFixture) step() clusterUpgradeStep { + for _, s := range Steps(f.a) { + if u, ok := s.(clusterUpgradeStep); ok { + return u + } + } + panic("no upgrade step") +} + +func (f *upgradeFixture) image(t *testing.T) string { + t.Helper() + image, _, _ := unstructured.NestedString(clusterOf(t, f.dyn).Object, "spec", "imageName") + return image +} + +// copies are the installer's copy claims, by name. +func (f *upgradeFixture) copies(t *testing.T) map[string]corev1.PersistentVolumeClaim { + t.Helper() + list, err := f.cs.CoreV1().PersistentVolumeClaims("kyq-kyidentity").List(context.Background(), metav1.ListOptions{}) + if err != nil { + t.Fatal(err) + } + out := map[string]corev1.PersistentVolumeClaim{} + for _, p := range list.Items { + if strings.HasPrefix(p.Name, "pre-upgrade-pg") { + out[p.Name] = p + } + } + return out +} + +// noClaimDeleted fails the test if anything deleted a claim. +func (f *upgradeFixture) noClaimDeleted(t *testing.T) { + t.Helper() + for _, a := range f.cs.Actions() { + if a.GetVerb() == "delete" && a.GetResource().Resource == "persistentvolumeclaims" { + t.Fatalf("claim deleted: %v", a) + } + } +} + +// copiesOf are the copy names one attempt makes, at stamp. +func copiesOf(stamp string) []string { + var out []string + for _, c := range []string{"database-1", "database-2", "database-3"} { + out = append(out, ClusterCopyClaim(17, c, stamp)) + } + return out +} + +// awakeOn17 fails the test unless the Cluster runs, unhibernated, on its 17 image. +func (f *upgradeFixture) awakeOn17(t *testing.T) { + t.Helper() + if f.image(t) != cluster17 || clusterOf(t, f.dyn).GetAnnotations()[hibernation] != "off" || imageMajor(f.data) != 17 { + t.Fatalf("not awake on 17: image %s, hibernation %q, data %s, events %v", f.image(t), clusterOf(t, f.dyn).GetAnnotations()[hibernation], f.data, f.events) + } +} + +const stamp1, stamp2 = "20261121-000000", "20261122-000000" + +func TestClusterUpgrade(t *testing.T) { + ctx := context.Background() + f := newUpgradeFixture(t) + step := f.step() + if done, err := step.Inspect(ctx); err != nil || done { + t.Fatalf("a 17 Cluster needs no upgrade: %v", err) + } + // This release's deploy alone never moves the data. + deploy := Steps(f.a)[3] + if err := deploy.Apply(ctx); err == nil || !strings.Contains(err.Error(), "database-upgrade moves it first") || imageMajor(f.image(t)) != 17 { + t.Fatalf("deploy over a 17 Cluster: %v, image %s", err, f.image(t)) + } + f.events = nil + // The operator writes the Cluster between every read and write: no write may carry the + // resourceVersion it read (CI run 45719982937). + if err := step.Apply(ctx); err != nil { + t.Fatal(err) + } + c := copiesOf(stamp1) + // A storage check per instance on its node while it runs; then hibernated, every + // instance copied while it is, then the image and the wake together. + want := []string{ + `pod [database-1] on node-1 while hibernation ""`, + `pod [database-2] on node-2 while hibernation ""`, + `pod [database-3] on node-3 while hibernation ""`, + "hibernation on", + `pod [database-1] on any node while hibernation "on"`, + "copy [database-1:pgdata] while hibernation on", + `pod [database-2] on any node while hibernation "on"`, + "copy [database-2:pgdata] while hibernation on", + `pod [database-3] on any node while hibernation "on"`, + "copy [database-3:pgdata] while hibernation on", + "hibernation off", "image 18", + } + if !slices.Equal(f.events, want) { + t.Fatalf("sequence:\n%s\nwant:\n%s", strings.Join(f.events, "\n"), strings.Join(want, "\n")) + } + if f.image(t) != f.want() || clusterOf(t, f.dyn).GetAnnotations()[hibernation] == "on" || imageMajor(f.data) != 18 { + t.Fatalf("after the upgrade: image %s, data %s", f.image(t), f.data) + } + copies := f.copies(t) + if got := slices.Sorted(maps.Keys(copies)); !slices.Equal(got, c) { + t.Fatalf("copies = %v", got) + } + for name, p := range copies { + src := strings.TrimSuffix(strings.TrimPrefix(name, "pre-upgrade-pg17-"), "-"+stamp1) + role := map[bool]string{true: "primary", false: "replica"}[strings.HasPrefix(src, "database-1")] + if p.Annotations[copiedAnnotation] != "verified" || p.Annotations[copiedAt] == "" || p.Annotations[copyClusterUID] != "cluster-uid" || !owned(&p) || + p.Labels[copyOfLabel] != src || p.Labels[copyMajorLabel] != "17" || p.Labels[copyRole] != role || p.Labels[clusterLabel] != "" || + ptr.Deref(p.Spec.StorageClassName, "") != "longhorn" || p.Spec.Resources.Requests.Storage().String() != "2Gi" { + t.Errorf("%s: %+v %+v", name, p.ObjectMeta, p.Spec) + } + } + // Copy pods run as the instances' postgres, reading the originals only. + for _, a := range f.cs.Actions() { + p, ok := a.(k8stesting.CreateAction) + if !ok || a.GetResource().Resource != "pods" || !strings.HasPrefix(p.GetObject().(*corev1.Pod).GenerateName, "kyq-pre-upgrade-") { + continue + } + pod := p.GetObject().(*corev1.Pod) + ct := pod.Spec.Containers[0] + if *ct.SecurityContext.RunAsUser != cnpgUID || *pod.Spec.SecurityContext.FSGroup != cnpgUID { + t.Errorf("copy pod runs as %d", *ct.SecurityContext.RunAsUser) + } + for _, m := range ct.VolumeMounts { + if strings.HasPrefix(m.Name, "src-") && (!m.ReadOnly || m.SubPath != "pgdata") { + t.Errorf("source mount %+v", m) + } + } + } + // ANALYZE of what pg_upgrade carried no statistics for, on the primary. + if len(f.execs) != 1 || f.execs[0][0] != "database-1" || !slices.Contains(f.execs[0], "--missing-stats-only") { + t.Errorf("execs = %v", f.execs) + } + note := step.Note() + for _, s := range []string{"kubectl -n kyq-kyidentity delete pvc " + strings.Join(c, " "), "PostgreSQL 17 to 18", "ANALYZE ran on database-1", "of database-2, verified"} { + if !strings.Contains(note, s) { + t.Errorf("note lacks %q: %s", s, note) + } + } + if err := step.Verify(ctx); err != nil { + t.Fatal(err) + } + // The deploy then finds the image it wants; a rerun copies nothing again. + if err := deploy.Apply(ctx); err != nil { + t.Fatal(err) + } + f.events = nil + if done, err := step.Inspect(ctx); err != nil || !done { + t.Fatalf("rerun: %v", err) + } + if len(f.copies(t)) != 3 { + t.Fatal("copies went") + } + f.noClaimDeleted(t) +} + +// A copy that fails wakes the Cluster on 17, unchanged: no image change, nothing deleted. The +// next attempt makes new copies beside the first one's, which stay. +func TestClusterUpgradeCopyFailure(t *testing.T) { + ctx := context.Background() + f := newUpgradeFixture(t) + f.copyFn = func(args []string) error { + if args[0] == "database-2:pgdata" { + return errors.New("database-2: copied contents differ from the original") + } + return nil + } + step := f.step() + err := step.Apply(ctx) + if err == nil || !strings.Contains(err.Error(), "started again on PostgreSQL 17, unchanged") || !strings.Contains(err.Error(), "copied contents differ") || + !strings.Contains(err.Error(), "kubectl -n kyq-kyidentity delete pvc "+strings.Join(copiesOf(stamp1), " ")) { + t.Fatalf("apply = %v", err) + } + if slices.Contains(f.events, "image 18") { + t.Fatalf("image changed: %v", f.events) + } + f.awakeOn17(t) + if c := f.copies(t)[ClusterCopyClaim(17, "database-2", stamp1)]; c.Annotations[copiedAnnotation] == "verified" { + t.Error("a failed copy is marked verified") + } + if err := step.Verify(ctx); err == nil { + t.Fatal("verify passes on 17 data") + } + if err := Steps(f.a)[3].Apply(ctx); err == nil || imageMajor(f.image(t)) != 17 { + t.Fatalf("deploy after a failed copy: %v", err) + } + f.noClaimDeleted(t) + + // The next run copies every claim again, into new claims, from the 17 data that took + // writes since. The first attempt's copies are kept untouched and listed. + first := f.copies(t) + f.copyFn, f.events = nil, nil + if err := step.Apply(ctx); err != nil { + t.Fatal(err) + } + if n := len(slices.DeleteFunc(slices.Clone(f.events), func(e string) bool { return !strings.HasPrefix(e, "copy ") })); n != 3 || f.image(t) != f.want() { + t.Fatalf("rerun: %v", f.events) + } + all := f.copies(t) + both := slices.Sorted(slices.Values(append(copiesOf(stamp1), copiesOf(stamp2)...))) + if got := slices.Sorted(maps.Keys(all)); !slices.Equal(got, both) { + t.Fatalf("copies %v, want %v", got, both) + } + for name, p := range first { + if all[name].ResourceVersion != p.ResourceVersion { + t.Errorf("the first attempt's copy %s was changed", name) + } + } + if !strings.Contains(step.Note(), "delete pvc "+strings.Join(both, " ")) { + t.Errorf("note: %s", step.Note()) + } + f.noClaimDeleted(t) +} + +// Whatever fails once the Cluster is hibernated wakes it on its 17 image, also when the +// failing write did land, and reports the error. +func TestClusterUpgradeFailsAfterHibernation(t *testing.T) { + lost := errors.New("connection reset") + for name, fail := range map[string]func(f *upgradeFixture) k8stesting.ReactionFunc{ + // The hibernation lands, its answer is lost. + "hibernation answer lost": func(f *upgradeFixture) k8stesting.ReactionFunc { + return func(action k8stesting.Action) (bool, runtime.Object, error) { + p := action.(k8stesting.PatchAction) + if p.GetResource().Resource == "clusters" && strings.Contains(string(p.GetPatch()), `"on"`) { + return f.applied(t, p, lost) + } + return false, nil, nil + } + }, + "copy not marked verified": func(f *upgradeFixture) k8stesting.ReactionFunc { + return func(action k8stesting.Action) (bool, runtime.Object, error) { + p := action.(k8stesting.PatchAction) + if p.GetResource().Resource == "persistentvolumeclaims" && strings.Contains(string(p.GetPatch()), "verified") { + return true, nil, lost + } + return false, nil, nil + } + }, + } { + t.Run(name, func(t *testing.T) { + f := newUpgradeFixture(t) + if strings.HasPrefix(name, "copy") { + f.cs.PrependReactor("patch", "persistentvolumeclaims", fail(f)) + } else { + f.dyn.PrependReactor("patch", "clusters", fail(f)) + } + err := f.step().Apply(context.Background()) + if err == nil || !errors.Is(err, lost) || !strings.Contains(err.Error(), "started again on PostgreSQL 17, unchanged") { + t.Fatalf("apply = %v", err) + } + f.awakeOn17(t) + if len(f.copies(t)) != 3 { + t.Fatalf("%d copies", len(f.copies(t))) + } + f.noClaimDeleted(t) + }) + } +} + +// A Cluster deleted and recreated, or changed, while it was copied is never switched to 18; +// a recreated one is not touched at all. +func TestClusterUpgradeClusterChangedDuringCopy(t *testing.T) { + for name, change := range map[string]func(o *unstructured.Unstructured){ + "recreated": func(o *unstructured.Unstructured) { o.SetUID("new-uid") }, + "image": func(o *unstructured.Unstructured) { + _ = unstructured.SetNestedField(o.Object, "pg:17.13", "spec", "imageName") + }, + } { + t.Run(name, func(t *testing.T) { + f := newUpgradeFixture(t) + f.copyFn = func([]string) error { + o := clusterOf(t, f.dyn) + change(o) + return f.dyn.Tracker().Update(clusterResource, o, o.GetNamespace()) + } + err := f.step().Apply(context.Background()) + if err == nil || slices.Contains(f.events, "image 18") || imageMajor(f.image(t)) != 17 { + t.Fatalf("apply = %v, events %v", err, f.events) + } + if name == "recreated" { + if !strings.Contains(err.Error(), "deleted or recreated") || !strings.Contains(err.Error(), "failed") || clusterOf(t, f.dyn).GetAnnotations()[hibernation] != "on" { + t.Fatalf("apply = %v", err) + } + } else { + f.awakeOn17(t) + } + if len(f.copies(t)) != 3 { + t.Fatalf("%d copies", len(f.copies(t))) + } + f.noClaimDeleted(t) + }) + } +} + +// A switch that landed with its answer lost is an upgrade under way: never set back to 17 +// then. One whose state cannot be read is reported, and nothing more is written. +func TestClusterUpgradeSwitchAnswerLost(t *testing.T) { + lost := errors.New("connection reset") + timeout := clusterTimeout + clusterTimeout = time.Second + t.Cleanup(func() { clusterTimeout = timeout }) + t.Run("landed", func(t *testing.T) { + f := newUpgradeFixture(t) + f.dyn.PrependReactor("patch", "clusters", func(action k8stesting.Action) (bool, runtime.Object, error) { + if p := action.(k8stesting.PatchAction); strings.Contains(string(p.GetPatch()), f.want()) { + return f.applied(t, p, lost) + } + return false, nil, nil + }) + if err := f.step().Apply(context.Background()); err != nil { + t.Fatal(err) + } + if f.image(t) != f.want() || imageMajor(f.data) != 18 || slices.Contains(f.events, "image 17") { + t.Fatalf("image %s, data %s, events %v", f.image(t), f.data, f.events) + } + }) + t.Run("unknown", func(t *testing.T) { + f := newUpgradeFixture(t) + switched := false + f.dyn.PrependReactor("patch", "clusters", func(action k8stesting.Action) (bool, runtime.Object, error) { + if p := action.(k8stesting.PatchAction); strings.Contains(string(p.GetPatch()), f.want()) { + switched = true + return f.applied(t, p, lost) + } + return false, nil, nil + }) + f.dyn.PrependReactor("get", "clusters", func(k8stesting.Action) (bool, runtime.Object, error) { + if switched { + return true, nil, lost + } + return false, nil, nil + }) + f.events = nil + err := f.step().Apply(context.Background()) + if err == nil || !strings.Contains(err.Error(), "cannot be read") || strings.Contains(err.Error(), "started again") { + t.Fatalf("apply = %v", err) + } + // applied bypasses the recorder: any event about the Cluster is a later write. + if f.image(t) != f.want() || slices.ContainsFunc(f.events, func(e string) bool { return strings.HasPrefix(e, "image") || e == "hibernation off" }) { + t.Fatalf("written after the lost switch: image %s, events %v", f.image(t), f.events) + } + f.noClaimDeleted(t) + }) +} + +// A failover while the copies are provisioned moves the primary: the copies carry the roles +// the instances had when the Cluster stopped. +func TestClusterUpgradeFailoverBeforeStop(t *testing.T) { + ctx := context.Background() + f := newUpgradeFixture(t) + failed := false + f.podFn = func(*corev1.Pod) error { + if failed { + return nil + } + failed = true + // Through the tracker: this runs inside the clientset's reactor. + gvr := corev1.SchemeGroupVersion.WithResource("persistentvolumeclaims") + for name, role := range map[string]string{"database-1": "replica", "database-2": "primary"} { + o, err := f.cs.Tracker().Get(gvr, "kyq-kyidentity", name) + if err != nil { + return err + } + p := o.(*corev1.PersistentVolumeClaim).DeepCopy() + p.Labels[cnpgRole] = role + if err := f.cs.Tracker().Update(gvr, p, "kyq-kyidentity"); err != nil { + return err + } + } + return nil + } + if err := f.step().Apply(ctx); err != nil { + t.Fatal(err) + } + copies := f.copies(t) + for claim, role := range map[string]string{"database-1": "replica", "database-2": "primary", "database-3": "replica"} { + if got := copies[ClusterCopyClaim(17, claim, stamp1)].Labels[copyRole]; got != role { + t.Errorf("copy of %s labelled %s, want %s", claim, got, role) + } + } +} + +// applied applies patch p, of the hibernation and the image, to the Cluster as the API server +// would, then answers with err. +func (f *upgradeFixture) applied(t *testing.T, p k8stesting.PatchAction, err error) (bool, runtime.Object, error) { + t.Helper() + var patch map[string]any + if jerr := json.Unmarshal(p.GetPatch(), &patch); jerr != nil { + t.Fatal(jerr) + } + o := clusterOf(t, f.dyn) + if v, found, _ := unstructured.NestedString(patch, "metadata", "annotations", hibernation); found { + o.SetAnnotations(map[string]string{hibernation: v}) + f.instances(v != "on") + } + if v, found, _ := unstructured.NestedString(patch, "spec", "imageName"); found { + _ = unstructured.SetNestedField(o.Object, v, "spec", "imageName") + } + if uerr := f.dyn.Tracker().Update(clusterResource, o, o.GetNamespace()); uerr != nil { + t.Fatal(uerr) + } + return true, nil, err +} + +// A separate WAL claim, which the installer never makes, refuses before anything stops: its +// pgdata/pg_wal links to a path the copy pod does not mount. +func TestClusterUpgradeWALClaimRefused(t *testing.T) { + ctx := context.Background() + f := newUpgradeFixture(t) + p := &corev1.PersistentVolumeClaim{ObjectMeta: metav1.ObjectMeta{Name: "database-1-wal", Namespace: "kyq-kyidentity", + Labels: map[string]string{clusterLabel: databaseName, cnpgInstance: "database-1", cnpgRole: "primary", cnpgPVCRole: "PG_WAL"}, + OwnerReferences: []metav1.OwnerReference{{APIVersion: clusterGroup + "/v1", Kind: "Cluster", Name: databaseName, UID: "cluster-uid"}}}} + if _, err := f.cs.CoreV1().PersistentVolumeClaims("kyq-kyidentity").Create(ctx, p, metav1.CreateOptions{}); err != nil { + t.Fatal(err) + } + err := f.step().Apply(ctx) + if err == nil || !strings.Contains(err.Error(), `"PG_WAL"`) || !strings.Contains(err.Error(), "nothing was stopped") { + t.Fatalf("apply = %v", err) + } + if len(f.events) != 0 || len(f.copies(t)) != 0 || f.image(t) != cluster17 { + t.Fatalf("events %v, %d copies", f.events, len(f.copies(t))) + } +} + +// A claim the storage refuses stops nothing. +func TestClusterUpgradeClaimRefused(t *testing.T) { + f := newUpgradeFixture(t) + f.cs.PrependReactor("create", "persistentvolumeclaims", func(k8stesting.Action) (bool, runtime.Object, error) { + return true, nil, apierrors.NewForbidden(corev1.Resource("persistentvolumeclaims"), "x", errors.New("exceeded quota")) + }) + err := f.step().Apply(context.Background()) + if err == nil || !strings.Contains(err.Error(), "exceeded quota") || !strings.Contains(err.Error(), "was not stopped") { + t.Fatalf("apply = %v", err) + } + if len(f.events) != 0 || f.image(t) != cluster17 { + t.Fatalf("events %v", f.events) + } +} + +// Storage that cannot provide a copy refuses before the Cluster is stopped, and names the +// earlier copies taking space, which it never deletes. +func TestClusterUpgradeStorageCheckRefused(t *testing.T) { + ctx := context.Background() + f := newUpgradeFixture(t) + // An earlier failed attempt's copies, and another Cluster's. + f.copyFn = func([]string) error { return errors.New("no space left on device") } + if err := f.step().Apply(ctx); err == nil { + t.Fatal("copy failure accepted") + } + f.copyFn = nil + labels := workloadLabels("rs") + labels[copyOfLabel] = "database-1" + other := &corev1.PersistentVolumeClaim{ObjectMeta: metav1.ObjectMeta{Name: "pre-upgrade-pg17-database-1-20250101-000000", Namespace: "kyq-kyidentity", + Labels: labels, Annotations: map[string]string{copyClusterUID: "earlier-uid", copiedAnnotation: "verified"}}, + Spec: corev1.PersistentVolumeClaimSpec{Resources: corev1.VolumeResourceRequirements{Requests: corev1.ResourceList{corev1.ResourceStorage: resource.MustParse("2Gi")}}}} + if _, err := f.cs.CoreV1().PersistentVolumeClaims("kyq-kyidentity").Create(ctx, other, metav1.CreateOptions{}); err != nil { + t.Fatal(err) + } + f.events = nil + f.podFn = func(p *corev1.Pod) error { + if p.Spec.Affinity != nil { // the storage check, while the Cluster runs + return errors.New("0/3 nodes are available: insufficient storage") + } + return nil + } + err := f.step().Apply(ctx) + if err == nil || !strings.Contains(err.Error(), "was not stopped") || !strings.Contains(err.Error(), "earlier copies take space") || + !strings.Contains(err.Error(), other.Name+" (2Gi, verified)") || !strings.Contains(err.Error(), ClusterCopyClaim(17, "database-2", stamp1)+" (2Gi, unverified)") { + t.Fatalf("apply = %v", err) + } + if slices.ContainsFunc(f.events, func(e string) bool { return strings.HasPrefix(e, "hibernation") || strings.HasPrefix(e, "image") }) { + t.Fatalf("the Cluster was touched: %v", f.events) + } + if f.image(t) != cluster17 || len(f.copies(t)) != 7 { + t.Fatalf("image %s, %d copies", f.image(t), len(f.copies(t))) + } + f.noClaimDeleted(t) +} + +// An operator older than 1.26 refuses the image: woken on 17, the copies kept. +func TestClusterUpgradeOperatorRefuses(t *testing.T) { + f := newUpgradeFixture(t) + f.dyn.PrependReactor("patch", "clusters", func(action k8stesting.Action) (bool, runtime.Object, error) { + if strings.Contains(string(action.(k8stesting.PatchAction).GetPatch()), f.want()) { + return true, nil, apierrors.NewBadRequest("can't upgrade between majors") + } + return false, nil, nil + }) + err := f.step().Apply(context.Background()) + if err == nil || !strings.Contains(err.Error(), "1.26") || !strings.Contains(err.Error(), "started again on PostgreSQL 17") { + t.Fatalf("apply = %v", err) + } + f.awakeOn17(t) + if len(f.copies(t)) != 3 { + t.Fatalf("after the refusal: %d copies", len(f.copies(t))) + } + f.noClaimDeleted(t) +} + +// A pg_upgrade that does not finish is rolled back as CloudNativePG documents: its image again. +func TestClusterUpgradeRollback(t *testing.T) { + f := newUpgradeFixture(t) + f.fail = true + timeout := clusterTimeout + clusterTimeout = 30 * time.Millisecond + t.Cleanup(func() { clusterTimeout = timeout }) + err := f.step().Apply(context.Background()) + if err == nil || !strings.Contains(err.Error(), "set back to "+cluster17) || !strings.Contains(err.Error(), "They stay until you delete them") { + t.Fatalf("apply = %v", err) + } + if f.image(t) != cluster17 || imageMajor(f.data) != 17 || !slices.Equal(f.events[len(f.events)-1:], []string{"image 17"}) { + t.Fatalf("after the rollback: image %s, events %v", f.image(t), f.events) + } + if len(f.copies(t)) != 3 { + t.Fatal("copies went") + } + f.noClaimDeleted(t) +} + +// A copy of another Cluster (one recreated from the copies) is never touched nor offered. +func TestClusterUpgradeForeignCopy(t *testing.T) { + ctx := context.Background() + f := newUpgradeFixture(t) + labels := workloadLabels("rs") + labels[copyOfLabel] = "database-2" + p := &corev1.PersistentVolumeClaim{ObjectMeta: metav1.ObjectMeta{Name: "pre-upgrade-pg17-database-2-20250101-000000", Namespace: "kyq-kyidentity", + Labels: labels, Annotations: map[string]string{copyClusterUID: "earlier-uid", copiedAnnotation: "verified"}}} + p, err := f.cs.CoreV1().PersistentVolumeClaims("kyq-kyidentity").Create(ctx, p, metav1.CreateOptions{}) + if err != nil { + t.Fatal(err) + } + step := f.step() + if err := step.Apply(ctx); err != nil { + t.Fatal(err) + } + if got := f.copies(t)[p.Name]; got.ResourceVersion != p.ResourceVersion { + t.Fatalf("the other Cluster's copy changed: %+v", got) + } + if strings.Contains(step.Note(), p.Name) { + t.Fatalf("note offers the other Cluster's copy: %s", step.Note()) + } + f.noClaimDeleted(t) +} + +// A fresh install starts on 18 directly: nothing to copy, nothing hibernated. +func TestClusterUpgradeFresh(t *testing.T) { + pollInterval = time.Millisecond + ctx := context.Background() + a, cs, dyn, _ := clusteredApp(t, 3) + var patched []types.PatchType + dyn.PrependReactor("patch", "clusters", func(action k8stesting.Action) (bool, runtime.Object, error) { + patched = append(patched, action.(k8stesting.PatchAction).GetPatchType()) + return false, nil, nil + }) + for _, s := range Steps(a)[:4] { + if done, err := s.Inspect(ctx); s.ID() == "kyidentity.database-upgrade" && (err != nil || !done) { + t.Fatalf("upgrade step without a Cluster: %v", err) + } + if err := s.Apply(ctx); err != nil { + t.Fatalf("%s: %v", s.ID(), err) + } + } + if image, _, _ := unstructured.NestedString(clusterOf(t, dyn).Object, "spec", "imageName"); imageMajor(image) != 18 || len(patched) != 0 { + t.Fatalf("fresh Cluster: %s, patches %v", image, patched) + } + list, _ := cs.CoreV1().PersistentVolumeClaims("kyq-kyidentity").List(ctx, metav1.ListOptions{}) + for _, p := range list.Items { + if strings.HasPrefix(p.Name, "pre-upgrade-") { + t.Fatalf("copy %s on a fresh install", p.Name) + } + } +} + +func TestImageMajor(t *testing.T) { + for ref, want := range map[string]int{ + cluster17: 17, "ghcr.io/cloudnative-pg/postgresql:18.7-minimal-trixie": 18, "localhost:5000/pg:16": 16, + "localhost:5000/pg": 0, "pg@sha256:abc": 0, "pg:latest": 0, + } { + if got := imageMajor(ref); got != want { + t.Errorf("%s: %d, want %d", ref, got, want) + } + } +} diff --git a/internal/kube/preupgrade.go b/internal/kube/preupgrade.go index 5581675..de328b7 100644 --- a/internal/kube/preupgrade.go +++ b/internal/kube/preupgrade.go @@ -23,22 +23,29 @@ import ( // copiedAnnotation marks a pre-upgrade claim whose copy was verified against the original. const copiedAnnotation = "kyquickstart/pre-upgrade" -// copyCommand copies each named volume's private directory into its pre-upgrade claim, -// replacing what an interrupted run left, then compares contents, modes, owners, sizes, -// times and link targets with the original. A link's own time is left out: BusyBox cp -a -// does not keep it. +// copyCommand copies each name:dir argument's dir (mounted at /src/name) into dir of its copy +// claim (at /dst/name), replacing what an interrupted run left, then compares contents, modes, +// owners, sizes, times and link targets with the original. A link's own time is left out: +// BusyBox cp -a does not keep it. const copyCommand = `exec 2>&1 for v in "$@"; do - s=/src/$v d=/dst/$v/` + privateDir + ` + n=${v%%:*} + s=/src/$n d=/dst/$n/${v#*:} rm -rf "$d" mkdir -m 700 "$d" cp -a "$s/." "$d/" - diff -r "$s" "$d" >/dev/null || { echo "$v: copied contents differ from the original"; exit 1; } + diff -r "$s" "$d" >/dev/null || { echo "$n: copied contents differ from the original"; exit 1; } l() { (cd "$1" && { find . ! -type l -exec stat -c '%n %f %u %g %s %Y' {} +; find . -type l -exec stat -c '%n %u %g %N' {} +; } | sort) > "$2"; } l "$s" /tmp/src; l "$d" /tmp/dst - cmp -s /tmp/src /tmp/dst || { echo "$v: copied modes, owners or times differ from the original:"; diff /tmp/src /tmp/dst | grep '^[-+][^-+]' | head -10; exit 1; } + cmp -s /tmp/src /tmp/dst || { echo "$n: copied modes, owners or times differ from the original:"; diff /tmp/src /tmp/dst | grep '^[-+][^-+]' | head -10; exit 1; } done` +// claimCopy is one claim's copy: dir of claim src goes into dir of claim dst. name is its +// argument and mount name in the copy pod. +type claimCopy struct{ name, src, dir, dst string } + +func (c claimCopy) arg() string { return c.name + ":" + c.dir } + // PreUpgradeClaim names volume's copy taken before upgrading from version. func PreUpgradeClaim(from, volume string) string { return "pre-upgrade-" + from + "-vol-" + volume } @@ -134,13 +141,15 @@ func PreUpgradeCopy(ctx context.Context, a App, from string) (claims []string, e // The copy pod, started once on the app's node while the app still runs: a claim the // storage cannot provide fails here, and node-local storage provisions each copy beside // its original. - check := a.copyPod(from, todo) + var copies []claimCopy + for _, v := range todo { + copies = append(copies, claimCopy{name: v, src: "vol-" + v, dir: privateDir, dst: PreUpgradeClaim(from, v)}) + } + check := a.copyPod(copies, a.Catalog.Kubernetes.RunAs, podSecurityContext(a.Catalog.Kubernetes)) if node, err := a.appNode(ctx); err != nil { return nil, err } else if node != "" { - check.Spec.Affinity = &corev1.Affinity{NodeAffinity: &corev1.NodeAffinity{RequiredDuringSchedulingIgnoredDuringExecution: &corev1.NodeSelector{ - NodeSelectorTerms: []corev1.NodeSelectorTerm{{MatchFields: []corev1.NodeSelectorRequirement{{Key: "metadata.name", Operator: corev1.NodeSelectorOpIn, Values: []string{node}}}}}, - }}} + pinTo(check, node) } start := time.Now() if err := a.Client.podSession(ctx, check, "pre-upgrade storage check", func(string) error { return nil }); err != nil { @@ -160,17 +169,7 @@ func PreUpgradeCopy(ctx context.Context, a App, from string) (claims []string, e if err := stop.waitStopped(ctx); err != nil { return nil, fmt.Errorf("stop for the pre-upgrade copy: %w", err) } - err = a.Client.podSession(ctx, a.copyPod(from, todo), "pre-upgrade copy", func(pod string) error { - out, err := a.Client.ExecReport(ctx, ns, pod, "copy", append([]string{"/bin/sh", "-euc", copyCommand, "copy"}, todo...)) - if err != nil { - if msg := strings.TrimSpace(string(out)); msg != "" { - return fmt.Errorf("pre-upgrade copy failed: %s", a.Redact.Redact(msg)) - } - return fmt.Errorf("pre-upgrade copy failed: %w", err) - } - return nil - }) - if err != nil { + if err := a.copyClaims(ctx, a.copyPod(copies, a.Catalog.Kubernetes.RunAs, podSecurityContext(a.Catalog.Kubernetes)), copies); err != nil { return nil, err } for _, v := range todo { @@ -187,38 +186,11 @@ func PreUpgradeCopy(ctx context.Context, a App, from string) (claims []string, e // claim list need list permissions preflight does not require; without them those parts are // left out. func (a App) storageRefusal(ctx context.Context, from string, volumes []string, start time.Time, cause error) error { - ns := namespaceOf(a.Name) var names []string for _, v := range volumes { names = append(names, PreUpgradeClaim(from, v)) } - msg := fmt.Sprintf("the target storage did not provide the pre-upgrade copies %s (%v); %s was not stopped", strings.Join(names, ", "), cause, a.Name) - if events, err := a.Client.cs.CoreV1().Events(ns).List(ctx, metav1.ListOptions{}); err == nil { - var seen []string - for _, e := range events.Items { - at := e.LastTimestamp.Time - if at.IsZero() { - at = e.EventTime.Time - } - ours := slices.Contains(names, e.InvolvedObject.Name) || e.InvolvedObject.Kind == "Pod" && strings.HasPrefix(e.InvolvedObject.Name, "kyq-pre-upgrade-") - text := strings.Join(strings.Fields(e.Reason+": "+e.Message), " ") - if e.Type != corev1.EventTypeWarning || !ours || at.Before(start.Add(-time.Second)) || slices.Contains(seen, text) { - continue - } - seen = append(seen, text) - } - if n := len(seen); n > 5 { - seen = seen[n-5:] - } - for i, t := range seen { - if len(t) > 300 { - seen[i] = t[:300] + "..." - } - } - if len(seen) > 0 { - msg += "; the cluster reports: " + strings.Join(seen, "; ") - } - } + msg := fmt.Sprintf("the target storage did not provide the pre-upgrade copies %s (%v); %s was not stopped%s", strings.Join(names, ", "), cause, a.Name, a.warnings(ctx, names, start)) if copies, err := PreUpgradeCopies(ctx, a); err == nil { var older []string for _, c := range copies { @@ -237,6 +209,47 @@ func (a App) storageRefusal(ctx context.Context, from string, volumes []string, return errors.New(msg) } +// pinTo schedules pod on node only. +func pinTo(pod *corev1.Pod, node string) { + pod.Spec.Affinity = &corev1.Affinity{NodeAffinity: &corev1.NodeAffinity{RequiredDuringSchedulingIgnoredDuringExecution: &corev1.NodeSelector{ + NodeSelectorTerms: []corev1.NodeSelectorTerm{{MatchFields: []corev1.NodeSelectorRequirement{{Key: "metadata.name", Operator: corev1.NodeSelectorOpIn, Values: []string{node}}}}}, + }}} +} + +// warnings are the cluster's warnings since start about the claims names and the copy pods, +// as "; the cluster reports: ...", or "" when there are none or events cannot be listed. +func (a App) warnings(ctx context.Context, names []string, start time.Time) string { + events, err := a.Client.cs.CoreV1().Events(namespaceOf(a.Name)).List(ctx, metav1.ListOptions{}) + if err != nil { + return "" + } + var seen []string + for _, e := range events.Items { + at := e.LastTimestamp.Time + if at.IsZero() { + at = e.EventTime.Time + } + ours := slices.Contains(names, e.InvolvedObject.Name) || e.InvolvedObject.Kind == "Pod" && strings.HasPrefix(e.InvolvedObject.Name, "kyq-pre-upgrade-") + text := strings.Join(strings.Fields(e.Reason+": "+e.Message), " ") + if e.Type != corev1.EventTypeWarning || !ours || at.Before(start.Add(-time.Second)) || slices.Contains(seen, text) { + continue + } + seen = append(seen, text) + } + if n := len(seen); n > 5 { + seen = seen[n-5:] + } + for i, t := range seen { + if len(t) > 300 { + seen[i] = t[:300] + "..." + } + } + if len(seen) == 0 { + return "" + } + return "; the cluster reports: " + strings.Join(seen, "; ") +} + // preUpgradeClaim creates volume's copy claim with the original's class and size. func (a App) preUpgradeClaim(ctx context.Context, from, volume string) error { pvcs := a.Client.cs.CoreV1().PersistentVolumeClaims(namespaceOf(a.Name)) @@ -283,20 +296,37 @@ func (a App) appNode(ctx context.Context) (string, error) { return nodes[0], nil } -// copyPod mounts each volume's private directory read-only and its copy claim, as the app's -// uid under the app's pod security, with no service token and nothing else. -func (a App) copyPod(from string, volumes []string) *corev1.Pod { - k := a.Catalog.Kubernetes +// copyClaims runs copyCommand for copies in pod, a copyPod. +func (a App) copyClaims(ctx context.Context, pod *corev1.Pod, copies []claimCopy) error { + args := []string{"/bin/sh", "-euc", copyCommand, "copy"} + for _, c := range copies { + args = append(args, c.arg()) + } + return a.Client.podSession(ctx, pod, "pre-upgrade copy", func(name string) error { + out, err := a.Client.ExecReport(ctx, pod.Namespace, name, "copy", args) + if err != nil { + if msg := strings.TrimSpace(string(out)); msg != "" { + return fmt.Errorf("pre-upgrade copy failed: %s", a.Redact.Redact(msg)) + } + return fmt.Errorf("pre-upgrade copy failed: %w", err) + } + return nil + }) +} + +// copyPod mounts each copy's source directory read-only and its copy claim, as uid under the +// pod security sc, with no service token and nothing else. +func (a App) copyPod(copies []claimCopy, uid int64, sc *corev1.PodSecurityContext) *corev1.Pod { res := corev1.ResourceList{corev1.ResourceCPU: resource.MustParse("500m"), corev1.ResourceMemory: resource.MustParse("256Mi")} mounts := []corev1.VolumeMount{{Name: "tmp", MountPath: "/tmp"}} vols := []corev1.Volume{{Name: "tmp", VolumeSource: corev1.VolumeSource{EmptyDir: &corev1.EmptyDirVolumeSource{}}}} - for _, v := range volumes { + for _, c := range copies { vols = append(vols, - corev1.Volume{Name: "src-" + v, VolumeSource: corev1.VolumeSource{PersistentVolumeClaim: &corev1.PersistentVolumeClaimVolumeSource{ClaimName: "vol-" + v, ReadOnly: true}}}, - corev1.Volume{Name: "dst-" + v, VolumeSource: corev1.VolumeSource{PersistentVolumeClaim: &corev1.PersistentVolumeClaimVolumeSource{ClaimName: PreUpgradeClaim(from, v)}}}) + corev1.Volume{Name: "src-" + c.name, VolumeSource: corev1.VolumeSource{PersistentVolumeClaim: &corev1.PersistentVolumeClaimVolumeSource{ClaimName: c.src, ReadOnly: true}}}, + corev1.Volume{Name: "dst-" + c.name, VolumeSource: corev1.VolumeSource{PersistentVolumeClaim: &corev1.PersistentVolumeClaimVolumeSource{ClaimName: c.dst}}}) mounts = append(mounts, - corev1.VolumeMount{Name: "src-" + v, MountPath: "/src/" + v, SubPath: privateDir, ReadOnly: true}, - corev1.VolumeMount{Name: "dst-" + v, MountPath: "/dst/" + v}) + corev1.VolumeMount{Name: "src-" + c.name, MountPath: "/src/" + c.name, SubPath: c.dir, ReadOnly: true}, + corev1.VolumeMount{Name: "dst-" + c.name, MountPath: "/dst/" + c.name}) } return &corev1.Pod{ ObjectMeta: metav1.ObjectMeta{GenerateName: "kyq-pre-upgrade-", Namespace: namespaceOf(a.Name), Labels: workloadLabels(a.ReleaseSet)}, @@ -305,13 +335,13 @@ func (a App) copyPod(from string, volumes []string) *corev1.Pod { ActiveDeadlineSeconds: ptr.To(int64(6 * 3600)), TerminationGracePeriodSeconds: ptr.To(int64(0)), AutomountServiceAccountToken: ptr.To(false), EnableServiceLinks: ptr.To(false), - SecurityContext: podSecurityContext(k), + SecurityContext: sc, Containers: []corev1.Container{{Name: "copy", Image: CredentialGeneratorImage, ImagePullPolicy: corev1.PullIfNotPresent, Command: []string{"/bin/sleep", "21600"}, Resources: corev1.ResourceRequirements{Requests: res, Limits: res}, SecurityContext: &corev1.SecurityContext{ AllowPrivilegeEscalation: ptr.To(false), ReadOnlyRootFilesystem: ptr.To(true), - RunAsNonRoot: ptr.To(true), RunAsUser: ptr.To(k.RunAs), RunAsGroup: ptr.To(k.RunAs), + RunAsNonRoot: ptr.To(true), RunAsUser: ptr.To(uid), RunAsGroup: ptr.To(uid), Capabilities: &corev1.Capabilities{Drop: []corev1.Capability{"ALL"}}, SeccompProfile: &corev1.SeccompProfile{Type: corev1.SeccompProfileTypeRuntimeDefault}, }, diff --git a/internal/kube/preupgrade_test.go b/internal/kube/preupgrade_test.go index f9cd7ce..f640f27 100644 --- a/internal/kube/preupgrade_test.go +++ b/internal/kube/preupgrade_test.go @@ -110,7 +110,7 @@ func TestPreUpgradeCopy(t *testing.T) { t.Errorf("%s: %+v", c.Name, c.ObjectMeta) } } - if len(*calls) != 1 || !slices.Equal((*calls)[0][3:], []string{"copy", "data", "cache"}) || (*calls)[0][2] != copyCommand { + if len(*calls) != 1 || !slices.Equal((*calls)[0][3:], []string{"copy", "data:private", "cache:private"}) || (*calls)[0][2] != copyCommand { t.Fatalf("exec = %v", *calls) } if !slices.Equal(checked, []string{"n1 true", " false"}) { @@ -200,7 +200,7 @@ func TestPreUpgradeCopyFailure(t *testing.T) { *calls = append(*calls, args) return nil, nil } - if _, err := PreUpgradeCopy(ctx, a, "1.10.0"); err != nil || !slices.Equal((*calls)[len(*calls)-1][3:], []string{"copy", "cache"}) { + if _, err := PreUpgradeCopy(ctx, a, "1.10.0"); err != nil || !slices.Equal((*calls)[len(*calls)-1][3:], []string{"copy", "cache:private"}) { t.Fatalf("partial rerun: %v %v", err, *calls) } } diff --git a/test/e2e/identity_cluster_kube_test.go b/test/e2e/identity_cluster_kube_test.go index 7f119bc..f7ab9a4 100644 --- a/test/e2e/identity_cluster_kube_test.go +++ b/test/e2e/identity_cluster_kube_test.go @@ -309,7 +309,7 @@ func TestKubernetesIdentityDatabaseCluster(t *testing.T) { ready++ } } - return ready == 3 && r.primary() != "" && kube.Steps(a)[3].Verify(ctx) == nil && slices.Equal(r.pods(), pods) && + return ready == 3 && r.primary() != "" && kube.Steps(a)[4].Verify(ctx) == nil && slices.Equal(r.pods(), pods) && !slices.ContainsFunc(pods, func(pod string) bool { return !r.signedIn(pod, sessions[pods[1]]) }) }) if got := r.sql("select count(*) from users"); got != "1" { diff --git a/test/e2e/identity_cluster_upgrade_kube_test.go b/test/e2e/identity_cluster_upgrade_kube_test.go new file mode 100644 index 0000000..9d4af2a --- /dev/null +++ b/test/e2e/identity_cluster_upgrade_kube_test.go @@ -0,0 +1,218 @@ +//go:build e2e + +package e2e + +import ( + "context" + "maps" + "os" + "os/exec" + "regexp" + "strings" + "testing" + "time" + + "github.com/Busnes-app/kyquickstart/internal/catalog" + "github.com/Busnes-app/kyquickstart/internal/engine" + "github.com/Busnes-app/kyquickstart/internal/kube" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/client-go/kubernetes" + "k8s.io/client-go/tools/clientcmd" +) + +// cluster17 is the CloudNativePG operand image earlier releases ran. +const cluster17 = "ghcr.io/cloudnative-pg/postgresql:17.12-minimal-trixie@sha256:4ae89311e5031155a139a5c6d31a80f6deb135443711e61ff7df41cb549fdcaa" + +// TestKubernetesIdentityDatabaseClusterUpgrade installs KyIdentity on a Cluster of three +// PostgreSQL 17 instances as an earlier release did, seeds it, and applies this release: the +// Cluster is copied and upgraded to 18 in place with its rows, roles and passwords. Then it +// goes back to 17 from the primary's copy, step by step as docs/guided-setup.md says. +func TestKubernetesIdentityDatabaseClusterUpgrade(t *testing.T) { + ctx := context.Background() + cat, err := catalog.Load(os.DirFS(relaysOffCatalog(t))) + if err != nil { + t.Fatal(err) + } + app := cat["kyidentity"] + image := os.Getenv("KYQ_TEST_IDENTITY_REPLICA_IMAGE") + if image == "" { + image = app.Images[app.Kubernetes.Image] + } + cluster, kc := kindClusterNodes(t, t.TempDir(), 3) + cfg, err := clientcmd.BuildConfigFromFlags("", kc) + if err != nil { + t.Fatal(err) + } + cs := kubernetes.NewForConfigOrDie(cfg) + connected, err := kube.Connect(kc, "") + if err != nil { + t.Fatal(err) + } + app.Kubernetes = app.Kubernetes.WithHost(catalogIdentityHost) + cluster18 := app.Images[app.Kubernetes.Replicas.ClusterImage] + app.Images = map[string]string{"kyidentity": image, "postgres_cluster": cluster18} + kindLoad(t, cluster, image) + r := &replicaCluster{t: t, ctx: ctx, cs: cs, c: connected, app: app} + kubectl := func(stdin string, args ...string) string { + t.Helper() + cmd := exec.Command("docker", append([]string{"exec", "-i", cluster + "-control-plane", "kubectl", "--kubeconfig", "/etc/kubernetes/admin.conf"}, args...)...) + cmd.Stdin = strings.NewReader(stdin) + out, err := cmd.CombinedOutput() + if err != nil { + t.Fatalf("kubectl %v: %v\n%s", args, err, out) + } + return strings.TrimSpace(string(out)) + } + t.Cleanup(func() { + if t.Failed() { + t.Logf("logs:\n%s", r.logs()) + t.Logf("cluster:\n%s", kubectl("", "-n", replicaNS, "get", "cluster,pods,pvc,jobs", "-o", "wide")) + t.Logf("describe:\n%s", kubectl("", "-n", replicaNS, "describe", "cluster", "database")) + t.Logf("operator:\n%s", kubectl("", "-n", operatorNS, "logs", "deploy/cnpg-controller-manager", "--tail", "80")) + } + }) + op := kube.App{Name: "cloudnative-pg", Client: connected, Catalog: cat["cloudnative-pg"], ReleaseSet: "e2e", Redact: &engine.Redactor{}} + if applied, err := r.run(kube.Steps(op)); err != nil { + t.Fatalf("operator: %v after %v", err, applied) + } + plan := func(clusterImage string) kube.App { + a := r.plan(3, "") + k := *a.Catalog.Kubernetes + k.DatabaseInstances = 3 + a.Catalog.Kubernetes = &k + a.Catalog.Images = maps.Clone(a.Catalog.Images) + a.Catalog.Images["postgres_cluster"] = clusterImage + return a + } + version := func() string { return r.sql("show server_version_num")[:2] } + // login connects as role over the network to the primary's Service, with password. + login := func(role, password string) (string, error) { + out, err := r.c.Exec(ctx, replicaNS, r.primary(), "postgres", []string{"env", "PGPASSWORD=" + password, "PGCONNECT_TIMEOUT=10", "psql", + "host=database-rw." + replicaNS + ".svc user=" + role + " dbname=kyidentity sslmode=require", "-Atc", "select count(*) from upgrade_check"}) + return strings.TrimSpace(string(out)), err + } + checkData := func(when, rows string) { + t.Helper() + if got := r.sql("select count(*) from upgrade_check"); got != rows { + t.Fatalf("%s: %s rows", when, got) + } + if got, err := login("reader", "reader-pw"); err != nil || got != rows { + t.Fatalf("%s: reader's password: %q %v", when, got, err) + } + if _, err := login("reader", "wrong-pw"); err == nil { + t.Fatalf("%s: a wrong password is accepted: the check above proves nothing", when) + } + } + + // The earlier release's install, on 17, with data and a role of its own. + started := time.Now() + if applied, err := r.run(kube.Steps(plan(cluster17))); err != nil { + t.Fatalf("install on 17: %v after %v", err, applied) + } + t.Logf("install on 17 took %s", time.Since(started).Round(time.Second)) + if v := version(); v != "17" { + t.Fatalf("installed on PostgreSQL %s", v) + } + r.sql("create table upgrade_check(n int primary key, s text collate \"C\"); insert into upgrade_check select g, md5(g::text) from generate_series(1, 1000) g; create role reader login password 'reader-pw'; grant select on upgrade_check to reader") + pods := r.pods() + password := string(r.secret("kyq-replica-keys")["bootstrap-admin-pass"]) + session := r.signIn(pods[0], password) + checkData("on 17", "1000") + primary := r.primary() + + // This release: copied, then upgraded in place. + a := plan(cluster18) + started = time.Now() + applied, err := r.run(kube.Steps(a)) + if err != nil { + t.Fatalf("upgrade: %v after %v", err, applied) + } + t.Logf("the upgrade took %s, steps %v", time.Since(started).Round(time.Second), applied) + for _, s := range kube.Steps(a) { + if n, ok := s.(engine.Noter); ok && s.ID() == "kyidentity.database-upgrade" { + t.Logf("note: %s", n.Note()) + } + } + if v := version(); v != "18" { + t.Fatalf("after the upgrade: PostgreSQL %s", v) + } + checkData("on 18", "1000") + for _, pod := range r.pods() { + if !r.signedIn(pod, session) { + t.Fatalf("%s refuses a session made on 17", pod) + } + } + copies, err := cs.CoreV1().PersistentVolumeClaims(replicaNS).List(ctx, metav1.ListOptions{LabelSelector: "kyquickstart/postgres=17"}) + if err != nil || len(copies.Items) != 3 { + t.Fatalf("copies: %v %v", copies, err) + } + var primaryCopy string + for _, c := range copies.Items { + if c.Annotations["kyquickstart/pre-upgrade"] != "verified" || c.Annotations["kyquickstart/copied-at"] == "" { + t.Fatalf("copy %s: %v", c.Name, c.Annotations) + } + if c.Labels["kyquickstart/instance-role"] == "primary" { + primaryCopy = c.Name + } + } + // Named for the claim and the attempt: pre-upgrade-pg17--. + if !regexp.MustCompile(`^pre-upgrade-pg17-` + primary + `-[0-9]{8}-[0-9]{6}$`).MatchString(primaryCopy) { + t.Fatalf("the primary's copy is %q, the primary was %s", primaryCopy, primary) + } + if applied, err := r.run(kube.Steps(a)); err != nil || len(applied) != 0 { + t.Fatalf("second apply: %v, applied %v", err, applied) + } + r.sql("insert into upgrade_check values (1001, 'written on 18')") + + // Back to 17 from the primary's copy, as docs/guided-setup.md "Going back to PostgreSQL 17" says. + pv := kubectl("", "-n", replicaNS, "get", "pvc", primaryCopy, "-o", "jsonpath={.spec.volumeName}") + class := kubectl("", "-n", replicaNS, "get", "pvc", primaryCopy, "-o", "jsonpath={.spec.storageClassName}") + size := kubectl("", "-n", replicaNS, "get", "pvc", primaryCopy, "-o", "jsonpath={.spec.resources.requests.storage}") + kubectl("", "patch", "pv", pv, "-p", `{"spec":{"persistentVolumeReclaimPolicy":"Retain"}}`) + kubectl("", "-n", replicaNS, "delete", "cluster", "database", "--wait") + r.eventually("the 18 Cluster's claims are gone", func() bool { + left, err := cs.CoreV1().PersistentVolumeClaims(replicaNS).List(ctx, metav1.ListOptions{LabelSelector: "cnpg.io/cluster=database"}) + return err == nil && len(left.Items) == 0 && len(r.instances()) == 0 + }) + kubectl("", "-n", replicaNS, "delete", "pvc", primaryCopy, "--wait") + kubectl("", "patch", "pv", pv, "--type", "json", "-p", `[{"op":"remove","path":"/spec/claimRef"}]`) + kubectl(`apiVersion: v1 +kind: PersistentVolumeClaim +metadata: + name: database-1 + namespace: `+replicaNS+` + labels: + cnpg.io/cluster: database + cnpg.io/instanceName: database-1 + cnpg.io/instanceRole: primary + role: primary + cnpg.io/pvcRole: PG_DATA + annotations: + cnpg.io/nodeSerial: "1" + cnpg.io/pvcStatus: ready +spec: + accessModes: [ReadWriteOnce] + storageClassName: `+class+` + volumeName: `+pv+` + resources: + requests: + storage: `+size+` +`, "apply", "-f", "-") + // The previous release's apply makes the Cluster on 17, which adopts the claim. + started = time.Now() + if applied, err := r.run(kube.Steps(plan(cluster17))); err != nil { + t.Fatalf("back on 17: %v after %v", err, applied) + } + t.Logf("the rollback took %s", time.Since(started).Round(time.Second)) + if v := version(); v != "17" { + t.Fatalf("after the rollback: PostgreSQL %s", v) + } + checkData("back on 17", "1000") + r.eventually("KyIdentity accepts the session made on 17 again", func() bool { + pods := r.pods() + return len(pods) == 3 && r.signedIn(pods[0], session) + }) + if n := len(r.instances()); n != 3 { + t.Fatalf("%d instances after the rollback", n) + } +}