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