@@ -15,6 +15,7 @@ import (
1515 "k8s.io/apimachinery/pkg/runtime/schema"
1616 dynamicfake "k8s.io/client-go/dynamic/fake"
1717 "k8s.io/client-go/kubernetes/scheme"
18+ k8stesting "k8s.io/client-go/testing"
1819 "k8s.io/client-go/tools/record"
1920 "sigs.k8s.io/controller-runtime/pkg/client"
2021 clientfake "sigs.k8s.io/controller-runtime/pkg/client/fake"
@@ -532,6 +533,203 @@ func TestPrepareForRestore_KeepOriginalPVCFalse_WaitsForTerminatingPVC(t *testin
532533 }
533534}
534535
536+ func makeUnstructuredDataVolume (name , namespace string ) * unstructured.Unstructured {
537+ dv := & unstructured.Unstructured {}
538+ dv .SetAPIVersion ("cdi.kubevirt.io/v1beta1" )
539+ dv .SetKind ("DataVolume" )
540+ dv .SetName (name )
541+ dv .SetNamespace (namespace )
542+ return dv
543+ }
544+
545+ // A DataVolume still in place makes CDI recreate the claim under its original
546+ // name, so the PVC must survive until the DataVolume is confirmed gone.
547+ func TestPrepareForRestore_KeepOriginalPVCFalse_KeepsPVCWhileDataVolumeRemains (t * testing.T ) {
548+ tests := []struct {
549+ name string
550+ deleteErr error
551+ wantErr bool
552+ }{
553+ {
554+ name : "DataVolume deletion fails" ,
555+ deleteErr : errors .NewForbidden (dataVolumeGVR .GroupResource (), "vm-disk-ubuntu-source" , nil ),
556+ wantErr : true ,
557+ },
558+ {
559+ name : "DataVolume deletion is still pending" ,
560+ },
561+ }
562+ for _ , tt := range tests {
563+ t .Run (tt .name , func (t * testing.T ) {
564+ ns := "tenant-root"
565+ restoreJob , backup , ur , target , opts := inPlaceVMRestoreWithoutKeep (ns )
566+ pvc := & corev1.PersistentVolumeClaim {
567+ ObjectMeta : metav1.ObjectMeta {Name : "vm-disk-ubuntu-source" , Namespace : ns },
568+ }
569+ reconciler := newTestRestoreJobReconcilerWithDynamic (t ,
570+ []runtime.Object {makeUnstructuredDataVolume ("vm-disk-ubuntu-source" , ns )},
571+ pvc , restoreJob , backup )
572+ reconciler .Interface .(* dynamicfake.FakeDynamicClient ).PrependReactor ("delete" , "datavolumes" ,
573+ func (k8stesting.Action ) (bool , runtime.Object , error ) {
574+ return true , nil , tt .deleteErr
575+ })
576+
577+ ctx := context .Background ()
578+ ready , result , err := reconciler .prepareForRestore (ctx , restoreJob , backup , ur , target , opts )
579+ if tt .wantErr {
580+ if err == nil {
581+ t .Fatal ("expected an error when the DataVolume cannot be deleted" )
582+ }
583+ } else {
584+ if err != nil {
585+ t .Fatalf ("prepareForRestore() error = %v" , err )
586+ }
587+ if result .RequeueAfter == 0 {
588+ t .Error ("expected a requeue while the DataVolume is still present" )
589+ }
590+ }
591+ if ready {
592+ t .Fatal ("expected ready=false while the DataVolume is still present" )
593+ }
594+
595+ got := & corev1.PersistentVolumeClaim {}
596+ if err := reconciler .Get (ctx , client .ObjectKeyFromObject (pvc ), got ); err != nil {
597+ t .Fatalf ("original PVC should survive while its DataVolume remains: %v" , err )
598+ }
599+ if got .DeletionTimestamp != nil {
600+ t .Error ("original PVC should not be marked for deletion while its DataVolume remains" )
601+ }
602+ })
603+ }
604+ }
605+
606+ // keepOriginalPVC=true must never delete the original claim, even when the
607+ // rename that preserves it fails and leaves it under its original name.
608+ func TestPrepareForRestore_KeepOriginalPVCTrue_FailedRenameKeepsPVC (t * testing.T ) {
609+ ns := "tenant-root"
610+ restoreJob , backup , ur , target , _ := inPlaceVMRestoreWithoutKeep (ns )
611+ opts := RestoreOptions {KeepOriginalPVC : new (true )}
612+
613+ pvc := & corev1.PersistentVolumeClaim {
614+ ObjectMeta : metav1.ObjectMeta {Name : "vm-disk-ubuntu-source" , Namespace : ns },
615+ // The PV does not exist, so renamePVC fails before touching the claim.
616+ Spec : corev1.PersistentVolumeClaimSpec {VolumeName : "pv-missing" },
617+ }
618+ reconciler := newTestRestoreJobReconciler (t , pvc , restoreJob , backup )
619+
620+ ctx := context .Background ()
621+ if _ , _ , err := reconciler .prepareForRestore (ctx , restoreJob , backup , ur , target , opts ); err != nil {
622+ t .Fatalf ("prepareForRestore() error = %v" , err )
623+ }
624+
625+ if err := reconciler .Get (ctx , client .ObjectKeyFromObject (pvc ), & corev1.PersistentVolumeClaim {}); err != nil {
626+ t .Errorf ("original PVC should survive a failed rename when keepOriginalPVC=true, got error: %v" , err )
627+ }
628+ }
629+
630+ // A Backup artifact can outlive its Velero Backup, which Velero garbage-collects
631+ // at TTL. The restore must fail before it halts the VM or deletes its disks.
632+ func TestReconcileVeleroRestore_UnusableVeleroBackupTouchesNothing (t * testing.T ) {
633+ tests := []struct {
634+ name string
635+ veleroBackup * velerov1.Backup
636+ wantMessage string
637+ }{
638+ {
639+ name : "Velero Backup expired" ,
640+ wantMessage : "Velero Backup cozy-velero/vb not found" ,
641+ },
642+ {
643+ name : "Velero Backup being deleted" ,
644+ veleroBackup : & velerov1.Backup {
645+ ObjectMeta : metav1.ObjectMeta {Name : "vb" , Namespace : veleroNamespace },
646+ Status : velerov1.BackupStatus {Phase : velerov1 .BackupPhaseDeleting },
647+ },
648+ wantMessage : `Velero Backup cozy-velero/vb is "Deleting"` ,
649+ },
650+ }
651+ for _ , tt := range tests {
652+ t .Run (tt .name , func (t * testing.T ) {
653+ ns := "tenant-root"
654+ restoreJob , backup , ur , _ , opts := inPlaceVMRestoreWithoutKeep (ns )
655+ rawOpts , err := json .Marshal (opts )
656+ if err != nil {
657+ t .Fatalf ("marshal options: %v" , err )
658+ }
659+ started := metav1 .Now ()
660+ restoreJob .Spec .Options = & runtime.RawExtension {Raw : rawOpts }
661+ restoreJob .Status = backupsv1alpha1.RestoreJobStatus {
662+ Phase : backupsv1alpha1 .RestoreJobPhaseRunning ,
663+ StartedAt : & started ,
664+ }
665+ backup .Spec .StrategyRef = corev1.TypedLocalObjectReference {Kind : "Velero" , Name : "cozy-default-velero" }
666+ backup .Spec .DriverMetadata = map [string ]string {veleroBackupNameMetadataKey : "vb" }
667+ backup .Status .UnderlyingResources = ur
668+
669+ pvc := & corev1.PersistentVolumeClaim {
670+ ObjectMeta : metav1.ObjectMeta {Name : "vm-disk-ubuntu-source" , Namespace : ns },
671+ }
672+ strategy := & strategyv1alpha1.Velero {ObjectMeta : metav1.ObjectMeta {Name : "cozy-default-velero" }}
673+ objs := []client.Object {restoreJob , backup , pvc , strategy }
674+ if tt .veleroBackup != nil {
675+ objs = append (objs , tt .veleroBackup )
676+ }
677+
678+ vm := & unstructured.Unstructured {}
679+ vm .SetAPIVersion ("kubevirt.io/v1" )
680+ vm .SetKind ("VirtualMachine" )
681+ vm .SetName (vmNamePrefix + "test-vm" )
682+ vm .SetNamespace (ns )
683+ if err := unstructured .SetNestedField (vm .Object , "Always" , "spec" , "runStrategy" ); err != nil {
684+ t .Fatalf ("set runStrategy: %v" , err )
685+ }
686+ reconciler := newTestRestoreJobReconcilerWithDynamic (t ,
687+ []runtime.Object {vm , makeUnstructuredDataVolume ("vm-disk-ubuntu-source" , ns )})
688+ testScheme := runtime .NewScheme ()
689+ _ = scheme .AddToScheme (testScheme )
690+ _ = backupsv1alpha1 .AddToScheme (testScheme )
691+ _ = velerov1 .AddToScheme (testScheme )
692+ _ = strategyv1alpha1 .AddToScheme (testScheme )
693+ reconciler .Client = clientfake .NewClientBuilder ().
694+ WithScheme (testScheme ).
695+ WithObjects (objs ... ).
696+ WithStatusSubresource (& backupsv1alpha1.RestoreJob {}).
697+ Build ()
698+ ctx := context .Background ()
699+
700+ if _ , err := reconciler .reconcileVeleroRestore (ctx , restoreJob , backup ); err != nil {
701+ t .Fatalf ("reconcileVeleroRestore() error = %v" , err )
702+ }
703+
704+ got := & backupsv1alpha1.RestoreJob {}
705+ if err := reconciler .Get (ctx , client .ObjectKeyFromObject (restoreJob ), got ); err != nil {
706+ t .Fatalf ("get RestoreJob: %v" , err )
707+ }
708+ if got .Status .Phase != backupsv1alpha1 .RestoreJobPhaseFailed {
709+ t .Fatalf ("phase = %q, want %q" , got .Status .Phase , backupsv1alpha1 .RestoreJobPhaseFailed )
710+ }
711+ ready := meta .FindStatusCondition (got .Status .Conditions , "Ready" )
712+ if ready == nil || ! strings .Contains (ready .Message , tt .wantMessage ) {
713+ t .Errorf ("Ready condition = %+v, want a message containing %q" , ready , tt .wantMessage )
714+ }
715+
716+ if err := reconciler .Get (ctx , client .ObjectKeyFromObject (pvc ), & corev1.PersistentVolumeClaim {}); err != nil {
717+ t .Errorf ("original PVC should survive a restore that cannot run: %v" , err )
718+ }
719+ if _ , err := reconciler .Resource (dataVolumeGVR ).Namespace (ns ).Get (ctx , "vm-disk-ubuntu-source" , metav1.GetOptions {}); err != nil {
720+ t .Errorf ("DataVolume should survive a restore that cannot run: %v" , err )
721+ }
722+ gotVM , err := reconciler .Resource (virtualMachineGVR ).Namespace (ns ).Get (ctx , vm .GetName (), metav1.GetOptions {})
723+ if err != nil {
724+ t .Fatalf ("get VirtualMachine: %v" , err )
725+ }
726+ if rs , _ , _ := unstructured .NestedString (gotVM .Object , "spec" , "runStrategy" ); rs != "Always" {
727+ t .Errorf ("VirtualMachine runStrategy = %q, want it left at %q" , rs , "Always" )
728+ }
729+ })
730+ }
731+ }
732+
535733func TestResolveRestoreTarget_VMDisk_CommonRestoreOptions (t * testing.T ) {
536734 tests := []struct {
537735 name string
0 commit comments