-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathmigrationplan_controller.go
More file actions
2975 lines (2682 loc) · 116 KB
/
Copy pathmigrationplan_controller.go
File metadata and controls
2975 lines (2682 loc) · 116 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright 2024.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package controller
import (
"context"
"encoding/json"
"fmt"
"os"
"os/user"
"reflect"
"strconv"
"strings"
"time"
"github.com/go-logr/logr"
"github.com/gophercloud/gophercloud/v2/openstack/compute/v2/flavors"
"github.com/pkg/errors"
vjailbreakv1alpha1 "github.com/platform9/vjailbreak/k8s/migration/api/v1alpha1"
"github.com/platform9/vjailbreak/k8s/migration/pkg/scope"
utils "github.com/platform9/vjailbreak/k8s/migration/pkg/utils"
"github.com/platform9/vjailbreak/k8s/migration/pkg/verrors"
"github.com/platform9/vjailbreak/pkg/common/constants"
openstackpkg "github.com/platform9/vjailbreak/pkg/common/openstack"
commonutils "github.com/platform9/vjailbreak/pkg/common/utils"
netappsdk "github.com/platform9/vjailbreak/pkg/vpwned/sdk/storage/netapp"
"github.com/platform9/vjailbreak/v2v-helper/pkg/k8sutils"
"github.com/platform9/vjailbreak/v2v-helper/vcenter"
batchv1 "k8s.io/api/batch/v1"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/util/retry"
"k8s.io/utils/ptr"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/builder"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
"sigs.k8s.io/controller-runtime/pkg/event"
"sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/controller-runtime/pkg/predicate"
"github.com/vmware/govmomi/object"
"github.com/vmware/govmomi/session"
govmomitypes "github.com/vmware/govmomi/vim25/types"
)
// VDDKDirectory is the path to VMware VDDK installation directory used for VM disk conversion
const VDDKDirectory = "/home/ubuntu/vmware-vix-disklib-distrib"
// StorageCopyMethod is the storage copy method value for Storage Accelerated copy
const StorageCopyMethod = "StorageAcceleratedCopy"
// MigrationPlanReconciler reconciles a MigrationPlan object
type MigrationPlanReconciler struct {
client.Client
Scheme *runtime.Scheme
ctxlog logr.Logger
MaxConcurrentReconciles int
}
var migrationPlanFinalizer = "migrationplan.vjailbreak.pf9.io/finalizer"
// The default image. This is replaced by Go linker flags in the Dockerfile
var v2vimage = "platform9/v2v-helper:v0.1"
// +kubebuilder:rbac:groups=core,resources=pods,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=core,resources=pods/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=core,resources=pods/log,verbs=get;list
// +kubebuilder:rbac:groups=core,resources=configmaps,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=core,resources=configmaps/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=batch,resources=jobs,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=vjailbreak.k8s.pf9.io,resources=migrationplans,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=vjailbreak.k8s.pf9.io,resources=migrationplans/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=vjailbreak.k8s.pf9.io,resources=migrationplans/finalizers,verbs=update
// +kubebuilder:rbac:groups=vjailbreak.k8s.pf9.io,resources=migrationtemplates,verbs=get;list;watch
// +kubebuilder:rbac:groups=vjailbreak.k8s.pf9.io,resources=migrationtemplates,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=vjailbreak.k8s.pf9.io,resources=migrationtemplates/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=vjailbreak.k8s.pf9.io,resources=migrationtemplates/finalizers,verbs=update
// +kubebuilder:rbac:groups=vjailbreak.k8s.pf9.io,resources=proxyvms,verbs=get;list;watch;update;patch
// Reconcile reads that state of the cluster for a MigrationPlan object and makes necessary changes
func (r *MigrationPlanReconciler) Reconcile(ctx context.Context, req ctrl.Request) (_ ctrl.Result, reterr error) {
r.ctxlog = log.FromContext(ctx)
migrationplan := &vjailbreakv1alpha1.MigrationPlan{}
if err := r.Get(ctx, req.NamespacedName, migrationplan); err != nil {
if apierrors.IsNotFound(err) {
return ctrl.Result{}, nil
}
r.ctxlog.Error(err, fmt.Sprintf("failed to read MigrationPlan '%s'", migrationplan.Name))
return ctrl.Result{}, errors.Wrapf(err, "failed to read MigrationPlan '%s'", migrationplan.Name)
}
err := utils.ValidateMigrationPlan(migrationplan)
if err != nil {
return ctrl.Result{}, errors.Wrap(err, "failed to validate MigrationPlan")
}
// Set default migration type if not provided
if migrationplan.Spec.MigrationStrategy.Type == "" {
vjailbreakSettings, err := k8sutils.GetVjailbreakSettings(ctx, r.Client)
if err != nil {
r.ctxlog.Error(err, "Failed to get vjailbreak settings")
return ctrl.Result{}, errors.Wrap(err, "failed to get vjailbreak settings")
}
migrationplan.Spec.MigrationStrategy.Type = vjailbreakSettings.DefaultMigrationMethod
// Update the spec
if err := r.Update(ctx, migrationplan); err != nil {
return ctrl.Result{}, errors.Wrap(err, "failed to update migration plan with default type")
}
}
migrationPlanScope, err := scope.NewMigrationPlanScope(scope.MigrationPlanScopeParams{
Logger: r.ctxlog,
Client: r.Client,
MigrationPlan: migrationplan,
})
if err != nil {
return ctrl.Result{}, errors.Wrap(err, "failed to create scope")
}
// Always close the scope when exiting this function such that we can persist any MigrationPlan changes.
defer func() {
if err := migrationPlanScope.Close(); err != nil && reterr == nil {
reterr = err
}
}()
// examine DeletionTimestamp to determine if object is under deletion or not
if !migrationplan.DeletionTimestamp.IsZero() {
return r.reconcileDelete(ctx, migrationPlanScope)
}
return r.reconcileNormal(ctx, migrationPlanScope)
}
func (r *MigrationPlanReconciler) reconcileNormal(ctx context.Context, scope *scope.MigrationPlanScope) (ctrl.Result, error) {
migrationplan := scope.MigrationPlan
log := scope.Logger
log.Info(fmt.Sprintf("Reconciling MigrationPlan '%s'", migrationplan.Name))
controllerutil.AddFinalizer(migrationplan, migrationPlanFinalizer)
res, err := r.ReconcileMigrationPlanJob(ctx, migrationplan, scope)
if err != nil {
return res, errors.Wrap(err, "failed to reconcile migration plan job")
}
return res, nil
}
//nolint:unparam //future use
func (r *MigrationPlanReconciler) reconcileDelete(
ctx context.Context,
scope *scope.MigrationPlanScope,
) (ctrl.Result, error) {
migrationplan := scope.MigrationPlan
ctxlog := log.FromContext(ctx).WithName(constants.MigrationControllerName)
// The object is being deleted
ctxlog.Info(fmt.Sprintf("MigrationPlan '%s' CR is being deleted", migrationplan.Name))
// Now that the finalizer has completed deletion tasks, we can remove it
// to allow deletion of the Migration object
controllerutil.RemoveFinalizer(migrationplan, migrationPlanFinalizer)
if err := r.Update(ctx, migrationplan); err != nil {
return ctrl.Result{}, errors.Wrap(err, "failed to remove finalizer")
}
return ctrl.Result{}, nil
}
func (r *MigrationPlanReconciler) getMigrationTemplateAndCreds(
ctx context.Context,
migrationplan *vjailbreakv1alpha1.MigrationPlan,
) (*vjailbreakv1alpha1.MigrationTemplate, *vjailbreakv1alpha1.VMwareCreds, *corev1.Secret, error) {
ctxlog := log.FromContext(ctx)
migrationtemplate := &vjailbreakv1alpha1.MigrationTemplate{}
if err := r.Get(ctx, types.NamespacedName{
Name: migrationplan.Spec.MigrationTemplate,
Namespace: migrationplan.Namespace,
}, migrationtemplate); err != nil {
ctxlog.Error(err, "Failed to get MigrationTemplate")
return nil, nil, nil, errors.Wrap(err, "failed to get MigrationTemplate")
}
vmwcreds := &vjailbreakv1alpha1.VMwareCreds{}
if ok, err := r.checkStatusSuccess(ctx, migrationtemplate.Namespace, migrationtemplate.Spec.Source.VMwareRef, true, vmwcreds); !ok {
return nil, nil, nil, errors.Wrap(err, "VMwareCreds not validated")
}
secret := &corev1.Secret{}
if err := r.Get(ctx, types.NamespacedName{
Name: vmwcreds.Spec.SecretRef.Name,
Namespace: migrationplan.Namespace,
}, secret); err != nil {
return nil, nil, nil, errors.Wrap(err, "failed to get vCenter Secret")
}
return migrationtemplate, vmwcreds, secret, nil
}
func (r *MigrationPlanReconciler) reconcilePostMigration(ctx context.Context, scope *scope.MigrationPlanScope, vm string) error {
migrationplan := scope.MigrationPlan
ctxlog := log.FromContext(ctx).WithName(constants.MigrationControllerName)
ctxlog.Info("Starting post-migration reconciliation for VM", "vm", vm, "migrationplan", migrationplan.Name)
if migrationplan.Spec.PostMigrationAction == nil {
ctxlog.Info("No post-migration actions configured for VM", "vm", vm)
return nil
}
if migrationplan.Spec.PostMigrationAction.RenameVM == nil &&
migrationplan.Spec.PostMigrationAction.MoveToFolder == nil {
ctxlog.Info("No post-migration actions enabled for VM", "vm", vm)
return nil
}
ctxlog.Info("Post-migration actions configured for VM",
"vm", vm,
"renameVM", migrationplan.Spec.PostMigrationAction.RenameVM,
"moveToFolder", migrationplan.Spec.PostMigrationAction.MoveToFolder,
"suffix", migrationplan.Spec.PostMigrationAction.Suffix,
"folderName", migrationplan.Spec.PostMigrationAction.FolderName)
// Get required resources
migrationtemplate, vmwcreds, secret, err := r.getMigrationTemplateAndCreds(ctx, migrationplan)
if err != nil {
return errors.Wrap(err, "failed to get migration resources")
}
vmMachine, err := GetVMwareMachineForVM(ctx, r, vm, migrationtemplate, vmwcreds)
if err != nil {
return errors.Wrapf(err, "failed to resolve VMwareMachine for post-migration actions on VM %s", vm)
}
vcenterVMName := vmMachine.Spec.VMInfo.Name
vmid := vmMachine.Spec.VMInfo.VMID
ctxlog.Info("Resolved vCenter VM for post-migration", "vmKey", vm, "vcenterName", vcenterVMName, "vmid", vmid)
// Extract and validate credentials
username, password, host, err := extractVCenterCredentials(secret)
if err != nil {
return errors.Wrap(err, "invalid vCenter credentials")
}
// Create vCenter client (datacenter is auto-detected from VM during move operation)
vcClient, _, err := createVCenterClientAndDC(ctx, host, username, password, vmwcreds.Spec.DataCenter)
if err != nil {
return errors.Wrap(err, "failed to create vCenter client")
}
defer func() {
if vcClient.VCClient != nil {
sessionManager := session.NewManager(vcClient.VCClient)
err = sessionManager.Logout(ctx) // Best effort logout
if err != nil {
ctxlog.Error(err, "Failed to logout from vCenter")
}
}
}()
if migrationplan.Spec.PostMigrationAction.RenameVM != nil && *migrationplan.Spec.PostMigrationAction.RenameVM {
if err := r.renameVM(ctx, vcClient, migrationplan, vmid); err != nil {
return errors.Wrap(err, "failed to rename VM")
}
}
if migrationplan.Spec.PostMigrationAction.MoveToFolder != nil && *migrationplan.Spec.PostMigrationAction.MoveToFolder {
if err := r.moveVMToFolder(ctx, vcClient, migrationplan, vmid); err != nil {
return errors.Wrap(err, "failed to move VM to folder")
}
}
return nil
}
func (*MigrationPlanReconciler) renameVM(
ctx context.Context,
vcClient *vcenter.VCenterClient,
migrationplan *vjailbreakv1alpha1.MigrationPlan,
vmid string,
) error {
ctxlog := log.FromContext(ctx)
suffix := migrationplan.Spec.PostMigrationAction.Suffix
if suffix == "" {
suffix = "_migrated_to_pcd"
ctxlog.Info("Using default suffix", "suffix", suffix)
}
vmObj := vcClient.GetVMByMOID(vmid)
currentName, err := vmObj.ObjectName(ctx)
if err != nil {
return errors.Wrapf(err, "failed to fetch current VM name for moid %s", vmid)
}
newVMName := currentName + suffix
ctxlog.Info("Starting VM rename operation", "oldName", currentName, "newName", newVMName, "vmid", vmid, "migrationplan", migrationplan.Name)
err = vcClient.RenameVM(ctx, vmid, newVMName)
if err != nil {
if strings.Contains(strings.ToLower(err.Error()), "not found") {
ctxlog.Info("VM not found for rename; possibly already processed or deleted", "oldName", currentName, "newName", newVMName)
return nil
}
ctxlog.Error(err, "Failed to rename VM", "oldName", currentName, "newName", newVMName, "migrationplan", migrationplan.Name)
return err
}
ctxlog.Info("Successfully renamed VM", "oldName", currentName, "newName", newVMName, "migrationplan", migrationplan.Name)
return nil
}
func (*MigrationPlanReconciler) moveVMToFolder(
ctx context.Context,
vcClient *vcenter.VCenterClient,
migrationplan *vjailbreakv1alpha1.MigrationPlan,
vmid string,
) error {
ctxlog := log.FromContext(ctx)
folderName := migrationplan.Spec.PostMigrationAction.FolderName
if folderName == "" {
folderName = "vjailbreakedVMs"
ctxlog.Info("Using default folder name", "folderName", folderName)
}
datacenterName := ""
vmObj := vcClient.GetVMByMOID(vmid)
if currentName, nameErr := vmObj.ObjectName(ctx); nameErr == nil {
if _, dc, dcErr := vcClient.GetVMWithDatacenter(ctx, currentName); dcErr == nil {
datacenterName = dc.Name()
} else {
ctxlog.Info("Could not resolve datacenter for VM, proceeding without datacenter context", "vmid", vmid, "err", dcErr)
}
} else {
ctxlog.Info("Could not get VM name for datacenter lookup, proceeding without datacenter context", "vmid", vmid, "err", nameErr)
}
ctxlog.Info("Starting VM move to folder operation", "vmid", vmid, "datacenter", datacenterName, "folder", folderName, "migrationplan", migrationplan.Name)
if err := vcClient.MovetoFolder(ctx, vmid, datacenterName, folderName); err != nil {
if strings.Contains(strings.ToLower(err.Error()), "not found") {
ctxlog.Info("VM not found for move; possibly already processed or deleted", "vmid", vmid)
return nil
}
ctxlog.Error(err, "VM move failed", "vmid", vmid, "folder", folderName, "migrationplan", migrationplan.Name)
return errors.Wrapf(err, "failed to move VM (moid=%s) to folder '%s'", vmid, folderName)
}
ctxlog.Info("Successfully moved VM to folder", "vmid", vmid, "folder", folderName, "migrationplan", migrationplan.Name)
return nil
}
func createVCenterClientAndDC(
ctx context.Context,
host, username, password, datacenterName string,
) (*vcenter.VCenterClient, *object.Datacenter, error) {
ctxlog := log.FromContext(ctx)
ctxlog.Info("Creating vCenter client...", "host", host, "insecure", true)
vcClient, err := vcenter.VCenterClientBuilder(ctx, username, password, host, true)
if err != nil {
ctxlog.Error(err, "Failed to create vCenter client")
return nil, nil, errors.Wrapf(err, "failed to create vCenter client")
}
ctxlog.Info("vCenter client created successfully")
if datacenterName == "" {
ctxlog.Info("No datacenter specified, returning client without datacenter scope")
return vcClient, nil, nil
}
ctxlog.Info("Using datacenter", "datacenter", datacenterName)
dc, err := vcClient.VCFinder.Datacenter(ctx, datacenterName)
if err != nil {
ctxlog.Error(err, "Failed to find datacenter")
return nil, nil, errors.Wrapf(err, "failed to find datacenter '%s'", datacenterName)
}
ctxlog.Info("Datacenter located", "datacenter", dc)
return vcClient, dc, nil
}
func extractVCenterCredentials(secret *corev1.Secret) (username, password, host string, err error) {
u, ok := secret.Data["VCENTER_USERNAME"]
if !ok {
err = errors.New("username not found in secret")
return
}
p, ok := secret.Data["VCENTER_PASSWORD"]
if !ok {
err = errors.New("password not found in secret")
return
}
h, ok := secret.Data["VCENTER_HOST"]
if !ok {
err = errors.New("host not found in secret")
return
}
username = string(u)
password = string(p)
host = string(h)
return
}
// GetVMwareMachineForVM fetches the VMwareMachine corresponding to a given VM name
func GetVMwareMachineForVM(ctx context.Context, r *MigrationPlanReconciler, vm string, migrationtemplate *vjailbreakv1alpha1.MigrationTemplate, vmwcreds *vjailbreakv1alpha1.VMwareCreds) (*vjailbreakv1alpha1.VMwareMachine, error) {
// Generate the expected VMwareMachine name
vmk8sname, err := commonutils.GetK8sCompatibleVMWareObjectName(vm, vmwcreds.Name)
if err != nil {
return nil, errors.Wrapf(err, "failed to get k8s compatible name for VM %s", vm)
}
// Fetch individual VMwareMachine
vmMachine := &vjailbreakv1alpha1.VMwareMachine{}
err = r.Get(ctx, types.NamespacedName{
Name: vmk8sname,
Namespace: migrationtemplate.Namespace,
}, vmMachine)
if err != nil {
if apierrors.IsNotFound(err) {
return nil, errors.Errorf("VMwareMachine %s not found for VM %s", vmk8sname, vm)
}
return nil, errors.Wrapf(err, "failed to get VMwareMachine %s for VM %s", vmk8sname, vm)
}
// Verify VMwareMachine has correct VMwareCreds label
if vmMachine.Labels == nil {
return nil, errors.Errorf("VMwareMachine %s has no labels", vmMachine.Name)
}
expectedLabel := vmwcreds.Name
actualLabel, exists := vmMachine.Labels[constants.VMwareCredsLabel]
if !exists {
return nil, errors.Errorf("VMwareMachine %s missing required label %s", vmMachine.Name, constants.VMwareCredsLabel)
}
if actualLabel != expectedLabel {
return nil, errors.Errorf("VMwareMachine %s has incorrect VMwareCreds label: expected %s, got %s", vmMachine.Name, expectedLabel, actualLabel)
}
vmidSuffixed := commonutils.GetVMUniqueKey(vmMachine.Spec.VMInfo.Name, vmMachine.Spec.VMInfo.VMID)
if vmidSuffixed != vm {
return nil, errors.Errorf("VMwareMachine %s VM key mismatch: expected %s, got %s", vmMachine.Name, vm, vmidSuffixed)
}
return vmMachine, nil
}
// ReconcileMigrationPlanJob reconciles jobs created by the migration plan
//
//nolint:gocyclo
func (r *MigrationPlanReconciler) ReconcileMigrationPlanJob(ctx context.Context,
migrationplan *vjailbreakv1alpha1.MigrationPlan,
scope *scope.MigrationPlanScope) (ctrl.Result, error) {
totalVMs := 0
for _, group := range migrationplan.Spec.VirtualMachines {
totalVMs += len(group)
}
allVMNames := make([]string, 0, totalVMs)
for _, group := range migrationplan.Spec.VirtualMachines {
allVMNames = append(allVMNames, group...)
}
if migrationplan.Status.MigrationStatus == corev1.PodSucceeded {
r.ctxlog.Info("Migration already completed, skipping job reconciliation", "migrationplan", migrationplan.Name)
return ctrl.Result{}, nil
}
if migrationplan.Status.MigrationStatus == corev1.PodFailed {
// Check if any Migration objects exist for this MigrationPlan
migrationList := &vjailbreakv1alpha1.MigrationList{}
listOpts := []client.ListOption{
client.InNamespace(migrationplan.Namespace),
client.MatchingLabels{"migrationplan": migrationplan.Name},
}
if err := r.List(ctx, migrationList, listOpts...); err != nil {
r.ctxlog.Error(err, "Failed to list migrations for retry check", "migrationplan", migrationplan.Name)
return ctrl.Result{}, errors.Wrap(err, "failed to list migrations for retry check")
}
// Map existing migrations to detect deletions
existingMigrationMap := make(map[string]bool)
hasExistingFailures := false
for _, m := range migrationList.Items {
vmKey := m.Annotations[constants.OriginalVMNameAnnotation]
if vmKey == "" {
vmKey = m.Labels[constants.MigrationVMKeyLabel] // backward compat: pre-fix CRs lacked annotation
}
if vmKey == "" {
vmKey = m.Spec.VMName
}
existingMigrationMap[vmKey] = true
if m.Status.Phase == vjailbreakv1alpha1.VMMigrationPhaseFailed || m.Status.Phase == vjailbreakv1alpha1.VMMigrationPhaseValidationFailed {
hasExistingFailures = true
}
}
retryTriggeredByDeletion := false
for _, name := range allVMNames {
if !existingMigrationMap[name] {
retryTriggeredByDeletion = true
break
}
}
// If the specific "Failed" objects are gone (user deleted them for retry),
// but the plan still says "Failed", we reset the plan status.
if !hasExistingFailures || retryTriggeredByDeletion {
if strings.HasPrefix(migrationplan.Status.MigrationMessage, constants.MigrationPlanValidationFailedPrefix) {
return ctrl.Result{}, nil
}
r.ctxlog.Info("Resetting Plan status for retry", "migrationplan", migrationplan.Name)
err := retry.RetryOnConflict(retry.DefaultBackoff, func() error {
latest := &vjailbreakv1alpha1.MigrationPlan{}
if getErr := r.Get(ctx, types.NamespacedName{Name: migrationplan.Name, Namespace: migrationplan.Namespace}, latest); getErr != nil {
if apierrors.IsNotFound(getErr) {
return nil
}
return getErr
}
latest.Status.MigrationStatus = ""
latest.Status.MigrationMessage = ""
return r.Status().Update(ctx, latest)
})
if err != nil {
return ctrl.Result{}, errors.Wrap(err, "failed to reset status for retry")
}
return ctrl.Result{Requeue: true}, nil
}
r.ctxlog.Info("Migration failures still exist, skipping reconciliation", "migrationplan", migrationplan.Name)
return ctrl.Result{}, nil
}
migrationtemplate, vmwcreds, _, err := r.getMigrationTemplateAndCreds(ctx, migrationplan)
if err != nil {
r.ctxlog.Error(err, "Failed to get migration template and credentials")
return ctrl.Result{}, err
}
terminalMigrations := make(map[string]bool)
for _, vmName := range allVMNames {
vmk8sname, err := commonutils.GetK8sCompatibleVMWareObjectName(vmName, vmwcreds.Name)
if err != nil {
r.ctxlog.Error(err, "Failed to convert VM name to k8s name", "vm", vmName)
continue
}
migrationName := utils.MigrationNameFromVMName(vmk8sname)
existingMigration := &vjailbreakv1alpha1.Migration{}
if err := r.Get(ctx, types.NamespacedName{Name: migrationName, Namespace: migrationplan.Namespace}, existingMigration); err == nil {
if existingMigration.Status.Phase == vjailbreakv1alpha1.VMMigrationPhaseSucceeded ||
existingMigration.Status.Phase == vjailbreakv1alpha1.VMMigrationPhaseFailed ||
existingMigration.Status.Phase == vjailbreakv1alpha1.VMMigrationPhaseValidationFailed ||
existingMigration.Status.Phase == vjailbreakv1alpha1.VMMigrationPhaseDataCopied {
terminalMigrations[vmName] = true
r.ctxlog.Info("Skipping terminal migration from validation", "vm", vmName, "phase", existingMigration.Status.Phase)
}
}
}
// Filter out VMs with terminal migrations for validation
vmsToValidate := []string{}
for _, vmName := range allVMNames {
if !terminalMigrations[vmName] {
vmsToValidate = append(vmsToValidate, vmName)
}
}
// Creds are fetched before validation because pre-flight now resolves each VM's
// target flavor, which needs the OpenStack endpoint.
// Fetch VMwareCreds CR
if ok, err := r.checkStatusSuccess(ctx, migrationtemplate.Namespace, migrationtemplate.Spec.Source.VMwareRef, true, vmwcreds); !ok {
return ctrl.Result{}, errors.Wrapf(err, "failed to check vmwarecreds status '%s'", migrationtemplate.Spec.Source.VMwareRef)
}
// Fetch OpenStackCreds CR
openstackcreds := &vjailbreakv1alpha1.OpenstackCreds{}
if ok, err := r.checkStatusSuccess(ctx, migrationtemplate.Namespace, migrationtemplate.Spec.Destination.OpenstackRef,
false, openstackcreds); !ok {
return ctrl.Result{}, errors.Wrapf(err, "failed to check openstackcreds status '%s'", migrationtemplate.Spec.Destination.OpenstackRef)
}
// Fetched once here and reused by validateMigrationPlanVMs below, so each VM
// is looked up at most once per reconcile instead of twice.
fetchedVMs, needsFlavorLookup := r.fetchVMsToValidate(ctx, migrationtemplate, vmwcreds, vmsToValidate)
// One Nova call for the whole plan; skipped if every VM is pinned. A
// failure here is just requeued, same as the creds checks above.
var candidateFlavors []flavors.Flavor
if needsFlavorLookup {
var err error
candidateFlavors, err = r.candidateFlavorsForPlan(ctx, migrationtemplate, openstackcreds)
if err != nil {
return ctrl.Result{}, errors.Wrap(err, "failed to list target flavors")
}
}
// Non-nil maps for the no-VMs-to-validate path; nil-checked below since some
// error paths still return a nil result.
validation := &migrationPlanValidation{
ResolvedFlavors: map[string]string{},
SkipReasons: map[string]string{},
}
var validationErr error
if len(vmsToValidate) > 0 {
// Validate VM OS types and resolve target flavors before proceeding.
validation, validationErr = r.validateMigrationPlanVMs(ctx, migrationplan, migrationtemplate, vmwcreds, openstackcreds, vmsToValidate, fetchedVMs, candidateFlavors)
}
if validationErr != nil {
r.ctxlog.Error(validationErr, "Migration plan validation failed", "migrationplan", migrationplan.Name)
for _, vmName := range allVMNames {
// Skip VMs with terminal migrations
if terminalMigrations[vmName] {
continue
}
vmMachine, err := GetVMwareMachineForVM(ctx, r, vmName, migrationtemplate, vmwcreds)
if err != nil {
r.ctxlog.Error(err, "Failed to get vmMachine for pre-creation", "vm", vmName)
continue
}
migrationObj, createErr := r.CreateMigration(ctx, migrationplan, vmName, vmMachine)
if createErr != nil {
r.ctxlog.Error(createErr, "Failed to create migration object during validation failure documentation", "vm", vmName)
continue
}
// Prefer the specific skip reason over the generic message.
reason := "VM failed migration plan validation"
if validation != nil {
if specific := validation.SkipReasons[vmName]; specific != "" {
reason = specific
}
}
r.markMigrationValidationFailed(ctx, migrationObj, vmName, reason)
}
if err := r.UpdateMigrationPlanStatus(ctx, migrationplan, corev1.PodFailed, fmt.Sprintf("Migration plan validation failed: %v", validationErr)); err != nil {
r.ctxlog.Error(err, "Failed to update migration plan status after validation failure")
}
return ctrl.Result{}, validationErr
}
// Every non-terminal VM in the plan gets a Migration CR, including ones that
// failed pre-flight validation. The UI's migrations table is built purely from
// Migration objects, so a VM without one is invisible there — no row, no
// placeholder, and no hint as to why it never migrated.
for _, vmName := range allVMNames {
// Skip VMs with terminal migrations
if terminalMigrations[vmName] {
continue
}
vmMachine, err := GetVMwareMachineForVM(ctx, r, vmName, migrationtemplate, vmwcreds)
if err != nil {
r.ctxlog.Error(err, "Failed to get vmMachine for migration creation", "vm", vmName)
continue
}
migrationObj, createErr := r.CreateMigration(ctx, migrationplan, vmName, vmMachine)
if createErr != nil {
r.ctxlog.Error(createErr, "Failed to create migration object", "vm", vmName)
continue
}
isValid := false
for _, v := range validation.ValidVMs {
if commonutils.GetVMUniqueKey(v.Spec.VMInfo.Name, v.Spec.VMInfo.VMID) == vmName {
isValid = true
break
}
}
if !isValid {
// Prefer the specific pre-flight reason so the UI shows something
// actionable ("no target flavor can satisfy this VM…") rather than a
// generic validation failure.
reason := validation.SkipReasons[vmName]
if reason == "" {
reason = "VM failed migration plan validation"
}
r.markMigrationValidationFailed(ctx, migrationObj, vmName, reason)
}
}
var arraycreds *vjailbreakv1alpha1.ArrayCreds
var proxyVM *vjailbreakv1alpha1.ProxyVM
// Check if StorageCopyMethod is StorageAcceleratedCopy
switch migrationtemplate.Spec.StorageCopyMethod {
case StorageCopyMethod:
// Fetch ArrayCredsMapping CR first
arrayCredsMapping := &vjailbreakv1alpha1.ArrayCredsMapping{}
if err := r.Get(ctx, types.NamespacedName{Name: migrationtemplate.Spec.ArrayCredsMapping, Namespace: migrationtemplate.Namespace}, arrayCredsMapping); err != nil {
return ctrl.Result{}, errors.Wrapf(err, "failed to get ArrayCredsMapping '%s'", migrationtemplate.Spec.ArrayCredsMapping)
}
// Validate ArrayCredsMapping has mappings
if len(arrayCredsMapping.Spec.Mappings) == 0 {
return ctrl.Result{}, errors.Errorf("ArrayCredsMapping '%s' has no mappings defined", migrationtemplate.Spec.ArrayCredsMapping)
}
for _, mapping := range arrayCredsMapping.Spec.Mappings {
arraycreds = &vjailbreakv1alpha1.ArrayCreds{}
if err := r.Get(ctx, types.NamespacedName{Name: mapping.Target, Namespace: migrationtemplate.Namespace}, arraycreds); err != nil {
return ctrl.Result{}, errors.Wrapf(err, "failed to get ArrayCreds '%s' from mapping", mapping.Target)
}
if arraycreds.Status.ArrayValidationStatus != string(corev1.PodSucceeded) {
return ctrl.Result{}, errors.Errorf("ArrayCreds '%s' is not validated (status: %s)", mapping.Target, arraycreds.Status.ArrayValidationStatus)
}
}
case constants.HotAddCopyMethod:
if migrationtemplate.Spec.ProxyVMRef == nil {
return ctrl.Result{}, errors.New("StorageCopyMethod is HotAdd but ProxyVMRef is not set in MigrationTemplate")
}
proxyVM = &vjailbreakv1alpha1.ProxyVM{}
if err := r.Get(ctx, types.NamespacedName{Name: migrationtemplate.Spec.ProxyVMRef.Name, Namespace: migrationtemplate.Namespace}, proxyVM); err != nil {
return ctrl.Result{}, errors.Wrapf(err, "failed to get ProxyVM '%s'", migrationtemplate.Spec.ProxyVMRef.Name)
}
if proxyVM.Status.ValidationStatus != constants.ProxyVMStatusReady {
return ctrl.Result{}, errors.Errorf("ProxyVM '%s' is not ready (status: %s)", proxyVM.Name, proxyVM.Status.ValidationStatus)
}
default:
arraycreds = nil
}
// Starting the Migrations
if migrationplan.Status.MigrationStatus == "" {
err := r.UpdateMigrationPlanStatus(ctx, migrationplan, corev1.PodRunning, "Migration(s) in progress")
if err != nil {
return ctrl.Result{}, errors.Wrap(err, "failed to update migration plan status")
}
}
// vmMachinesArr is created to maintain order in which VM migration is triggered
vmMachinesArr := validation.ValidVMs
vmMachinesMap := make(map[string]*vjailbreakv1alpha1.VMwareMachine, len(validation.ValidVMs))
for _, vmMachine := range validation.ValidVMs {
vmMachinesMap[vmMachine.Spec.VMInfo.Name] = vmMachine
}
// Migrate RDM disks if any
err = r.migrateRDMdisks(ctx, migrationplan, vmMachinesMap, openstackcreds)
if err != nil {
return r.handleRDMDiskMigrationError(ctx, migrationplan, err)
}
if paused, err := r.checkAndHandlePausedPlan(ctx, migrationplan); paused {
return ctrl.Result{}, err
}
for _, parallelvms := range migrationplan.Spec.VirtualMachines {
migrationobjs := &vjailbreakv1alpha1.MigrationList{}
err := r.TriggerMigration(ctx, migrationplan, migrationobjs, openstackcreds, vmwcreds, arraycreds, migrationtemplate, vmMachinesArr, proxyVM, validation.ResolvedFlavors)
if err != nil {
if strings.Contains(err.Error(), "VDDK_MISSING") {
r.ctxlog.Info("Requeuing due to missing VDDK files.")
return ctrl.Result{RequeueAfter: 30 * time.Second}, nil
}
return ctrl.Result{}, errors.Wrapf(err, "failed to trigger migration")
}
// Fetch all migrations for this plan to catch already-completed migrations from previous reconciliations
allMigrations := &vjailbreakv1alpha1.MigrationList{}
listOpts := []client.ListOption{
client.InNamespace(migrationplan.Namespace),
client.MatchingLabels{"migrationplan": migrationplan.Name},
}
if err := r.List(ctx, allMigrations, listOpts...); err != nil {
r.ctxlog.Error(err, "Failed to list all migrations for post-migration processing", "migrationplan", migrationplan.Name)
return ctrl.Result{}, errors.Wrap(err, "failed to list migrations for post-migration processing")
}
outcome, err := r.processMigrationPhases(ctx, scope, migrationplan, allMigrations, parallelvms)
if err != nil {
return ctrl.Result{}, err
}
if !outcome.AllFinished {
// Don't requeue - rely on event-driven reconciliation when Migrations reach terminal states
return ctrl.Result{}, nil
}
// Every migration is terminal and at least one failed. Post-migration has
// already run for the successful ones, so the plan can now be marked failed
// without starving anything — a single bad VM no longer aborts the plan while
// its siblings are still copying.
if len(outcome.FailedVMs) > 0 {
total := outcome.FinishedVMs + len(outcome.FailedVMs)
msg := fmt.Sprintf("%d of %d VMs migrated successfully; %d failed: %s",
outcome.FinishedVMs, total, len(outcome.FailedVMs), strings.Join(outcome.FailureSummaries, "; "))
r.ctxlog.Info("MigrationPlan finished with failures", "migrationplan", migrationplan.Name, "failedVMs", outcome.FailedVMs)
if err := r.UpdateMigrationPlanStatus(ctx, migrationplan, corev1.PodFailed, msg); err != nil {
return ctrl.Result{}, errors.Wrap(err, "failed to update migration plan status after partial failure")
}
return ctrl.Result{}, nil
}
}
r.ctxlog.Info(fmt.Sprintf("All VMs in MigrationPlan '%s' have been successfully migrated", migrationplan.Name))
migrationplan.Status.MigrationStatus = corev1.PodSucceeded
migrationplan.Status.MigrationMessage = "All migrations completed successfully"
err = r.Status().Update(ctx, migrationplan)
if err != nil {
return ctrl.Result{}, errors.Wrap(err, "failed to update migration plan status")
}
return ctrl.Result{}, nil
}
// checkAndHandlePausedPlan checks if migration plan is paused and handles it
func (r *MigrationPlanReconciler) checkAndHandlePausedPlan(ctx context.Context, migrationplan *vjailbreakv1alpha1.MigrationPlan) (bool, error) {
if !utils.IsMigrationPlanPaused(ctx, migrationplan.Name, r.Client) {
return false, nil
}
migrationplan.Status.MigrationStatus = "Paused"
migrationplan.Status.MigrationMessage = "Migration plan is paused"
if err := r.Update(ctx, migrationplan); err != nil {
return true, errors.Wrap(err, "failed to update migration plan status")
}
return true, nil
}
// processMigrationPhases processes migration phases for triggered migrations
func (r *MigrationPlanReconciler) processMigrationPhases(
ctx context.Context,
scope *scope.MigrationPlanScope,
migrationplan *vjailbreakv1alpha1.MigrationPlan,
migrationobjs *vjailbreakv1alpha1.MigrationList,
parallelvms []string,
) (*migrationPhaseOutcome, error) {
outcome := &migrationPhaseOutcome{AllFinished: true}
r.ctxlog.Info("Processing migration phases", "migrationplan", migrationplan.Name, "totalMigrations", len(migrationobjs.Items), "currentBatch", parallelvms)
for i := 0; i < len(migrationobjs.Items); i++ {
migration := migrationobjs.Items[i]
switch migration.Status.Phase {
case vjailbreakv1alpha1.VMMigrationPhaseFailed, vjailbreakv1alpha1.VMMigrationPhaseValidationFailed:
// Record and keep going. Returning here would abandon post-migration for
// every healthy VM in the plan and, because ReconcileMigrationPlanJob
// skips reconciliation for a PodFailed plan, park the plan permanently on
// the strength of one bad VM.
r.ctxlog.Info("Migration failed for VM", "vm", migration.Spec.VMName, "phase", migration.Status.Phase)
outcome.FailedVMs = append(outcome.FailedVMs, migration.Spec.VMName)
outcome.FailureSummaries = append(outcome.FailureSummaries,
fmt.Sprintf("%s (%s)", migration.Spec.VMName, firstConditionMessage(&migration)))
continue
case vjailbreakv1alpha1.VMMigrationPhaseDataCopied:
r.ctxlog.Info("Data-only migration completed for VM, skipping post-migration actions", "vm", migration.Spec.VMName, "migrationplan", migrationplan.Name)
outcome.FinishedVMs++
continue
case vjailbreakv1alpha1.VMMigrationPhaseSucceeded:
outcome.FinishedVMs++
if migration.Annotations != nil && migration.Annotations[constants.PostMigrationCompleteAnnotation] == constants.AnnotationValueTrue {
r.ctxlog.Info("Post-migration already completed for VM, skipping", "vm", migration.Spec.VMName)
continue
}
r.ctxlog.Info("Migration succeeded for VM, applying post-migration actions", "vm", migration.Spec.VMName, "migrationplan", migrationplan.Name)
vmKey := migration.Annotations[constants.OriginalVMNameAnnotation]
if vmKey == "" {
vmKey = migration.Labels[constants.MigrationVMKeyLabel] // backward compat: pre-fix CRs lacked annotation
}
if vmKey == "" {
vmKey = migration.Spec.VMName
}
err := r.reconcilePostMigration(ctx, scope, vmKey)
if err != nil {
r.ctxlog.Error(err, "Post-migration actions failed for VM", "vm", migration.Spec.VMName)
return nil, errors.Wrap(err, "failed post-migration")
}
migrationCopy := migration.DeepCopy()
if migrationCopy.Annotations == nil {
migrationCopy.Annotations = make(map[string]string)
}
migrationCopy.Annotations[constants.PostMigrationCompleteAnnotation] = constants.AnnotationValueTrue
if err := r.Update(ctx, migrationCopy); err != nil {
r.ctxlog.Error(err, "Failed to set post-migration complete annotation", "vm", migration.Spec.VMName)
}
r.ctxlog.Info("Post-migration actions completed for VM", "vm", migration.Spec.VMName, "migrationplan", migrationplan.Name)
continue
default:
r.ctxlog.Info("VM migration still in progress",
"vm", migration.Spec.VMName,
"phase", migration.Status.Phase,
"currentBatch", parallelvms)
outcome.AllFinished = false
}
}
return outcome, nil
}
// migrationPhaseOutcome summarises one pass over a plan's Migration objects.
type migrationPhaseOutcome struct {
// AllFinished is true when no migration is still in a non-terminal phase.
AllFinished bool
// FinishedVMs counts migrations that reached Succeeded or DataCopied.
FinishedVMs int
// FailedVMs names the migrations in Failed or ValidationFailed.
FailedVMs []string
// FailureSummaries pairs each failed VM with its reason, for the plan status
// message.
FailureSummaries []string
}
// firstConditionMessage returns a human-readable reason for a migration's current
// state, preferring the most recently transitioned condition. Guards against an
// empty Conditions slice, which would otherwise panic on Conditions[0].
func firstConditionMessage(migration *vjailbreakv1alpha1.Migration) string {
if len(migration.Status.Conditions) == 0 {
return string(migration.Status.Phase)
}
newest := migration.Status.Conditions[0]
for _, condition := range migration.Status.Conditions[1:] {
if condition.LastTransitionTime.After(newest.LastTransitionTime.Time) {
newest = condition
}
}
if newest.Message == "" {
return string(migration.Status.Phase)
}
return newest.Message
}
// handleRDMDiskMigrationError handles errors that occur during RDM disk migration
func (r *MigrationPlanReconciler) handleRDMDiskMigrationError(ctx context.Context, migrationplan *vjailbreakv1alpha1.MigrationPlan, err error) (ctrl.Result, error) {
if err == verrors.ErrRDMDiskNotMigrated {
delay := 25 * time.Second
r.ctxlog.Info("RDM disk not migrated yet, requeuing MigrationPlan for polling.", "requeueAfter", delay)
// Refetch the migration plan to get the latest version before updating
if err := r.Get(ctx, types.NamespacedName{Name: migrationplan.Name, Namespace: migrationplan.Namespace}, migrationplan); err != nil {
r.ctxlog.Error(err, "Failed to refetch MigrationPlan before updating status")
return ctrl.Result{RequeueAfter: delay}, nil
}
newMessage := "RDM disk not migrated yet, requeuing MigrationPlan."
if migrationplan.Status.MigrationMessage != newMessage || migrationplan.Status.MigrationStatus != corev1.PodPending {
if err := r.UpdateMigrationPlanStatus(ctx, migrationplan, corev1.PodPending, newMessage); err != nil {
r.ctxlog.Error(err, "Failed to update MigrationPlan status")
}
}
return ctrl.Result{RequeueAfter: delay}, nil
}
// Handle any other RDM disk migration errors
r.ctxlog.Info("RDM disk migration failed, failing MigrationPlan.", "error", err.Error())
migrationList := &vjailbreakv1alpha1.MigrationList{}
listOpts := []client.ListOption{
client.InNamespace(migrationplan.Namespace),
client.MatchingLabels{"migrationplan": migrationplan.Name},
}
if listErr := r.List(ctx, migrationList, listOpts...); listErr != nil {
r.ctxlog.Error(listErr, "Failed to list migrations for RDM disk failure handling", "migrationplan", migrationplan.Name)
} else {
message := fmt.Sprintf("RDM disk migration failed: %s", err)
for i := range migrationList.Items {
m := migrationList.Items[i]
if m.Status.Phase == vjailbreakv1alpha1.VMMigrationPhaseSucceeded ||
m.Status.Phase == vjailbreakv1alpha1.VMMigrationPhaseFailed ||
m.Status.Phase == vjailbreakv1alpha1.VMMigrationPhaseValidationFailed ||
m.Status.Phase == vjailbreakv1alpha1.VMMigrationPhaseDataCopied {
continue
}
r.markMigrationValidationFailed(ctx, &m, m.Spec.VMName, message)
}
}
// Refetch the migration plan to get the latest version before updating
if refetchErr := r.Get(ctx, types.NamespacedName{Name: migrationplan.Name, Namespace: migrationplan.Namespace}, migrationplan); refetchErr != nil {