mirror of
https://github.com/cozystack/cozystack.git
synced 2026-11-30 04:06:34 +09:00
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 <aleksei.artamonov@aenix.io> Signed-off-by: Andrey Kolkov <androndo@gmail.com>
This commit is contained in:
1 parent
2495ebfaa0
commit
6d1eeba65b
9 files changed
+1419
-16
No files matched your search
@@ -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}"
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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 \
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -312,8 +312,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
|
||||
@@ -326,7 +328,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()
|
||||
}
|
||||
|
||||
|
||||
@@ -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"]
|
||||
|
||||
Reference in new issue
Block a user