diff --git a/internal/backupcontroller/backup_controller.go b/internal/backupcontroller/backup_controller.go index a8908d34d..b5fad8c54 100644 --- a/internal/backupcontroller/backup_controller.go +++ b/internal/backupcontroller/backup_controller.go @@ -145,8 +145,9 @@ func (r *BackupReconciler) cleanupOnDelete(ctx context.Context, backup *backupsv // a tenant's own bucket is deleted too: the Backup proves it owns // it, and tenants cannot delete Backups, so the delete comes from an // administrator or from namespace teardown. Teardown can remove the - // operator Backup first, and the dump is then left behind with a - // Warning, since its storage is read from it (see cleanupMariaDBBackup). + // operator Backup first; a recorded dump on the platform bucket is + // then still deleted, and any other is left behind with a Warning + // (see cleanupMariaDBBackup). return r.cleanupMariaDBBackup(ctx, backup) case strategyv1alpha1.MongoDBStrategyKind: // Split by flow (see cleanupMongoDBBackup). A legacy backup writes to the diff --git a/internal/backupcontroller/backupjob_controller.go b/internal/backupcontroller/backupjob_controller.go index 4b96c2087..a892c34e9 100644 --- a/internal/backupcontroller/backupjob_controller.go +++ b/internal/backupcontroller/backupjob_controller.go @@ -393,9 +393,7 @@ func strategyNotReadyDeadlineExceeded(startedAt *metav1.Time) bool { 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, 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)) + return r.markBackupJobFailed(ctx, j, strategyNotProvisionedMessage(j, strategyName)) } meta.SetStatusCondition(&j.Status.Conditions, metav1.Condition{ Type: "Ready", @@ -408,3 +406,9 @@ func (r *BackupJobReconciler) requeueStrategyNotReady(ctx context.Context, j *ba } 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) +} diff --git a/internal/backupcontroller/mariadbstrategy_cleanup.go b/internal/backupcontroller/mariadbstrategy_cleanup.go index 912bb0038..457b4d7a4 100644 --- a/internal/backupcontroller/mariadbstrategy_cleanup.go +++ b/internal/backupcontroller/mariadbstrategy_cleanup.go @@ -3,6 +3,7 @@ package backupcontroller import ( "context" + "encoding/json" "errors" "fmt" "slices" @@ -44,7 +45,8 @@ var mariadbDumpCleanupTimeout = 10 * time.Second // no dump is proven the Backup is released with a Warning and nothing is // deleted, the operator Backup included, since it is what any later // attribution would start from. A failed delete holds the Backup and -// retries, as the Redis and Rabbitmq cleanups do. +// retries, as the Redis and Rabbitmq cleanups do. When the operator Backup +// is gone, cleanupOrphanedMariaDBDump deletes the dump instead. func (r *BackupReconciler) cleanupMariaDBBackup(ctx context.Context, backup *backupsv1alpha1.Backup) (ctrl.Result, error) { logger := getLogger(ctx) if backup.Annotations[mariadbSkipArtifactCleanupAnnotation] == "true" { @@ -75,7 +77,10 @@ func (r *BackupReconciler) cleanupMariaDBBackup(ctx context.Context, backup *bac op := &mariadbtypes.Backup{} if err := r.Get(ctx, types.NamespacedName{Namespace: backup.Namespace, Name: opName}, op); err != nil { - if apierrors.IsNotFound(err) || apimeta.IsNoMatchError(err) { + if apierrors.IsNotFound(err) { + return r.cleanupOrphanedMariaDBDump(ctx, backup, opName) + } + if apimeta.IsNoMatchError(err) { return r.releaseMariaDBCleanup(ctx, backup, "the dump", fmt.Sprintf("k8s.mariadb.com/Backup %s is gone, so the storage and credentials its dump was written with cannot be read", opName)), nil } @@ -173,6 +178,96 @@ func (r *BackupReconciler) cleanupMariaDBBackup(ctx context.Context, backup *bac return ctrl.Result{}, nil } +// cleanupOrphanedMariaDBDump deletes the recorded dump of a Backup whose +// operator Backup is gone, as it can be by the time a namespace being torn +// down reaches the Backup's finalizer: mariadb-operator puts none on its +// Backup. The storage comes from the snapshot the Backup was made with. +// Only a dump on the platform bucket is deleted, since the platform +// credentials are the only ones that do not go with the namespace, and only +// a recorded one: attributing a dump needs the operator Backup's lifetime. +func (r *BackupReconciler) cleanupOrphanedMariaDBDump(ctx context.Context, backup *backupsv1alpha1.Backup, opName string) (ctrl.Result, error) { + gone := fmt.Sprintf("k8s.mariadb.com/Backup %s is gone", opName) + name := backup.Spec.DriverMetadata[mariadbDumpFileKey] + if name == "" { + return r.releaseMariaDBCleanup(ctx, backup, "the dump", gone+" and the Backup records no dump, so none can be attributed to it"), nil + } + if _, ok := parseMariaDBLogicalBackupFile(name); !ok { + return r.releaseMariaDBCleanup(ctx, backup, "the dump", + fmt.Sprintf("driverMetadata %s=%q is not the name of a mariadb-operator dump", mariadbDumpFileKey, name)), nil + } + storage, err := mariadbSnapshotStorage(backup) + if err != nil { + return r.releaseMariaDBCleanup(ctx, backup, "the dump", fmt.Sprintf("%s and its storage cannot be read from the Backup: %v", gone, err)), nil + } + if storage.S3 == nil { + return r.releaseMariaDBCleanup(ctx, backup, "the dump on a storage volume", "PVC and Volume storage is not reachable from the controller"), nil + } + op := &mariadbtypes.Backup{ + ObjectMeta: metav1.ObjectMeta{Namespace: backup.Namespace, Name: opName}, + Spec: mariadbtypes.BackupSpec{Storage: storage}, + } + location := fmt.Sprintf("s3://%s/%s%s", storage.S3.Bucket, mariadbOperatorS3Prefix(storage.S3.Prefix), name) + + conn, onPlatform, err := r.mariadbPlatformConnection(ctx, op) + if err != nil { + return r.retryMariaDBCleanup(ctx, backup, location, fmt.Errorf("resolve S3 credentials: %w", err)) + } + if !onPlatform { + return r.releaseMariaDBCleanup(ctx, backup, location, + gone+", and the dump is not on the platform bucket or the platform credentials cannot be read, so no credentials to reach it are left"), nil + } + + s3ctx, cancel := context.WithTimeout(ctx, mariadbDumpCleanupTimeout) + defer cancel() + store := r.objectStore() + lister, err := store.lister(conn) + if err != nil { + return r.retryMariaDBCleanup(ctx, backup, location, fmt.Errorf("build S3 client: %w", err)) + } + other, found, err := contestedMariaDBDump(s3ctx, lister, r.apiReader(), op, name) + if err != nil { + return r.retryMariaDBCleanup(ctx, backup, location, err) + } + if other != "" { + return r.releaseMariaDBCleanup(ctx, backup, location, + fmt.Sprintf("the recorded dump also falls in the lifetime of k8s.mariadb.com/Backup %s, which may have written it", other)), nil + } + if !found { + getLogger(ctx).Info("MariaDB dump already absent", "backup", backup.Name, "dump", location, "endpoint", conn.Endpoint, "operatorBackup", opName) + if r.Recorder != nil { + r.Recorder.Eventf(backup, corev1.EventTypeNormal, "ArtifactAlreadyAbsent", + "%s was not found when listed through %s, so it was deleted earlier or never reached that storage", location, conn.Endpoint) + } + return ctrl.Result{}, nil + } + remover, err := store.remover(conn) + if err != nil { + return r.retryMariaDBCleanup(ctx, backup, location, fmt.Errorf("build S3 client: %w", err)) + } + if err := remover.RemoveObject(s3ctx, storage.S3.Bucket, mariadbOperatorS3Prefix(storage.S3.Prefix)+name); err != nil { + return r.retryMariaDBCleanup(ctx, backup, location, err) + } + getLogger(ctx).Info("deleted MariaDB dump of a gone operator Backup", "backup", backup.Name, "dump", location, "operatorBackup", opName) + return ctrl.Result{}, nil +} + +// mariadbSnapshotStorage returns the storage the Backup's operator Backup +// was made with, from the snapshot in status.underlyingResources. +func mariadbSnapshotStorage(backup *backupsv1alpha1.Backup) (mariadbtypes.BackupStorage, error) { + raw := backup.Status.UnderlyingResources + if raw == nil || len(raw.Raw) == 0 { + return mariadbtypes.BackupStorage{}, errors.New("status.underlyingResources is empty") + } + var snap mariadbBackupSnapshot + if err := json.Unmarshal(raw.Raw, &snap); err != nil { + return mariadbtypes.BackupStorage{}, fmt.Errorf("decode status.underlyingResources: %w", err) + } + if snap.Kind != mariadbBackupSnapshotKind || snap.Storage == nil { + return mariadbtypes.BackupStorage{}, fmt.Errorf("status.underlyingResources is not a %s with storage", mariadbBackupSnapshotKind) + } + return buildMariaDBBackupStorage(*snap.Storage) +} + // contestedMariaDBDump returns the name of another operator Backup on op's // bucket and prefix whose run, finished or not, could have written the dump // name, or "" when none could, and whether the listing found the dump. The @@ -261,30 +356,44 @@ func (r *BackupReconciler) activeRestoreOf(ctx context.Context, backup *backupsv // recorded endpoint may be the one the platform moved off, where the dump // would be found missing and reported deleted. func (r *BackupReconciler) mariadbCleanupConnection(ctx context.Context, op *mariadbtypes.Backup) (s3Connection, error) { - if r.CredentialsConfig.IsEnabled() { - conn, bucket, err := r.platformS3Connection(ctx) - var projErr *ProjectionError - switch { - case errors.As(err, &projErr) && projErr.Reason == ReasonAPIError: - return s3Connection{}, err - case err != nil: - getLogger(ctx).Info("cannot read the platform backup credentials; using the operator Backup's own", "operatorBackup", op.Name, "error", err) - case bucket == op.Spec.Storage.S3.Bucket && op.Spec.Storage.S3.AccessKeyIdSecretKeyRef.Name == r.CredentialsConfig.TargetSecretName: - // A strategy can pin a private CA for the platform bucket; the - // platform credentials carry none. - if tls := op.Spec.Storage.S3.TLS; conn.Secure && tls != nil && tls.CASecretKeyRef != nil { - ca, err := r.objectStore().secretValue(ctx, op.Namespace, tls.CASecretKeyRef.Name, tls.CASecretKeyRef.Key) - if err != nil { - return s3Connection{}, err - } - conn.CAPEM = []byte(ca) - } - return conn, nil - } + conn, onPlatform, err := r.mariadbPlatformConnection(ctx, op) + if err != nil || onPlatform { + return conn, err } return mariadbS3Connection(ctx, r.objectStore(), op.Namespace, op.Spec.Storage.S3) } +// mariadbPlatformConnection returns the platform's connection to the bucket +// op wrote to, and false when op did not write to the platform bucket or the +// platform credentials are missing or malformed. Only a failed read of the +// platform credentials is an error. +func (r *BackupReconciler) mariadbPlatformConnection(ctx context.Context, op *mariadbtypes.Backup) (s3Connection, bool, error) { + if !r.CredentialsConfig.IsEnabled() { + return s3Connection{}, false, nil + } + conn, bucket, err := r.platformS3Connection(ctx) + var projErr *ProjectionError + switch { + case errors.As(err, &projErr) && projErr.Reason == ReasonAPIError: + return s3Connection{}, false, err + case err != nil: + getLogger(ctx).Info("cannot read the platform backup credentials; using the operator Backup's own", "operatorBackup", op.Name, "error", err) + return s3Connection{}, false, nil + case bucket != op.Spec.Storage.S3.Bucket || op.Spec.Storage.S3.AccessKeyIdSecretKeyRef.Name != r.CredentialsConfig.TargetSecretName: + return s3Connection{}, false, nil + } + // A strategy can pin a private CA for the platform bucket; the platform + // credentials carry none. + if tls := op.Spec.Storage.S3.TLS; conn.Secure && tls != nil && tls.CASecretKeyRef != nil { + ca, err := r.objectStore().secretValue(ctx, op.Namespace, tls.CASecretKeyRef.Name, tls.CASecretKeyRef.Key) + if err != nil { + return s3Connection{}, false, err + } + conn.CAPEM = []byte(ca) + } + return conn, true, nil +} + // platformS3Connection reads the platform's backup bucket from the Secret // cozy-backups-creds is projected from, and its TLS from the scheme of // BACKUP_STORAGE_ENDPOINT, which is how the default strategy sets diff --git a/internal/backupcontroller/mariadbstrategy_cleanup_test.go b/internal/backupcontroller/mariadbstrategy_cleanup_test.go index 7efb3046f..477fa4953 100644 --- a/internal/backupcontroller/mariadbstrategy_cleanup_test.go +++ b/internal/backupcontroller/mariadbstrategy_cleanup_test.go @@ -15,6 +15,7 @@ import ( apierrors "k8s.io/apimachinery/pkg/api/errors" apimeta "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" "k8s.io/client-go/tools/record" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" @@ -1377,3 +1378,144 @@ func (f *fakeS3Bucket) StatObject(_ context.Context, _, key string) (int64, erro } return 0, errors.New("not found") } + +// orphanedCleanupBackup is cleanupBackup made of a run that stored to s3, +// as status.underlyingResources records it. +func orphanedCleanupBackup(t *testing.T, s3 *strategyv1alpha1.MariaDBS3Template, dumpFile string) *backupsv1alpha1.Backup { + t.Helper() + rendered := newRenderedMariaDBTemplate() + rendered.Storage.S3 = s3 + snap, err := marshalMariaDBBackupSnapshot(rendered, nil) + if err != nil { + t.Fatal(err) + } + backup := cleanupBackup(dumpFile) + backup.Status.UnderlyingResources = snap + return backup +} + +func cleanupStorage() *strategyv1alpha1.MariaDBS3Template { + s3 := newRenderedMariaDBTemplate().Storage.S3 + s3.Prefix = "tenant/db" + return s3 +} + +func cleanupDumpListing() *fakeS3Bucket { + return &fakeS3Bucket{objects: []s3ObjectInfo{{Key: cleanupPrefix + cleanupDumpName, LastModified: cleanupCreated.Add(2 * time.Minute)}}} +} + +// Namespace teardown deletes the operator Backup, which carries no +// finalizer, before the Backup's finalizer runs; the tenant's own Secrets +// go with it, so only the platform credentials reach the dump. +func TestCleanupMariaDBBackup_GoneOperatorBackupDeletesTheRecordedDumpOnThePlatformBucket(t *testing.T) { + bucket := cleanupDumpListing() + r, rec := cleanupReconciler(t, bucket, tenantNamespace(), platformCredsSecret("bkt", "s3.new.example")) + r.CredentialsConfig = platformCredsConfig("https://s3.new.example") + + res, err := r.cleanupMariaDBBackup(context.Background(), orphanedCleanupBackup(t, cleanupStorage(), cleanupDumpName)) + if err != nil || requeues(res) { + t.Fatalf("got res=%+v err=%v, want the Backup released", res, err) + } + if want := "bkt/" + cleanupPrefix + cleanupDumpName; len(bucket.removed) != 1 || bucket.removed[0] != want { + t.Errorf("removed %v, want [%s]", bucket.removed, want) + } + for _, conn := range bucket.conns { + if conn.Endpoint != "s3.new.example" || conn.AccessKey != "PLATFORM" { + t.Errorf("connection = %+v, want the platform's endpoint and keys", conn) + } + } + if events := drainEvents(rec); hasEvent(events, "Warning ArtifactNotDeleted") { + t.Errorf("events = %v, want no ArtifactNotDeleted", events) + } +} + +func TestCleanupMariaDBBackup_GoneOperatorBackupWithTheDumpAlreadyGone(t *testing.T) { + bucket := &fakeS3Bucket{} + r, rec := cleanupReconciler(t, bucket, tenantNamespace(), platformCredsSecret("bkt", "s3.new.example")) + r.CredentialsConfig = platformCredsConfig("https://s3.new.example") + + res, err := r.cleanupMariaDBBackup(context.Background(), orphanedCleanupBackup(t, cleanupStorage(), cleanupDumpName)) + if err != nil || requeues(res) || len(bucket.removed) != 0 { + t.Fatalf("got res=%+v err=%v removed=%v, want released with nothing deleted", res, err, bucket.removed) + } + if events := drainEvents(rec); !hasEvent(events, "Normal ArtifactAlreadyAbsent") { + t.Errorf("events = %v, want a Normal ArtifactAlreadyAbsent", events) + } +} + +func TestCleanupMariaDBBackup_GoneOperatorBackupWithAContestedDumpIsReleased(t *testing.T) { + bucket := cleanupDumpListing() + running := cleanupOperatorBackup(t) + running.Name = "op-running" + running.Status.Conditions = nil + r, rec := cleanupReconciler(t, bucket, running, tenantNamespace(), platformCredsSecret("bkt", "s3.new.example")) + r.CredentialsConfig = platformCredsConfig("https://s3.new.example") + + res, err := r.cleanupMariaDBBackup(context.Background(), orphanedCleanupBackup(t, cleanupStorage(), cleanupDumpName)) + if err != nil || requeues(res) || len(bucket.removed) != 0 { + t.Fatalf("got res=%+v err=%v removed=%v, want released with nothing deleted", res, err, bucket.removed) + } + if events := drainEvents(rec); !hasEvent(events, "Warning ArtifactNotDeleted") { + t.Errorf("events = %v, want a Warning ArtifactNotDeleted", events) + } +} + +func TestCleanupMariaDBBackup_GoneOperatorBackupFailedDeleteRetries(t *testing.T) { + bucket := cleanupDumpListing() + bucket.removeErr = errors.New("connection refused") + r, rec := cleanupReconciler(t, bucket, tenantNamespace(), platformCredsSecret("bkt", "s3.new.example")) + r.CredentialsConfig = platformCredsConfig("https://s3.new.example") + + res, err := r.cleanupMariaDBBackup(context.Background(), orphanedCleanupBackup(t, cleanupStorage(), cleanupDumpName)) + if err != nil || !requeues(res) { + t.Fatalf("got res=%+v err=%v, want the Backup held for a retry", res, err) + } + if events := drainEvents(rec); !hasEvent(events, "Warning ArtifactCleanupFailed") { + t.Errorf("events = %v, want a Warning ArtifactCleanupFailed", events) + } +} + +func TestCleanupMariaDBBackup_GoneOperatorBackupReleasesWhatItCannotReach(t *testing.T) { + ownCreds := cleanupStorage() + ownCreds.AccessKeyIDSecretKeyRef.Name = "own-creds" + otherBucket := cleanupStorage() + otherBucket.Bucket = "tenant-own-bucket" + onVolume := cleanupBackup(cleanupDumpName) + onVolume.Status.UnderlyingResources = &runtime.RawExtension{Raw: []byte( + `{"kind":"` + mariadbBackupSnapshotKind + `","storage":{"persistentVolumeClaim":{"accessModes":["ReadWriteOnce"]}}}`)} + foreignKind := orphanedCleanupBackup(t, cleanupStorage(), cleanupDumpName) + foreignKind.Status.UnderlyingResources.Raw = []byte(strings.Replace(string(foreignKind.Status.UnderlyingResources.Raw), + mariadbBackupSnapshotKind, "SomethingElse", 1)) + cases := map[string]struct { + backup *backupsv1alpha1.Backup + platform bool + }{ + "no dump recorded": {backup: orphanedCleanupBackup(t, cleanupStorage(), ""), platform: true}, + "no storage snapshot": {backup: cleanupBackup(cleanupDumpName), platform: true}, + "another bucket": {backup: orphanedCleanupBackup(t, otherBucket, cleanupDumpName), platform: true}, + "the tenant's own Secret": {backup: orphanedCleanupBackup(t, ownCreds, cleanupDumpName), platform: true}, + "platform credentials gone": {backup: orphanedCleanupBackup(t, cleanupStorage(), cleanupDumpName)}, + "dump on a volume": {backup: onVolume, platform: true}, + "recorded name not a dump": {backup: orphanedCleanupBackup(t, cleanupStorage(), "backup.tar"), platform: true}, + "snapshot of another kind": {backup: foreignKind, platform: true}, + } + for name, tc := range cases { + t.Run(name, func(t *testing.T) { + bucket := cleanupDumpListing() + objs := []client.Object{tenantNamespace(), s3CredsSecret("tenant", "creds")} + if tc.platform { + objs = append(objs, platformCredsSecret("bkt", "s3.new.example")) + } + r, rec := cleanupReconciler(t, bucket, objs...) + r.CredentialsConfig = platformCredsConfig("https://s3.new.example") + + res, err := r.cleanupMariaDBBackup(context.Background(), tc.backup) + if err != nil || requeues(res) || len(bucket.removed) != 0 { + t.Fatalf("got res=%+v err=%v removed=%v, want released with nothing deleted", res, err, bucket.removed) + } + if events := drainEvents(rec); !hasEvent(events, "Warning ArtifactNotDeleted") { + t.Errorf("events = %v, want a Warning ArtifactNotDeleted", events) + } + }) + } +} diff --git a/internal/backupcontroller/mariadbstrategy_controller.go b/internal/backupcontroller/mariadbstrategy_controller.go index a8fd29a01..845a78e57 100644 --- a/internal/backupcontroller/mariadbstrategy_controller.go +++ b/internal/backupcontroller/mariadbstrategy_controller.go @@ -6,6 +6,7 @@ import ( "encoding/json" "errors" "fmt" + "strings" "time" batchv1 "k8s.io/api/batch/v1" @@ -134,7 +135,7 @@ func (r *BackupJobReconciler) reconcileMariaDB(ctx context.Context, j *backupsv1 } if err := validateMariaDBApplicationRef(j.Spec.ApplicationRef); err != nil { - return r.markBackupJobFailed(ctx, j, err.Error()) + return r.failMariaDBBackupJob(ctx, j, err.Error()) } if j.Status.StartedAt == nil { @@ -162,6 +163,9 @@ func (r *BackupJobReconciler) reconcileMariaDB(ctx context.Context, j *backupsv1 strategy := &strategyv1alpha1.MariaDB{} if err := r.Get(ctx, client.ObjectKey{Name: resolved.StrategyRef.Name}, strategy); err != nil { if apierrors.IsNotFound(err) { + if strategyNotReadyDeadlineExceeded(j.Status.StartedAt) { + return r.failMariaDBBackupJob(ctx, j, strategyNotProvisionedMessage(j, resolved.StrategyRef.Name)) + } return r.requeueStrategyNotReady(ctx, j, resolved.StrategyRef.Name) } return ctrl.Result{}, err @@ -170,14 +174,14 @@ func (r *BackupJobReconciler) reconcileMariaDB(ctx context.Context, j *backupsv1 app, err := r.getMariaDBApp(ctx, j.Namespace, j.Spec.ApplicationRef.Name) if err != nil { if apierrors.IsNotFound(err) { - return r.markBackupJobFailed(ctx, j, fmt.Sprintf("MariaDB application not found: %s/%s", j.Namespace, j.Spec.ApplicationRef.Name)) + return r.failMariaDBBackupJob(ctx, j, fmt.Sprintf("MariaDB application not found: %s/%s", j.Namespace, j.Spec.ApplicationRef.Name)) } return ctrl.Result{}, err } rendered, err := renderMariaDBTemplate(strategy.Spec.Template, app, resolved.Parameters) if err != nil { - return r.markBackupJobFailed(ctx, j, fmt.Sprintf("failed to template MariaDB strategy: %v", err)) + return r.failMariaDBBackupJob(ctx, j, fmt.Sprintf("failed to template MariaDB strategy: %v", err)) } // Operator-side MariaDB CR carries the prefixed release name (see @@ -192,7 +196,7 @@ func (r *BackupJobReconciler) reconcileMariaDB(ctx context.Context, j *backupsv1 &mariadbtypes.MariaDB{}); err != nil { if apierrors.IsNotFound(err) { if mariadbBackupDeadlineExceeded(j.Status.StartedAt) { - return r.markBackupJobFailed(ctx, j, fmt.Sprintf( + return r.failMariaDBBackupJob(ctx, j, fmt.Sprintf( "k8s.mariadb.com/MariaDB %s/%s never reached existence within %s", j.Namespace, mdbName, mariadbDefaultBackupDeadline)) } @@ -210,9 +214,30 @@ func (r *BackupJobReconciler) reconcileMariaDB(ctx context.Context, j *backupsv1 return ctrl.Result{}, err } - mdbBackup, err := r.ensureMariaDBBackup(ctx, j, rendered) - if err != nil { - return r.markBackupJobFailed(ctx, j, fmt.Sprintf("failed to ensure k8s.mariadb.com/Backup: %v", err)) + // A job that is Running has created its run, and one past the deadline + // is only waited for: either way the run is read past the cache and never + // started again. A pass whose status write failed after + // failMariaDBBackupJob deleted the run would otherwise start another, and + // the cache can miss a run created a moment ago. + var mdbBackup *mariadbtypes.Backup + if pastDeadline := mariadbBackupDeadlineExceeded(j.Status.StartedAt); pastDeadline || j.Status.Phase == backupsv1alpha1.BackupJobPhaseRunning { + runs, err := r.mariadbRunsOf(ctx, j) + if err != nil { + return ctrl.Result{}, err + } + if len(runs) == 0 { + if pastDeadline { + return r.markBackupJobFailed(ctx, j, fmt.Sprintf( + "k8s.mariadb.com Backup did not complete within %s; no k8s.mariadb.com/Backup of this BackupJob is left", mariadbDefaultBackupDeadline)) + } + return r.markBackupJobFailed(ctx, j, "the k8s.mariadb.com/Backup of this BackupJob is gone") + } + mdbBackup = &runs[0] + } else { + mdbBackup, err = r.ensureMariaDBBackup(ctx, j, rendered) + if err != nil { + return r.failMariaDBBackupJob(ctx, j, fmt.Sprintf("failed to ensure k8s.mariadb.com/Backup: %v", err)) + } } if j.Status.Phase != backupsv1alpha1.BackupJobPhaseRunning { @@ -226,7 +251,10 @@ func (r *BackupJobReconciler) reconcileMariaDB(ctx context.Context, j *backupsv1 switch { case cond != nil && cond.Reason == mariadbtypes.ConditionReasonJobFailed: - return r.markBackupJobFailed(ctx, j, mariadbJobFailedMessage(ctx, r.Client, "Backup", mdbBackup.Namespace, mdbBackup.Name, cond)) + // A run at Complete=False/JobFailed counts as unfinished to the dump + // cleanup and is deleted; one at Complete=True/JobFailed has a + // bounded window and is kept. + return r.failMariaDBBackupJob(ctx, j, mariadbJobFailedMessage(ctx, r.Client, "Backup", mdbBackup.Namespace, mdbBackup.Name, cond)) case cond != nil && cond.Status == metav1.ConditionTrue && cond.Reason == mariadbtypes.ConditionReasonJobComplete: // Backup completed successfully. Materialise the Cozystack artifact @@ -236,7 +264,7 @@ func (r *BackupJobReconciler) reconcileMariaDB(ctx context.Context, j *backupsv1 if j.Status.BackupRef != nil { return ctrl.Result{}, nil } - artifact, err := r.createMariaDBBackupArtifact(ctx, j, resolved, mdbBackup, rendered) + artifact, err := r.createMariaDBBackupArtifact(ctx, j, resolved, mdbBackup, mariadbRunTemplate(rendered, mdbBackup)) if err != nil { return r.failBackupArtifact(ctx, j, err) } @@ -262,13 +290,137 @@ func (r *BackupJobReconciler) reconcileMariaDB(ctx context.Context, j *backupsv1 // Backup eventually fails the BackupJob instead of pinning it Running // forever. if mariadbBackupDeadlineExceeded(j.Status.StartedAt) { - return r.markBackupJobFailed(ctx, j, fmt.Sprintf( - "k8s.mariadb.com Backup did not complete within %s (%s)", mariadbDefaultBackupDeadline, mariadbCompleteDetail(cond))) + return r.giveUpOnMariaDBBackup(ctx, j, mdbBackup) } return ctrl.Result{RequeueAfter: mariadbPollInterval}, nil } } +// giveUpOnMariaDBBackup fails a BackupJob past its deadline through +// failMariaDBBackupJob, unless its run has completed or failed by now. +func (r *BackupJobReconciler) giveUpOnMariaDBBackup(ctx context.Context, j *backupsv1alpha1.BackupJob, op *mariadbtypes.Backup) (ctrl.Result, error) { + // Read past the cache, which can trail a Complete the operator has just + // written, or still hold a Backup an earlier pass deleted before its + // status write failed. + fresh := &mariadbtypes.Backup{} + var cond *metav1.Condition + if err := r.apiReader().Get(ctx, client.ObjectKeyFromObject(op), fresh); err != nil { + if !apierrors.IsNotFound(err) { + return ctrl.Result{}, err + } + } else { + cond = apimeta.FindStatusCondition(fresh.Status.Conditions, mariadbtypes.ConditionTypeComplete) + if cond != nil && (cond.Reason == mariadbtypes.ConditionReasonJobFailed || + cond.Status == metav1.ConditionTrue && cond.Reason == mariadbtypes.ConditionReasonJobComplete) { + return ctrl.Result{RequeueAfter: mariadbPollInterval}, nil + } + } + return r.failMariaDBBackupJob(ctx, j, fmt.Sprintf( + "k8s.mariadb.com Backup did not complete within %s (%s)", mariadbDefaultBackupDeadline, mariadbCompleteDetail(cond))) +} + +// mariadbRunsOf lists the operator Backups of a BackupJob past the cache, +// which can miss one created a moment ago. +func (r *BackupJobReconciler) mariadbRunsOf(ctx context.Context, j *backupsv1alpha1.BackupJob) ([]mariadbtypes.Backup, error) { + runs := &mariadbtypes.BackupList{} + if err := r.apiReader().List(ctx, runs, client.InNamespace(j.Namespace), client.MatchingLabels{ + backupsv1alpha1.OwningJobNameLabel: j.Name, + backupsv1alpha1.OwningJobNamespaceLabel: j.Namespace, + }); err != nil { + // Without the operator's CRDs there is no run to delete, and a job + // failing for that reason must still be failed. + if apimeta.IsNoMatchError(err) { + return nil, nil + } + return nil, fmt.Errorf("list k8s.mariadb.com/Backups of BackupJob %s: %w", j.Name, err) + } + return runs.Items, nil +} + +// failMariaDBBackupJob fails a BackupJob that has started, after deleting +// each of its operator Backups that has not completed. No Backup is made of +// such a run, so nothing else would ever delete it, and while it stands +// short of Complete its window has no end: the dump cleanup would count it +// as a possible writer of every later dump of the application +// (neighbourMariaDBRuns). Deleting it also deletes its Job and so stops a +// run still going; a dump that run has already uploaded is left untracked. +// One that has completed, on any reason, has a bounded window and is kept. +func (r *BackupJobReconciler) failMariaDBBackupJob(ctx context.Context, j *backupsv1alpha1.BackupJob, message string) (ctrl.Result, error) { + runs, err := r.mariadbRunsOf(ctx, j) + if err != nil { + return ctrl.Result{}, err + } + var deleted []string + for i := range runs { + run := &runs[i] + if apimeta.IsStatusConditionTrue(run.Status.Conditions, mariadbtypes.ConditionTypeComplete) { + continue + } + // Read before the delete, which takes the run's Job and pods with it. + stuck := r.mariadbRunStuckReason(ctx, run) + // The preconditions keep a run that completes after the listing from + // being deleted: the delete then conflicts and the next pass sees it. + policy := metav1.DeletePropagationBackground + err := r.Delete(ctx, run, &client.DeleteOptions{ + PropagationPolicy: &policy, + Preconditions: &metav1.Preconditions{UID: &run.UID, ResourceVersion: &run.ResourceVersion}, + }) + if apierrors.IsConflict(err) { + return ctrl.Result{RequeueAfter: mariadbPollInterval}, nil + } + if err != nil && !apierrors.IsNotFound(err) { + err = fmt.Errorf("delete k8s.mariadb.com/Backup %s/%s: %w", run.Namespace, run.Name, err) + apimeta.SetStatusCondition(&j.Status.Conditions, metav1.Condition{ + Type: "Ready", + Status: metav1.ConditionFalse, + Reason: "OperatorBackupDeleteFailed", + Message: fmt.Sprintf("%s; retrying: %v", message, err), + }) + if updateErr := r.Status().Update(ctx, j); updateErr != nil { + getLogger(ctx).Info("cannot record the failed operator Backup delete", "backupjob", j.Name, "error", updateErr) + } + return ctrl.Result{}, err + } + getLogger(ctx).Info("deleted the unfinished operator Backup of a failed BackupJob", "operatorBackup", run.Name, "namespace", run.Namespace) + deleted = append(deleted, run.Namespace+"/"+run.Name) + if stuck != "" { + message += "; " + stuck + } + } + if len(deleted) > 0 { + message += fmt.Sprintf("; k8s.mariadb.com/Backup %s is deleted", strings.Join(deleted, ", ")) + } + return r.markBackupJobFailed(ctx, j, message) +} + +// mariadbRunStuckReason names what held up a run's pod, or "" when it +// cannot tell. The operator names the Job after the run, and the Job +// controller labels its pods with job-name. +func (r *BackupJobReconciler) mariadbRunStuckReason(ctx context.Context, run *mariadbtypes.Backup) string { + pods := &corev1.PodList{} + if err := r.List(ctx, pods, client.InNamespace(run.Namespace), client.MatchingLabels{"job-name": run.Name}); err != nil { + getLogger(ctx).Info("cannot read the pods of an operator Backup", "operatorBackup", run.Name, "error", err) + return "" + } + for i := range pods.Items { + pod := &pods.Items[i] + for _, c := range pod.Status.Conditions { + if c.Type == corev1.PodScheduled && c.Status == corev1.ConditionFalse { + return fmt.Sprintf("pod %s not scheduled: %s: %s", pod.Name, c.Reason, c.Message) + } + } + for _, cs := range append(append([]corev1.ContainerStatus(nil), pod.Status.InitContainerStatuses...), pod.Status.ContainerStatuses...) { + if w := cs.State.Waiting; w != nil && w.Reason != "" && w.Reason != "PodInitializing" { + return fmt.Sprintf("pod %s container %s waiting: %s: %s", pod.Name, cs.Name, w.Reason, w.Message) + } + if t := cs.State.Terminated; t != nil && t.ExitCode != 0 { + return fmt.Sprintf("pod %s container %s terminated: %s: %s", pod.Name, cs.Name, t.Reason, t.Message) + } + } + } + return "" +} + // mariadbJobFailedMessage names the operator object whose Job failed and // carries that Job's own Failed condition, because the operator's condition // message is only "Failed". The operator names the Job after the object. @@ -364,16 +516,15 @@ func (r *BackupJobReconciler) ensureMariaDBBackup(ctx context.Context, j *backup // the BackupJob's OwningJob{Name,Namespace}, if any. Returns (nil, nil) // when no match is found. // -// In steady state at most one Backup CR carries a given OwningJob label -// pair (ensureMariaDBBackup is idempotent by this label). The list path -// can in theory observe two if two controller replicas raced Create -// between the first list returning empty and the cache catching up. The -// driver picks list.Items[0] deterministically; the V(1) breadcrumb on -// duplicates exists so an operator triaging "wrong Backup got reused" -// has a log line to grep for instead of staring at silent reuse. +// The listing reads past the cache: a pass whose status write failed right +// after it created the run would otherwise miss that run and create a +// second. Two controller replicas racing Create can still make two; the +// driver picks list.Items[0] deterministically, and the V(1) breadcrumb on +// duplicates exists so an operator triaging "wrong Backup got reused" has a +// log line to grep for instead of staring at silent reuse. func (r *BackupJobReconciler) findMariaDBBackupForJob(ctx context.Context, j *backupsv1alpha1.BackupJob) (*mariadbtypes.Backup, error) { list := &mariadbtypes.BackupList{} - if err := r.List(ctx, list, + if err := r.apiReader().List(ctx, list, client.InNamespace(j.Namespace), client.MatchingLabels{ backupsv1alpha1.OwningJobNameLabel: j.Name, @@ -396,6 +547,49 @@ func (r *BackupJobReconciler) findMariaDBBackupForJob(ctx context.Context, j *ba return &list.Items[0], nil } +// mariadbRunTemplate returns rendered with the storage run was created +// with: the strategy is rendered again on every pass, and one edited during +// the run would otherwise record storage the dump never went to. +func mariadbRunTemplate(rendered *strategyv1alpha1.MariaDBTemplate, run *mariadbtypes.Backup) *strategyv1alpha1.MariaDBTemplate { + storage := run.Spec.Storage + if storage.S3 == nil && storage.PersistentVolumeClaim == nil && storage.Volume == nil { + return rendered + } + out := rendered.DeepCopy() + out.Storage = strategyv1alpha1.MariaDBStorageTemplate{ + PersistentVolumeClaim: storage.PersistentVolumeClaim.DeepCopy(), + Volume: storage.Volume.DeepCopy(), + } + s3 := storage.S3 + if s3 == nil { + return out + } + out.Storage.S3 = &strategyv1alpha1.MariaDBS3Template{ + Bucket: s3.Bucket, + Endpoint: s3.Endpoint, + Prefix: s3.Prefix, + Region: s3.Region, + AccessKeyIDSecretKeyRef: strategyv1alpha1.MariaDBSecretKeySelector{ + Name: s3.AccessKeyIdSecretKeyRef.Name, + Key: s3.AccessKeyIdSecretKeyRef.Key, + }, + SecretAccessKeySecretKeyRef: strategyv1alpha1.MariaDBSecretKeySelector{ + Name: s3.SecretAccessKeySecretKeyRef.Name, + Key: s3.SecretAccessKeySecretKeyRef.Key, + }, + } + if ref := s3.SessionTokenSecretKeyRef; ref != nil { + out.Storage.S3.SessionTokenSecretKeyRef = &strategyv1alpha1.MariaDBSecretKeySelector{Name: ref.Name, Key: ref.Key} + } + if tls := s3.TLS; tls != nil { + out.Storage.S3.TLS = &strategyv1alpha1.MariaDBS3TLS{Enabled: tls.Enabled} + if ref := tls.CASecretKeyRef; ref != nil { + out.Storage.S3.TLS.CASecretKeyRef = &strategyv1alpha1.MariaDBSecretKeySelector{Name: ref.Name, Key: ref.Key} + } + } + return out +} + // createMariaDBBackupArtifact materialises a Cozystack Backup resource // carrying the metadata callers need to drive a future restore. The // rendered storage descriptor plus the BackupClass parameters are persisted @@ -862,10 +1056,9 @@ func (r *RestoreJobReconciler) resolveMariaDBRestoreTarget(restoreJob *backupsv1 // Backup.status.underlyingResources at backup time. Carries the rendered // storage descriptor and BackupClass parameters. The current restore path // resolves the operator-side k8s.mariadb.com/Backup CR directly and fails -// terminally when it has been reaped; this snapshot is reserved for a -// future fallback path that would re-materialise the operator Backup from -// the persisted state. Keep the shape stable so an older snapshot stays -// machine-readable when that fallback lands. +// terminally when it has been reaped; the dump cleanup reads the storage +// from here once that CR is gone (cleanupOrphanedMariaDBDump). Keep the +// shape stable so an older snapshot stays machine-readable. // // SECRET-HANDLING CONTRACT (this is plaintext-readable to anyone with read // access to backups.cozystack.io/Backups): diff --git a/internal/backupcontroller/mariadbstrategy_controller_test.go b/internal/backupcontroller/mariadbstrategy_controller_test.go index 9696d1eac..7ba9b2c5e 100644 --- a/internal/backupcontroller/mariadbstrategy_controller_test.go +++ b/internal/backupcontroller/mariadbstrategy_controller_test.go @@ -18,6 +18,7 @@ import ( "k8s.io/apimachinery/pkg/runtime" "k8s.io/client-go/kubernetes/scheme" "k8s.io/client-go/tools/record" + ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" clientfake "sigs.k8s.io/controller-runtime/pkg/client/fake" "sigs.k8s.io/controller-runtime/pkg/client/interceptor" @@ -888,11 +889,13 @@ var mariadbCompleteOutcomeCases = []struct { wantFailed bool wantDone bool wantMessage []string + // The operator Backup of a run given up on before it completed goes. + wantOpDeleted bool }{ {name: "Complete=True/JobComplete succeeds", status: metav1.ConditionTrue, reason: mariadbtypes.ConditionReasonJobComplete, message: "Success", wantDone: true}, {name: "Complete=True/JobFailed fails with the Job's failure", status: metav1.ConditionTrue, reason: mariadbtypes.ConditionReasonJobFailed, message: "Failed", failedJob: true, wantFailed: true, wantMessage: []string{"tenant/op", "BackoffLimitExceeded", "Job has reached the specified backoff limit"}}, - {name: "Complete=False/JobFailed fails with the Job's failure", status: metav1.ConditionFalse, reason: mariadbtypes.ConditionReasonJobFailed, message: "Failed", failedJob: true, wantFailed: true, + {name: "Complete=False/JobFailed fails with the Job's failure", status: metav1.ConditionFalse, reason: mariadbtypes.ConditionReasonJobFailed, message: "Failed", failedJob: true, wantFailed: true, wantOpDeleted: true, wantMessage: []string{"tenant/op", "BackoffLimitExceeded", "Job has reached the specified backoff limit"}}, {name: "Complete=True/JobFailed with its Job gone fails", status: metav1.ConditionTrue, reason: mariadbtypes.ConditionReasonJobFailed, message: "Failed", wantFailed: true, wantMessage: []string{"tenant/op", "Job tenant/op not found"}}, @@ -901,12 +904,14 @@ var mariadbCompleteOutcomeCases = []struct { {name: "Complete=False/JobRunning keeps waiting", status: metav1.ConditionFalse, reason: mariadbtypes.ConditionReasonJobRunning, message: "Running"}, {name: "Complete=False/Failed keeps waiting", status: metav1.ConditionFalse, reason: "Failed", message: "Error creating Job"}, {name: "no Complete condition keeps waiting", noCondition: true}, - {name: "no Complete condition past the deadline fails", noCondition: true, expired: true, wantFailed: true, + {name: "no Complete condition past the deadline fails", noCondition: true, expired: true, wantFailed: true, wantOpDeleted: true, wantMessage: []string{"no Complete condition observed"}}, {name: "Complete=True with an unknown reason past the deadline fails", status: metav1.ConditionTrue, reason: "SomethingElse", message: "Something", expired: true, wantFailed: true, wantMessage: []string{"Complete=True/SomethingElse"}}, - {name: "Complete=False/Failed past the deadline carries the operator's message", status: metav1.ConditionFalse, reason: "Failed", message: "Error creating Job", expired: true, wantFailed: true, + {name: "Complete=False/Failed past the deadline carries the operator's message", status: metav1.ConditionFalse, reason: "Failed", message: "Error creating Job", expired: true, wantFailed: true, wantOpDeleted: true, wantMessage: []string{"Complete=False/Failed: Error creating Job"}}, + {name: "Complete=False/JobRunning past the deadline fails", status: metav1.ConditionFalse, reason: mariadbtypes.ConditionReasonJobRunning, message: "Running", expired: true, wantFailed: true, wantOpDeleted: true, + wantMessage: []string{"Complete=False/JobRunning"}}, } func mariadbCompleteConditions(noCondition bool, status metav1.ConditionStatus, reason, message string) []metav1.Condition { @@ -1016,6 +1021,16 @@ func TestReconcileMariaDBBackup_CompleteConditionOutcome(t *testing.T) { if err := c.List(context.Background(), artifacts, client.InNamespace("tenant")); err != nil { t.Fatalf("list Backups: %v", err) } + err = c.Get(context.Background(), client.ObjectKeyFromObject(operatorBackup), &mariadbtypes.Backup{}) + if err != nil && !apierrors.IsNotFound(err) { + t.Fatalf("get operator Backup: %v", err) + } + if deleted := apierrors.IsNotFound(err); deleted != tc.wantOpDeleted { + t.Errorf("operator Backup deleted = %v, want %v", deleted, tc.wantOpDeleted) + } + if tc.wantOpDeleted { + assertMariaDBFailureMessage(t, stored.Status.Message, []string{"k8s.mariadb.com/Backup tenant/op is deleted"}) + } switch { case tc.wantFailed: if stored.Status.Phase != backupsv1alpha1.BackupJobPhaseFailed { @@ -1243,3 +1258,632 @@ func newRenderedMariaDBTemplate() *strategyv1alpha1.MariaDBTemplate { Compression: "gzip", } } + +// pastDeadlineFixture is a Running BackupJob past its deadline whose +// operator Backup "op" carries the given Complete conditions. +func pastDeadlineFixture(conditions []metav1.Condition) (*backupsv1alpha1.BackupJob, *mariadbtypes.Backup, []client.Object, *ResolvedBackupConfig) { + group := strategyv1alpha1.GroupVersion.Group + resolved := &ResolvedBackupConfig{StrategyRef: corev1.TypedLocalObjectReference{ + APIGroup: &group, Kind: strategyv1alpha1.MariaDBStrategyKind, Name: "mdb-strategy", + }} + seed := newMariaDBBackupJob("bj", "tenant") + seed.Status.StartedAt = mariadbOutcomeStartedAt(true) + seed.Status.Phase = backupsv1alpha1.BackupJobPhaseRunning + op := &mariadbtypes.Backup{ + ObjectMeta: metav1.ObjectMeta{Namespace: "tenant", Name: "op", Labels: map[string]string{ + backupsv1alpha1.OwningJobNameLabel: seed.Name, + backupsv1alpha1.OwningJobNamespaceLabel: seed.Namespace, + }}, + Status: mariadbtypes.BackupStatus{Conditions: conditions}, + } + objs := []client.Object{ + seed, + newMariaDBApp(seed.Spec.ApplicationRef.Name, "tenant"), + &strategyv1alpha1.MariaDB{ObjectMeta: metav1.ObjectMeta{Name: "mdb-strategy"}, Spec: strategyv1alpha1.MariaDBSpec{Template: *newRenderedMariaDBTemplate()}}, + &mariadbtypes.MariaDB{ObjectMeta: metav1.ObjectMeta{Namespace: "tenant", Name: mariadbNameForApp(seed.Spec.ApplicationRef.Name)}}, + } + return seed, op, objs, resolved +} + +func reconcileStoredMariaDBJob(t *testing.T, r *BackupJobReconciler, seed *backupsv1alpha1.BackupJob, resolved *ResolvedBackupConfig) (ctrl.Result, error) { + t.Helper() + bj := &backupsv1alpha1.BackupJob{} + if err := r.Get(context.Background(), client.ObjectKeyFromObject(seed), bj); err != nil { + t.Fatalf("get BackupJob: %v", err) + } + return r.reconcileMariaDB(context.Background(), bj, resolved) +} + +// A pass that deleted the run and then failed to persist Failed must not +// start another run on its retry. +func TestReconcileMariaDBBackup_RetryAfterTheDeadlineStartsNoNewRun(t *testing.T) { + seed, op, objs, resolved := pastDeadlineFixture(nil) + base := newMariaDBStrategyTestClient(t, append(objs, op)...) + statusFailed, creates := false, 0 + c := interceptor.NewClient(base.(client.WithWatch), interceptor.Funcs{ + Create: func(ctx context.Context, cl client.WithWatch, obj client.Object, opts ...client.CreateOption) error { + if _, ok := obj.(*mariadbtypes.Backup); ok { + creates++ + } + return cl.Create(ctx, obj, opts...) + }, + SubResourceUpdate: func(ctx context.Context, cl client.Client, sub string, obj client.Object, opts ...client.SubResourceUpdateOption) error { + if !statusFailed { + statusFailed = true + return apierrors.NewConflict(backupsv1alpha1.GroupVersion.WithResource("backupjobs").GroupResource(), seed.Name, errors.New("stale")) + } + return cl.SubResource(sub).Update(ctx, obj, opts...) + }, + }) + r := &BackupJobReconciler{Client: c, Scheme: base.Scheme(), Recorder: record.NewFakeRecorder(10)} + + if _, err := reconcileStoredMariaDBJob(t, r, seed, resolved); err == nil { + t.Fatal("first pass: want the injected status conflict") + } + if _, err := reconcileStoredMariaDBJob(t, r, seed, resolved); err != nil { + t.Fatalf("second pass: %v", err) + } + if creates != 0 { + t.Errorf("created %d operator Backups, want none past the deadline", creates) + } + stored := &backupsv1alpha1.BackupJob{} + if err := c.Get(context.Background(), client.ObjectKeyFromObject(seed), stored); err != nil { + t.Fatal(err) + } + if stored.Status.Phase != backupsv1alpha1.BackupJobPhaseFailed { + t.Errorf("phase = %q, want Failed", stored.Status.Phase) + } +} + +// The cache can trail a Complete the operator has just written; a run that +// completed is handed to the success path, not deleted. +func TestReconcileMariaDBBackup_DeadlineReadsTheRunPastTheCache(t *testing.T) { + seed, op, objs, resolved := pastDeadlineFixture(nil) + cached := newMariaDBStrategyTestClient(t, append(objs, op)...) + done := op.DeepCopy() + done.Status.Conditions = []metav1.Condition{mariadbBackupSucceeded(metav1.Now())} + live := newMariaDBStrategyTestClient(t, append(objs, done)...) + r := &BackupJobReconciler{Client: cached, APIReader: live, Scheme: cached.Scheme(), Recorder: record.NewFakeRecorder(10)} + + if _, err := reconcileStoredMariaDBJob(t, r, seed, resolved); err != nil { + t.Fatalf("reconcile: %v", err) + } + if err := cached.Get(context.Background(), client.ObjectKeyFromObject(op), &mariadbtypes.Backup{}); err != nil { + t.Errorf("operator Backup: %v, want it kept", err) + } + stored := &backupsv1alpha1.BackupJob{} + if err := cached.Get(context.Background(), client.ObjectKeyFromObject(seed), stored); err != nil { + t.Fatal(err) + } + if stored.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed { + t.Errorf("phase = Failed (%q), want the completed run taken", stored.Status.Message) + } +} + +func TestReconcileMariaDBBackup_RefusedDeadlineDeleteIsSurfaced(t *testing.T) { + seed, op, objs, resolved := pastDeadlineFixture(nil) + base := newMariaDBStrategyTestClient(t, append(objs, op)...) + c := interceptor.NewClient(base.(client.WithWatch), interceptor.Funcs{ + Delete: func(ctx context.Context, cl client.WithWatch, obj client.Object, opts ...client.DeleteOption) error { + if _, ok := obj.(*mariadbtypes.Backup); ok { + return apierrors.NewForbidden(mariadbtypes.GroupVersion.WithResource("backups").GroupResource(), obj.GetName(), errors.New("denied by policy")) + } + return cl.Delete(ctx, obj, opts...) + }, + }) + r := &BackupJobReconciler{Client: c, Scheme: base.Scheme(), Recorder: record.NewFakeRecorder(10)} + + if _, err := reconcileStoredMariaDBJob(t, r, seed, resolved); err == nil { + t.Fatal("want the refused delete returned for a retry") + } + stored := &backupsv1alpha1.BackupJob{} + if err := c.Get(context.Background(), client.ObjectKeyFromObject(seed), stored); err != nil { + t.Fatal(err) + } + if stored.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed { + t.Error("phase = Failed, want the BackupJob kept until its run is deleted") + } + ready := apimeta.FindStatusCondition(stored.Status.Conditions, "Ready") + if ready == nil || ready.Reason != "OperatorBackupDeleteFailed" || !strings.Contains(ready.Message, "denied by policy") { + t.Errorf("Ready = %+v, want False/OperatorBackupDeleteFailed naming the cause", ready) + } +} + +// A run created just before the deadline can be missing from the cache; +// the BackupJob must not be failed as if it had none. +func TestReconcileMariaDBBackup_DeadlineFindsARunTheCacheMissed(t *testing.T) { + seed, op, objs, resolved := pastDeadlineFixture([]metav1.Condition{{ + Type: mariadbtypes.ConditionTypeComplete, Status: metav1.ConditionFalse, + Reason: mariadbtypes.ConditionReasonJobRunning, LastTransitionTime: metav1.Now(), + }}) + base := newMariaDBStrategyTestClient(t, objs...) + creates := 0 + cached := interceptor.NewClient(base.(client.WithWatch), interceptor.Funcs{ + Create: func(ctx context.Context, cl client.WithWatch, obj client.Object, opts ...client.CreateOption) error { + if _, ok := obj.(*mariadbtypes.Backup); ok { + creates++ + } + return cl.Create(ctx, obj, opts...) + }, + }) + live := newMariaDBStrategyTestClient(t, append(objs, op)...) + r := &BackupJobReconciler{Client: cached, APIReader: live, Scheme: base.Scheme(), Recorder: record.NewFakeRecorder(10)} + + if _, err := reconcileStoredMariaDBJob(t, r, seed, resolved); err != nil { + t.Fatalf("reconcile: %v", err) + } + if creates != 0 { + t.Errorf("created %d operator Backups past the deadline, want none", creates) + } + stored := &backupsv1alpha1.BackupJob{} + if err := cached.Get(context.Background(), client.ObjectKeyFromObject(seed), stored); err != nil { + t.Fatal(err) + } + if strings.Contains(stored.Status.Message, "is left") { + t.Errorf("message = %q, want the BackupJob not failed for want of a run", stored.Status.Message) + } +} + +// A run that completes between the read and the delete makes the delete +// conflict on its preconditions; the next pass hands it to the success path. +func TestReconcileMariaDBBackup_DeadlineDeleteIsConditionalOnTheRunRead(t *testing.T) { + seed, op, objs, resolved := pastDeadlineFixture(nil) + base := newMariaDBStrategyTestClient(t, append(objs, op)...) + var preconditions *metav1.Preconditions + c := interceptor.NewClient(base.(client.WithWatch), interceptor.Funcs{ + Delete: func(ctx context.Context, cl client.WithWatch, obj client.Object, opts ...client.DeleteOption) error { + if _, ok := obj.(*mariadbtypes.Backup); ok { + do := &client.DeleteOptions{} + do.ApplyOptions(opts) + preconditions = do.Preconditions + return apierrors.NewConflict(mariadbtypes.GroupVersion.WithResource("backups").GroupResource(), obj.GetName(), errors.New("precondition failed")) + } + return cl.Delete(ctx, obj, opts...) + }, + }) + r := &BackupJobReconciler{Client: c, Scheme: base.Scheme(), Recorder: record.NewFakeRecorder(10)} + + res, err := reconcileStoredMariaDBJob(t, r, seed, resolved) + if err != nil || res.RequeueAfter == 0 { + t.Fatalf("got res=%+v err=%v, want a requeue", res, err) + } + if preconditions == nil || preconditions.UID == nil || preconditions.ResourceVersion == nil { + t.Errorf("preconditions = %+v, want the UID and resourceVersion that were read", preconditions) + } + stored := &backupsv1alpha1.BackupJob{} + if err := c.Get(context.Background(), client.ObjectKeyFromObject(seed), stored); err != nil { + t.Fatal(err) + } + if stored.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed { + t.Error("phase = Failed, want the run re-read on the next pass") + } +} + +// Every way a started BackupJob fails deletes a run that has not completed, +// not only the deadline: mariadb-operator leaves the run of a MariaDB that +// went away at Complete=False for good. +func TestReconcileMariaDBBackup_FailingAStartedJobDeletesItsUnfinishedRun(t *testing.T) { + running := []metav1.Condition{{ + Type: mariadbtypes.ConditionTypeComplete, Status: metav1.ConditionFalse, + Reason: "Failed", Message: "MariaDB not found", LastTransitionTime: metav1.Now(), + }} + cases := []struct { + name string + conditions []metav1.Condition + dropApp bool + dropMariaDB bool + dropStrategy bool + expired bool + wantMessage string + wantDeleted bool + }{ + {name: "application deleted mid-run", conditions: running, dropApp: true, wantMessage: "MariaDB application not found", wantDeleted: true}, + {name: "application deleted after the run completed", conditions: []metav1.Condition{mariadbBackupSucceeded(metav1.Now())}, dropApp: true, + wantMessage: "MariaDB application not found"}, + {name: "MariaDB gone past the deadline", conditions: running, dropMariaDB: true, expired: true, wantMessage: "never reached existence", wantDeleted: true}, + {name: "strategy gone past the deadline", conditions: running, dropStrategy: true, expired: true, wantMessage: "was not provisioned", wantDeleted: true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + seed, op, objs, resolved := pastDeadlineFixture(tc.conditions) + seed.Status.StartedAt = mariadbOutcomeStartedAt(tc.expired) + var kept []client.Object + for _, obj := range objs { + switch obj.(type) { + case *mariadbapp.MariaDB: + if tc.dropApp { + continue + } + case *mariadbtypes.MariaDB: + if tc.dropMariaDB { + continue + } + case *strategyv1alpha1.MariaDB: + if tc.dropStrategy { + continue + } + } + kept = append(kept, obj) + } + c := newMariaDBStrategyTestClient(t, append(kept, op)...) + r := &BackupJobReconciler{Client: c, Scheme: c.Scheme(), Recorder: record.NewFakeRecorder(10)} + + if _, err := reconcileStoredMariaDBJob(t, r, seed, resolved); err != nil { + t.Fatalf("reconcile: %v", err) + } + stored := &backupsv1alpha1.BackupJob{} + if err := c.Get(context.Background(), client.ObjectKeyFromObject(seed), stored); err != nil { + t.Fatal(err) + } + if stored.Status.Phase != backupsv1alpha1.BackupJobPhaseFailed || !strings.Contains(stored.Status.Message, tc.wantMessage) { + t.Errorf("phase=%q message=%q, want Failed with %q", stored.Status.Phase, stored.Status.Message, tc.wantMessage) + } + err := c.Get(context.Background(), client.ObjectKeyFromObject(op), &mariadbtypes.Backup{}) + if err != nil && !apierrors.IsNotFound(err) { + t.Fatal(err) + } + if deleted := apierrors.IsNotFound(err); deleted != tc.wantDeleted { + t.Errorf("operator Backup deleted = %v, want %v", deleted, tc.wantDeleted) + } + }) + } +} + +// The deadline can pass between listing the run and giving up on it, by +// when the operator may have finished it; the cache can trail that. +func TestGiveUpOnMariaDBBackup_HandsAFinishedRunBack(t *testing.T) { + for _, reason := range []string{mariadbtypes.ConditionReasonJobComplete, mariadbtypes.ConditionReasonJobFailed} { + t.Run(reason, func(t *testing.T) { + seed, op, objs, _ := pastDeadlineFixture(nil) + cached := newMariaDBStrategyTestClient(t, append(objs, op)...) + finished := op.DeepCopy() + finished.Status.Conditions = []metav1.Condition{{ + Type: mariadbtypes.ConditionTypeComplete, Status: metav1.ConditionTrue, Reason: reason, LastTransitionTime: metav1.Now(), + }} + live := newMariaDBStrategyTestClient(t, append(objs, finished)...) + r := &BackupJobReconciler{Client: cached, APIReader: live, Scheme: cached.Scheme(), Recorder: record.NewFakeRecorder(10)} + + bj := &backupsv1alpha1.BackupJob{} + if err := cached.Get(context.Background(), client.ObjectKeyFromObject(seed), bj); err != nil { + t.Fatal(err) + } + res, err := r.giveUpOnMariaDBBackup(context.Background(), bj, op) + if err != nil || res.RequeueAfter == 0 { + t.Fatalf("got res=%+v err=%v, want a requeue", res, err) + } + if err := live.Get(context.Background(), client.ObjectKeyFromObject(op), &mariadbtypes.Backup{}); err != nil { + t.Errorf("operator Backup: %v, want it kept", err) + } + stored := &backupsv1alpha1.BackupJob{} + if err := cached.Get(context.Background(), client.ObjectKeyFromObject(seed), stored); err != nil { + t.Fatal(err) + } + if stored.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed { + t.Error("phase = Failed, want the finished run handed back") + } + }) + } +} + +// Deleting a stuck run takes its pod with it, so what held the pod up is +// kept on the BackupJob. +func TestReconcileMariaDBBackup_DeadlineKeepsWhyTheRunWasStuck(t *testing.T) { + cases := map[string]struct { + status corev1.PodStatus + want string + }{ + "unschedulable": { + status: corev1.PodStatus{Conditions: []corev1.PodCondition{{ + Type: corev1.PodScheduled, Status: corev1.ConditionFalse, Reason: "Unschedulable", Message: "0/3 nodes are available", + }}}, + want: "pod op-abc not scheduled: Unschedulable: 0/3 nodes are available", + }, + "image not pulled": { + status: corev1.PodStatus{ContainerStatuses: []corev1.ContainerStatus{{ + Name: "mariadb", State: corev1.ContainerState{Waiting: &corev1.ContainerStateWaiting{Reason: "ImagePullBackOff", Message: "back-off pulling image"}}, + }}}, + want: "pod op-abc container mariadb waiting: ImagePullBackOff", + }, + } + for name, tc := range cases { + t.Run(name, func(t *testing.T) { + seed, op, objs, resolved := pastDeadlineFixture(nil) + pod := &corev1.Pod{ + ObjectMeta: metav1.ObjectMeta{Namespace: "tenant", Name: "op-abc", Labels: map[string]string{"job-name": op.Name}}, + Status: tc.status, + } + c := newMariaDBStrategyTestClient(t, append(objs, op, pod)...) + r := &BackupJobReconciler{Client: c, Scheme: c.Scheme(), Recorder: record.NewFakeRecorder(10)} + + if _, err := reconcileStoredMariaDBJob(t, r, seed, resolved); err != nil { + t.Fatalf("reconcile: %v", err) + } + stored := &backupsv1alpha1.BackupJob{} + if err := c.Get(context.Background(), client.ObjectKeyFromObject(seed), stored); err != nil { + t.Fatal(err) + } + if stored.Status.Phase != backupsv1alpha1.BackupJobPhaseFailed || !strings.Contains(stored.Status.Message, tc.want) { + t.Errorf("phase=%q message=%q, want Failed naming %q", stored.Status.Phase, stored.Status.Message, tc.want) + } + }) + } +} + +// A Running job has created its run: a retry after the run was deleted and +// Failed was not persisted fails the job instead of starting another, even +// with the deadline not reached and a cache that no longer shows the run. +func TestReconcileMariaDBBackup_RunningJobNeverStartsASecondRun(t *testing.T) { + seed, op, objs, resolved := pastDeadlineFixture([]metav1.Condition{{ + Type: mariadbtypes.ConditionTypeComplete, Status: metav1.ConditionFalse, + Reason: mariadbtypes.ConditionReasonJobFailed, Message: "Failed", LastTransitionTime: metav1.Now(), + }}) + seed.Status.StartedAt = mariadbOutcomeStartedAt(false) + live := newMariaDBStrategyTestClient(t, append(objs, op)...) + statusFailed, creates := false, 0 + cached := interceptor.NewClient(live.(client.WithWatch), interceptor.Funcs{ + List: func(ctx context.Context, cl client.WithWatch, list client.ObjectList, opts ...client.ListOption) error { + if _, ok := list.(*mariadbtypes.BackupList); ok { + return nil + } + return cl.List(ctx, list, opts...) + }, + Create: func(ctx context.Context, cl client.WithWatch, obj client.Object, opts ...client.CreateOption) error { + if _, ok := obj.(*mariadbtypes.Backup); ok { + creates++ + } + return cl.Create(ctx, obj, opts...) + }, + SubResourceUpdate: func(ctx context.Context, cl client.Client, sub string, obj client.Object, opts ...client.SubResourceUpdateOption) error { + if !statusFailed { + statusFailed = true + return apierrors.NewConflict(backupsv1alpha1.GroupVersion.WithResource("backupjobs").GroupResource(), seed.Name, errors.New("stale")) + } + return cl.SubResource(sub).Update(ctx, obj, opts...) + }, + }) + r := &BackupJobReconciler{Client: cached, APIReader: live, Scheme: live.Scheme(), Recorder: record.NewFakeRecorder(10)} + + if _, err := reconcileStoredMariaDBJob(t, r, seed, resolved); err == nil { + t.Fatal("first pass: want the injected status conflict") + } + if _, err := reconcileStoredMariaDBJob(t, r, seed, resolved); err != nil { + t.Fatalf("second pass: %v", err) + } + if creates != 0 { + t.Errorf("created %d operator Backups, want none", creates) + } + stored := &backupsv1alpha1.BackupJob{} + if err := live.Get(context.Background(), client.ObjectKeyFromObject(seed), stored); err != nil { + t.Fatal(err) + } + if stored.Status.Phase != backupsv1alpha1.BackupJobPhaseFailed { + t.Errorf("phase = %q, want Failed", stored.Status.Phase) + } +} + +// The Backup made of a completed run names the storage the run wrote to, +// not the strategy as rendered now. +func TestReconcileMariaDBBackup_BackupRecordsTheRunsStorage(t *testing.T) { + seed, op, objs, resolved := pastDeadlineFixture([]metav1.Condition{mariadbBackupSucceeded(metav1.Now())}) + seed.Status.StartedAt = mariadbOutcomeStartedAt(false) + atStart := newRenderedMariaDBTemplate() + atStart.Storage.S3.Bucket = "run-bucket" + atStart.Storage.S3.Prefix = "run/prefix" + storage, err := buildMariaDBBackupStorage(atStart.Storage) + if err != nil { + t.Fatal(err) + } + op.Spec.Storage = storage + c := newMariaDBStrategyTestClient(t, append(objs, op)...) + r := &BackupJobReconciler{Client: c, Scheme: c.Scheme(), Recorder: record.NewFakeRecorder(10)} + + if _, err := reconcileStoredMariaDBJob(t, r, seed, resolved); err != nil { + t.Fatalf("reconcile: %v", err) + } + backup := &backupsv1alpha1.Backup{} + if err := c.Get(context.Background(), client.ObjectKey{Namespace: seed.Namespace, Name: seed.Name}, backup); err != nil { + t.Fatalf("get Backup: %v", err) + } + if uri := backup.Spec.DriverMetadata[mariadbStorageURIKey]; !strings.HasPrefix(uri, "s3://run-bucket/run/prefix/") { + t.Errorf("storage URI = %q, want the run's bucket and prefix", uri) + } + recorded, err := mariadbSnapshotStorage(backup) + if err != nil { + t.Fatal(err) + } + if recorded.S3 == nil || recorded.S3.Bucket != "run-bucket" || recorded.S3.Prefix != "run/prefix" { + t.Errorf("snapshot storage = %+v, want the run's", recorded.S3) + } +} + +// A pass that created the run and then failed to persist Running retries +// with no phase; a cache that has not seen the run yet must not make it +// create a second. +func TestReconcileMariaDBBackup_RetryBeforeRunningStartsNoSecondRun(t *testing.T) { + seed, _, objs, resolved := pastDeadlineFixture(nil) + seed.Status.StartedAt = mariadbOutcomeStartedAt(false) + seed.Status.Phase = "" + live := newMariaDBStrategyTestClient(t, objs...) + statusFailed, creates := false, 0 + cached := interceptor.NewClient(live.(client.WithWatch), interceptor.Funcs{ + List: func(ctx context.Context, cl client.WithWatch, list client.ObjectList, opts ...client.ListOption) error { + if _, ok := list.(*mariadbtypes.BackupList); ok { + return nil + } + return cl.List(ctx, list, opts...) + }, + Create: func(ctx context.Context, cl client.WithWatch, obj client.Object, opts ...client.CreateOption) error { + if _, ok := obj.(*mariadbtypes.Backup); ok { + creates++ + } + return cl.Create(ctx, obj, opts...) + }, + SubResourceUpdate: func(ctx context.Context, cl client.Client, sub string, obj client.Object, opts ...client.SubResourceUpdateOption) error { + if !statusFailed { + statusFailed = true + return apierrors.NewConflict(backupsv1alpha1.GroupVersion.WithResource("backupjobs").GroupResource(), seed.Name, errors.New("stale")) + } + return cl.SubResource(sub).Update(ctx, obj, opts...) + }, + }) + r := &BackupJobReconciler{Client: cached, APIReader: live, Scheme: live.Scheme(), Recorder: record.NewFakeRecorder(10)} + + if _, err := reconcileStoredMariaDBJob(t, r, seed, resolved); err == nil { + t.Fatal("first pass: want the injected status conflict") + } + if _, err := reconcileStoredMariaDBJob(t, r, seed, resolved); err != nil { + t.Fatalf("second pass: %v", err) + } + if creates != 1 { + t.Errorf("created %d operator Backups, want 1", creates) + } +} + +// A failing BackupJob deletes only its own runs: the unfinished run of +// another BackupJob in the same namespace is left alone. +func TestReconcileMariaDBBackup_FailingJobKeepsAnotherJobsRun(t *testing.T) { + running := []metav1.Condition{{ + Type: mariadbtypes.ConditionTypeComplete, Status: metav1.ConditionFalse, + Reason: mariadbtypes.ConditionReasonJobRunning, LastTransitionTime: metav1.Now(), + }} + seed, op, objs, resolved := pastDeadlineFixture(running) + other := op.DeepCopy() + other.Name = "other-op" + other.Labels = map[string]string{ + backupsv1alpha1.OwningJobNameLabel: "other-bj", + backupsv1alpha1.OwningJobNamespaceLabel: seed.Namespace, + } + c := newMariaDBStrategyTestClient(t, append(objs, op, other)...) + r := &BackupJobReconciler{Client: c, Scheme: c.Scheme(), Recorder: record.NewFakeRecorder(10)} + + if _, err := reconcileStoredMariaDBJob(t, r, seed, resolved); err != nil { + t.Fatalf("reconcile: %v", err) + } + if err := c.Get(context.Background(), client.ObjectKeyFromObject(op), &mariadbtypes.Backup{}); !apierrors.IsNotFound(err) { + t.Errorf("own run: %v, want it deleted", err) + } + if err := c.Get(context.Background(), client.ObjectKeyFromObject(other), &mariadbtypes.Backup{}); err != nil { + t.Errorf("another BackupJob's run: %v, want it kept", err) + } +} + +// A Create that times out can still have stored the run. +func TestReconcileMariaDBBackup_FailedCreateDeletesARunItStored(t *testing.T) { + seed, _, objs, resolved := pastDeadlineFixture(nil) + seed.Status.StartedAt = mariadbOutcomeStartedAt(false) + seed.Status.Phase = "" + base := newMariaDBStrategyTestClient(t, objs...) + creates := 0 + c := interceptor.NewClient(base.(client.WithWatch), interceptor.Funcs{ + Create: func(ctx context.Context, cl client.WithWatch, obj client.Object, opts ...client.CreateOption) error { + if _, ok := obj.(*mariadbtypes.Backup); ok { + creates++ + if err := cl.Create(ctx, obj, opts...); err != nil { + return err + } + return apierrors.NewTimeoutError("request timed out", 1) + } + return cl.Create(ctx, obj, opts...) + }, + }) + r := &BackupJobReconciler{Client: c, Scheme: base.Scheme(), Recorder: record.NewFakeRecorder(10)} + + if _, err := reconcileStoredMariaDBJob(t, r, seed, resolved); err != nil { + t.Fatalf("reconcile: %v", err) + } + if creates != 1 { + t.Fatalf("operator Backup Create called %d times, want 1", creates) + } + runs := &mariadbtypes.BackupList{} + if err := c.List(context.Background(), runs); err != nil { + t.Fatal(err) + } + if len(runs.Items) != 0 { + t.Errorf("%d operator Backups left, want the stored run deleted", len(runs.Items)) + } + stored := &backupsv1alpha1.BackupJob{} + if err := c.Get(context.Background(), client.ObjectKeyFromObject(seed), stored); err != nil { + t.Fatal(err) + } + if stored.Status.Phase != backupsv1alpha1.BackupJobPhaseFailed { + t.Errorf("phase = %q, want Failed", stored.Status.Phase) + } +} + +// A strategy edited during a run renders storage the dump never went to; +// the Backup records the run's own, which the dump cleanup reads once the +// run is gone. +func TestMariaDBRunTemplate_RecordsTheRunsStorage(t *testing.T) { + atStart := newRenderedMariaDBTemplate() + atStart.Storage.S3.Prefix = "tenant/db" + atStart.Storage.S3.SessionTokenSecretKeyRef = &strategyv1alpha1.MariaDBSecretKeySelector{Name: "creds", Key: "token"} + atStart.Storage.S3.TLS = &strategyv1alpha1.MariaDBS3TLS{Enabled: true, CASecretKeyRef: &strategyv1alpha1.MariaDBSecretKeySelector{Name: "ca", Key: "ca.crt"}} + storage, err := buildMariaDBBackupStorage(atStart.Storage) + if err != nil { + t.Fatal(err) + } + run := &mariadbtypes.Backup{Spec: mariadbtypes.BackupSpec{Storage: storage}} + + now := newRenderedMariaDBTemplate() + now.Storage.S3.Bucket = "moved" + now.Storage.S3.Prefix = "elsewhere" + + got := mariadbRunTemplate(now, run) + if !apiequality.Semantic.DeepEqual(got.Storage, atStart.Storage) { + t.Errorf("storage = %+v, want the run's %+v", got.Storage.S3, atStart.Storage.S3) + } + if now.Storage.S3.Bucket != "moved" { + t.Error("the rendered template was modified in place") + } + if uri := mariadbBackupURI(got, &mariadbtypes.Backup{ObjectMeta: metav1.ObjectMeta{Name: "op"}}); !strings.HasPrefix(uri, "s3://"+atStart.Storage.S3.Bucket+"/tenant/db/") { + t.Errorf("storage URI = %q, want it under the run's bucket and prefix", uri) + } + + t.Run("strategy moved off S3", func(t *testing.T) { + onVolume := newRenderedMariaDBTemplate() + onVolume.Storage = strategyv1alpha1.MariaDBStorageTemplate{PersistentVolumeClaim: &corev1.PersistentVolumeClaimSpec{}} + if got := mariadbRunTemplate(onVolume, run); got.Storage.S3 == nil || got.Storage.PersistentVolumeClaim != nil { + t.Errorf("storage = %+v, want the run's S3 only", got.Storage) + } + }) + t.Run("strategy moved onto S3", func(t *testing.T) { + pvcRun := &mariadbtypes.Backup{Spec: mariadbtypes.BackupSpec{Storage: mariadbtypes.BackupStorage{PersistentVolumeClaim: &corev1.PersistentVolumeClaimSpec{}}}} + if got := mariadbRunTemplate(now, pvcRun); got.Storage.S3 != nil || got.Storage.PersistentVolumeClaim == nil { + t.Errorf("storage = %+v, want the run's volume claim only", got.Storage) + } + }) +} + +// Without mariadb-operator's CRDs no run can exist, and a BackupJob failing +// for another reason must still reach Failed. +func TestReconcileMariaDBBackup_FailsWithoutTheOperatorCRDs(t *testing.T) { + seed, _, objs, resolved := pastDeadlineFixture(nil) + seed.Status.StartedAt = mariadbOutcomeStartedAt(false) + var kept []client.Object + for _, obj := range objs { + if _, ok := obj.(*mariadbapp.MariaDB); !ok { + kept = append(kept, obj) + } + } + base := newMariaDBStrategyTestClient(t, kept...) + c := interceptor.NewClient(base.(client.WithWatch), interceptor.Funcs{ + List: func(ctx context.Context, cl client.WithWatch, list client.ObjectList, opts ...client.ListOption) error { + if _, ok := list.(*mariadbtypes.BackupList); ok { + return &apimeta.NoKindMatchError{GroupKind: mariadbtypes.GroupVersion.WithKind("Backup").GroupKind()} + } + return cl.List(ctx, list, opts...) + }, + }) + r := &BackupJobReconciler{Client: c, Scheme: base.Scheme(), Recorder: record.NewFakeRecorder(10)} + + if _, err := reconcileStoredMariaDBJob(t, r, seed, resolved); err != nil { + t.Fatalf("reconcile: %v", err) + } + stored := &backupsv1alpha1.BackupJob{} + if err := c.Get(context.Background(), client.ObjectKeyFromObject(seed), stored); err != nil { + t.Fatal(err) + } + if stored.Status.Phase != backupsv1alpha1.BackupJobPhaseFailed { + t.Errorf("phase = %q, want Failed", stored.Status.Phase) + } +} diff --git a/packages/system/backupstrategy-controller/templates/rbac.yaml b/packages/system/backupstrategy-controller/templates/rbac.yaml index b7b872d9e..2b88735ab 100644 --- a/packages/system/backupstrategy-controller/templates/rbac.yaml +++ b/packages/system/backupstrategy-controller/templates/rbac.yaml @@ -166,7 +166,8 @@ rules: # rendered" preconditions, create one-shot k8s.mariadb.com/Backup CRs on # the BackupJob path, and create k8s.mariadb.com/Restore CRs on the # RestoreJob path. A Backup is deleted once the dump it wrote is, when its -# Cozystack Backup is deleted; a Restore is never deleted. +# Cozystack Backup is deleted, or when its BackupJob gives up on it before +# it completes; a Restore is never deleted. - apiGroups: ["k8s.mariadb.com"] resources: ["mariadbs"] verbs: ["get", "list", "watch"]