forked from vmware-tanzu/vm-operator
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvolumebatch_controller.go
More file actions
1321 lines (1122 loc) · 44.7 KB
/
volumebatch_controller.go
File metadata and controls
1321 lines (1122 loc) · 44.7 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
// © Broadcom. All Rights Reserved.
// The term "Broadcom" refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package volumebatch
import (
"context"
"errors"
"fmt"
"slices"
"strings"
"github.com/go-logr/logr"
corev1 "k8s.io/api/core/v1"
storagev1 "k8s.io/api/storage/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/sets"
storagehelpers "k8s.io/component-helpers/storage/volume"
ctrl "sigs.k8s.io/controller-runtime"
"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/handler"
"sigs.k8s.io/controller-runtime/pkg/manager"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"sigs.k8s.io/controller-runtime/pkg/source"
cnsv1alpha1 "github.com/vmware-tanzu/vm-operator/external/vsphere-csi-driver/api/v1alpha1"
pkgerr "github.com/vmware-tanzu/vm-operator/pkg/errors"
"github.com/vmware-tanzu/vm-operator/pkg/util/ptr"
vmopv1 "github.com/vmware-tanzu/vm-operator/api/v1alpha5"
pkgcfg "github.com/vmware-tanzu/vm-operator/pkg/config"
pkgconst "github.com/vmware-tanzu/vm-operator/pkg/constants"
pkgctx "github.com/vmware-tanzu/vm-operator/pkg/context"
pkglog "github.com/vmware-tanzu/vm-operator/pkg/log"
"github.com/vmware-tanzu/vm-operator/pkg/patch"
"github.com/vmware-tanzu/vm-operator/pkg/providers"
"github.com/vmware-tanzu/vm-operator/pkg/providers/vsphere/constants"
"github.com/vmware-tanzu/vm-operator/pkg/record"
pkgutil "github.com/vmware-tanzu/vm-operator/pkg/util"
vmopv1util "github.com/vmware-tanzu/vm-operator/pkg/util/vmopv1"
)
const (
controllerName = "volumebatch"
// In BatchAttachment status, CSI hardcode a volume name entry with :detaching
// suffix if it's being detached. CSI only adds that after they have finished
// a CNS detach call, which could take up to minutes. So we still want to add
// that suffix ourselves as soon as a volume is removed from vm.spec.volumes.
//
// Note: The reason why we have this suffix is because there is a case that
// a volume's PVC was changed, that means we need to detach current vol,
// and attach another one. But since volume name is unique, and there is a
// chance that detaching can fail, so there might be some time we need to
// keep track of both old volume and new volume at the same time in vm status.
// Then we would need a distinct volume name for these two disks.
volumeNameDetachSuffix = ":detaching"
)
// AddToManager adds this package's controller to the provided manager.
func AddToManager(ctx *pkgctx.ControllerManagerContext, mgr manager.Manager) error {
var (
controllerNameShort = fmt.Sprintf("%s-controller", strings.ToLower(controllerName))
controllerNameLong = fmt.Sprintf("%s/%s/%s", ctx.Namespace, ctx.Name, controllerNameShort)
)
// Set up field index for CnsNodeVmAttachment by NodeUUID to efficiently query legacy attachments
if err := mgr.GetFieldIndexer().IndexField(
ctx,
&cnsv1alpha1.CnsNodeVmAttachment{},
"spec.nodeuuid",
func(rawObj client.Object) []string {
attachment := rawObj.(*cnsv1alpha1.CnsNodeVmAttachment)
return []string{attachment.Spec.NodeUUID}
}); err != nil {
return err
}
// Set up field index for VirtualMachine by ClaimName to efficiently query VMs
// referencing a PVC.
if err := mgr.GetFieldIndexer().IndexField(
ctx,
&vmopv1.VirtualMachine{},
"spec.volumes.persistentVolumeClaim.claimName",
func(rawObj client.Object) []string {
vm := rawObj.(*vmopv1.VirtualMachine)
pvcs := make([]string, 0, len(vm.Spec.Volumes))
for _, volume := range vm.Spec.Volumes {
if pvc := volume.PersistentVolumeClaim; pvc != nil && pvc.ClaimName != "" {
pvcs = append(pvcs, pvc.ClaimName)
}
}
return pvcs
}); err != nil {
return err
}
r := NewReconciler(
ctx,
mgr.GetClient(),
ctrl.Log.WithName("controllers").WithName("volumebatch"),
record.New(mgr.GetEventRecorderFor(controllerNameLong)),
ctx.VMProvider,
)
c, err := controller.New(controllerName, mgr, controller.Options{
Reconciler: r,
MaxConcurrentReconciles: ctx.MaxConcurrentReconciles,
LogConstructor: pkglog.ControllerLogConstructor(controllerNameShort, &vmopv1.VirtualMachine{}, mgr.GetScheme()),
})
if err != nil {
return err
}
if err := c.Watch(source.Kind(
mgr.GetCache(),
&vmopv1.VirtualMachine{},
&handler.TypedEnqueueRequestForObject[*vmopv1.VirtualMachine]{},
)); err != nil {
return fmt.Errorf("failed to start VirtualMachine watch: %w", err)
}
// Watch for changes to CnsNodeVMBatchAttachment, and enqueue a
// request to the owner VirtualMachine.
if err := c.Watch(source.Kind(
mgr.GetCache(),
&cnsv1alpha1.CnsNodeVMBatchAttachment{},
handler.TypedEnqueueRequestForOwner[*cnsv1alpha1.CnsNodeVMBatchAttachment](
mgr.GetScheme(),
mgr.GetRESTMapper(),
&vmopv1.VirtualMachine{},
handler.OnlyControllerOwner(),
),
)); err != nil {
return fmt.Errorf(
"failed to start VirtualMachine watch "+
"for CnsNodeVMBatchAttachment: %w", err)
}
if pkgcfg.FromContext(ctx).Features.AllDisksArePVCs {
// Watch for changes for CnsRegisterVolume, and enqueue
// VirtualMachine which is the owner of CnsRegisterVolume.
if err := c.Watch(source.Kind(
mgr.GetCache(),
&cnsv1alpha1.CnsRegisterVolume{},
handler.TypedEnqueueRequestForOwner[*cnsv1alpha1.CnsRegisterVolume](
mgr.GetScheme(),
mgr.GetRESTMapper(),
&vmopv1.VirtualMachine{},
handler.OnlyControllerOwner(),
),
)); err != nil {
return fmt.Errorf(
"failed to start VirtualMachine watch "+
"for CnsRegisterVolume: %w", err)
}
}
if pkgcfg.FromContext(ctx).Features.AllDisksArePVCs ||
pkgcfg.FromContext(ctx).Features.InstanceStorage {
// Watch for changes for PersistentVolumeClaim, and enqueue
// VirtualMachine which is the owner of PersistentVolumeClaim.
if err := c.Watch(source.Kind(
mgr.GetCache(),
&corev1.PersistentVolumeClaim{},
handler.TypedEnqueueRequestForOwner[*corev1.PersistentVolumeClaim](
mgr.GetScheme(),
mgr.GetRESTMapper(),
&vmopv1.VirtualMachine{},
),
)); err != nil {
return fmt.Errorf(
"failed to start VirtualMachine watch "+
"for PersistentVolumeClaim: %w", err)
}
// Watch for changes for PersistentVolumeClaim, and enqueue
// VirtualMachine that reference the PVC in their Spec.Volumes.
//
// TODO(BMV): This should cover every case that the above OwnerRef
// mapper does, and that can be removed later.
if err := c.Watch(source.Kind(
mgr.GetCache(),
&corev1.PersistentVolumeClaim{},
handler.TypedEnqueueRequestsFromMapFunc(
vmopv1util.PVCToVirtualMachineVolumeClaimNameMapper(ctx, r.Client)),
)); err != nil {
return fmt.Errorf(
"failed to start VirtualMachine claim names watch "+
"for PersistentVolumeClaim: %w", err)
}
}
return nil
}
func NewReconciler(
ctx context.Context,
client client.Client,
logger logr.Logger,
recorder record.Recorder,
vmProvider providers.VirtualMachineProviderInterface) *Reconciler {
return &Reconciler{
Context: ctx,
Client: client,
logger: logger,
recorder: recorder,
VMProvider: vmProvider,
}
}
var _ reconcile.Reconciler = &Reconciler{}
type Reconciler struct {
client.Client
Context context.Context
logger logr.Logger
recorder record.Recorder
VMProvider providers.VirtualMachineProviderInterface
}
// +kubebuilder:rbac:groups=vmoperator.vmware.com,resources=virtualmachines,verbs=get;list;watch;
// +kubebuilder:rbac:groups=vmoperator.vmware.com,resources=virtualmachines/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=cns.vmware.com,resources=cnsnodevmbatchattachments,verbs=create;delete;get;list;watch;patch;update
// +kubebuilder:rbac:groups=cns.vmware.com,resources=cnsnodevmbatchattachments/status,verbs=get;list
// +kubebuilder:rbac:groups=cns.vmware.com,resources=cnsnodevmattachments,verbs=delete;get;list;watch
// Reconcile reconciles a VirtualMachine object and processes the volumes for batch attachment.
func (r *Reconciler) Reconcile(ctx context.Context, request ctrl.Request) (_ ctrl.Result, reterr error) {
ctx = pkgcfg.JoinContext(ctx, r.Context)
vm := &vmopv1.VirtualMachine{}
if err := r.Get(ctx, request.NamespacedName, vm); err != nil {
return ctrl.Result{}, client.IgnoreNotFound(err)
}
volCtx := &pkgctx.VolumeContext{
Context: ctx,
Logger: pkglog.FromContextOrDefault(ctx),
VM: vm,
}
if metav1.HasAnnotation(vm.ObjectMeta, vmopv1.PauseAnnotation) {
volCtx.Logger.Info("Skipping reconciliation since VirtualMachine contains the pause annotation")
return ctrl.Result{}, nil
}
// If the VM has a pause reconcile label key, Skip volume reconciliation.
if val, ok := vm.Labels[vmopv1.PausedVMLabelKey]; ok {
volCtx.Logger.Info("Skipping reconciliation because a pause operation "+
"has been initiated on this VirtualMachine.",
"pausedBy", val)
return ctrl.Result{}, nil
}
patchHelper, err := patch.NewHelper(vm, r.Client)
if err != nil {
return ctrl.Result{}, fmt.Errorf("failed to init patch helper for %s: %w", volCtx, err)
}
defer func() {
if err := patchHelper.Patch(ctx, vm); err != nil {
if reterr == nil {
reterr = err
}
volCtx.Logger.Error(err, "patch failed")
}
}()
if !vm.DeletionTimestamp.IsZero() {
return ctrl.Result{}, r.ReconcileDelete(volCtx)
}
if err := r.ReconcileNormal(volCtx); err != nil {
return pkgerr.ResultFromError(err)
}
return vmopv1util.ShouldRequeueForInstanceStoragePVCs(ctx, volCtx.VM), nil
}
func errOrNoRequeueErr(err1, err2 error) error {
if err1 == nil {
return err2
}
if err2 == nil {
return err1
}
mergedErr := fmt.Errorf("%w, %w", err1, err2)
if pkgerr.IsNoRequeueError(err1) && pkgerr.IsNoRequeueError(err2) {
return pkgerr.NoRequeueError{
Message: mergedErr.Error(),
DoNotErr: pkgerr.IsNoRequeueNoError(err1) &&
pkgerr.IsNoRequeueNoError(err2),
}
}
return mergedErr
}
func (r *Reconciler) ReconcileNormal(ctx *pkgctx.VolumeContext) error {
ctx.Logger.Info("Reconciling VirtualMachine for batch volume processing")
defer func() {
ctx.Logger.Info("Finished Reconciling VirtualMachine for batch volume processing")
}()
// Reconcile instance storage volumes if configured
if pkgcfg.FromContext(ctx).Features.InstanceStorage &&
vmopv1util.IsInstanceStoragePresent(ctx.VM) {
ready, err := vmopv1util.ReconcileInstanceStoragePVCs(ctx, r.Client, r.Client, r.recorder)
if err != nil || !ready {
return err
}
}
if ctx.VM.Status.InstanceUUID == "" {
// CSI requires the InstanceUUID to match up the batch
// attachment request with the VM.
if len(ctx.VM.Spec.Volumes) != 0 {
ctx.Logger.Info("VM Status does not yet have InstanceUUID. Deferring volume attachment")
}
return nil
}
if ctx.VM.Status.BiosUUID == "" {
// CSI requires the BiosUUID to match up the legacy attachment
// request with the VM.
if len(ctx.VM.Spec.Volumes) != 0 {
ctx.Logger.Info("VM Status does not yet have BiosUUID. Deferring volume attachment")
}
return nil
}
legacyAttachments, err := pkgutil.GetCnsNodeVMAttachmentsForVM(ctx, r.Client, ctx.VM)
if err != nil {
return fmt.Errorf(
"error getting existing CnsNodeVmAttachments for VM: %w", err)
}
// Get legacy CnsNodeVmAttachments for this VM. We need to handle
// detachments via this resource for the brownfield VMs.
attachmentsToDelete := r.attachmentsToDelete(ctx, legacyAttachments)
// Delete attachments for this VM that exist but are not currently referenced in the Spec.
deleteErr := r.deleteOrphanedAttachments(ctx, attachmentsToDelete)
if deleteErr != nil {
ctx.Logger.Error(deleteErr, "Error deleting orphaned CnsNodeVmAttachments")
// Keep going to the create/update processing below.
//
// This is the to maintain the behavior of the existing
// volume controller. In batch processing, we will skip
// any volume that has a corresponding attachment, so we
// should not land in a situation where the attachment is
// tracked by both legacy and batch methods.
}
// Get existing VM managed volumes status. Since we only update managed
// volumes here, we skip all classic volumes.
existingVMManagedVolStatus := map[string]vmopv1.VirtualMachineVolumeStatus{}
for _, vol := range ctx.VM.Status.Volumes {
if vol.Type != vmopv1.VolumeTypeClassic {
existingVMManagedVolStatus[vol.Name] = vol
}
}
volumeSpecsForBatch, volumeSpecsForLegacy := categorizeVolumeSpecs(ctx, legacyAttachments)
// Get existing batch attachment for this VM.
batchAttachment, err := r.getBatchAttachmentForVM(ctx)
if err != nil {
return fmt.Errorf("error getting existing CnsNodeVMBatchAttachment for VM: %w", err)
}
// Only need to validate the hardware for once during the first time of
// creating the batchAttachment.
if batchAttachment == nil && len(volumeSpecsForBatch) > 0 {
if err := r.validateHardwareVersion(ctx); err != nil {
return fmt.Errorf("hardware version validation failed: %w", err)
}
}
// Process volumes and create/update batch attachment.
// filter Volume spec that doesn't cause error and return them
// for constructing the VM's volumeStatus.
filteredVolumeSpecsForBatch, processErr :=
r.processBatchAttachmentAndFilterVolumeSpecs(
ctx,
volumeSpecsForBatch,
batchAttachment,
)
if processErr != nil {
ctx.Logger.Error(processErr, "Error processing CnsNodeVMBatchAttachments")
// Keep going to return aggregated error below.
}
// Record the volumes currently in status so we can log what's removed.
beforeStatusVolumes := make(map[string]string, len(ctx.VM.Spec.Volumes))
for _, vol := range ctx.VM.Status.Volumes {
if vol.Type == vmopv1.VolumeTypeManaged {
name := strings.TrimSuffix(vol.Name, volumeNameDetachSuffix)
beforeStatusVolumes[name] = vol.DiskUUID
}
}
volumeStatusesForBatch := r.getVMVolStatusesFromBatchAttachment(
ctx,
batchAttachment,
filteredVolumeSpecsForBatch,
existingVMManagedVolStatus,
)
volumeStatusesForLegacy := r.getVMVolStatusesFromLegacyAttachments(
ctx,
legacyAttachments,
attachmentsToDelete,
existingVMManagedVolStatus,
volumeSpecsForLegacy,
)
updateVMVolumeStatus(
ctx,
volumeStatusesForBatch,
volumeStatusesForLegacy,
)
if len(beforeStatusVolumes) > 0 {
for _, vol := range ctx.VM.Status.Volumes {
if vol.Type != vmopv1.VolumeTypeManaged {
continue
}
name := strings.TrimSuffix(vol.Name, volumeNameDetachSuffix)
// Might not know the UUID before being attached, but also the volume
// spec can be updated with a different PVC. Remove entries with an
// empty UUID but we could just do this by name, with the potential
// for missing actual removals.
uuid, ok := beforeStatusVolumes[name]
if ok && (uuid == "" || uuid == vol.DiskUUID) {
delete(beforeStatusVolumes, name)
}
}
if len(beforeStatusVolumes) > 0 {
ctx.Logger.Info("Removing detached volumes from VM Status",
"removedCount", len(beforeStatusVolumes),
"removedVolumes", beforeStatusVolumes)
}
}
return errOrNoRequeueErr(deleteErr, processErr)
}
// getBatchAttachmentForVM returns the CnsNodeVMBatchAttachment resource for the
// VM. We assume that the name of the resource matches the name of the VM.
// Returns nil if no CNSNodeVMBatchAttachment resource exists for the VM.
func (r *Reconciler) getBatchAttachmentForVM(
ctx *pkgctx.VolumeContext,
) (*cnsv1alpha1.CnsNodeVMBatchAttachment, error) {
attachment := &cnsv1alpha1.CnsNodeVMBatchAttachment{}
if err := r.Client.Get(ctx, client.ObjectKey{
Name: pkgutil.CNSBatchAttachmentNameForVM(ctx.VM.Name),
Namespace: ctx.VM.Namespace,
}, attachment); err != nil {
if !apierrors.IsNotFound(err) {
return nil, fmt.Errorf("failed to find CnsNodeVMBatchAttachment: %w", err)
}
return nil, nil
}
// Ensure that the attachment is owned by the VM.
if !metav1.IsControlledBy(attachment, ctx.VM) {
return nil, fmt.Errorf("CnsNodeVMBatchAttachment %s has a different controlling owner",
attachment.Name)
}
return attachment, nil
}
// processBatchAttachmentAndFilterVolumeSpecs processes the batch attachment and returns the
// volume specs constructed for the batch attachment.
func (r *Reconciler) processBatchAttachmentAndFilterVolumeSpecs(
ctx *pkgctx.VolumeContext,
vmVolumeSpecsForBatch []vmopv1.VirtualMachineVolume,
batchAttachment *cnsv1alpha1.CnsNodeVMBatchAttachment,
) ([]cnsv1alpha1.VolumeSpec, error) {
var (
toBeBuiltPvcVols = make([]vmopv1.VirtualMachineVolume, 0)
existingVolVolKey = sets.New[string]()
toAddVolVolKey = sets.New[string]()
retErr error
)
// Record the 'volumeName:pvcName' pair in existing batchAttachment spec.
// So we could tell whether we need to verify the PVC of it.
if batchAttachment != nil {
for _, vol := range batchAttachment.Spec.Volumes {
existingVolVolKey.Insert(vol.Name + ":" + vol.PersistentVolumeClaim.ClaimName)
}
}
for _, vol := range vmVolumeSpecsForBatch {
if vol.PersistentVolumeClaim == nil {
ctx.Logger.V(4).Info("PVC not set for Volume", "volName", vol.Name)
continue
}
// If volumes are already added to batchAttachment, no need to
// handlePVCWithWFFC or check boundness.
key := vol.Name + ":" + vol.PersistentVolumeClaim.ClaimName
if existingVolVolKey.Has(key) {
existingVolVolKey.Delete(key)
toBeBuiltPvcVols = append(toBeBuiltPvcVols, vol)
continue
}
pvc, err := r.getPVC(ctx, vol.PersistentVolumeClaim.ClaimName)
if err != nil {
retErr = errOrNoRequeueErr(retErr,
fmt.Errorf("failed to get PVC %s for volume %s: %w",
vol.PersistentVolumeClaim.ClaimName, vol.Name, err))
continue
}
// Handle PVC with WFFC first since it handles PVCS that are unbound.
if err := r.handlePVCWithWFFC(ctx, vol, pvc); err != nil {
retErr = errOrNoRequeueErr(retErr,
fmt.Errorf("failed to handle PVC %s with WFFC for volume %s: %w",
pvc.Name, vol.Name, err))
continue
}
// Ignore pvcs that are not bound.
if pvc.Status.Phase != corev1.ClaimBound {
ctx.Logger.V(4).Info("PVC is not bound",
"pvcName", pvc.Name,
"volName", vol.Name,
"phase", pvc.Status.Phase)
continue
}
toAddVolVolKey.Insert(key)
toBeBuiltPvcVols = append(toBeBuiltPvcVols, vol)
}
// Remaining existing batch keys are no longer referenced in the
// VM spec so they are going to be removed.
toRemovePvcVolVolKey := existingVolVolKey
volumeSpecs, err := r.buildVolumeSpecs(toBeBuiltPvcVols, ctx.VM.Status.Hardware)
if err != nil {
retErr = errOrNoRequeueErr(retErr, err)
}
// Create or update batch attachment.
if err := r.createOrUpdateBatchAttachment(ctx, volumeSpecs); err != nil {
retErr = errOrNoRequeueErr(retErr, err)
} else if toAddVolVolKey.Len() > 0 || toRemovePvcVolVolKey.Len() > 0 {
ctx.Logger.Info(
"Added/removed volumes to CnsNodeVMBatchAttachment",
"addedCount", len(toAddVolVolKey),
"addedVolumes", toAddVolVolKey.UnsortedList(),
"removedCount", len(toRemovePvcVolVolKey),
"removedVolumes", toRemovePvcVolVolKey.UnsortedList())
}
return volumeSpecs, retErr
}
func (r *Reconciler) getPVC(
ctx *pkgctx.VolumeContext,
pvcName string,
) (corev1.PersistentVolumeClaim, error) {
pvc := corev1.PersistentVolumeClaim{}
pvcKey := client.ObjectKey{
Namespace: ctx.VM.Namespace,
Name: pvcName,
}
if err := r.Get(ctx, pvcKey, &pvc); err != nil {
return pvc, fmt.Errorf("cannot get PVC: %w", err)
}
return pvc, nil
}
// createOrUpdateBatchAttachment handles the creation or update of
// CnsNodeVMBatchAttachment.
func (r *Reconciler) createOrUpdateBatchAttachment(
ctx *pkgctx.VolumeContext,
volumeSpecs []cnsv1alpha1.VolumeSpec) error {
// Validate the volume specs before attempting to create/update
if err := r.validateVolumeSpecs(ctx, volumeSpecs); err != nil {
return fmt.Errorf("volume spec validation failed: %w", err)
}
// TODO (OracleRAC): workaround when batchAttachment.spec.volumeSpec is not
// empty. Will remove this once CSI has updated their API.
if volumeSpecs == nil {
volumeSpecs = make([]cnsv1alpha1.VolumeSpec, 0)
}
vm := ctx.VM
attachmentName := pkgutil.CNSBatchAttachmentNameForVM(vm.Name)
batchAttachment := &cnsv1alpha1.CnsNodeVMBatchAttachment{
ObjectMeta: metav1.ObjectMeta{
Name: attachmentName,
Namespace: vm.Namespace,
},
}
operationResult, err := controllerutil.CreateOrPatch(
ctx,
r.Client,
batchAttachment,
func() error {
if err := controllerutil.SetControllerReference(
vm, batchAttachment, r.Client.Scheme(),
); err != nil {
return fmt.Errorf("failed to set controller reference "+
"on CnsNodeVMBatchAttachment: %w", err)
}
// Update the Spec with the desired volumeSpecs
batchAttachment.Spec = cnsv1alpha1.CnsNodeVMBatchAttachmentSpec{
InstanceUUID: vm.Status.InstanceUUID,
Volumes: volumeSpecs,
}
return nil
})
if err != nil {
return fmt.Errorf("failed to create or patch CnsNodeVMBatchAttachment %s: %w",
attachmentName, err)
}
switch operationResult {
case controllerutil.OperationResultCreated:
ctx.Logger.Info("Created CnsNodeVMBatchAttachment",
"attachment", attachmentName)
case controllerutil.OperationResultUpdated:
ctx.Logger.Info("Updated CnsNodeVMBatchAttachment",
"attachment", attachmentName)
}
return nil
}
// buildVolumeSpecs builds a volume spec that will be used to create
// the CnsNodeVMBatchAttachment object.
func (r *Reconciler) buildVolumeSpecs(
volumes []vmopv1.VirtualMachineVolume,
hardware *vmopv1.VirtualMachineHardwareStatus,
) ([]cnsv1alpha1.VolumeSpec, error) {
// Return nil and wait for next reconcile when the status is updated if
// hardware is nil Or noops when there is no volumes to be attached.
if hardware == nil || len(volumes) == 0 {
return nil, nil
}
var (
buildErrMsg = "failed to build volume specs:"
volumeSpecs = make([]cnsv1alpha1.VolumeSpec, 0, len(volumes))
ctrlDevKeyMap = make(map[pkgutil.ControllerID]int32)
)
for _, ctrlStatus := range hardware.Controllers {
ctrlDevKeyMap[pkgutil.ControllerID{
ControllerType: ctrlStatus.Type,
BusNumber: ctrlStatus.BusNumber,
}] = ctrlStatus.DeviceKey
}
for _, vol := range volumes {
// The validating webhook should have verified it already.
// It returns NoRequeueError because we do not want to keep reconciling
// volume with incorrect spec unless the spec is fixed.
if vol.ControllerBusNumber == nil {
return nil, pkgerr.NoRequeueError{Message: fmt.Sprintf(
"%s volume %q is missing controller bus number", buildErrMsg, vol.Name)}
}
ctrlDevKey, ok := ctrlDevKeyMap[pkgutil.ControllerID{
ControllerType: vol.ControllerType,
BusNumber: *vol.ControllerBusNumber,
}]
if !ok {
return nil, pkgerr.NoRequeueError{Message: fmt.Sprintf(
"%s waiting for the device controller %q %q to be created for volume %q",
buildErrMsg, vol.ControllerType, *vol.ControllerBusNumber, vol.Name)}
}
// Map VM volume spec to CNS batch attachment spec
cnsVolumeSpec := cnsv1alpha1.VolumeSpec{
Name: vol.Name,
PersistentVolumeClaim: cnsv1alpha1.PersistentVolumeClaimSpec{
ClaimName: vol.PersistentVolumeClaim.ClaimName,
ControllerKey: ptr.To(ctrlDevKey),
},
}
if vol.UnitNumber != nil {
cnsVolumeSpec.PersistentVolumeClaim.UnitNumber = vol.UnitNumber
}
// Apply application type presets first
// Ideally, this would already have been mutated by the webhook, but just handle that here anyway.
if err := r.applyApplicationTypePresets(&vol, &cnsVolumeSpec); err != nil {
return nil, pkgerr.NoRequeueError{Message: fmt.Errorf(
"%s failed to apply application type presets for volume %s: %w",
buildErrMsg, vol.Name, err).Error()}
}
// Map disk mode (can override application type presets)
diskMode, err := pkgutil.GetCnsDiskModeFromDiskMode(vol.DiskMode)
if err != nil {
return nil, pkgerr.NoRequeueError{Message: fmt.Errorf(
"%s failed to get CNS disk mode for volume %s: %w",
buildErrMsg, vol.Name, err).Error()}
}
cnsVolumeSpec.PersistentVolumeClaim.DiskMode = diskMode
// Map sharing mode (can override application type presets)
sharingMode, err := pkgutil.GetCnsSharingModeFromSharingMode(vol.SharingMode)
if err != nil {
return nil, pkgerr.NoRequeueError{Message: fmt.Errorf(
"%s failed to get CNS sharing mode for volume %s: %w",
buildErrMsg, vol.Name, err).Error()}
}
cnsVolumeSpec.PersistentVolumeClaim.SharingMode = sharingMode
volumeSpecs = append(volumeSpecs, cnsVolumeSpec)
}
return volumeSpecs, nil
}
func (r *Reconciler) applyApplicationTypePresets(
vol *vmopv1.VirtualMachineVolume,
cnsSpec *cnsv1alpha1.VolumeSpec) error {
switch vol.ApplicationType {
case vmopv1.VolumeApplicationTypeOracleRAC:
// OracleRAC preset: diskMode=IndependentPersistent, sharingMode=MultiWriter
cnsSpec.PersistentVolumeClaim.DiskMode = cnsv1alpha1.IndependentPersistent
cnsSpec.PersistentVolumeClaim.SharingMode = cnsv1alpha1.SharingMultiWriter
case vmopv1.VolumeApplicationTypeMicrosoftWSFC:
// MicrosoftWSFC preset: diskMode=IndependentPersistent
// Note: Controller sharing mode requirements will be handled by CNS controller
cnsSpec.PersistentVolumeClaim.DiskMode = cnsv1alpha1.IndependentPersistent
case "":
// No application type specified, use defaults
break
default:
return fmt.Errorf("unsupported application type: %s", vol.ApplicationType)
}
return nil
}
// getVMVolStatusesFromBatchAttachment filters vm managed volumes status with
// data extracted from existingBatchAttachment.status.volumeStatus and volumeSpecs
// and return it.
// If there is existing volume status in batchAttachment.status and volume's PVC hasn't been
// changed, then just construct a detailed vmVolStatus using those info.
// Otherwise just add a basic status.
func (r *Reconciler) getVMVolStatusesFromBatchAttachment(
ctx *pkgctx.VolumeContext,
existingAttachment *cnsv1alpha1.CnsNodeVMBatchAttachment,
volumeSpecs []cnsv1alpha1.VolumeSpec,
existingVMManagedVolStatus map[string]vmopv1.VirtualMachineVolumeStatus,
) []vmopv1.VirtualMachineVolumeStatus {
// Update VM.Status.Volumes based on the batch attachment status
volumeStatuses := make([]vmopv1.VirtualMachineVolumeStatus, 0, len(ctx.VM.Status.Volumes))
existingAttachVolStatus := make(map[string]cnsv1alpha1.VolumeStatus)
if existingAttachment != nil {
for _, volStatus := range existingAttachment.Status.VolumeStatus {
existingAttachVolStatus[volStatus.Name] = volStatus
}
}
// Get the mapping of controller key to controller type and bus number.
// Because cnsv1alpha1.VolumeSpec only has controller key.
ctrlDevKeyMap := make(map[int32]pkgutil.ControllerID)
for _, ctrlStatus := range ctx.VM.Status.Hardware.Controllers {
ctrlDevKeyMap[ctrlStatus.DeviceKey] = pkgutil.ControllerID{
ControllerType: ctrlStatus.Type,
BusNumber: ctrlStatus.BusNumber,
}
}
// Target IDs of the classic disks in VM volume status.
existingClassicDiskTargetIDs := sets.New[string]()
for _, volStatus := range ctx.VM.Status.Volumes {
if volStatus.Type == vmopv1.VolumeTypeClassic {
existingClassicDiskTargetIDs.Insert(vmopv1util.GetTargetID(volStatus))
}
}
for _, volSpec := range volumeSpecs {
if controllerKey := volSpec.PersistentVolumeClaim.ControllerKey; controllerKey != nil {
controllerID := ctrlDevKeyMap[*controllerKey]
volControllerInfo := vmopv1.VirtualMachineVolumeStatus{
ControllerType: controllerID.ControllerType,
ControllerBusNumber: ptr.To(controllerID.BusNumber),
UnitNumber: volSpec.PersistentVolumeClaim.UnitNumber,
}
if existingClassicDiskTargetIDs.Has(vmopv1util.GetTargetID(volControllerInfo)) {
ctx.Logger.V(4).Info("current volume exists in vm status as a Classic disk, skip adding new entry",
"targetID", vmopv1util.GetTargetID(volControllerInfo),
"name", volSpec.Name)
continue
}
}
// By default just add a basic status.
vmVolStatus := vmopv1.VirtualMachineVolumeStatus{
Name: volSpec.Name,
Type: vmopv1.VolumeTypeManaged,
}
// If the batchAttachment.status already has this volume, and its
// PVC hasn't been changed, get its detailed info from vm.status.vol
// and batchAttachment.status.vol.
if attachVolStatus, ok := existingAttachVolStatus[volSpec.Name]; ok &&
volSpec.PersistentVolumeClaim.ClaimName == attachVolStatus.PersistentVolumeClaim.ClaimName {
vmVolStatus = attachmentStatusToVolumeStatus(volSpec.Name, attachVolStatus)
updateVolumeStatusWithExistingVMStatus(&vmVolStatus, existingVMManagedVolStatus)
// Add PVC capacity information
if err := r.updateVolumeStatusWithPVCInfo(
ctx,
attachVolStatus.PersistentVolumeClaim.ClaimName,
&vmVolStatus); err != nil {
ctx.Logger.Error(err, "failed to get volume status limit")
}
}
volumeStatuses = append(volumeStatuses, vmVolStatus)
}
volumeStatuses = append(volumeStatuses,
getVolumeStatusWithDetachingVolumeFromBatchAttachment(
existingAttachVolStatus,
volumeSpecs,
)...,
)
return volumeStatuses
}
func (r *Reconciler) updateVolumeStatusWithPVCInfo(
ctx *pkgctx.VolumeContext,
pvcName string, status *vmopv1.VirtualMachineVolumeStatus) error {
pvc := &corev1.PersistentVolumeClaim{}
pvcKey := client.ObjectKey{
Namespace: ctx.VM.Namespace,
Name: pvcName,
}
if err := r.Get(ctx, pvcKey, pvc); err != nil {
return err
}
if v, ok := pvc.Spec.Resources.Requests[corev1.ResourceStorage]; ok {
// Use the request if it exists.
status.Requested = &v
}
if v, ok := pvc.Spec.Resources.Limits[corev1.ResourceStorage]; ok {
// Use the limit if it exists.
status.Limit = &v
} else {
// Otherwise use the requested capacity.
status.Limit = status.Requested
}
return nil
}
func (r *Reconciler) ReconcileDelete(_ *pkgctx.VolumeContext) error {
// Do nothing here since we depend on the Garbage Collector to do the
// deletion of the dependent CNSNodeVMBatchAttachment objects when their
// owning VM is deleted.
// We require the Volume provider to handle the situation where the VM is
// deleted before the volumes are detached & removed.
return nil
}
// handlePVCWithWFFC handles PVCs with WaitForFirstConsumer binding mode.
// This ensures proper node selection for storage classes requiring it.
func (r *Reconciler) handlePVCWithWFFC(
ctx *pkgctx.VolumeContext,
volume vmopv1.VirtualMachineVolume,
pvc corev1.PersistentVolumeClaim,
) error {
if volume.PersistentVolumeClaim.InstanceVolumeClaim != nil {
return nil
}
if pvc.Status.Phase == corev1.ClaimBound {
// Regardless of the StorageClass binding mode there is nothing to done if already bound.
return nil
}
if pvc.Annotations[storagehelpers.AnnSelectedNode] != "" {
// Once set, this annotation cannot really be changed so just keep going.
return nil
}
scName := pvc.Spec.StorageClassName
if scName == nil {
return errors.New("PVC does not have StorageClassName set")
} else if *scName == "" {
return nil
}
sc := &storagev1.StorageClass{}
if err := r.Get(ctx, client.ObjectKey{Name: *scName}, sc); err != nil {
return fmt.Errorf("cannot get StorageClass: %w", err)
}
if mode := sc.VolumeBindingMode; mode == nil ||
*mode != storagev1.VolumeBindingWaitForFirstConsumer {
return nil
}
if !pkgcfg.FromContext(ctx).Features.VMWaitForFirstConsumerPVC {
return errors.New("PVC with WFFC storage class support is not enabled")
}
zoneName := ctx.VM.Status.Zone
if zoneName == "" {
// Fallback to the label value if Status hasn't been updated yet.
zoneName = ctx.VM.Labels[corev1.LabelTopologyZone]
if zoneName == "" {
return errors.New("VM does not have Zone set")
}
}
if pvc.Annotations == nil {
pvc.Annotations = map[string]string{}
}
pvc.Annotations[constants.CNSSelectedNodeIsZoneAnnotationKey] = "true"
pvc.Annotations[storagehelpers.AnnSelectedNode] = zoneName
if err := r.Client.Update(ctx, &pvc); err != nil {
return fmt.Errorf("cannot update PVC to add selected-node annotation: %w", err)
}
return nil
}
// validateHardwareVersion validates that the VM hardware version supports requested features.
// This ensures compatibility between VM hardware version and volume features.
func (r *Reconciler) validateHardwareVersion(ctx *pkgctx.VolumeContext) error {
hardwareVersion, err := r.VMProvider.GetVirtualMachineHardwareVersion(ctx, ctx.VM)
if err != nil {
return fmt.Errorf("failed to get VM hardware version: %w", err)
}
// If hardware version is 0, which means we failed to parse the version
// from VM, then just assume that it is above minimal requirement.
if hardwareVersion.IsValid() && hardwareVersion < pkgconst.MinSupportedHWVersionForPVC {
retErr := fmt.Errorf("vm has an unsupported "+
"hardware version %d for PersistentVolumes. "+
"Minimum supported hardware version %d",
hardwareVersion, pkgconst.MinSupportedHWVersionForPVC)
r.recorder.EmitEvent(ctx.VM, "VolumeAttachment", retErr, true)
return retErr
}
return nil
}