From 6d1eeba65b243e2060b440957d6b7d25125b92ff Mon Sep 17 00:00:00 2001 From: Alexey Artamonov Date: Tue, 24 Nov 2026 14:34:28 +0300 Subject: [PATCH] fix(postgres): bound a backup whose cnpg Backup stalls in pending CloudNativePG keeps a Backup pending either behind a started or running backup of the same Cluster, which is healthy, or because the instance to run it on cannot be found or is not ready, which lasts as long as the Cluster is fenced. The BackupJob waited on both forever. The driver now tells the two apart by whether any backup of the Cluster is started or running. It does not model which pending Backup CloudNativePG lets through first. With none running, the job records a CNPGBackupStalled condition and fails once that has lasted the backup deadline. Before it gives up it reads the Cluster's backups again from the apiserver, since the cache can still show pending one that has just started. Its own Backup is deleted, conditionally on the version read so a Backup CloudNativePG has just started is kept, because otherwise it would run later with no Backup recording it. The give-up is persisted before the delete, so a Backup found missing afterwards fails the job only when the driver removed it; one deleted by hand is replaced and its stall counts afresh. The reason CloudNativePG gives exists only as an event on a Backup, so the driver reads the newest Warning on its own Backup, or on another pending backup of the Cluster when its own carries none, by UID and uncached, which needs list on events but no watch. A job is no longer held on the plugin rollout another job started when the Cluster is fenced and every instance pod postdates that attach: a fenced Cluster is neither healthy nor ready until the fence is lifted, so waiting on that would only delay the bound by up to the rollout deadline. The postgres e2e fences the source Cluster, checks that a BackupJob reports the stall with that reason, then lifts the fence and checks the same job completes with the stall ended. That exercises the events grant and the involvedObject.uid selector against a real apiserver. The step creates the BackupJob only once every instance pod has gone NotReady, since the fence takes effect asynchronously and CloudNativePG starts a Backup on a target that is still Ready. Assisted-by: LLM Signed-off-by: Alexey Artamonov Signed-off-by: Andrey Kolkov --- examples/backups/postgres/00-helpers.sh | 3 + examples/backups/postgres/README.md | 2 +- examples/backups/postgres/cleanup.sh | 9 +- examples/backups/postgres/run-all.sh | 77 +- hack/e2e-chainsaw/postgres/chainsaw-test.yaml | 8 +- .../cnpg_pending_bound_test.go | 1034 +++++++++++++++++ .../cnpgstrategy_controller.go | 293 ++++- .../cnpgstrategy_controller_test.go | 3 + .../templates/rbac.yaml | 6 +- 9 files changed, 1419 insertions(+), 16 deletions(-) create mode 100644 internal/backupcontroller/cnpg_pending_bound_test.go diff --git a/examples/backups/postgres/00-helpers.sh b/examples/backups/postgres/00-helpers.sh index ac004e504..c935bf093 100755 --- a/examples/backups/postgres/00-helpers.sh +++ b/examples/backups/postgres/00-helpers.sh @@ -28,6 +28,9 @@ export BACKUPJOB_NAME="${BACKUPJOB_NAME:-pg-src-adhoc}" # is the deterministic "WAL past the recovery target is archived" gate for the # point-in-time restore (see run-all.sh step 45). export BACKUPJOB_POSTMARKER_NAME="${BACKUPJOB_POSTMARKER_NAME:-pg-src-postmarker}" +# A BackupJob submitted while the source Cluster is fenced, so CloudNativePG +# keeps its Backup pending until the fence is lifted (see run-all.sh step 26). +export BACKUPJOB_FENCED_NAME="${BACKUPJOB_FENCED_NAME:-pg-src-fenced}" export RESTOREJOB_TOCOPY_NAME="${RESTOREJOB_TOCOPY_NAME:-pg-src-to-pg-target}" export RESTOREJOB_PITR_NAME="${RESTOREJOB_PITR_NAME:-pg-src-to-pg-target-pitr}" export RESTOREJOB_UNREACHABLE_NAME="${RESTOREJOB_UNREACHABLE_NAME:-pg-src-to-pg-target-unreachable}" diff --git a/examples/backups/postgres/README.md b/examples/backups/postgres/README.md index 998149101..44491dee4 100644 --- a/examples/backups/postgres/README.md +++ b/examples/backups/postgres/README.md @@ -31,7 +31,7 @@ NAMESPACE=tenant-root examples/backups/postgres/run-all.sh NAMESPACE=tenant-root examples/backups/postgres/cleanup.sh ``` -`run-all.sh` writes a sentinel row into the source, waits for the `BackupJob` to reach `Succeeded`, restores to a copy, and asserts the sentinel round-tripped through S3 into the restored copy. It then runs a **point-in-time recovery**: it writes a `before` marker, captures the server timestamp, writes an `after` marker, and restores the copy to that timestamp (`45-restorejob-pitr.yaml`), asserting the `before` row survived and the `after` row did not. Finally it submits a RestoreJob with a `recoveryTime` an hour in the future and asserts it **fails fast** with `status.phase: Failed` and reason `RecoveryTargetUnreachable` (rather than hanging to the restore deadline). Set `SKIP_RESTORE=1` to stop after a successful backup, or `SKIP_PITR=1` to stop after the latest-point restore. +`run-all.sh` writes a sentinel row into the source, waits for the `BackupJob` to reach `Succeeded`, then fences the source Cluster for a while: a second `BackupJob` must report the stall (`CNPGBackupStalled`) with the reason CloudNativePG recorded, and complete once the fence is lifted. It then restores to a copy, and asserts the sentinel round-tripped through S3 into the restored copy. It then runs a **point-in-time recovery**: it writes a `before` marker, captures the server timestamp, writes an `after` marker, and restores the copy to that timestamp (`45-restorejob-pitr.yaml`), asserting the `before` row survived and the `after` row did not. Finally it submits a RestoreJob with a `recoveryTime` an hour in the future and asserts it **fails fast** with `status.phase: Failed` and reason `RecoveryTargetUnreachable` (rather than hanging to the restore deadline). Set `SKIP_RESTORE=1` to stop after a successful backup, or `SKIP_PITR=1` to stop after the latest-point restore. ## Automated e2e diff --git a/examples/backups/postgres/cleanup.sh b/examples/backups/postgres/cleanup.sh index 52bab728e..7b8f86ee7 100755 --- a/examples/backups/postgres/cleanup.sh +++ b/examples/backups/postgres/cleanup.sh @@ -20,6 +20,13 @@ for app in "$PG_SRC_NAME" "$PG_TARGET_NAME"; do fi done +# Run-all step 26 fences the source Cluster; an aborted run leaves it fenced. +if kubectl get clusters.postgresql.cnpg.io "$PG_SRC_CLUSTER" --namespace "$NAMESPACE" >/dev/null 2>&1; then + log_substep "Lifting the fence on ${PG_SRC_CLUSTER} (no-op if not fenced)..." + kubectl annotate clusters.postgresql.cnpg.io "$PG_SRC_CLUSTER" --namespace "$NAMESPACE" \ + 'cnpg.io/fencedInstances-' >/dev/null || true +fi + log_substep "Deleting RestoreJobs..." kubectl -n "$NAMESPACE" delete restorejob.backups.cozystack.io \ "$RESTOREJOB_TOCOPY_NAME" "$RESTOREJOB_PITR_NAME" "$RESTOREJOB_UNREACHABLE_NAME" \ @@ -28,7 +35,7 @@ kubectl -n "$NAMESPACE" delete restorejob.backups.cozystack.io \ log_substep "Deleting Plan + BackupJob + derived Backup artefacts..." kubectl -n "$NAMESPACE" delete plan.backups.cozystack.io "$PLAN_NAME" --ignore-not-found kubectl -n "$NAMESPACE" delete backupjob.backups.cozystack.io \ - "$BACKUPJOB_NAME" "$BACKUPJOB_POSTMARKER_NAME" --ignore-not-found + "$BACKUPJOB_NAME" "$BACKUPJOB_POSTMARKER_NAME" "$BACKUPJOB_FENCED_NAME" --ignore-not-found # Only the Backups of THIS demo's apps — never `--all`: on a shared cluster the # namespace can hold Backup artefacts of other applications and flows. for b in $(kubectl -n "$NAMESPACE" get backups.backups.cozystack.io \ diff --git a/examples/backups/postgres/run-all.sh b/examples/backups/postgres/run-all.sh index 83e7cfb7a..ec6bfedc0 100755 --- a/examples/backups/postgres/run-all.sh +++ b/examples/backups/postgres/run-all.sh @@ -8,7 +8,8 @@ # automated test can never drift. Stops on the first failure. # # Flow: Bucket -> source Postgres (+ a sentinel row) -> CNPG strategy + -# BackupClass -> ad-hoc BackupJob (wait Succeeded) -> empty target Postgres + +# BackupClass -> ad-hoc BackupJob (wait Succeeded) -> a BackupJob on a fenced +# Cluster (stall reported, then Succeeded once unfenced) -> empty target Postgres + # to-copy RestoreJob (wait Succeeded) -> assert the sentinel round-tripped # through S3 into the restored copy. # @@ -158,6 +159,80 @@ BACKUP_NAME=$(kubectl -n "$NAMESPACE" get backupjobs.backups.cozystack.io "$BACK [[ -n "$BACKUP_NAME" ]] || { log_error "BackupJob succeeded but reported no backupRef"; exit 1; } log_success "Backup artefact: ${BACKUP_NAME}" +print_header "Step 26: A BackupJob on a fenced Cluster reports the stall, then completes once the fence is lifted" +# Fencing stops PostgreSQL on every instance, so no backup target is ready and +# CloudNativePG keeps the Backup pending with a Warning event on it, while no +# other backup of the Cluster runs. The driver must record that as a stall +# carrying the event, which it reads by the Backup's UID, and must end the +# stall once CloudNativePG starts the Backup. Failing at the 30m deadline is +# left to the unit tests. +kubectl annotate clusters.postgresql.cnpg.io "$PG_SRC_CLUSTER" --namespace "$NAMESPACE" \ + --overwrite 'cnpg.io/fencedInstances=["*"]' +# The fence takes effect asynchronously, and CloudNativePG starts a Backup on +# a target instance that is still Ready, so the BackupJob is created only once +# every instance has gone NotReady. +FENCED_PODS=$(kubectl get pods --namespace "$NAMESPACE" \ + --selector "cnpg.io/cluster=${PG_SRC_CLUSTER},cnpg.io/podRole=instance" \ + --output jsonpath='{.items[*].metadata.name}') +[[ -n "$FENCED_PODS" ]] || { log_error "no instance pods of ${PG_SRC_CLUSTER} to wait on"; exit 1; } +for pod in $FENCED_PODS; do + wait_for_field pods "$pod" '{.status.conditions[?(@.type=="Ready")].status}' False "$NAMESPACE" 300 +done +kubectl apply --namespace "$NAMESPACE" --filename - < time.Minute { + t.Errorf("%s started at %s, want now: the bound counts from when the stall was first seen", backupCondCNPGBackupStalled, stalled.LastTransitionTime) + } + ready := apimeta.FindStatusCondition(j.Status.Conditions, "Ready") + if ready == nil || ready.Reason != "WaitingForCNPGBackup" { + t.Fatalf("Ready condition = %+v, want WaitingForCNPGBackup", ready) + } + for _, want := range []string{"bj-cnpg", "BackupPending", pendingTargetEvent} { + if !strings.Contains(ready.Message, want) { + t.Errorf("Ready message %q does not mention %q", ready.Message, want) + } + } + for _, unwanted := range []string{"FindingPod", "Restarted backup"} { + if strings.Contains(ready.Message, unwanted) { + t.Errorf("Ready message %q carries %q instead of the newest Warning", ready.Message, unwanted) + } + } +} + +// TestReconcileCNPG_StalledPendingBackupFailsAtBound: once the Backup has been +// stalled for the bound, the BackupJob fails with the cause and the Backup is +// deleted, so CloudNativePG does not run it later with no Backup recording it. +func TestReconcileCNPG_StalledPendingBackupFailsAtBound(t *testing.T) { + since := time.Now().Add(-cnpgDefaultBackupDeadline - time.Minute) + f, b := newPendingBoundFixture(t, "pending", &since) + f.recordCNPGEvent(b, corev1.EventTypeWarning, "BackupPending", pendingTargetEvent, time.Now().Add(-time.Minute)) + + j, backups := f.pass() + if j.Status.Phase != backupsv1alpha1.BackupJobPhaseFailed { + t.Fatalf("BackupJob phase = %q, want Failed once the Backup is stalled past the bound", j.Status.Phase) + } + if len(backups) != 0 { + t.Fatalf("cnpg.io/Backups = %v, want the abandoned one deleted", cnpgBackupNames(backups)) + } + for _, want := range []string{"bj-cnpg", pendingTargetEvent, cnpgDefaultBackupDeadline.String(), "deleted"} { + if !strings.Contains(j.Status.Message, want) { + t.Errorf("failure message %q does not mention %q", j.Status.Message, want) + } + } + + // A further pass, as after a lost status write, must not create a new + // cnpg.io/Backup for a job that gave up. + j.Status.Phase = backupsv1alpha1.BackupJobPhaseRunning + if err := f.c.Status().Update(context.Background(), j); err != nil { + t.Fatalf("roll the BackupJob back to Running: %v", err) + } + j, backups = f.pass() + if len(backups) != 0 { + t.Fatalf("cnpg.io/Backups = %v after the job gave up, want none recreated", cnpgBackupNames(backups)) + } + if j.Status.Phase != backupsv1alpha1.BackupJobPhaseFailed { + t.Errorf("BackupJob phase = %q, want Failed", j.Status.Phase) + } + if !strings.Contains(j.Status.Message, pendingTargetEvent) { + t.Errorf("failure message %q after a lost status write does not carry the recorded reason", j.Status.Message) + } +} + +// TestReconcileCNPG_StalledBackupThatStartsIsNotDeleted: CloudNativePG may +// start the Backup between the driver's read and its delete. The delete is +// conditional on the Backup it read, so a Backup that moved on is kept and +// the job is not failed. +func TestReconcileCNPG_StalledBackupThatStartsIsNotDeleted(t *testing.T) { + since := time.Now().Add(-cnpgDefaultBackupDeadline - time.Minute) + f, _ := newPendingBoundFixture(t, "pending", &since) + f.r.Client = interceptor.NewClient(f.c.(client.WithWatch), interceptor.Funcs{ + Delete: func(ctx context.Context, cl client.WithWatch, obj client.Object, opts ...client.DeleteOption) error { + if _, ok := obj.(*cnpgtypes.Backup); ok { + f.setCNPGPhase(obj.GetName(), "started") + } + return cl.Delete(ctx, obj, opts...) + }, + }) + + ctx := context.Background() + j := &backupsv1alpha1.BackupJob{} + if err := f.c.Get(ctx, client.ObjectKey{Namespace: rolloutNS, Name: "bj"}, j); err != nil { + t.Fatalf("get BackupJob: %v", err) + } + _, err := f.r.reconcileCNPG(ctx, j, f.resolved) + if !apierrors.IsConflict(err) { + t.Fatalf("reconcileCNPG error = %v, want the Conflict from the conditional delete", err) + } + persisted := &backupsv1alpha1.BackupJob{} + if err := f.c.Get(ctx, client.ObjectKey{Namespace: rolloutNS, Name: "bj"}, persisted); err != nil { + t.Fatalf("get BackupJob: %v", err) + } + if persisted.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed { + t.Fatalf("BackupJob failed although its Backup started: %s", persisted.Status.Message) + } + b := &cnpgtypes.Backup{} + if err := f.c.Get(ctx, client.ObjectKey{Namespace: rolloutNS, Name: "bj-cnpg"}, b); err != nil { + t.Fatalf("the Backup CloudNativePG started was deleted: %v", err) + } +} + +// TestReconcileCNPG_QueuedBackupIsNotBounded: CloudNativePG keeps a Backup +// pending while another backup of the same Cluster runs. That wait is healthy +// and does not count toward the bound, however long the job has been stalled +// before it. +func TestReconcileCNPG_QueuedBackupIsNotBounded(t *testing.T) { + for _, tc := range []struct { + name string + aheadPhase string + aheadAge time.Duration + }{ + {name: "another backup runs", aheadPhase: "running", aheadAge: time.Minute}, + {name: "another backup started", aheadPhase: "started", aheadAge: time.Minute}, + } { + t.Run(tc.name, func(t *testing.T) { + since := time.Now().Add(-cnpgDefaultBackupDeadline - time.Minute) + f, _ := newPendingBoundFixture(t, "pending", &since) + f.create(newPendingBoundCNPGBackup("scheduled", time.Now().Add(-tc.aheadAge), tc.aheadPhase, nil)) + + j, backups := f.pass() + if j.Status.Phase != backupsv1alpha1.BackupJobPhaseRunning { + t.Fatalf("BackupJob phase = %q (%s), want Running while queued", j.Status.Phase, j.Status.Message) + } + if len(backups) != 2 { + t.Fatalf("cnpg.io/Backups = %v, want both kept", cnpgBackupNames(backups)) + } + if cond := apimeta.FindStatusCondition(j.Status.Conditions, backupCondCNPGBackupStalled); cond == nil || cond.Status != metav1.ConditionFalse { + t.Fatalf("%s condition = %+v, want False while queued, so the next stall counts afresh", backupCondCNPGBackupStalled, cond) + } + ready := apimeta.FindStatusCondition(j.Status.Conditions, "Ready") + if ready == nil || !strings.Contains(ready.Message, "scheduled") { + t.Errorf("Ready condition = %+v, want it to name the backup it waits behind", ready) + } + }) + } +} + +// TestReconcileCNPG_QueueIsPerCluster: backups of another Cluster in the same +// namespace, and finished backups of this one, do not hold the Backup back. +func TestReconcileCNPG_QueueIsPerCluster(t *testing.T) { + since := time.Now().Add(-cnpgDefaultBackupDeadline - time.Minute) + f, _ := newPendingBoundFixture(t, "pending", &since) + other := newPendingBoundCNPGBackup("other-cluster", time.Now().Add(-2*time.Hour), "running", nil) + other.Spec.Cluster.Name = "postgres-other" + f.create(other) + done := newPendingBoundCNPGBackup("done", time.Now().Add(-2*time.Hour), cnpgBackupPhaseComplete, nil) + f.create(done) + broken := newPendingBoundCNPGBackup("broken", time.Now().Add(-2*time.Hour), cnpgBackupPhaseFailed, nil) + f.create(broken) + // A finished backup's Warning is not why this Backup waits, so it must + // not stand in for the reason. + f.recordEvent("done-warning", done, "done reason", time.Now().Add(-time.Minute)) + f.recordEvent("broken-warning", broken, "broken reason", time.Now().Add(-time.Minute)) + + j, _ := f.pass() + if j.Status.Phase != backupsv1alpha1.BackupJobPhaseFailed { + t.Fatalf("BackupJob phase = %q (%s), want Failed: nothing of this Cluster is ahead of the stalled Backup", j.Status.Phase, j.Status.Message) + } + for _, unwanted := range []string{"other-cluster", "done", "broken"} { + if strings.Contains(j.Status.Message, unwanted) { + t.Errorf("failure message %q names %s, which does not hold the Backup", j.Status.Message, unwanted) + } + } +} + +// TestReconcileCNPG_StallCountsAfresh: CloudNativePG puts a Backup back into +// pending when it restarts it on another instance. A stall that ended, here +// by the Backup starting, does not carry its time into the next one. +func TestReconcileCNPG_StallCountsAfresh(t *testing.T) { + since := time.Now().Add(-cnpgDefaultBackupDeadline - time.Minute) + f, _ := newPendingBoundFixture(t, "started", &since) + + j, _ := f.pass() + if cond := apimeta.FindStatusCondition(j.Status.Conditions, backupCondCNPGBackupStalled); cond == nil || cond.Status != metav1.ConditionFalse { + t.Fatalf("%s condition = %+v, want False once the Backup started", backupCondCNPGBackupStalled, cond) + } + + f.setCNPGPhase("bj-cnpg", "pending") + j, backups := f.pass() + if j.Status.Phase != backupsv1alpha1.BackupJobPhaseRunning { + t.Fatalf("BackupJob phase = %q (%s), want Running: the new stall has just begun", j.Status.Phase, j.Status.Message) + } + if len(backups) != 1 { + t.Fatalf("cnpg.io/Backups = %v, want the restarted one kept", cnpgBackupNames(backups)) + } + cond := apimeta.FindStatusCondition(j.Status.Conditions, backupCondCNPGBackupStalled) + if cond == nil || cond.Status != metav1.ConditionTrue || time.Since(cond.LastTransitionTime.Time) > time.Minute { + t.Fatalf("%s condition = %+v, want True from now", backupCondCNPGBackupStalled, cond) + } +} + +// TestReconcileCNPG_UnreadableEventsDoNotHideTheStall: without the event the +// BackupJob still reports the stall and still fails at the bound, and says +// the reason could not be read rather than omitting it. +func TestReconcileCNPG_UnreadableEventsDoNotHideTheStall(t *testing.T) { + since := time.Now().Add(-cnpgDefaultBackupDeadline - time.Minute) + f, _ := newPendingBoundFixture(t, "pending", &since) + f.r.Client = interceptor.NewClient(f.c.(client.WithWatch), interceptor.Funcs{ + List: func(ctx context.Context, cl client.WithWatch, list client.ObjectList, opts ...client.ListOption) error { + if _, ok := list.(*corev1.EventList); ok { + return apierrors.NewForbidden(corev1.Resource("events"), "", errors.New("no list grant")) + } + return cl.List(ctx, list, opts...) + }, + }) + + j, backups := f.pass() + if j.Status.Phase != backupsv1alpha1.BackupJobPhaseFailed { + t.Fatalf("BackupJob phase = %q (%s), want Failed at the bound", j.Status.Phase, j.Status.Message) + } + if len(backups) != 0 { + t.Fatalf("cnpg.io/Backups = %v, want the abandoned one deleted", cnpgBackupNames(backups)) + } + if !strings.Contains(j.Status.Message, "forbidden") { + t.Errorf("failure message %q does not say why the CloudNativePG reason is missing", j.Status.Message) + } +} + +// TestReconcileCNPG_StalledBackupAlreadyGoneStillFails: a Backup that is gone +// by the time the driver deletes it, for example removed by hand, still ends +// the job, which otherwise would retry the delete forever. +func TestReconcileCNPG_StalledBackupAlreadyGoneStillFails(t *testing.T) { + since := time.Now().Add(-cnpgDefaultBackupDeadline - time.Minute) + f, _ := newPendingBoundFixture(t, "pending", &since) + f.r.Client = interceptor.NewClient(f.c.(client.WithWatch), interceptor.Funcs{ + Delete: func(ctx context.Context, cl client.WithWatch, obj client.Object, opts ...client.DeleteOption) error { + if err := cl.Delete(ctx, obj); err != nil { + return err + } + return cl.Delete(ctx, obj, opts...) + }, + }) + + j, _ := f.pass() + if j.Status.Phase != backupsv1alpha1.BackupJobPhaseFailed { + t.Fatalf("BackupJob phase = %q (%s), want Failed", j.Status.Phase, j.Status.Message) + } +} + +// TestReconcileCNPG_EndedStallDoesNotFailTheJob: only a stall still going on +// counts. A job whose Backup was queued, and then removed, gets a new Backup +// rather than failing on the time of a stall that is over. +func TestReconcileCNPG_EndedStallDoesNotFailTheJob(t *testing.T) { + j := newRolloutBackupJob(time.Now().Add(-2 * cnpgDefaultBackupDeadline)) + j.Status.Phase = backupsv1alpha1.BackupJobPhaseRunning + j.Status.Conditions = []metav1.Condition{{ + Type: backupCondCNPGBackupStalled, + Status: metav1.ConditionFalse, + Reason: "Queued", + LastTransitionTime: metav1.NewTime(time.Now().Add(-cnpgDefaultBackupDeadline - time.Minute)), + }} + f := newCNPGRolloutFixture(t, j, + newRolloutCluster(cnpgClusterHealthyPhase, buildBarmanPlugin(rolloutCluster, rolloutCluster)), + newRolloutInstancePod(time.Now().Add(-time.Hour))) + + got, backups := f.pass() + if got.Status.Phase != backupsv1alpha1.BackupJobPhaseRunning { + t.Fatalf("BackupJob phase = %q (%s), want Running", got.Status.Phase, got.Status.Message) + } + if len(backups) != 1 { + t.Fatalf("cnpg.io/Backups = %v, want a new one", cnpgBackupNames(backups)) + } +} + +// TestReconcileCNPG_ProgressingBackupGetsNoStallCondition: a Backup that runs +// without ever stalling leaves no stall condition on the job. +func TestReconcileCNPG_ProgressingBackupGetsNoStallCondition(t *testing.T) { + f, _ := newPendingBoundFixture(t, "running", nil) + + j, _ := f.pass() + if cond := apimeta.FindStatusCondition(j.Status.Conditions, backupCondCNPGBackupStalled); cond != nil { + t.Fatalf("%s condition = %+v on a job whose Backup never stalled", backupCondCNPGBackupStalled, cond) + } +} + +// TestReconcileCNPG_BackupAmongPendingOnesIsBounded: other pending backups of +// the Cluster do not make the wait healthy, whichever of them CloudNativePG +// would let through first. With no warning on its own Backup, the job fails at +// the bound with the reason recorded on another pending one, and deletes its +// own Backup only: the other may belong to another job, or to a +// ScheduledBackup. +func TestReconcileCNPG_BackupAmongPendingOnesIsBounded(t *testing.T) { + for _, tc := range []struct { + name string + otherPhase string + otherAge time.Duration + otherName string + }{ + {name: "an older backup is pending", otherPhase: "pending", otherAge: 2 * time.Hour, otherName: "scheduled"}, + {name: "an older backup not yet seen by CloudNativePG", otherPhase: "", otherAge: 2 * time.Hour, otherName: "scheduled"}, + {name: "a newer backup is pending", otherPhase: "pending", otherAge: -time.Minute, otherName: "later"}, + } { + t.Run(tc.name, func(t *testing.T) { + since := time.Now().Add(-cnpgDefaultBackupDeadline - time.Minute) + f, _ := newPendingBoundFixture(t, "pending", &since) + other := newPendingBoundCNPGBackup(tc.otherName, time.Now().Add(-tc.otherAge), tc.otherPhase, nil) + f.create(other) + f.recordCNPGEvent(other, corev1.EventTypeWarning, "BackupPending", pendingTargetEvent, time.Now().Add(-time.Minute)) + + j, backups := f.pass() + if j.Status.Phase != backupsv1alpha1.BackupJobPhaseFailed { + t.Fatalf("BackupJob phase = %q (%s), want Failed", j.Status.Phase, j.Status.Message) + } + if names := cnpgBackupNames(backups); len(names) != 1 || names[0] != tc.otherName { + t.Fatalf("cnpg.io/Backups = %v, want only %s, which the job does not own", names, tc.otherName) + } + for _, want := range []string{tc.otherName, pendingTargetEvent} { + if !strings.Contains(j.Status.Message, want) { + t.Errorf("failure message %q does not mention %q", j.Status.Message, want) + } + } + }) + } +} + +// TestReconcileCNPG_OwnReasonComesFirst: a warning on the job's own Backup is +// its reason, even when another pending backup of the Cluster carries a newer +// one. +func TestReconcileCNPG_OwnReasonComesFirst(t *testing.T) { + f, b := newPendingBoundFixture(t, "pending", nil) + other := newPendingBoundCNPGBackup("other", b.CreationTimestamp.Time, "pending", nil) + f.create(other) + f.recordCNPGEvent(b, corev1.EventTypeWarning, "BackupPending", "own reason", time.Now().Add(-time.Hour)) + f.recordCNPGEvent(other, corev1.EventTypeWarning, "BackupPending", "other reason", time.Now().Add(-time.Minute)) + + j, _ := f.pass() + stalled := apimeta.FindStatusCondition(j.Status.Conditions, backupCondCNPGBackupStalled) + if stalled == nil || !strings.Contains(stalled.Message, "own reason") || strings.Contains(stalled.Message, "other reason") { + t.Fatalf("%s condition = %+v, want the reason of the job's own Backup only", backupCondCNPGBackupStalled, stalled) + } +} + +// TestCNPGEventTime: the time an event was last seen, whichever field the +// recorder filled in. core/v1 recorders set LastTimestamp, events.k8s.io ones +// EventTime and, for a repeated event, Series. +func TestCNPGEventTime(t *testing.T) { + base := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) + for _, tc := range []struct { + name string + e corev1.Event + want time.Time + }{ + {name: "series", want: base.Add(3 * time.Hour), e: corev1.Event{ + Series: &corev1.EventSeries{LastObservedTime: metav1.NewMicroTime(base.Add(3 * time.Hour))}, + EventTime: metav1.NewMicroTime(base.Add(time.Hour)), + }}, + {name: "series over last timestamp", want: base.Add(3 * time.Hour), e: corev1.Event{ + Series: &corev1.EventSeries{LastObservedTime: metav1.NewMicroTime(base.Add(3 * time.Hour))}, + LastTimestamp: metav1.NewTime(base.Add(2 * time.Hour)), + }}, + {name: "last timestamp", want: base.Add(2 * time.Hour), e: corev1.Event{ + LastTimestamp: metav1.NewTime(base.Add(2 * time.Hour)), + EventTime: metav1.NewMicroTime(base.Add(time.Hour)), + }}, + {name: "event time", want: base.Add(time.Hour), e: corev1.Event{ + EventTime: metav1.NewMicroTime(base.Add(time.Hour)), + ObjectMeta: metav1.ObjectMeta{CreationTimestamp: metav1.NewTime(base)}, + }}, + {name: "creation", want: base, e: corev1.Event{ + ObjectMeta: metav1.ObjectMeta{CreationTimestamp: metav1.NewTime(base)}, + }}, + } { + t.Run(tc.name, func(t *testing.T) { + if got := cnpgEventTime(&tc.e); !got.Equal(tc.want) { + t.Errorf("cnpgEventTime = %s, want %s", got, tc.want) + } + }) + } +} + +// recordEvent records a Warning on obj under an explicit name, which is the +// order the fake client lists events in. +func (f *cnpgRolloutFixture) recordEvent(name string, obj *cnpgtypes.Backup, message string, at time.Time) { + f.t.Helper() + f.create(&corev1.Event{ + ObjectMeta: metav1.ObjectMeta{Namespace: rolloutNS, Name: name}, + InvolvedObject: corev1.ObjectReference{ + APIVersion: cnpgtypes.GroupVersion.String(), + Kind: "Backup", + Namespace: obj.Namespace, + Name: obj.Name, + UID: obj.UID, + }, + Type: corev1.EventTypeWarning, + Reason: "BackupPending", + Message: message, + LastTimestamp: metav1.NewTime(at), + }) +} + +// TestReconcileCNPG_ReasonIsTheNewestWarningOfTheBackup: the reason is the +// Warning last recorded on the Backup itself, whatever order the events are +// listed in, and never one recorded on another object of the namespace. +func TestReconcileCNPG_ReasonIsTheNewestWarningOfTheBackup(t *testing.T) { + f, b := newPendingBoundFixture(t, "pending", nil) + f.recordEvent("a-old", b, "old reason", time.Now().Add(-time.Hour)) + f.recordEvent("m-new", b, "new reason", time.Now().Add(-2*time.Minute)) + unrelated := newPendingBoundCNPGBackup("other-cluster", time.Now(), "pending", nil) + unrelated.Spec.Cluster.Name = "postgres-other" + f.create(unrelated) + f.recordEvent("z-unrelated", unrelated, "unrelated reason", time.Now().Add(-time.Minute)) + + j, _ := f.pass() + stalled := apimeta.FindStatusCondition(j.Status.Conditions, backupCondCNPGBackupStalled) + if stalled == nil || !strings.Contains(stalled.Message, "new reason") { + t.Fatalf("%s condition = %+v, want the newest Warning of the Backup", backupCondCNPGBackupStalled, stalled) + } + for _, unwanted := range []string{"old reason", "unrelated reason"} { + if strings.Contains(stalled.Message, unwanted) { + t.Errorf("%s message %q carries %q", backupCondCNPGBackupStalled, stalled.Message, unwanted) + } + } +} + +// TestReconcileCNPG_FinishedBackupEndsTheStall: a Backup can go from pending +// straight to a terminal phase between two passes. The finished job then +// reports the stall as over rather than a Backup CloudNativePG has not +// started. +func TestReconcileCNPG_FinishedBackupEndsTheStall(t *testing.T) { + for _, tc := range []struct { + phase string + wantPhase backupsv1alpha1.BackupJobPhase + }{ + {phase: cnpgBackupPhaseComplete, wantPhase: backupsv1alpha1.BackupJobPhaseSucceeded}, + {phase: cnpgBackupPhaseFailed, wantPhase: backupsv1alpha1.BackupJobPhaseFailed}, + } { + t.Run(tc.phase, func(t *testing.T) { + since := time.Now().Add(-time.Minute) + f, _ := newPendingBoundFixture(t, tc.phase, &since) + + j, _ := f.pass() + if j.Status.Phase != tc.wantPhase { + t.Fatalf("BackupJob phase = %q (%s), want %q", j.Status.Phase, j.Status.Message, tc.wantPhase) + } + if cond := apimeta.FindStatusCondition(j.Status.Conditions, backupCondCNPGBackupStalled); cond == nil || cond.Status != metav1.ConditionFalse { + t.Fatalf("%s condition = %+v, want False once the Backup finished", backupCondCNPGBackupStalled, cond) + } + }) + } +} + +// TestReconcileCNPG_QueueReadErrorIsRetried: unlike the reason, which the job +// can do without, the queue decides whether the wait is healthy. A failed read +// of it is retried; read as empty it would make a Backup queued behind a +// running one look stalled, and fail the job and delete its Backup. +func TestReconcileCNPG_QueueReadErrorIsRetried(t *testing.T) { + since := time.Now().Add(-cnpgDefaultBackupDeadline - time.Minute) + f, _ := newPendingBoundFixture(t, "pending", &since) + f.create(newPendingBoundCNPGBackup("scheduled", time.Now().Add(-time.Minute), "running", nil)) + readErr := errors.New("cache not synced") + f.r.Client = interceptor.NewClient(f.c.(client.WithWatch), interceptor.Funcs{ + List: func(ctx context.Context, cl client.WithWatch, list client.ObjectList, opts ...client.ListOption) error { + lo := &client.ListOptions{} + lo.ApplyOptions(opts) + if _, ok := list.(*cnpgtypes.BackupList); ok && lo.LabelSelector == nil { + return readErr + } + return cl.List(ctx, list, opts...) + }, + }) + + ctx := context.Background() + j := &backupsv1alpha1.BackupJob{} + if err := f.c.Get(ctx, client.ObjectKey{Namespace: rolloutNS, Name: "bj"}, j); err != nil { + t.Fatalf("get BackupJob: %v", err) + } + if _, err := f.r.reconcileCNPG(ctx, j, f.resolved); !errors.Is(err, readErr) { + t.Fatalf("reconcileCNPG error = %v, want the queue read error", err) + } + persisted := &backupsv1alpha1.BackupJob{} + if err := f.c.Get(ctx, client.ObjectKey{Namespace: rolloutNS, Name: "bj"}, persisted); err != nil { + t.Fatalf("get BackupJob: %v", err) + } + if persisted.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed { + t.Fatalf("BackupJob failed on a queue read error: %s", persisted.Status.Message) + } + if err := f.c.Get(ctx, client.ObjectKey{Namespace: rolloutNS, Name: "bj-cnpg"}, &cnpgtypes.Backup{}); err != nil { + t.Fatalf("the queued Backup was deleted on a queue read error: %v", err) + } +} + +// TestReconcileCNPG_ReasonIsReadUncached: the events are read through the +// uncached reader. The cached client would start a cluster-wide informer on +// events, which the controller has no watch grant for and no UID index in. +func TestReconcileCNPG_ReasonIsReadUncached(t *testing.T) { + f, b := newPendingBoundFixture(t, "pending", nil) + f.recordCNPGEvent(b, corev1.EventTypeWarning, "BackupPending", pendingTargetEvent, time.Now().Add(-time.Minute)) + f.r.APIReader = f.c + f.r.Client = interceptor.NewClient(f.c.(client.WithWatch), interceptor.Funcs{ + List: func(ctx context.Context, cl client.WithWatch, list client.ObjectList, opts ...client.ListOption) error { + if _, ok := list.(*corev1.EventList); ok { + return errors.New("events read through the cache") + } + return cl.List(ctx, list, opts...) + }, + }) + + j, _ := f.pass() + stalled := apimeta.FindStatusCondition(j.Status.Conditions, backupCondCNPGBackupStalled) + if stalled == nil || !strings.Contains(stalled.Message, pendingTargetEvent) { + t.Fatalf("%s condition = %+v, want the reason read through the uncached reader", backupCondCNPGBackupStalled, stalled) + } +} + +// TestReconcileCNPG_GiveUpRechecksTheQueueUncached: a backup that started is +// seen as such before the job gives up, even while the cache still shows it +// pending, so the job does not delete a Backup queued behind it. +func TestReconcileCNPG_GiveUpRechecksTheQueueUncached(t *testing.T) { + since := time.Now().Add(-cnpgDefaultBackupDeadline - time.Minute) + f, _ := newPendingBoundFixture(t, "pending", &since) + f.create(newPendingBoundCNPGBackup("scheduled", time.Now().Add(-time.Minute), "started", nil)) + f.r.APIReader = f.c + f.r.Client = interceptor.NewClient(f.c.(client.WithWatch), interceptor.Funcs{ + List: func(ctx context.Context, cl client.WithWatch, list client.ObjectList, opts ...client.ListOption) error { + if err := cl.List(ctx, list, opts...); err != nil { + return err + } + if backups, ok := list.(*cnpgtypes.BackupList); ok { + for i := range backups.Items { + backups.Items[i].Status.Phase = "pending" + } + } + return nil + }, + }) + + j, backups := f.pass() + if j.Status.Phase != backupsv1alpha1.BackupJobPhaseRunning { + t.Fatalf("BackupJob phase = %q (%s), want Running behind the started backup", j.Status.Phase, j.Status.Message) + } + if len(backups) != 2 { + t.Fatalf("cnpg.io/Backups = %v, want both kept", cnpgBackupNames(backups)) + } + if cond := apimeta.FindStatusCondition(j.Status.Conditions, backupCondCNPGBackupStalled); cond == nil || cond.Status != metav1.ConditionFalse { + t.Fatalf("%s condition = %+v, want the stall ended by the recheck, so a later delete by hand is not taken for a give-up", backupCondCNPGBackupStalled, cond) + } + + f.r.Client = f.c + j, _ = f.pass() + if cond := apimeta.FindStatusCondition(j.Status.Conditions, backupCondCNPGBackupStalled); cond == nil || cond.Status != metav1.ConditionFalse { + t.Fatalf("%s condition = %+v, want False once the cache shows the started backup", backupCondCNPGBackupStalled, cond) + } +} + +// TestReconcileCNPG_QueueIsReadFromTheCache: passes that do not give up read +// the queue from the cache, so a job polling behind a long backup does not +// list every cnpg.io/Backup of the namespace from the apiserver. +func TestReconcileCNPG_QueueIsReadFromTheCache(t *testing.T) { + f, _ := newPendingBoundFixture(t, "pending", nil) + f.create(newPendingBoundCNPGBackup("scheduled", time.Now().Add(-time.Minute), "running", nil)) + f.r.APIReader = interceptor.NewClient(f.c.(client.WithWatch), interceptor.Funcs{ + List: func(ctx context.Context, cl client.WithWatch, list client.ObjectList, opts ...client.ListOption) error { + lo := &client.ListOptions{} + lo.ApplyOptions(opts) + if _, ok := list.(*cnpgtypes.BackupList); ok && lo.LabelSelector == nil { + return errors.New("queue read uncached") + } + return cl.List(ctx, list, opts...) + }, + }) + + j, _ := f.pass() + if ready := apimeta.FindStatusCondition(j.Status.Conditions, "Ready"); ready == nil || !strings.Contains(ready.Message, "queued behind") { + t.Fatalf("Ready condition = %+v, want the job queued behind the running backup", ready) + } +} + +// TestReconcileCNPG_StalledBackupDeletedByHandCountsAfresh: a stalled Backup +// deleted outside the driver is replaced, and the replacement's stall counts +// from its own start rather than failing the job on the time of the old one. +func TestReconcileCNPG_StalledBackupDeletedByHandCountsAfresh(t *testing.T) { + since := time.Now().Add(-cnpgDefaultBackupDeadline - time.Minute) + f, b := newPendingBoundFixture(t, "pending", &since) + if err := f.c.Delete(context.Background(), b); err != nil { + t.Fatalf("delete cnpg.io/Backup: %v", err) + } + + j, backups := f.pass() + if j.Status.Phase != backupsv1alpha1.BackupJobPhaseRunning { + t.Fatalf("BackupJob phase = %q (%s), want Running with a new Backup", j.Status.Phase, j.Status.Message) + } + if len(backups) != 1 { + t.Fatalf("cnpg.io/Backups = %v, want a new one", cnpgBackupNames(backups)) + } + if cond := apimeta.FindStatusCondition(j.Status.Conditions, backupCondCNPGBackupStalled); cond == nil || cond.Status != metav1.ConditionFalse { + t.Fatalf("%s condition = %+v, want False for the deleted Backup's stall", backupCondCNPGBackupStalled, cond) + } + + f.setCNPGPhase(backups[0].Name, "pending") + j, backups = f.pass() + if j.Status.Phase != backupsv1alpha1.BackupJobPhaseRunning || len(backups) != 1 { + t.Fatalf("BackupJob phase = %q (%s), cnpg.io/Backups = %v, want Running on the new Backup's fresh stall", j.Status.Phase, j.Status.Message, cnpgBackupNames(backups)) + } + cond := apimeta.FindStatusCondition(j.Status.Conditions, backupCondCNPGBackupStalled) + if cond == nil || cond.Status != metav1.ConditionTrue || time.Since(cond.LastTransitionTime.Time) > time.Minute { + t.Fatalf("%s condition = %+v, want True from now", backupCondCNPGBackupStalled, cond) + } +} + +// TestReconcileCNPG_GivingUpIsRecordedBeforeTheDelete: the job records that it +// gives up before it deletes its Backup, so a pass that finds the Backup gone +// fails the job rather than mistaking the delete for one made by hand. +func TestReconcileCNPG_GivingUpIsRecordedBeforeTheDelete(t *testing.T) { + since := time.Now().Add(-cnpgDefaultBackupDeadline - time.Minute) + f, _ := newPendingBoundFixture(t, "pending", &since) + deleteErr := errors.New("apiserver unavailable") + f.r.Client = interceptor.NewClient(f.c.(client.WithWatch), interceptor.Funcs{ + Delete: func(ctx context.Context, cl client.WithWatch, obj client.Object, opts ...client.DeleteOption) error { + if _, ok := obj.(*cnpgtypes.Backup); ok { + return deleteErr + } + return cl.Delete(ctx, obj, opts...) + }, + }) + + ctx := context.Background() + j := &backupsv1alpha1.BackupJob{} + if err := f.c.Get(ctx, client.ObjectKey{Namespace: rolloutNS, Name: "bj"}, j); err != nil { + t.Fatalf("get BackupJob: %v", err) + } + if _, err := f.r.reconcileCNPG(ctx, j, f.resolved); !errors.Is(err, deleteErr) { + t.Fatalf("reconcileCNPG error = %v, want the delete error", err) + } + persisted := &backupsv1alpha1.BackupJob{} + if err := f.c.Get(ctx, client.ObjectKey{Namespace: rolloutNS, Name: "bj"}, persisted); err != nil { + t.Fatalf("get BackupJob: %v", err) + } + cond := apimeta.FindStatusCondition(persisted.Status.Conditions, backupCondCNPGBackupStalled) + if cond == nil || cond.Status != metav1.ConditionTrue || cond.Reason != cnpgStallAbandoningReason { + t.Fatalf("persisted %s condition = %+v, want True with reason %s", backupCondCNPGBackupStalled, cond, cnpgStallAbandoningReason) + } +} + +// TestReconcileCNPG_EndedStallIsPersistedAlone: the end of a stall is written +// even when the Ready condition it comes with is unchanged. +func TestReconcileCNPG_EndedStallIsPersistedAlone(t *testing.T) { + since := time.Now().Add(-time.Minute) + f, _ := newPendingBoundFixture(t, "pending", &since) + f.create(newPendingBoundCNPGBackup("scheduled", time.Now().Add(-time.Minute), "running", nil)) + + j, _ := f.pass() + if cond := apimeta.FindStatusCondition(j.Status.Conditions, backupCondCNPGBackupStalled); cond == nil || cond.Status != metav1.ConditionFalse { + t.Fatalf("%s condition = %+v, want False while queued", backupCondCNPGBackupStalled, cond) + } + apimeta.SetStatusCondition(&j.Status.Conditions, metav1.Condition{ + Type: backupCondCNPGBackupStalled, + Status: metav1.ConditionTrue, + Reason: "NotStarted", + Message: "stalled", + }) + if err := f.c.Status().Update(context.Background(), j); err != nil { + t.Fatalf("seed a True stall: %v", err) + } + + j, _ = f.pass() + if cond := apimeta.FindStatusCondition(j.Status.Conditions, backupCondCNPGBackupStalled); cond == nil || cond.Status != metav1.ConditionFalse { + t.Fatalf("%s condition = %+v, want False persisted although Ready did not change", backupCondCNPGBackupStalled, cond) + } +} + +// newAttachedByAnotherJobFixture is a Cluster another backup job attached the +// plugin to ten minutes ago, with one instance pod created at podCreated that +// is not ready. +func newAttachedByAnotherJobFixture(t *testing.T, fenced string, podCreated time.Time) *cnpgRolloutFixture { + t.Helper() + j := newRolloutBackupJob(time.Now()) + j.Status.Phase = backupsv1alpha1.BackupJobPhaseRunning + cluster := newRolloutCluster("Cluster is fenced", buildBarmanPlugin(rolloutCluster, rolloutCluster)) + cluster.Annotations = map[string]string{ + cnpgPluginAttachedAtAnnotation: time.Now().Add(-10 * time.Minute).UTC().Format(time.RFC3339), + } + if fenced != "" { + cluster.Annotations[cnpgFencedInstancesAnnotation] = fenced + } + if fenced != `["*"]` { + cluster.Status.Phase = "Waiting for the instances to become active" + } + pod := newRolloutInstancePod(podCreated) + pod.Status.Conditions = []corev1.PodCondition{{Type: corev1.PodReady, Status: corev1.ConditionFalse}} + return newCNPGRolloutFixture(t, j, cluster, pod) +} + +// TestReconcileCNPG_FencedClusterIsNotHeldByAnotherJobsRollout: a fenced +// Cluster stays unhealthy until the fence is lifted, so a job is not held on +// a rollout another job started once every instance pod postdates it. Its +// Backup is created and stalls, which starts the bound. +func TestReconcileCNPG_FencedClusterIsNotHeldByAnotherJobsRollout(t *testing.T) { + f := newAttachedByAnotherJobFixture(t, `["*"]`, time.Now().Add(-5*time.Minute)) + + j, backups := f.pass() + if len(backups) != 1 { + t.Fatalf("cnpg.io/Backups = %v, want the job's Backup created on the fenced Cluster (Ready: %+v)", + cnpgBackupNames(backups), apimeta.FindStatusCondition(j.Status.Conditions, "Ready")) + } + f.setCNPGPhase(backups[0].Name, "pending") + j, _ = f.pass() + if cond := apimeta.FindStatusCondition(j.Status.Conditions, backupCondCNPGBackupStalled); cond == nil || cond.Status != metav1.ConditionTrue { + t.Fatalf("%s condition = %+v, want True", backupCondCNPGBackupStalled, cond) + } +} + +// TestReconcileCNPG_RolloutGateStillHoldsWhenItMust: an instance pod older +// than another job's attach means that rollout is unfinished, fenced or not, +// and an unfenced Cluster whose pods are not ready is still waited on. +func TestReconcileCNPG_RolloutGateStillHoldsWhenItMust(t *testing.T) { + for _, tc := range []struct { + name string + fenced string + podCreated time.Time + }{ + {name: "fenced, pod predates the attach", fenced: `["*"]`, podCreated: time.Now().Add(-20 * time.Minute)}, + {name: "not fenced, pod not ready", podCreated: time.Now().Add(-5 * time.Minute)}, + {name: "fence lifted to an empty list, pod not ready", fenced: `[]`, podCreated: time.Now().Add(-5 * time.Minute)}, + {name: "fence lifted to an empty list spelled with a space, pod not ready", fenced: `[ ]`, podCreated: time.Now().Add(-5 * time.Minute)}, + } { + t.Run(tc.name, func(t *testing.T) { + f := newAttachedByAnotherJobFixture(t, tc.fenced, tc.podCreated) + + j, backups := f.pass() + if len(backups) != 0 { + t.Fatalf("cnpg.io/Backups = %v, want none while the rollout is waited on", cnpgBackupNames(backups)) + } + if ready := apimeta.FindStatusCondition(j.Status.Conditions, "Ready"); ready == nil || ready.Reason != "WaitingForPluginRollout" { + t.Fatalf("Ready condition = %+v, want WaitingForPluginRollout", ready) + } + }) + } +} + +// TestReconcileCNPG_FailedQueueRecheckDoesNotClaimTheDelete: when the +// uncached read of the queue fails, the job has not given up yet, so a +// Backup deleted by hand before the next pass is replaced rather than taken +// for the driver's own delete. +func TestReconcileCNPG_FailedQueueRecheckDoesNotClaimTheDelete(t *testing.T) { + since := time.Now().Add(-cnpgDefaultBackupDeadline - time.Minute) + f, b := newPendingBoundFixture(t, "pending", &since) + readErr := errors.New("apiserver unavailable") + f.r.APIReader = interceptor.NewClient(f.c.(client.WithWatch), interceptor.Funcs{ + List: func(ctx context.Context, cl client.WithWatch, list client.ObjectList, opts ...client.ListOption) error { + lo := &client.ListOptions{} + lo.ApplyOptions(opts) + if _, ok := list.(*cnpgtypes.BackupList); ok && lo.LabelSelector == nil { + return readErr + } + return cl.List(ctx, list, opts...) + }, + }) + + ctx := context.Background() + j := &backupsv1alpha1.BackupJob{} + if err := f.c.Get(ctx, client.ObjectKey{Namespace: rolloutNS, Name: "bj"}, j); err != nil { + t.Fatalf("get BackupJob: %v", err) + } + if _, err := f.r.reconcileCNPG(ctx, j, f.resolved); !errors.Is(err, readErr) { + t.Fatalf("reconcileCNPG error = %v, want the queue read error", err) + } + if err := f.c.Delete(ctx, b); err != nil { + t.Fatalf("delete cnpg.io/Backup by hand: %v", err) + } + + f.r.APIReader = f.c + got, backups := f.pass() + if got.Status.Phase != backupsv1alpha1.BackupJobPhaseRunning { + t.Fatalf("BackupJob phase = %q (%s), want Running: the driver never deleted the Backup", got.Status.Phase, got.Status.Message) + } + if len(backups) != 1 { + t.Fatalf("cnpg.io/Backups = %v, want a replacement for the one deleted by hand", cnpgBackupNames(backups)) + } +} + +// TestReconcileCNPG_StartedStallIsPersistedAlone: the start of a stall is +// written even when the Ready condition it comes with is unchanged, so the +// bound starts counting. +func TestReconcileCNPG_StartedStallIsPersistedAlone(t *testing.T) { + f, _ := newPendingBoundFixture(t, "pending", nil) + j, _ := f.pass() + if cond := apimeta.FindStatusCondition(j.Status.Conditions, backupCondCNPGBackupStalled); cond == nil || cond.Status != metav1.ConditionTrue { + t.Fatalf("%s condition = %+v, want True on the first stalled pass", backupCondCNPGBackupStalled, cond) + } + // A stall ended by a pass that left Ready as it was, as the give-up + // recheck does when it finds a backup running. + apimeta.SetStatusCondition(&j.Status.Conditions, metav1.Condition{ + Type: backupCondCNPGBackupStalled, + Status: metav1.ConditionFalse, + Reason: "Queued", + Message: "queued", + }) + if err := f.c.Status().Update(context.Background(), j); err != nil { + t.Fatalf("seed an ended stall: %v", err) + } + + j, _ = f.pass() + if cond := apimeta.FindStatusCondition(j.Status.Conditions, backupCondCNPGBackupStalled); cond == nil || cond.Status != metav1.ConditionTrue { + t.Fatalf("%s condition = %+v, want True persisted although Ready did not change", backupCondCNPGBackupStalled, cond) + } +} + +// TestReconcileCNPG_HandDeleteEndsTheStallBeforeTheReplacement: the end of a +// stall whose Backup was deleted by hand is persisted before the replacement +// is created. Otherwise a lost write later in the pass would leave the old +// stall True, and the replacement would be failed and deleted on the old +// stall's time as soon as it went pending. +func TestReconcileCNPG_HandDeleteEndsTheStallBeforeTheReplacement(t *testing.T) { + since := time.Now().Add(-cnpgDefaultBackupDeadline - time.Minute) + f, b := newPendingBoundFixture(t, "pending", &since) + if err := f.c.Delete(context.Background(), b); err != nil { + t.Fatalf("delete cnpg.io/Backup by hand: %v", err) + } + created := 0 + f.r.Client = interceptor.NewClient(f.c.(client.WithWatch), interceptor.Funcs{ + Create: func(ctx context.Context, cl client.WithWatch, obj client.Object, opts ...client.CreateOption) error { + if _, ok := obj.(*cnpgtypes.Backup); ok { + created++ + j := &backupsv1alpha1.BackupJob{} + if err := cl.Get(ctx, client.ObjectKey{Namespace: rolloutNS, Name: "bj"}, j); err != nil { + t.Fatalf("get BackupJob: %v", err) + } + if apimeta.IsStatusConditionTrue(j.Status.Conditions, backupCondCNPGBackupStalled) { + t.Errorf("replacement cnpg.io/Backup created while the deleted one's stall is still persisted True") + } + } + return cl.Create(ctx, obj, opts...) + }, + }) + + f.pass() + if created != 1 { + t.Fatalf("created %d cnpg.io/Backup(s), want the one replacement", created) + } +} + +// TestReconcileCNPG_QueueIsPerNamespace: Cluster names repeat across tenants, +// so a running backup of a same-named Cluster in another namespace does not +// queue this Backup. +func TestReconcileCNPG_QueueIsPerNamespace(t *testing.T) { + since := time.Now().Add(-cnpgDefaultBackupDeadline - time.Minute) + f, _ := newPendingBoundFixture(t, "pending", &since) + foreign := newPendingBoundCNPGBackup("foreign-running", time.Now().Add(-time.Minute), "running", nil) + foreign.Namespace = "other-tenant" + f.create(foreign) + + j, _ := f.pass() + if j.Status.Phase != backupsv1alpha1.BackupJobPhaseFailed { + t.Fatalf("BackupJob phase = %q (%s), want Failed: the running backup belongs to another tenant", j.Status.Phase, j.Status.Message) + } + if strings.Contains(j.Status.Message, "foreign-running") { + t.Errorf("failure message %q names the other tenant's backup", j.Status.Message) + } +} + +// TestReconcileCNPG_ReasonFromTheNewestOtherPendingBackup: with no Warning on +// the job's own Backup, the reason is the newest Warning across the other +// pending backups of the Cluster, whichever is listed first. +func TestReconcileCNPG_ReasonFromTheNewestOtherPendingBackup(t *testing.T) { + f, _ := newPendingBoundFixture(t, "pending", nil) + older := newPendingBoundCNPGBackup("a-older", time.Now().Add(-time.Hour), "pending", nil) + f.create(older) + newer := newPendingBoundCNPGBackup("b-newer", time.Now().Add(-time.Hour), "pending", nil) + f.create(newer) + f.recordEvent("a-older-warning", older, "older reason", time.Now().Add(-10*time.Minute)) + f.recordEvent("b-newer-warning", newer, "newer reason", time.Now().Add(-time.Minute)) + + j, _ := f.pass() + stalled := apimeta.FindStatusCondition(j.Status.Conditions, backupCondCNPGBackupStalled) + if stalled == nil || !strings.Contains(stalled.Message, "newer reason") || !strings.Contains(stalled.Message, "b-newer") { + t.Fatalf("%s condition = %+v, want the newest Warning, recorded on b-newer", backupCondCNPGBackupStalled, stalled) + } + if strings.Contains(stalled.Message, "older reason") { + t.Errorf("%s message %q carries the older Warning", backupCondCNPGBackupStalled, stalled.Message) + } +} + +// TestReconcileCNPG_QueueReadErrorBeforeTheBoundStartsNoStall: a failed read +// of the queue is retried rather than read as an empty queue, which would +// start a stall the job may not be in. +func TestReconcileCNPG_QueueReadErrorBeforeTheBoundStartsNoStall(t *testing.T) { + f, _ := newPendingBoundFixture(t, "pending", nil) + f.create(newPendingBoundCNPGBackup("scheduled", time.Now().Add(-time.Minute), "running", nil)) + readErr := errors.New("cache not synced") + f.r.Client = interceptor.NewClient(f.c.(client.WithWatch), interceptor.Funcs{ + List: func(ctx context.Context, cl client.WithWatch, list client.ObjectList, opts ...client.ListOption) error { + lo := &client.ListOptions{} + lo.ApplyOptions(opts) + if _, ok := list.(*cnpgtypes.BackupList); ok && lo.LabelSelector == nil { + return readErr + } + return cl.List(ctx, list, opts...) + }, + }) + + ctx := context.Background() + j := &backupsv1alpha1.BackupJob{} + if err := f.c.Get(ctx, client.ObjectKey{Namespace: rolloutNS, Name: "bj"}, j); err != nil { + t.Fatalf("get BackupJob: %v", err) + } + if _, err := f.r.reconcileCNPG(ctx, j, f.resolved); !errors.Is(err, readErr) { + t.Fatalf("reconcileCNPG error = %v, want the queue read error", err) + } + persisted := &backupsv1alpha1.BackupJob{} + if err := f.c.Get(ctx, client.ObjectKey{Namespace: rolloutNS, Name: "bj"}, persisted); err != nil { + t.Fatalf("get BackupJob: %v", err) + } + if apimeta.IsStatusConditionTrue(persisted.Status.Conditions, backupCondCNPGBackupStalled) { + t.Fatalf("%s was persisted True on a failed queue read", backupCondCNPGBackupStalled) + } +} diff --git a/internal/backupcontroller/cnpgstrategy_controller.go b/internal/backupcontroller/cnpgstrategy_controller.go index caf2fac39..b8df89263 100644 --- a/internal/backupcontroller/cnpgstrategy_controller.go +++ b/internal/backupcontroller/cnpgstrategy_controller.go @@ -44,6 +44,7 @@ const ( cnpgClusterLabel = "cnpg.io/cluster" cnpgBackupPhaseComplete = "completed" cnpgBackupPhaseFailed = "failed" + cnpgBackupPhasePending = "pending" cnpgBackupPhaseStarted = "started" cnpgBackupPhaseRunning = "running" @@ -186,10 +187,10 @@ const ( // recorded in DestinationWriteHeld when that is later. Retrying the WAL // archive destination write is counted from the first failure since the // last successful write or the last wait for another backup or a - // restore. A Backup that exists is not capped: CloudNativePG keeps a - // healthy one pending while another backup of the same Cluster runs, or - // while it restarts one on another instance, so no fixed deadline tells - // those apart from a stuck one. + // restore. It also caps how long a Backup that exists may stay stalled + // (see backupCondCNPGBackupStalled). A Backup queued behind a started or + // running backup of the same Cluster, or one that has started, is not + // capped. cnpgDefaultBackupDeadline = 30 * time.Minute cnpgClusterHealthyPhase = "Cluster in healthy state" @@ -237,6 +238,10 @@ const ( // cannot be lost to a failed BackupJob status write after the attach. cnpgPluginAttachedAtAnnotation = "backups.cozystack.io/barman-plugin-attached-at" + // CloudNativePG's utils.FencedInstanceAnnotation: a JSON list of fenced + // instance names, "*" for all of them. + cnpgFencedInstancesAnnotation = "cnpg.io/fencedInstances" + // Annotation on the ObjectStore carrying, as RFC 3339, when a backup job // last changed its configuration. It is written by the apply that makes // the change, so it cannot be lost apart from it. @@ -263,6 +268,21 @@ const ( // corrupt rather than as written by a leader whose clock ran ahead. cnpgAttachClockSkewTolerance = 5 * time.Minute + // Condition Type recorded while the job's cnpg.io/Backup is pending and no + // backup of the Cluster is started or running. Its LastTransitionTime to + // True starts the cnpgDefaultBackupDeadline count; False, written in any + // other phase of the Backup, while it is queued behind a running backup, + // or once the Backup is deleted outside the driver, ends it. + backupCondCNPGBackupStalled = "CNPGBackupStalled" + + // Reason of a True backupCondCNPGBackupStalled persisted before the + // driver deletes the Backup it gives up on. Only a Backup missing under + // this reason fails the job; one missing under any other was deleted by + // someone else. + cnpgStallAbandoningReason = "Abandoning" + + cnpgEventInvolvedUIDField = "involvedObject.uid" + cnpgPodRoleLabel = "cnpg.io/podRole" cnpgPodRoleInstance = "instance" ) @@ -386,6 +406,19 @@ func (r *BackupJobReconciler) reconcileCNPG(ctx context.Context, j *backupsv1alp if err != nil { return ctrl.Result{}, err } + if stalled := apimeta.FindStatusCondition(j.Status.Conditions, backupCondCNPGBackupStalled); existingBackup == nil && stalled != nil && stalled.Status == metav1.ConditionTrue { + if stalled.Reason == cnpgStallAbandoningReason { + // The pass that gave up deleted the Backup and lost the status + // write; creating a new Backup would restart a job that failed. + return r.markBackupJobFailed(ctx, j, cnpgStallFailedMessage(stalled.Message)) + } + // Someone else deleted the stalled Backup. The one created below is + // a fresh attempt, and its stall, if any, counts from its own start. + endCNPGStall(j, "BackupDeleted", "the stalled cnpg.io/Backup was deleted outside the driver") + if err := r.Status().Update(ctx, j); err != nil { + return ctrl.Result{}, err + } + } rollout := apimeta.FindStatusCondition(j.Status.Conditions, backupCondPluginRolledOut) awaitingRollout := existingBackup == nil && rollout != nil && rollout.Status == metav1.ConditionFalse @@ -601,7 +634,17 @@ func (r *BackupJobReconciler) reconcileCNPG(ctx context.Context, j *backupsv1alp logger.Info("ignoring an unusable attach record another backup job left", "cluster", clusterName, "annotation", cnpgPluginAttachedAtAnnotation, "error", err) } else if time.Since(recorded) < cnpgDefaultBackupDeadline { - pending, err := r.cnpgPluginRolloutPending(ctx, j.Namespace, clusterName, attachment, metav1.NewTime(recorded)) + var pending string + if attachment.fenced { + // A fenced Cluster is neither healthy nor ready until the + // fence is lifted, however far the rollout got, so only an + // instance pod older than the attach shows it unfinished. + // Past that the Backup is created, and the bound on a + // stalled Backup applies to it. + pending, err = r.cnpgInstancePodsPending(ctx, j.Namespace, clusterName, metav1.NewTime(recorded), false) + } else { + pending, err = r.cnpgPluginRolloutPending(ctx, j.Namespace, clusterName, attachment, metav1.NewTime(recorded)) + } if err != nil { return ctrl.Result{}, err } @@ -647,6 +690,7 @@ func (r *BackupJobReconciler) reconcileCNPG(ctx context.Context, j *backupsv1alp if j.Status.BackupRef != nil { return ctrl.Result{}, nil } + endCNPGStall(j, "BackupCompleted", "cnpg.io Backup completed") destination, err := cnpgArtifactDestination(cnpgBackup, rendered) if err != nil { return r.markBackupJobFailed(ctx, j, fmt.Sprintf("refusing to create the Backup artifact: %v", err)) @@ -678,17 +722,23 @@ func (r *BackupJobReconciler) reconcileCNPG(ctx context.Context, j *backupsv1alp case cnpgBackupPhaseFailed: // CloudNativePG does not reconcile a Backup out of a terminal phase, // so waiting on a failed one cannot change the outcome. - return r.markBackupJobFailed(ctx, j, cnpgBackupFailedMessage(cnpgBackup, message)) + failed := cnpgBackupFailedMessage(cnpgBackup, message) + endCNPGStall(j, "BackupFailed", failed) + return r.markBackupJobFailed(ctx, j, failed) + + case cnpgBackupPhasePending: + return r.waitOnPendingCNPGBackup(ctx, j, cnpgBackup, clusterName) default: waiting := fmt.Sprintf("waiting for cnpg.io/Backup %s/%s, phase %q", cnpgBackup.Namespace, cnpgBackup.Name, phase) + ended := endCNPGStall(j, "BackupProgressing", waiting) if apimeta.SetStatusCondition(&j.Status.Conditions, metav1.Condition{ Type: "Ready", Status: metav1.ConditionFalse, Reason: "WaitingForCNPGBackup", Message: waiting, - }) { + }) || ended { if err := r.Status().Update(ctx, j); err != nil { return ctrl.Result{}, err } @@ -697,6 +747,212 @@ func (r *BackupJobReconciler) reconcileCNPG(ctx context.Context, j *backupsv1alp } } +// waitOnPendingCNPGBackup bounds a pending Backup unless another backup of +// the Cluster is started or running. CloudNativePG keeps a Backup pending +// behind one that is (waitIfOtherBackupsRunning), which is healthy. With none, +// a pending Backup waits on the instance to run on, which can be missing or +// not ready for as long as the Cluster is fenced. Which pending Backup +// CloudNativePG lets through first is left to it: the decision reads only +// whether a backup of the Cluster executes. +func (r *BackupJobReconciler) waitOnPendingCNPGBackup(ctx context.Context, j *backupsv1alpha1.BackupJob, b *cnpgtypes.Backup, clusterName string) (ctrl.Result, error) { + running, pending, err := r.cnpgClusterBackups(ctx, r.Client, b, clusterName) + if err != nil { + return ctrl.Result{}, err + } + if running != nil { + waiting := fmt.Sprintf("cnpg.io/Backup %s/%s is queued behind cnpg.io/Backup %s/%s of the same Cluster, phase %q", + b.Namespace, b.Name, running.Namespace, running.Name, running.Status.Phase) + ended := endCNPGStall(j, "Queued", waiting) + if apimeta.SetStatusCondition(&j.Status.Conditions, metav1.Condition{ + Type: "Ready", + Status: metav1.ConditionFalse, + Reason: "WaitingForCNPGBackup", + Message: waiting, + }) || ended { + if err := r.Status().Update(ctx, j); err != nil { + return ctrl.Result{}, err + } + } + return ctrl.Result{RequeueAfter: cnpgPollInterval}, nil + } + + stall := fmt.Sprintf("cnpg.io/Backup %s/%s is pending and CloudNativePG runs no backup of the Cluster: %s", + b.Namespace, b.Name, r.cnpgBackupPendingReason(ctx, b, pending)) + stallStarted := !apimeta.IsStatusConditionTrue(j.Status.Conditions, backupCondCNPGBackupStalled) + apimeta.SetStatusCondition(&j.Status.Conditions, metav1.Condition{ + Type: backupCondCNPGBackupStalled, + Status: metav1.ConditionTrue, + Reason: "NotStarted", + Message: stall, + }) + if cnpgStallExpired(apimeta.FindStatusCondition(j.Status.Conditions, backupCondCNPGBackupStalled)) { + // The cache can still show pending a backup that has started, and + // the conditional delete below sees only this Backup. A running one + // found now leaves the Backup queued, and the stall ends here so the + // next one counts afresh and an Abandoning reason left by a pass + // whose delete failed is cleared. + running, _, err := r.cnpgClusterBackups(ctx, r.apiReader(), b, clusterName) + if err != nil { + return ctrl.Result{}, err + } + if running != nil { + endCNPGStall(j, "Queued", fmt.Sprintf("cnpg.io/Backup %s/%s is queued behind cnpg.io/Backup %s/%s of the same Cluster, phase %q", + b.Namespace, b.Name, running.Namespace, running.Name, running.Status.Phase)) + if err := r.Status().Update(ctx, j); err != nil { + return ctrl.Result{}, err + } + return ctrl.Result{RequeueAfter: cnpgPollInterval}, nil + } + // Persisted only once the job is about to delete, so a pass that + // finds the Backup gone tells this give-up from a delete by someone + // else, and a recheck that failed claims nothing. + apimeta.SetStatusCondition(&j.Status.Conditions, metav1.Condition{ + Type: backupCondCNPGBackupStalled, + Status: metav1.ConditionTrue, + Reason: cnpgStallAbandoningReason, + Message: stall, + }) + if err := r.Status().Update(ctx, j); err != nil { + return ctrl.Result{}, err + } + // Conditional on the Backup as read: one CloudNativePG started since + // fails the delete with Conflict and is waited on instead. + uid, rv := b.UID, b.ResourceVersion + if err := r.Delete(ctx, b, client.Preconditions{UID: &uid, ResourceVersion: &rv}); err != nil && !apierrors.IsNotFound(err) { + return ctrl.Result{}, err + } + return r.markBackupJobFailed(ctx, j, cnpgStallFailedMessage(stall)) + } + if apimeta.SetStatusCondition(&j.Status.Conditions, metav1.Condition{ + Type: "Ready", + Status: metav1.ConditionFalse, + Reason: "WaitingForCNPGBackup", + Message: fmt.Sprintf("%s; the BackupJob fails if this lasts %s", stall, cnpgDefaultBackupDeadline), + }) || stallStarted { + if err := r.Status().Update(ctx, j); err != nil { + return ctrl.Result{}, err + } + } + return ctrl.Result{RequeueAfter: cnpgPollInterval}, nil +} + +// cnpgClusterBackups returns a started or running backup of the Cluster other +// than b, if any, and otherwise the Cluster's other unfinished backups. +func (r *BackupJobReconciler) cnpgClusterBackups(ctx context.Context, reader client.Reader, b *cnpgtypes.Backup, clusterName string) (running *cnpgtypes.Backup, pending []cnpgtypes.Backup, err error) { + list := &cnpgtypes.BackupList{} + if err := reader.List(ctx, list, client.InNamespace(b.Namespace)); err != nil { + return nil, nil, err + } + for i := range list.Items { + item := &list.Items[i] + if item.Spec.Cluster.Name != clusterName || item.UID == b.UID { + continue + } + switch phase := item.Status.Phase; { + case cnpgBackupExecuting(phase): + return item, nil, nil + case phase != cnpgBackupPhaseComplete && phase != cnpgBackupPhaseFailed: + pending = append(pending, *item) + } + } + return nil, pending, nil +} + +func cnpgBackupExecuting(phase string) bool { + return phase == cnpgBackupPhaseStarted || phase == cnpgBackupPhaseRunning +} + +// cnpgBackupPendingReason returns the newest Warning event CloudNativePG +// recorded on b, the only place it says why it keeps a Backup pending. When b +// carries none, the newest one on another pending backup of the Cluster +// stands in: CloudNativePG records the cause on whichever of them it tries, +// and the others wait on the same instance. The events are read uncached and +// by the Backup's UID, so the driver needs no cluster-wide watch on events. +func (r *BackupJobReconciler) cnpgBackupPendingReason(ctx context.Context, b *cnpgtypes.Backup, others []cnpgtypes.Backup) string { + newest, err := r.newestCNPGWarning(ctx, b) + if err != nil { + getLogger(ctx).Info("cannot read the events of the cnpg.io/Backup", "backup", b.Name, "error", err.Error()) + return fmt.Sprintf("the reason CloudNativePG recorded cannot be read: %v", err) + } + if newest != nil { + return fmt.Sprintf("%s: %s", newest.Reason, newest.Message) + } + var from *cnpgtypes.Backup + for i := range others { + e, err := r.newestCNPGWarning(ctx, &others[i]) + if err != nil { + getLogger(ctx).Info("cannot read the events of the cnpg.io/Backup", "backup", others[i].Name, "error", err.Error()) + continue + } + if e != nil && (newest == nil || cnpgEventTime(e).After(cnpgEventTime(newest))) { + newest, from = e, &others[i] + } + } + if newest == nil { + return "CloudNativePG recorded no warning event on it or on another pending backup of the Cluster" + } + return fmt.Sprintf("%s: %s (recorded on cnpg.io/Backup %s/%s, also pending)", + newest.Reason, newest.Message, from.Namespace, from.Name) +} + +func (r *BackupJobReconciler) newestCNPGWarning(ctx context.Context, b *cnpgtypes.Backup) (*corev1.Event, error) { + events := &corev1.EventList{} + if err := r.apiReader().List(ctx, events, + client.InNamespace(b.Namespace), + client.MatchingFields{cnpgEventInvolvedUIDField: string(b.UID)}, + ); err != nil { + return nil, err + } + var newest *corev1.Event + for i := range events.Items { + e := &events.Items[i] + if e.Type != corev1.EventTypeWarning { + continue + } + if newest == nil || cnpgEventTime(e).After(cnpgEventTime(newest)) { + newest = e + } + } + return newest, nil +} + +func cnpgEventTime(e *corev1.Event) time.Time { + switch { + case e.Series != nil && !e.Series.LastObservedTime.IsZero(): + return e.Series.LastObservedTime.Time + case !e.LastTimestamp.IsZero(): + return e.LastTimestamp.Time + case !e.EventTime.IsZero(): + return e.EventTime.Time + } + return e.CreationTimestamp.Time +} + +// endCNPGStall flips a True backupCondCNPGBackupStalled to False, so a later +// stall counts from its own start, and reports whether it did; the caller +// persists the change. A job that never stalled gets no condition. +func endCNPGStall(j *backupsv1alpha1.BackupJob, reason, message string) bool { + if !apimeta.IsStatusConditionTrue(j.Status.Conditions, backupCondCNPGBackupStalled) { + return false + } + return apimeta.SetStatusCondition(&j.Status.Conditions, metav1.Condition{ + Type: backupCondCNPGBackupStalled, + Status: metav1.ConditionFalse, + Reason: reason, + Message: message, + }) +} + +func cnpgStallExpired(stalled *metav1.Condition) bool { + return stalled != nil && stalled.Status == metav1.ConditionTrue && + time.Since(stalled.LastTransitionTime.Time) > cnpgDefaultBackupDeadline +} + +func cnpgStallFailedMessage(stall string) string { + return fmt.Sprintf("%s, for longer than %s; deleted the cnpg.io/Backup so it does not run later with no Backup recording it", + stall, cnpgDefaultBackupDeadline) +} + // cnpgBackupFailedMessage carries the error CloudNativePG recorded. When the // plugin run itself failed that is only its exit status, and the storage // error behind it is logged by the plugin-barman-cloud sidecar. @@ -846,6 +1102,7 @@ func (r *BackupJobReconciler) applyClusterPluginBackup(ctx context.Context, name clusterStatus: existing.Status, } attachment.attachedAt = existing.Annotations[cnpgPluginAttachedAtAnnotation] + attachment.fenced = cnpgClusterFenced(existing.Annotations) if live := currentBarmanServerName(existing); live != "" { attachment.serverName = live } else { @@ -1011,6 +1268,9 @@ type cnpgPluginAttachment struct { // pass applied to the ObjectStore, zero when it wrote none. destinationChangedAt time.Time clusterStatus cnpgtypes.ClusterStatus + // fenced is set while the Cluster carries a non-empty + // cnpgFencedInstancesAnnotation. + fenced bool } // cnpgPluginRolloutPending returns why the rollout that attaching the @@ -1034,6 +1294,23 @@ func (r *BackupJobReconciler) cnpgPluginRolloutPending(ctx context.Context, name } return pending, nil } + return r.cnpgInstancePodsPending(ctx, namespace, clusterName, attachedAt, true) +} + +// cnpgClusterFenced reports whether the Cluster fences any instance. A value +// that is not a JSON list counts as not fenced, which keeps the stricter +// rollout wait. +func cnpgClusterFenced(annotations map[string]string) bool { + var fenced []string + if err := json.Unmarshal([]byte(annotations[cnpgFencedInstancesAnnotation]), &fenced); err != nil { + return false + } + return len(fenced) > 0 +} + +// cnpgInstancePodsPending returns which instance pod of the Cluster predates +// attachedAt, or, with requireReady, is not ready; "" when none does. +func (r *BackupJobReconciler) cnpgInstancePodsPending(ctx context.Context, namespace, clusterName string, attachedAt metav1.Time, requireReady bool) (string, error) { pods := &corev1.PodList{} if err := r.List(ctx, pods, client.InNamespace(namespace), client.MatchingLabels{ cnpgClusterLabel: clusterName, @@ -1049,7 +1326,7 @@ func (r *BackupJobReconciler) cnpgPluginRolloutPending(ctx context.Context, name if !pod.CreationTimestamp.After(attachedAt.Time) { return fmt.Sprintf("instance pod %s/%s predates the barman-cloud plugin", namespace, pod.Name), nil } - if pod.DeletionTimestamp != nil || !podReady(pod) { + if requireReady && (pod.DeletionTimestamp != nil || !podReady(pod)) { return fmt.Sprintf("instance pod %s/%s is not ready", namespace, pod.Name), nil } } diff --git a/internal/backupcontroller/cnpgstrategy_controller_test.go b/internal/backupcontroller/cnpgstrategy_controller_test.go index 3dc3e6735..cea45b69c 100644 --- a/internal/backupcontroller/cnpgstrategy_controller_test.go +++ b/internal/backupcontroller/cnpgstrategy_controller_test.go @@ -5990,6 +5990,9 @@ func newCNPGStrategyTestClient(t *testing.T, objs ...client.Object) client.Clien WithScheme(s). WithObjects(objs...). WithStatusSubresource(&backupsv1alpha1.BackupJob{}, &backupsv1alpha1.RestoreJob{}, &backupsv1alpha1.Backup{}). + WithIndex(&corev1.Event{}, cnpgEventInvolvedUIDField, func(o client.Object) []string { + return []string{string(o.(*corev1.Event).InvolvedObject.UID)} + }). Build() } diff --git a/packages/system/backupstrategy-controller/templates/rbac.yaml b/packages/system/backupstrategy-controller/templates/rbac.yaml index 883fd1fe9..3cac2fe41 100644 --- a/packages/system/backupstrategy-controller/templates/rbac.yaml +++ b/packages/system/backupstrategy-controller/templates/rbac.yaml @@ -117,10 +117,12 @@ rules: - apiGroups: [""] resources: ["namespaces"] verbs: ["get", "list", "watch"] -# Events from Recorder.Event() calls +# Events from Recorder.Event() calls. list: the CNPG driver reads the events +# CloudNativePG records on a pending cnpg.io/Backup by UID, uncached, so no +# watch is needed. - apiGroups: [""] resources: ["events"] - verbs: ["create", "patch"] + verbs: ["create", "patch", "list"] # Leader election (--leader-elect) - apiGroups: ["coordination.k8s.io"] resources: ["leases"]