mirror of
https://github.com/cozystack/cozystack.git
synced 2026-11-30 04:06:34 +09:00
## What this PR does Closes #5291. Two paths left a MariaDB dump and its `k8s.mariadb.com/Backup` behind after the dump cleanup from #5233. **A run that never completes.** When the operator Backup stays short of `Complete` past `mariadbDefaultBackupDeadline`, the BackupJob now deletes it (background propagation, so its Job goes too) before it marks itself `Failed`, and says so in the failure message. No Cozystack `Backup` is ever made of such a run, so nothing else deleted it, and while it stood its window had no end: `contestedMariaDBDump` counted it as a possible writer of every later dump of the application, and every later `Backup` was released with `ArtifactNotDeleted`. Deleting the Job also stops a run that is still going from uploading a dump nobody tracks. An operator Backup that is `Complete=True` on a reason the driver does not know has a bounded window and is kept, as before. The decision is made on the operator Backup read from the API server, not the cache. A run the operator has just marked complete or failed goes down the normal path and is not deleted. The delete carries the UID and resourceVersion that were read, so a run that completes between the read and the delete is not deleted either. Past the deadline no new run is created, so a pass that deleted the run and then failed to persist `Failed` does not start another one on retry. A delete the API server keeps refusing shows as `Ready=False/OperatorBackupDeleteFailed` on the BackupJob. The delete also removes the run's pod, so before it the controller copies what held the pod up into the failure message: an unschedulable pod, or a container that is waiting or has failed. The MariaDB driver's other failure exits take the same path: the MariaDB application was deleted, the MariaDB CR never came back, the strategy disappeared past its deadline, the strategy no longer renders, the applicationRef is rejected, or the run could not be created. Past the deadline, the run is taken from the API server listing and `ensureMariaDBBackup` is not called, so a cache that has not seen the run cannot cause a second one to be created. mariadb-operator leaves the run of a MariaDB that went away at `Complete=False` for good, so if the application was later recreated under the same name, that run used to contest every later dump. The deadline is still 30 minutes from `StartedAt`, but a dump that is still running at that point is now stopped instead of being left to finish outside Cozystack. **Namespace teardown.** mariadb-operator puts no finalizer on its `Backup`, so during teardown it is usually gone before the Cozystack `Backup` finalizer runs. When the operator Backup is not found, the cleanup now: - takes bucket, prefix and Secret references from the snapshot in `status.underlyingResources`; - goes on only for a recorded dump (`k8s.mariadb.com/dump-file`) on the platform bucket written with the projected platform Secret, reached with the platform credentials, which do not depend on the namespace; - keeps the dump, with a `Warning ArtifactNotDeleted`, when another operator Backup, finished or not, could have written it (the same `contestedMariaDBDump` check as before); - retries a failed delete through `retryMariaDBCleanup`, which releases the `Backup` once the namespace is terminating. The snapshot and the storage URI now record the storage the run was created with, whatever its kind, rather than the strategy as rendered when the run completed. A strategy edited during a run therefore cannot send the cleanup to the wrong place. The BackupJob looks for its run on the API server rather than in the cache, so a retry after a failed status write never starts a second run. A `Running` BackupJob never starts a run at all, and if its run is gone the job is failed. A `Backup` with no recorded dump, no snapshot, a dump on another bucket or written with the tenant's own Secret, or unreadable platform credentials is released with a `Warning`, as before. A missing operator CRD keeps the old release path. The platform-bucket check that `mariadbCleanupConnection` used is now `mariadbPlatformConnection`, shared by both paths. Its behaviour is unchanged. Not covered: - Operator Backups left behind by BackupJobs that failed before this change are still there, because terminal BackupJobs are not reconciled again. Deleting them by hand releases the dumps they hold. - Deleting a BackupJob that is still running leaves its operator Backup, which has no ownerRef and no finalizer. This was already the case and is not addressed here. - The driver-independent terminal exits in `backupjob_controller.go` (BackupClass resolution, credentials projection) still fail a BackupJob without looking at a MariaDB run. - A run that is stopped at the deadline after it has uploaded its dump leaves that dump untracked. No `Backup` is ever made of such a run. The other fail-safe cases listed in the issue (a `Restore` that never completes, the single `Backup` worker, non-204 DELETE responses, endpoint moves) are not addressed here. Tests: `go test ./internal/backupcontroller/...`. The deadline outcome table now also checks whether the operator Backup was deleted. New cleanup tests cover a missing operator Backup: the dump deleted with the platform credentials, already absent, contested by an unfinished run, a failed delete held for retry, and each case it cannot reach (volume storage, a recorded name that is not a dump, a snapshot of another kind). Deadline tests cover a retry after a failed status write, a cache that trails a completed run or misses a new one, a delete conditional on the run that was read, a refused delete, and the application or MariaDB going away mid-run. ### Screenshots N/A, no UI changes. ### Downstream repositories I checked the trigger map in `docs/agents/contributing.md` against the diff. The diff touches `internal/backupcontroller/mariadbstrategy_*.go` and their tests. It also adds a message helper in `internal/backupcontroller/backupjob_controller.go` and changes comments in `internal/backupcontroller/backup_controller.go` and `packages/system/backupstrategy-controller/templates/rbac.yaml`. No values, schemas, CRDs, RBAC rules, annotations or telemetry change. - [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 ```release-note fix(backups): MariaDB dumps are no longer left in the bucket when a backup run never completes or when a tenant namespace is deleted. A BackupJob that times out now deletes the operator Backup it gave up on, so that run no longer blocks the deletion of later dumps. A Backup whose operator Backup is already gone now deletes its recorded dump from the platform bucket using the platform credentials. A MariaDB backup run that has not completed 30 minutes after its BackupJob started is now stopped. ``` <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Bug Fixes** * MariaDB backup cleanup now removes a recorded dump from the platform bucket when its operator Backup is already gone, while leaving contested or insufficiently verified dumps untouched. * Failed dump deletions are retried, and cleanup reports when a dump is already absent. * Backup jobs are less likely to start duplicate runs during retries, and completed backups retain the storage configuration used by their run. * Failure handling preserves completed runs and includes operator-run completion details when available. * Backup jobs now recheck the operator Backup before failing on a deadline, helping account for runs that completed or failed in the meantime. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
415 lines
18 KiB
Go
415 lines
18 KiB
Go
package backupcontroller
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
"slices"
|
|
"strings"
|
|
"time"
|
|
|
|
apierrors "k8s.io/apimachinery/pkg/api/errors"
|
|
"k8s.io/apimachinery/pkg/api/meta"
|
|
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
|
"k8s.io/apimachinery/pkg/runtime"
|
|
"k8s.io/apimachinery/pkg/types"
|
|
"k8s.io/client-go/dynamic"
|
|
"k8s.io/client-go/rest"
|
|
"k8s.io/client-go/tools/record"
|
|
ctrl "sigs.k8s.io/controller-runtime"
|
|
"sigs.k8s.io/controller-runtime/pkg/client"
|
|
"sigs.k8s.io/controller-runtime/pkg/client/apiutil"
|
|
"sigs.k8s.io/controller-runtime/pkg/log"
|
|
|
|
strategyv1alpha1 "github.com/cozystack/cozystack/api/backups/strategy/v1alpha1"
|
|
backupsv1alpha1 "github.com/cozystack/cozystack/api/backups/v1alpha1"
|
|
)
|
|
|
|
// BackupJobReconciler reconciles BackupJob with a strategy from the
|
|
// strategy.backups.cozystack.io API group.
|
|
type BackupJobReconciler struct {
|
|
client.Client
|
|
dynamic.Interface
|
|
meta.RESTMapper
|
|
Scheme *runtime.Scheme
|
|
Recorder record.EventRecorder
|
|
CredentialsConfig BackupCredentialsConfig
|
|
// APIReader is the manager's uncached reader, through which Reconcile
|
|
// re-reads the BackupJob before dispatching to a driver. Wired in
|
|
// SetupWithManager.
|
|
APIReader client.Reader
|
|
|
|
// newS3ObjectLister overrides the S3 client used to measure artifact
|
|
// sizes; nil means a real minio client. Set by unit tests.
|
|
newS3ObjectLister func(conn s3Connection) (s3ObjectLister, error)
|
|
|
|
// now is a test seam for the clock that paces Velero deletion retries.
|
|
now func() time.Time
|
|
}
|
|
|
|
func (r *BackupJobReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
|
|
logger := log.FromContext(ctx)
|
|
logger.Info("reconciling BackupJob", "namespace", req.Namespace, "name", req.Name)
|
|
|
|
j := &backupsv1alpha1.BackupJob{}
|
|
err := r.Get(ctx, types.NamespacedName{Namespace: req.Namespace, Name: req.Name}, j)
|
|
if err != nil {
|
|
if apierrors.IsNotFound(err) {
|
|
logger.V(1).Info("BackupJob not found, skipping")
|
|
return ctrl.Result{}, nil
|
|
}
|
|
logger.Error(err, "failed to get BackupJob")
|
|
return ctrl.Result{}, err
|
|
}
|
|
|
|
// A terminal BackupJob never reaches credentials projection or strategy
|
|
// dispatch: a finished run must not keep projecting Secrets or
|
|
// re-running dispatch on every requeue, which would otherwise
|
|
// materialise cozy-backups-creds in tenant namespaces long after the
|
|
// BackupJob is done and pin needless work on the apiserver. A Failed
|
|
// one only has the failed Velero backups it left behind deleted.
|
|
if j.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed {
|
|
logger.V(1).Info("BackupJob already terminal, cleaning up its Velero Backups", "phase", j.Status.Phase)
|
|
return r.deleteFailedJobVeleroBackups(ctx, j)
|
|
}
|
|
if j.Status.Phase == backupsv1alpha1.BackupJobPhaseSucceeded {
|
|
logger.V(1).Info("BackupJob already terminal, skipping", "phase", j.Status.Phase)
|
|
return ctrl.Result{}, nil
|
|
}
|
|
|
|
// The cache can trail this reconciler's own writes. A pass that stamps
|
|
// StartedAt and then fails the job has already requeued it through the
|
|
// first write, so the next pass can start before the informer has seen
|
|
// Failed, retry the step that failed, and create a driver object for a
|
|
// job that is over and that nothing will track. Re-read the job past the
|
|
// cache; the check above only spares finished jobs the extra request.
|
|
if err := r.apiReader().Get(ctx, req.NamespacedName, j); err != nil {
|
|
if apierrors.IsNotFound(err) {
|
|
return ctrl.Result{}, nil
|
|
}
|
|
logger.Error(err, "failed to re-read BackupJob")
|
|
return ctrl.Result{}, err
|
|
}
|
|
if j.Status.Phase == backupsv1alpha1.BackupJobPhaseSucceeded || j.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed {
|
|
logger.V(1).Info("BackupJob terminal on the apiserver ahead of the cache, skipping", "phase", j.Status.Phase)
|
|
return ctrl.Result{}, nil
|
|
}
|
|
|
|
// Normalize ApplicationRef (default apiGroup if not specified)
|
|
normalizedAppRef := NormalizeApplicationRef(j.Spec.ApplicationRef)
|
|
|
|
// Resolve BackupClass first so we know whether this BackupJob even
|
|
// targets a strategy this controller owns. Projecting credentials
|
|
// before this point would (a) leak cozy-backups-creds into namespaces
|
|
// that use third-party strategies and (b) terminally fail BackupJobs
|
|
// with an unrelated pre-existing cozy-backups-creds (ownership guard
|
|
// kicks in even though no platform strategy is involved).
|
|
resolved, err := ResolveBackupClass(ctx, r.Client, j.Spec.BackupClassName, normalizedAppRef)
|
|
if err != nil {
|
|
// ErrNoMatchingStrategy is a documented configuration error
|
|
// (e.g. tenant fires FoundationDB BackupJob against cozy-default,
|
|
// which intentionally does not bind FDB). Mark Failed terminally
|
|
// so the tenant sees the misbinding instead of an infinite
|
|
// requeue loop with no status signal.
|
|
if errors.Is(err, ErrNoMatchingStrategy) {
|
|
return r.markBackupJobFailed(ctx, j, fmt.Sprintf("BackupClass %q does not bind a strategy for Kind %q; see https://cozystack.io/docs/v1/operations/services/backup-classes/", j.Spec.BackupClassName, normalizedAppRef.Kind))
|
|
}
|
|
// BackupClass not found yet is transient on a fresh install:
|
|
// during the bootstrap window the cozy-default BackupClass is
|
|
// gated on a populated BucketClaim status. Surface a clear
|
|
// Ready=False condition + requeue rather than spamming Error
|
|
// logs on every backoff cycle, mirroring the projection
|
|
// transient-vs-terminal split below.
|
|
if apierrors.IsNotFound(err) {
|
|
meta.SetStatusCondition(&j.Status.Conditions, metav1.Condition{
|
|
Type: "Ready",
|
|
Status: metav1.ConditionFalse,
|
|
Reason: "BackupClassNotFound",
|
|
Message: fmt.Sprintf("BackupClass %q not found; the platform may still be bootstrapping", j.Spec.BackupClassName),
|
|
})
|
|
if updateErr := r.Status().Update(ctx, j); updateErr != nil {
|
|
logger.Error(updateErr, "failed to update BackupJob status to BackupClassNotFound")
|
|
}
|
|
return ctrl.Result{RequeueAfter: CredentialsProjectionRequeue}, nil
|
|
}
|
|
logger.Error(err, "failed to resolve BackupClass", "backupClassName", j.Spec.BackupClassName)
|
|
return ctrl.Result{}, err
|
|
}
|
|
|
|
strategyRef := resolved.StrategyRef
|
|
|
|
// Validate strategyRef
|
|
if strategyRef.APIGroup == nil {
|
|
logger.V(1).Info("BackupJob resolved StrategyRef has nil APIGroup, skipping", "backupjob", j.Name)
|
|
return ctrl.Result{}, nil
|
|
}
|
|
|
|
if *strategyRef.APIGroup != strategyv1alpha1.GroupVersion.Group {
|
|
logger.V(1).Info("BackupJob resolved StrategyRef.APIGroup doesn't match, skipping",
|
|
"backupjob", j.Name,
|
|
"expected", strategyv1alpha1.GroupVersion.Group,
|
|
"got", *strategyRef.APIGroup)
|
|
return ctrl.Result{}, nil
|
|
}
|
|
|
|
// Reject unsupported Kinds inside the platform APIGroup BEFORE
|
|
// credentials projection. Without this guard a BackupClass that
|
|
// resolves to e.g. strategy.backups.cozystack.io/MadeUpKind would
|
|
// leak cozy-backups-creds into the tenant namespace and then
|
|
// silently no-op in the dispatch switch below — leaving the
|
|
// BackupJob in a phaseless state forever.
|
|
supported := slices.Contains(supportedBackupStrategyKinds(), strategyRef.Kind)
|
|
if !supported {
|
|
return r.markBackupJobFailed(ctx, j, fmt.Sprintf("strategy Kind %q is not supported by this controller (supported: %s)", strategyRef.Kind, strings.Join(supportedBackupStrategyKinds(), ", ")))
|
|
}
|
|
|
|
// Hold a run that has not started while a restore writes into its
|
|
// application. Only before StartedAt: every driver stamps it on its
|
|
// first pass, and a run already moving data is not interrupted here.
|
|
if j.Status.StartedAt == nil {
|
|
restore, err := activeRestoreTargeting(ctx, r.Client, j.Namespace, normalizedAppRef)
|
|
if err != nil {
|
|
logger.Error(err, "failed to check for a restore in progress")
|
|
return ctrl.Result{}, err
|
|
}
|
|
if restore != "" {
|
|
return r.holdForRestore(ctx, j, restore)
|
|
}
|
|
if err := r.releaseRestoreHold(ctx, j); err != nil {
|
|
return ctrl.Result{}, err
|
|
}
|
|
}
|
|
|
|
// Now project the platform-managed S3 credentials into the tenant
|
|
// namespace so default Strategy CRs can reference a deterministic
|
|
// Secret name. The projection is idempotent and silently skipped on
|
|
// clusters where it is not configured (legacy chart-managed flow).
|
|
//
|
|
// Failure handling: SourceSecretMissing / APIError are transient — the
|
|
// Bucket controller may not have produced the source Secret yet on a
|
|
// fresh install. Mark Ready=False and requeue rather than terminally
|
|
// failing the BackupJob (which would force tenants to recreate it and
|
|
// would silently fail Plan-driven runs). TargetSecretNotOwned and
|
|
// SourceSecretMalformed are operator-visible misconfigurations that
|
|
// will not self-heal — fail terminally so the tenant gets a clear
|
|
// message.
|
|
if err := ProjectBackupCredentials(ctx, r.Client, r.CredentialsConfig, j.Namespace); err != nil {
|
|
return r.handleProjectionError(ctx, j, err)
|
|
}
|
|
|
|
logger.Info("processing BackupJob", "backupjob", j.Name, "strategyKind", strategyRef.Kind, "backupClassName", j.Spec.BackupClassName)
|
|
switch strategyRef.Kind {
|
|
case strategyv1alpha1.JobStrategyKind:
|
|
return r.reconcileJob(ctx, j, resolved)
|
|
case strategyv1alpha1.VeleroStrategyKind:
|
|
return r.reconcileVelero(ctx, j, resolved)
|
|
case strategyv1alpha1.CNPGStrategyKind:
|
|
return r.reconcileCNPG(ctx, j, resolved)
|
|
case strategyv1alpha1.AltinityStrategyKind:
|
|
return r.reconcileAltinity(ctx, j, resolved)
|
|
case strategyv1alpha1.MariaDBStrategyKind:
|
|
return r.reconcileMariaDB(ctx, j, resolved)
|
|
case strategyv1alpha1.MongoDBStrategyKind:
|
|
return r.reconcileMongoDB(ctx, j, resolved)
|
|
case strategyv1alpha1.FoundationDBStrategyKind:
|
|
return r.reconcileFoundationDB(ctx, j, resolved)
|
|
case strategyv1alpha1.EtcdStrategyKind:
|
|
return r.reconcileEtcd(ctx, j, resolved)
|
|
case strategyv1alpha1.RabbitmqStrategyKind:
|
|
return r.reconcileRabbitmq(ctx, j, resolved)
|
|
case strategyv1alpha1.RedisStrategyKind:
|
|
return r.reconcileRedis(ctx, j, resolved)
|
|
case strategyv1alpha1.KafkaStrategyKind:
|
|
return r.reconcileKafka(ctx, j, resolved)
|
|
case strategyv1alpha1.KubernetesStrategyKind:
|
|
return r.reconcileKubernetes(ctx, j, resolved)
|
|
default:
|
|
logger.V(1).Info("BackupJob resolved StrategyRef.Kind not supported, skipping",
|
|
"backupjob", j.Name,
|
|
"kind", strategyRef.Kind,
|
|
"supported", supportedBackupStrategyKinds())
|
|
return ctrl.Result{}, nil
|
|
}
|
|
}
|
|
|
|
// supportedBackupStrategyKinds returns every strategy.Kind the dispatch
|
|
// switch above handles. Centralised so the unsupported-strategy diagnostic
|
|
// can't drift out of sync with the real dispatch table - the unit test
|
|
// TestSupportedBackupStrategyKindsMatchesDispatch locks in this invariant.
|
|
func supportedBackupStrategyKinds() []string {
|
|
return []string{
|
|
strategyv1alpha1.JobStrategyKind,
|
|
strategyv1alpha1.VeleroStrategyKind,
|
|
strategyv1alpha1.CNPGStrategyKind,
|
|
strategyv1alpha1.AltinityStrategyKind,
|
|
strategyv1alpha1.MariaDBStrategyKind,
|
|
strategyv1alpha1.MongoDBStrategyKind,
|
|
strategyv1alpha1.FoundationDBStrategyKind,
|
|
strategyv1alpha1.EtcdStrategyKind,
|
|
strategyv1alpha1.RabbitmqStrategyKind,
|
|
strategyv1alpha1.RedisStrategyKind,
|
|
strategyv1alpha1.KafkaStrategyKind,
|
|
strategyv1alpha1.KubernetesStrategyKind,
|
|
}
|
|
}
|
|
|
|
// SetupWithManager registers our controller with the Manager and sets up watches.
|
|
func (r *BackupJobReconciler) SetupWithManager(mgr ctrl.Manager) error {
|
|
// index BackupJob by backupClassName for efficient lookups when BackupClass changes
|
|
if err := mgr.GetFieldIndexer().IndexField(context.Background(), &backupsv1alpha1.BackupJob{}, "spec.backupClassName", func(obj client.Object) []string {
|
|
job := obj.(*backupsv1alpha1.BackupJob)
|
|
if job.Spec.BackupClassName == "" {
|
|
return []string{}
|
|
}
|
|
return []string{job.Spec.BackupClassName}
|
|
}); err != nil {
|
|
return err
|
|
}
|
|
|
|
r.APIReader = mgr.GetAPIReader()
|
|
cfg := mgr.GetConfig()
|
|
var err error
|
|
if r.Interface, err = dynamic.NewForConfig(cfg); err != nil {
|
|
return err
|
|
}
|
|
var h *http.Client
|
|
if h, err = rest.HTTPClientFor(cfg); err != nil {
|
|
return err
|
|
}
|
|
if r.RESTMapper, err = apiutil.NewDynamicRESTMapper(cfg, h); err != nil {
|
|
return err
|
|
}
|
|
return ctrl.NewControllerManagedBy(mgr).
|
|
For(&backupsv1alpha1.BackupJob{}).
|
|
Complete(r)
|
|
}
|
|
|
|
// apiReader returns the uncached reader. Reconcilers built by hand in unit
|
|
// tests have none and fall back to their fake Client, which has no cache to
|
|
// bypass.
|
|
func (r *BackupJobReconciler) apiReader() client.Reader {
|
|
if r.APIReader != nil {
|
|
return r.APIReader
|
|
}
|
|
return r.Client
|
|
}
|
|
|
|
// handleProjectionError classifies a credentials-projection error as
|
|
// transient (requeue) or terminal (mark Failed). Transient errors record
|
|
// a Ready=False condition without setting Phase=Failed so the BackupJob
|
|
// resumes once the underlying issue (source Secret propagation, apiserver
|
|
// hiccup) clears.
|
|
func (r *BackupJobReconciler) handleProjectionError(ctx context.Context, j *backupsv1alpha1.BackupJob, err error) (ctrl.Result, error) {
|
|
logger := getLogger(ctx)
|
|
// Tenant-side projection failures must be visible in the same
|
|
// Prometheus counter as system-side failures so the
|
|
// "rate(failures_total) > 0 or absent_over_time(successes_total[10m])"
|
|
// alert in https://cozystack.io/docs/v1/operations/services/backup-classes/ catches them. The system
|
|
// projector reports against system namespaces (cozy-velero etc.);
|
|
// here we attribute against the BackupJob's tenant namespace.
|
|
credentialsProjectionFailures.WithLabelValues(j.Namespace, classifyReason(err)).Inc()
|
|
if IsTransient(err) {
|
|
meta.SetStatusCondition(&j.Status.Conditions, metav1.Condition{
|
|
Type: "Ready",
|
|
Status: metav1.ConditionFalse,
|
|
Reason: "CredentialsProjectionPending",
|
|
Message: err.Error(),
|
|
})
|
|
if updateErr := r.Status().Update(ctx, j); updateErr != nil {
|
|
logger.Error(updateErr, "failed to update BackupJob status to projection-pending")
|
|
}
|
|
logger.Info("backup credentials projection transient failure; requeueing", "message", err.Error())
|
|
return ctrl.Result{RequeueAfter: CredentialsProjectionRequeue}, nil
|
|
}
|
|
return r.markBackupJobFailed(ctx, j, fmt.Sprintf("failed to project backup credentials: %v", err))
|
|
}
|
|
|
|
// markBackupJobFailed records a terminal Failed phase on the BackupJob.
|
|
func (r *BackupJobReconciler) markBackupJobFailed(ctx context.Context, backupJob *backupsv1alpha1.BackupJob, message string) (ctrl.Result, error) {
|
|
logger := getLogger(ctx)
|
|
now := metav1.Now()
|
|
backupJob.Status.CompletedAt = &now
|
|
backupJob.Status.Phase = backupsv1alpha1.BackupJobPhaseFailed
|
|
backupJob.Status.Message = message
|
|
|
|
// SetStatusCondition keeps Conditions matching the +listType=map +listMapKey=type
|
|
// CRD contract: a previously-set Ready condition (e.g. from a transient
|
|
// retry path that flipped through ConditionFalse with a different
|
|
// Reason) is updated in-place rather than appended, and LastTransitionTime
|
|
// is preserved unless Status changes.
|
|
meta.SetStatusCondition(&backupJob.Status.Conditions, metav1.Condition{
|
|
Type: "Ready",
|
|
Status: metav1.ConditionFalse,
|
|
Reason: "BackupFailed",
|
|
Message: message,
|
|
})
|
|
|
|
if err := r.Status().Update(ctx, backupJob); err != nil {
|
|
logger.Error(err, "failed to update BackupJob status to Failed")
|
|
return ctrl.Result{}, err
|
|
}
|
|
logger.Debug("BackupJob failed", "message", message)
|
|
return ctrl.Result{}, nil
|
|
}
|
|
|
|
// StrategyNotReadyDeadline bounds how long a BackupJob/RestoreJob may sit in
|
|
// the transient StrategyNotReady state before it is failed terminally. It must
|
|
// be comfortably longer than a Flux HelmRelease reconcile cycle (default 10m)
|
|
// so a legitimate bootstrap self-heal — backupstrategy-controller ships the
|
|
// cozy-default BackupClass before its Strategy CRs, which are gated on the
|
|
// BucketClaim status — is never killed mid-flight. 30m gives ~3 Flux cycles,
|
|
// matching mariadbDefaultBackupDeadline.
|
|
const StrategyNotReadyDeadline = 30 * time.Minute
|
|
|
|
// strategyNotReadyDeadlineExceeded reports whether a job that has been waiting
|
|
// on a missing Strategy CR has exhausted the bootstrap-window grace period.
|
|
// Returns false when StartedAt is nil so the first reconcile (which sets it)
|
|
// never trips the gate.
|
|
func strategyNotReadyDeadlineExceeded(startedAt *metav1.Time) bool {
|
|
if startedAt == nil {
|
|
return false
|
|
}
|
|
return time.Since(startedAt.Time) > StrategyNotReadyDeadline
|
|
}
|
|
|
|
// requeueStrategyNotReady surfaces a transient Ready=False/StrategyNotReady
|
|
// condition on the BackupJob and requeues. Drivers call this when the
|
|
// strategyRef.name referenced by a (resolved) BackupClass points at a
|
|
// Strategy CR that does not exist yet — which happens during the
|
|
// platform bootstrap window where backupstrategy-controller's chart
|
|
// has rendered cozy-default BackupClass (always present) but its
|
|
// strategy templates are still gated on the BucketClaim status
|
|
// reconciling. Flux re-renders the chart once the BucketClaim status
|
|
// populates, the Strategy CR appears, and the next reconcile picks it
|
|
// up. Terminal failure here would force tenants to recreate BackupJobs
|
|
// every time they raced the bootstrap.
|
|
//
|
|
// The wait is bounded by StrategyNotReadyDeadline: a strategyRef.name that
|
|
// never resolves (e.g. a typo in a custom BackupClass) would otherwise requeue
|
|
// forever with no operator-visible "this will never succeed" signal. Mirrors
|
|
// the MariaDB CR-existence deadline. Every driver sets StartedAt before this is
|
|
// called, so the clock has already started.
|
|
func (r *BackupJobReconciler) requeueStrategyNotReady(ctx context.Context, j *backupsv1alpha1.BackupJob, strategyName string) (ctrl.Result, error) {
|
|
logger := getLogger(ctx)
|
|
if strategyNotReadyDeadlineExceeded(j.Status.StartedAt) {
|
|
return r.markBackupJobFailed(ctx, j, strategyNotProvisionedMessage(j, strategyName))
|
|
}
|
|
meta.SetStatusCondition(&j.Status.Conditions, metav1.Condition{
|
|
Type: "Ready",
|
|
Status: metav1.ConditionFalse,
|
|
Reason: "StrategyNotReady",
|
|
Message: fmt.Sprintf("Strategy %q referenced by BackupClass %q is not yet provisioned; the platform may still be initialising backup storage", strategyName, j.Spec.BackupClassName),
|
|
})
|
|
if updateErr := r.Status().Update(ctx, j); updateErr != nil {
|
|
logger.Error(updateErr, "failed to update BackupJob status to StrategyNotReady")
|
|
}
|
|
return ctrl.Result{RequeueAfter: CredentialsProjectionRequeue}, nil
|
|
}
|
|
|
|
func strategyNotProvisionedMessage(j *backupsv1alpha1.BackupJob, strategyName string) string {
|
|
return fmt.Sprintf(
|
|
"Strategy %q referenced by BackupClass %q was not provisioned within %s; check the strategyRef name or the platform backup-storage bootstrap",
|
|
strategyName, j.Spec.BackupClassName, StrategyNotReadyDeadline)
|
|
}
|