fix(postgres): bound a backup whose cnpg Backup stalls in pending (#5320)

<!-- Thank you for making a contribution! Here are some tips for you:
- Use Conventional Commits for the PR title: `type(scope): description`
- Types: feat, fix, security (a fix that comes through a security
advisory), docs, style, refactor, perf, test, build, ci, chore
- Scopes are not an exhaustive list — pick the most specific scope for
the change and extend the list when a genuinely new area appears.
Examples:
- System components: dashboard, platform, operator, cilium, kube-ovn,
linstor, fluxcd, cluster-api
- Managed apps: postgres, mariadb, redis, kafka, clickhouse,
virtual-machine, kubernetes
- Development and maintenance: api, hack, tests, ci, docs, maintenance
- Breaking changes: append `!` after type/scope (`feat(api)!: ...`) or
add a `BREAKING CHANGE:` footer
- If it's a work in progress, consider creating this PR as a draft.
- Don't hesistate to ask for opinion and review in the community chats,
even if it's still a draft.
- Fixes merged to `main` reach the release lines the backport batch runs
for automatically, so do not open backport PRs by hand:
https://github.com/cozystack/cozystack/blob/main/docs/release/backports.md
-->

## What this PR does

Part of #5209. The other part, a Plan that does not start a run while
its previous BackupJob is still running, follows in a separate PR.

A Postgres BackupJob whose `cnpg.io/Backup` never left `pending` stayed
`Running` with no bound. In CloudNativePG 1.30.0 a Backup is pending for
one of two reasons: it is queued behind a started or running backup of
the same Cluster (`waitIfOtherBackupsRunning`), which is healthy, or the
instance to run it on cannot be found or is not ready
(`startBackupManagedByInstance`), which lasts for as long as the Cluster
is fenced. A restart on another instance goes through the second path
too.

The driver tells the two apart only by whether a backup of the Cluster
is `started` or `running`; it does not model which pending Backup
CloudNativePG lets through first. Each poll reads the Cluster's backups
from the cache, and the job reads them again from the apiserver right
before it gives up, since the cache can still show pending a backup that
has just started. Behind a started or running backup the wait stays
uncapped and the BackupJob says which backup it waits for. Otherwise the
BackupJob records a `CNPGBackupStalled` condition, and once that has
lasted the backup deadline (30 minutes, the same bound as the plugin
rollout wait) the BackupJob fails with the cause, and its own
`cnpg.io/Backup` is deleted so it does not run later with no Cozystack
`Backup` recording it. The delete is conditional on the UID and
resourceVersion the driver read, so a Backup CloudNativePG started in
between is kept. The give-up is recorded before the delete, so a Backup
found missing later fails the job only when the driver removed it; a
Backup deleted by hand is replaced and its stall counts afresh. The
stall also ends, and a later one counts afresh, as soon as the Backup
moves to any other phase.

The reason CloudNativePG gives (`BackupPending: Backup target pod not
ready: ...`) exists only as an event on the Backup, so the condition and
the failure message carry the newest Warning event recorded on the job's
own Backup, or, when it carries none, on another pending backup of the
same Cluster. The events are listed by the Backup's UID through the
uncached reader, so the controller gains `list` on events and no watch;
when the read fails, the message says so instead of omitting the reason.

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 there would only delay the bound by up to the rollout
deadline. An instance pod older than the attach still holds the job, so
a Backup never starts on a pod without the plugin.

The postgres e2e (`examples/backups/postgres/run-all.sh` step 26) fences
the source Cluster, checks that a BackupJob reports the stall with the
reason CloudNativePG recorded, which exercises the `involvedObject.uid`
selector and the events grant against a real apiserver and replaces a
helm-unittest that only matched the rendered rule, then lifts the fence
and checks that the same job completes with the stall ended. Failing at
the deadline is covered by the unit tests.

Known limit, left as is: a backup of the Cluster in `finalizing` does
not count as running, which only a hand-made `volumeSnapshot` Backup can
reach, since platform flows create plugin backups only.

### Screenshots

<!-- REQUIRED for UI changes: attach screenshots or screen recordings
demonstrating
the visual impact of your changes. PRs with UI changes without
screenshots will not be merged. -->

### Downstream repositories

<!--
Cozystack is upstream for repositories that are NOT kept in sync with it
automatically, and nothing in CI compares the two sides, so a change
here can break them silently.

Which change forces what, and which file to touch, is the trigger map in
docs/agents/contributing.md under "Downstream Repositories". Walk it
before you tick anything.

IF YOU ARE AN AI AGENT OR AN LLM, THIS IS PART OF THE TASK, NOT A FORM
TO FILL IN:

1. Walk the trigger map against the actual diff of this PR, file by
file. Do not decide from the PR title or from your memory of what you
changed.
2. For every repository you tick, open the follow-up PR there and link
it on the same line. A ticked box with no link claims work that does not
exist, which is worse than an empty box. Search that repository for an
open PR or issue covering it first, and link that instead of filing a
duplicate.
3. When the follow-up is out of scope, or needs a decision that is not
yours to make, open an issue in that repository instead, link that, and
say so in the PR body. Do not push a speculative PR into another
repository just to fill a line here.
4. Do not tick "No downstream repository is affected" to make the
checklist go away. If you are unsure, leave every box empty and say so
in the PR body, so a human decides.
-->

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

### Release note

<!--  Write a release note:
- Explain what has changed internally and for users.
- Start with the same `type(scope):` prefix as in the PR title
- Follow the guidelines at
https://github.com/kubernetes/community/blob/master/contributors/guide/release-notes.md.
-->

```release-note
fix(postgres): a Postgres BackupJob whose cnpg.io/Backup stays pending because its target instance is not ready, for example while the Cluster is fenced, now fails after 30 minutes with the reason CloudNativePG gives, and the abandoned cnpg.io/Backup is removed. A Backup queued behind a running backup of the same Cluster is not affected.
```


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

## Summary by CodeRabbit

* **Bug Fixes**
* Pending backups that stall for 30 minutes now fail with a recorded
reason. Backups queued behind an executing backup, progressing, or
finished are not incorrectly treated as stalled.
* Backup handling accounts for concurrent progress, external deletion,
and retries, and reports the newest available warning for a pending
backup.
* Fenced clusters now use instance-pod creation time when evaluating
plugin rollout readiness.

* **Tests**
* Expanded coverage for stalled backups, warning reporting, queue
handling, and fenced-cluster backup recovery.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
This commit is contained in:
Andrey Kolkov authored and GitHub committed 2026-11-26 15:59:36 +07:00
commit ef32ff8d71
9 files changed
+1419 -16

No files matched your search

+3
View File
@@ -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}"
+1 -1
View File
@@ -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
+8 -1
View File
@@ -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 \
+76 -1
View File
@@ -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 - <<EOF
apiVersion: backups.cozystack.io/v1alpha1
kind: BackupJob
metadata:
name: ${BACKUPJOB_FENCED_NAME}
spec:
applicationRef:
apiGroup: apps.cozystack.io
kind: Postgres
name: ${PG_SRC_NAME}
backupClassName: ${BACKUPCLASS_NAME}
EOF
STALLED_PATH='{.status.conditions[?(@.type=="CNPGBackupStalled")].status}'
# CloudNativePG retries a pending Backup every 30s and the driver polls every
# 5s, so the stall shows within a minute of the Backup being created. Its
# event recorder is asynchronous, so the first stall message can predate the
# event, and a single events read can fail; the driver rewrites the message
# on its next pass. A job that finishes first fails the step at once.
log_substep "Waiting for ${BACKUPJOB_FENCED_NAME} to report the stall with the reason CloudNativePG recorded..."
STALL_WAIT=0
while true; do
# One read, so the phase, the stall and its message come from the same
# pass of the driver; the message goes last since it may contain the
# separator.
FENCED_STATE=$(kubectl get backupjobs.backups.cozystack.io "$BACKUPJOB_FENCED_NAME" --namespace "$NAMESPACE" \
--output jsonpath='{.status.phase}|{.status.conditions[?(@.type=="CNPGBackupStalled")].status}|{.status.conditions[?(@.type=="CNPGBackupStalled")].message}' || true)
IFS='|' read -r FENCED_PHASE STALLED STALL_MESSAGE <<<"$FENCED_STATE"
if [[ "$FENCED_PHASE" == Failed || "$FENCED_PHASE" == Succeeded ]]; then
log_error "${BACKUPJOB_FENCED_NAME} reached '${FENCED_PHASE}' before reporting the stall: $(kubectl get backupjobs.backups.cozystack.io "$BACKUPJOB_FENCED_NAME" --namespace "$NAMESPACE" --output jsonpath='{.status.message}')"
exit 1
fi
if [[ "$STALLED" == True ]]; then
case "$STALL_MESSAGE" in
*"cannot be read"*|*"recorded no warning event"*) ;;
*) break ;;
esac
fi
if [[ $STALL_WAIT -ge 420 ]]; then
log_error "${BACKUPJOB_FENCED_NAME} did not report the stall with the reason CloudNativePG recorded (CNPGBackupStalled '${STALLED}'): ${STALL_MESSAGE}"
exit 1
fi
sleep 5
STALL_WAIT=$((STALL_WAIT + 5))
done
log_info "Stall: ${STALL_MESSAGE}"
kubectl annotate clusters.postgresql.cnpg.io "$PG_SRC_CLUSTER" --namespace "$NAMESPACE" 'cnpg.io/fencedInstances-'
wait_for_field clusters.postgresql.cnpg.io "$PG_SRC_CLUSTER" \
'{.status.phase}' 'Cluster in healthy state' "$NAMESPACE" 360
wait_for_field backupjobs.backups.cozystack.io "$BACKUPJOB_FENCED_NAME" \
'{.status.phase}' Succeeded "$NAMESPACE" 1200 Failed
STALLED=$(kubectl get backupjobs.backups.cozystack.io "$BACKUPJOB_FENCED_NAME" --namespace "$NAMESPACE" \
--output jsonpath="$STALLED_PATH")
[[ "$STALLED" == "False" ]] || { log_error "CNPGBackupStalled is '${STALLED}' on the BackupJob that completed, want False"; exit 1; }
log_success "The stall was reported while fenced and ended when the backup ran"
if [[ "${SKIP_RESTORE:-0}" == "1" ]]; then
log_warning "SKIP_RESTORE=1: stopping after a successful backup."
exit 0
@@ -429,8 +429,10 @@ spec:
steps:
- name: run
try:
# The 66m budget is the whole documented flow: bucket provisioning, a
# 2-replica source Postgres, the plugin base backup to S3, an empty target
# The 76m budget is the whole documented flow: bucket provisioning, a
# 2-replica source Postgres, the plugin base backup to S3, a second backup
# held pending on the fenced Cluster until the fence is lifted (step 26,
# which waits for the Cluster to come back healthy), an empty target
# app, and THREE sequential purge + re-bootstrap restores against it - the
# latest-point to-copy restore, the point-in-time restore (step 45), and
# the negative unreachable-target restore (step 46, which sets a short
@@ -443,7 +445,7 @@ spec:
# run-all.sh fails fast on terminal BackupJob/RestoreJob phases and stalled
# HelmReleases rather than polling out the budget.
- script:
timeout: 66m
timeout: 76m
content: |
set -eu
cd ../../..
File diff suppressed because it is too large. Load diff
@@ -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
}
}
@@ -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()
}
@@ -118,10 +118,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"]