-
Notifications
You must be signed in to change notification settings - Fork 173
/
controller.go
1587 lines (1508 loc) · 69.7 KB
/
controller.go
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 2019 The Kubernetes Authors.
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 wcpguest
import (
"fmt"
"net/http"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/container-storage-interface/spec/lib/go/csi"
"github.com/davecgh/go-spew/spew"
"github.com/fsnotify/fsnotify"
snapshotterClientSet "github.com/kubernetes-csi/external-snapshotter/client/v4/clientset/versioned"
"github.com/prometheus/client_golang/prometheus/promhttp"
vmoperatortypes "github.com/vmware-tanzu/vm-operator-api/api/v1alpha1"
"golang.org/x/net/context"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/timestamppb"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/watch"
clientset "k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/cache"
"sigs.k8s.io/controller-runtime/pkg/client"
cnsoperatorv1alpha1 "sigs.k8s.io/vsphere-csi-driver/v2/pkg/apis/cnsoperator"
cnsfileaccessconfigv1alpha1 "sigs.k8s.io/vsphere-csi-driver/v2/pkg/apis/cnsoperator/cnsfileaccessconfig/v1alpha1"
cnsconfig "sigs.k8s.io/vsphere-csi-driver/v2/pkg/common/config"
csifault "sigs.k8s.io/vsphere-csi-driver/v2/pkg/common/fault"
"sigs.k8s.io/vsphere-csi-driver/v2/pkg/common/prometheus"
"sigs.k8s.io/vsphere-csi-driver/v2/pkg/csi/service/common"
"sigs.k8s.io/vsphere-csi-driver/v2/pkg/csi/service/common/commonco"
"sigs.k8s.io/vsphere-csi-driver/v2/pkg/csi/service/logger"
csitypes "sigs.k8s.io/vsphere-csi-driver/v2/pkg/csi/types"
k8s "sigs.k8s.io/vsphere-csi-driver/v2/pkg/kubernetes"
)
var (
// controllerCaps represents the capability of controller service
controllerCaps = []csi.ControllerServiceCapability_RPC_Type{
csi.ControllerServiceCapability_RPC_CREATE_DELETE_VOLUME,
csi.ControllerServiceCapability_RPC_PUBLISH_UNPUBLISH_VOLUME,
csi.ControllerServiceCapability_RPC_EXPAND_VOLUME,
}
)
type controller struct {
supervisorClient clientset.Interface
supervisorSnapshotterClient snapshotterClientSet.Interface
restClientConfig *rest.Config
vmOperatorClient client.Client
cnsOperatorClient client.Client
vmWatcher *cache.ListWatch
supervisorNamespace string
tanzukubernetesClusterUID string
}
// New creates a CNS controller
func New() csitypes.CnsController {
return &controller{}
}
// Init is initializing controller struct
func (c *controller) Init(config *cnsconfig.Config, version string) error {
ctx, log := logger.GetNewContextWithLogger()
log.Infof("Initializing WCPGC CSI controller")
var err error
// connect to the CSI controller in supervisor cluster
c.supervisorNamespace, err = cnsconfig.GetSupervisorNamespace(ctx)
if err != nil {
return err
}
c.tanzukubernetesClusterUID = config.GC.TanzuKubernetesClusterUID
c.restClientConfig = k8s.GetRestClientConfigForSupervisor(ctx, config.GC.Endpoint, config.GC.Port)
c.supervisorClient, err = k8s.NewSupervisorClient(ctx, c.restClientConfig)
if err != nil {
log.Errorf("failed to create supervisorClient. Error: %+v", err)
return err
}
c.supervisorSnapshotterClient, err = k8s.NewSupervisorSnapshotClient(ctx, c.restClientConfig)
if err != nil {
log.Errorf("failed to create supervisorSnapshotterClient. Error: %+v", err)
return err
}
c.vmOperatorClient, err = k8s.NewClientForGroup(ctx, c.restClientConfig, vmoperatortypes.GroupName)
if err != nil {
log.Errorf("failed to create vmOperatorClient. Error: %+v", err)
return err
}
c.cnsOperatorClient, err = k8s.NewClientForGroup(ctx, c.restClientConfig, cnsoperatorv1alpha1.GroupName)
if err != nil {
log.Errorf("failed to create cnsOperatorClient. Error: %+v", err)
return err
}
c.vmWatcher, err = k8s.NewVirtualMachineWatcher(ctx, c.restClientConfig, c.supervisorNamespace)
if err != nil {
log.Errorf("failed to create vmWatcher. Error: %+v", err)
return err
}
pvcsiConfigPath := common.GetConfigPath(ctx)
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Errorf("failed to create fsnotify watcher. err=%v", err)
return err
}
go func() {
for {
log.Debugf("Waiting for event on fsnotify watcher")
select {
case event, ok := <-watcher.Events:
if !ok {
return
}
log.Debugf("fsnotify event: %q", event.String())
if event.Op&fsnotify.Remove == fsnotify.Remove {
for {
reloadConfigErr := c.ReloadConfiguration()
if reloadConfigErr == nil {
log.Infof("Successfully reloaded configuration from: %q", pvcsiConfigPath)
break
}
log.Errorf("failed to reload configuration. will retry again in 5 seconds. err: %+v", reloadConfigErr)
time.Sleep(5 * time.Second)
}
}
case err, ok := <-watcher.Errors:
if !ok {
return
}
log.Errorf("fsnotify error: %+v", err)
}
log.Debugf("fsnotify event processed")
}
}()
cfgDirPath := filepath.Dir(pvcsiConfigPath)
log.Infof("Adding watch on path: %q", cfgDirPath)
err = watcher.Add(cfgDirPath)
if err != nil {
log.Errorf("failed to watch on path: %q. err=%v", cfgDirPath, err)
return err
}
log.Infof("Adding watch on path: %q", cnsconfig.DefaultpvCSIProviderPath)
err = watcher.Add(cnsconfig.DefaultpvCSIProviderPath)
if err != nil {
log.Errorf("failed to watch on path: %q. err=%v", cnsconfig.DefaultpvCSIProviderPath, err)
return err
}
// Go module to keep the metrics http server running all the time.
go func() {
prometheus.CsiInfo.WithLabelValues(version).Set(1)
for {
log.Info("Starting the http server to expose Prometheus metrics..")
http.Handle("/metrics", promhttp.Handler())
err = http.ListenAndServe(":2112", nil)
if err != nil {
log.Warnf("Http server that exposes the Prometheus exited with err: %+v", err)
}
log.Info("Restarting http server to expose Prometheus metrics..")
}
}()
return nil
}
// ReloadConfiguration reloads configuration from the secret, and reset restClientConfig, supervisorClient
// and re-create vmOperatorClient using new config
func (c *controller) ReloadConfiguration() error {
ctx, log := logger.GetNewContextWithLogger()
log.Info("Reloading Configuration")
cfg, err := common.GetConfig(ctx)
if err != nil {
log.Errorf("failed to read config. Error: %+v", err)
return err
}
if cfg != nil {
c.restClientConfig = k8s.GetRestClientConfigForSupervisor(ctx, cfg.GC.Endpoint, cfg.GC.Port)
c.supervisorClient, err = k8s.NewSupervisorClient(ctx, c.restClientConfig)
if err != nil {
log.Errorf("failed to create supervisorClient. Error: %+v", err)
return err
}
c.supervisorSnapshotterClient, err = k8s.NewSupervisorSnapshotClient(ctx, c.restClientConfig)
if err != nil {
log.Errorf("failed to create supervisorSnapshotterClient. Error: %+v", err)
return err
}
log.Infof("successfully re-created supervisorClient using updated configuration")
c.vmOperatorClient, err = k8s.NewClientForGroup(ctx, c.restClientConfig, vmoperatortypes.GroupName)
if err != nil {
log.Errorf("failed to create vmOperatorClient. Error: %+v", err)
return err
}
c.vmWatcher, err = k8s.NewVirtualMachineWatcher(ctx, c.restClientConfig, c.supervisorNamespace)
if err != nil {
log.Errorf("failed to create vmWatcher. Error: %+v", err)
return err
}
log.Infof("successfully re-created vmOperatorClient using updated configuration")
c.cnsOperatorClient, err = k8s.NewClientForGroup(ctx, c.restClientConfig, cnsoperatorv1alpha1.GroupName)
if err != nil {
log.Errorf("failed to create cnsOperatorClient. Error: %+v", err)
return err
}
}
return nil
}
// CreateVolume is creating CNS Volume using volume request specified
// in CreateVolumeRequest
func (c *controller) CreateVolume(ctx context.Context, req *csi.CreateVolumeRequest) (
*csi.CreateVolumeResponse, error) {
start := time.Now()
ctx = logger.NewContextWithLogger(ctx)
log := logger.GetLogger(ctx)
volumeType := prometheus.PrometheusUnknownVolumeType
createVolumeInternal := func() (
*csi.CreateVolumeResponse, string, error) {
log.Infof("CreateVolume: called with args %+v", *req)
//TODO: If the err is returned by invoking CNS API, then faultType should be
// populated by the underlying layer.
// If the request failed due to validate the request, "csi.fault.InvalidArgument" will be return.
// If thr reqeust failed due to object not found, "csi.fault.NotFound" will be return.
// For all other cases, the faultType will be set to "csi.fault.Internal" for now.
// Later we may need to define different csi faults.
err := validateGuestClusterCreateVolumeRequest(ctx, req)
if err != nil {
log.Errorf("validation for CreateVolume Request: %+v has failed. Error: %+v", *req, err)
return nil, csifault.CSIInvalidArgumentFault, err
}
isFileVolumeRequest := common.IsFileVolumeRequest(ctx, req.GetVolumeCapabilities())
if isFileVolumeRequest {
volumeType = prometheus.PrometheusFileVolumeType
} else {
volumeType = prometheus.PrometheusBlockVolumeType
}
// Get PVC name and disk size for the supervisor cluster
// We use default prefix 'pvc-' for pvc created in the guest cluster, it is mandatory.
supervisorPVCName := c.tanzukubernetesClusterUID + "-" + req.Name[4:]
var volumeSnapshotName string
// Volume Size - Default is 10 GiB
volSizeBytes := int64(common.DefaultGbDiskSize * common.GbInBytes)
if req.GetCapacityRange() != nil && req.GetCapacityRange().RequiredBytes != 0 {
volSizeBytes = int64(req.GetCapacityRange().GetRequiredBytes())
}
volSizeMB := int64(common.RoundUpSize(volSizeBytes, common.MbInBytes))
volumeSource := req.GetVolumeContentSource()
// Get supervisorStorageClass and accessMode
var supervisorStorageClass string
for param := range req.Parameters {
paramName := strings.ToLower(param)
if paramName == common.AttributeSupervisorStorageClass {
supervisorStorageClass = req.Parameters[param]
}
}
accessMode := req.GetVolumeCapabilities()[0].GetAccessMode().GetMode()
pvc, err := c.supervisorClient.CoreV1().PersistentVolumeClaims(c.supervisorNamespace).Get(
ctx, supervisorPVCName, metav1.GetOptions{})
if err != nil {
if errors.IsNotFound(err) {
diskSize := strconv.FormatInt(volSizeMB, 10) + "Mi"
var annotations map[string]string
if !isFileVolumeRequest && commonco.ContainerOrchestratorUtility.IsFSSEnabled(ctx, common.TKGsHA) &&
req.AccessibilityRequirements != nil {
// Generate volume topology requirement annotation.
annotations = make(map[string]string)
topologyAnnotation, err := generateGuestClusterRequestedTopologyJSON(req.AccessibilityRequirements.Preferred)
if err != nil {
msg := fmt.Sprintf("failed to generate accessibility topology for pvc with name: %s "+
"on namespace: %s from supervisorCluster. Error: %+v",
supervisorPVCName, c.supervisorNamespace, err)
return nil, csifault.CSIInternalFault, status.Errorf(codes.Internal, msg)
}
annotations[common.AnnGuestClusterRequestedTopology] = topologyAnnotation
}
if commonco.ContainerOrchestratorUtility.IsFSSEnabled(ctx, common.BlockVolumeSnapshot) &&
volumeSource != nil {
volumeSnapshotName = volumeSource.GetSnapshot().GetSnapshotId()
}
claim := getPersistentVolumeClaimSpecWithStorageClass(supervisorPVCName, c.supervisorNamespace,
diskSize, supervisorStorageClass, getAccessMode(accessMode), annotations, volumeSnapshotName)
log.Debugf("PVC claim spec is %+v", spew.Sdump(claim))
pvc, err = c.supervisorClient.CoreV1().PersistentVolumeClaims(c.supervisorNamespace).Create(
ctx, claim, metav1.CreateOptions{})
if err != nil {
msg := fmt.Sprintf("failed to create pvc with name: %s on namespace: %s in supervisorCluster. Error: %+v",
supervisorPVCName, c.supervisorNamespace, err)
log.Error(msg)
return nil, csifault.CSIInternalFault, status.Errorf(codes.Internal, msg)
}
} else {
msg := fmt.Sprintf("failed to get pvc with name: %s on namespace: %s from supervisorCluster. Error: %+v",
supervisorPVCName, c.supervisorNamespace, err)
log.Error(msg)
return nil, csifault.CSIInternalFault, status.Errorf(codes.Internal, msg)
}
}
isBound, err := isPVCInSupervisorClusterBound(ctx, c.supervisorClient,
pvc, time.Duration(getProvisionTimeoutInMin(ctx))*time.Minute)
if !isBound {
msg := fmt.Sprintf("failed to create volume on namespace: %s in supervisor cluster. Error: %+v",
c.supervisorNamespace, err)
log.Error(msg)
eventList, err := c.supervisorClient.CoreV1().Events(c.supervisorNamespace).List(ctx,
metav1.ListOptions{FieldSelector: "involvedObject.name=" + pvc.Name})
if err != nil {
log.Errorf("Unable to fetch events for pvc %q/%q from supervisor cluster with err: %+v",
c.supervisorNamespace, pvc.Name, err)
return nil, csifault.CSIInternalFault, status.Errorf(codes.Internal, msg)
}
log.Errorf("Last observed events on the pvc %q/%q in supervisor cluster: %+v",
c.supervisorNamespace, pvc.Name, spew.Sdump(eventList.Items))
return nil, csifault.CSIInternalFault, status.Errorf(codes.Internal, msg)
}
attributes := make(map[string]string)
if commonco.ContainerOrchestratorUtility.IsFSSEnabled(ctx, common.FileVolume) && isFileVolumeRequest {
attributes[common.AttributeDiskType] = common.DiskTypeFileVolume
} else {
attributes[common.AttributeDiskType] = common.DiskTypeBlockVolume
}
resp := &csi.CreateVolumeResponse{
Volume: &csi.Volume{
VolumeId: supervisorPVCName,
CapacityBytes: int64(volSizeMB * common.MbInBytes),
VolumeContext: attributes,
},
}
// Set the Snapshot VolumeContentSource in the CreateVolumeResponse
if commonco.ContainerOrchestratorUtility.IsFSSEnabled(ctx, common.BlockVolumeSnapshot) &&
volumeSnapshotName != "" {
resp.Volume.ContentSource = &csi.VolumeContentSource{
Type: &csi.VolumeContentSource_Snapshot{
Snapshot: &csi.VolumeContentSource_SnapshotSource{
SnapshotId: volumeSnapshotName,
},
},
}
}
// Calculate node affinity terms for topology aware provisioning.
var accessibleTopologies []map[string]string
if !isFileVolumeRequest && commonco.ContainerOrchestratorUtility.IsFSSEnabled(ctx, common.TKGsHA) &&
req.AccessibilityRequirements != nil {
// Retrieve the latest version of the PVC
pvc, err = c.supervisorClient.CoreV1().PersistentVolumeClaims(c.supervisorNamespace).Get(
ctx, supervisorPVCName, metav1.GetOptions{})
if err != nil {
msg := fmt.Sprintf("failed to get pvc with name: %s on namespace: %s from supervisorCluster. "+
"Error: %+v", supervisorPVCName, c.supervisorNamespace, err)
return nil, csifault.CSIInternalFault, logger.LogNewErrorCode(log, codes.Internal, msg)
}
// Generate accessible topologies for volume.
accessibleTopologies, err = generateVolumeAccessibleTopologyFromPVCAnnotation(pvc)
if err != nil {
msg := fmt.Sprintf("failed to generate volume accessible topology for pvc with name: %s on "+
"namespace: %s from supervisorCluster requirements with err: %+v",
c.supervisorNamespace, pvc.Name, err)
return nil, csifault.CSIInternalFault, logger.LogNewErrorCode(log, codes.Internal, msg)
}
log.Infof("Volume %q created is accessible from zones: %+v", supervisorPVCName,
accessibleTopologies)
// Add topology segments to the CreateVolumeResponse.
for _, topoSegments := range accessibleTopologies {
volumeTopology := &csi.Topology{
Segments: topoSegments,
}
resp.Volume.AccessibleTopology = append(resp.Volume.AccessibleTopology, volumeTopology)
}
}
return resp, "", nil
}
resp, faultType, err := createVolumeInternal()
log.Debugf("createVolumeInternal: returns fault %q", faultType)
if err != nil {
log.Errorf("Operation failed, reporting failure status to Prometheus."+
" Operation Type: %q, Volume Type: %q, Fault Type: %q",
prometheus.PrometheusCreateVolumeOpType, volumeType, faultType)
prometheus.CsiControlOpsHistVec.WithLabelValues(volumeType, prometheus.PrometheusCreateVolumeOpType,
prometheus.PrometheusFailStatus, faultType).Observe(time.Since(start).Seconds())
} else {
log.Infof("Volume created successfully. Volume Handle: %q, PV Name: %q", resp.Volume.VolumeId, req.Name)
prometheus.CsiControlOpsHistVec.WithLabelValues(volumeType, prometheus.PrometheusCreateVolumeOpType,
prometheus.PrometheusPassStatus, faultType).Observe(time.Since(start).Seconds())
}
log.Debugf("CreateVolume response: %+v", resp)
return resp, err
}
// DeleteVolume is deleting CNS Volume specified in DeleteVolumeRequest
func (c *controller) DeleteVolume(ctx context.Context, req *csi.DeleteVolumeRequest) (
*csi.DeleteVolumeResponse, error) {
start := time.Now()
ctx = logger.NewContextWithLogger(ctx)
log := logger.GetLogger(ctx)
volumeType := prometheus.PrometheusUnknownVolumeType
deleteVolumeInternal := func() (
*csi.DeleteVolumeResponse, string, error) {
log.Infof("DeleteVolume: called with args: %+v", *req)
//TODO: If the err is returned by invoking CNS API, then faultType should be
// populated by the underlying layer.
// If the request failed due to validate the request, "csi.fault.InvalidArgument" will be return.
// If thr reqeust failed due to object not found, "csi.fault.NotFound" will be return.
// For all other cases, the faultType will be set to "csi.fault.Internal" for now.
// Later we may need to define different csi faults.
var err error
err = validateGuestClusterDeleteVolumeRequest(ctx, req)
if err != nil {
msg := fmt.Sprintf("Validation for Delete Volume Request: %+v has failed. Error: %+v", *req, err)
log.Error(msg)
return nil, csifault.CSIInvalidArgumentFault, err
}
// Retrieve Supervisor PVC
svPVC, err := c.supervisorClient.CoreV1().PersistentVolumeClaims(c.supervisorNamespace).Get(
ctx, req.VolumeId, metav1.GetOptions{})
if err != nil {
if errors.IsNotFound(err) {
log.Debugf("PVC: %q not found in the Supervisor cluster. Assuming the volume is already deleted.",
req.VolumeId)
return &csi.DeleteVolumeResponse{}, "", nil
}
msg := fmt.Sprintf("failed to retrieve supervisor PVC %q in %q namespace. Error: %+v",
req.VolumeId, c.supervisorNamespace, err)
log.Error(msg)
return nil, csifault.CSIInternalFault, status.Error(codes.Internal, msg)
}
volumeType = prometheus.PrometheusBlockVolumeType
for _, accessMode := range svPVC.Spec.AccessModes {
if accessMode == corev1.ReadWriteMany || accessMode == corev1.ReadOnlyMany {
volumeType = prometheus.PrometheusFileVolumeType
}
}
err = c.supervisorClient.CoreV1().PersistentVolumeClaims(c.supervisorNamespace).Delete(
ctx, req.VolumeId, *metav1.NewDeleteOptions(0))
if err != nil {
if errors.IsNotFound(err) {
log.Debugf("PVC: %q not found in the Supervisor cluster. Assuming this volume to be deleted.", req.VolumeId)
return &csi.DeleteVolumeResponse{}, "", nil
}
msg := fmt.Sprintf("DeleteVolume Request: %+v has failed. Error: %+v", *req, err)
log.Error(msg)
return nil, csifault.CSIInternalFault, status.Errorf(codes.Internal, msg)
}
log.Infof("DeleteVolume: Volume deleted successfully. VolumeID: %q", req.VolumeId)
return &csi.DeleteVolumeResponse{}, "", nil
}
resp, faultType, err := deleteVolumeInternal()
log.Debugf("deleteVolumeInternal: returns fault %q for volume %q", faultType, req.VolumeId)
if err != nil {
log.Errorf("Operation failed, reporting failure status to Prometheus."+
" Operation Type: %q, Volume Type: %q, Fault Type: %q",
prometheus.PrometheusDeleteVolumeOpType, volumeType, faultType)
prometheus.CsiControlOpsHistVec.WithLabelValues(volumeType, prometheus.PrometheusDeleteVolumeOpType,
prometheus.PrometheusFailStatus, faultType).Observe(time.Since(start).Seconds())
} else {
log.Infof("Volume %q deleted successfully.", req.VolumeId)
prometheus.CsiControlOpsHistVec.WithLabelValues(volumeType, prometheus.PrometheusDeleteVolumeOpType,
prometheus.PrometheusPassStatus, faultType).Observe(time.Since(start).Seconds())
}
return resp, err
}
// ControllerPublishVolume attaches a volume to the Node VM.
// volume id and node name is retrieved from ControllerPublishVolumeRequest
func (c *controller) ControllerPublishVolume(ctx context.Context, req *csi.ControllerPublishVolumeRequest) (
*csi.ControllerPublishVolumeResponse, error) {
start := time.Now()
ctx = logger.NewContextWithLogger(ctx)
log := logger.GetLogger(ctx)
volumeType := prometheus.PrometheusUnknownVolumeType
controllerPublishVolumeInternal := func() (
*csi.ControllerPublishVolumeResponse, string, error) {
log.Infof("ControllerPublishVolume: called with args %+v", *req)
//TODO: If the err is returned by invoking CNS API, then faultType should be
// populated by the underlying layer.
// If the request failed due to validate the request, "csi.fault.InvalidArgument" will be return.
// If thr reqeust failed due to object not found, "csi.fault.NotFound" will be return.
// For all other cases, the faultType will be set to "csi.fault.Internal" for now.
// Later we may need to define different csi faults.
// Check whether the request is for a block or file volume
isFileVolumeRequest := common.IsFileVolumeRequest(ctx, []*csi.VolumeCapability{req.GetVolumeCapability()})
err := validateGuestClusterControllerPublishVolumeRequest(ctx, req)
if err != nil {
msg := fmt.Sprintf("Validation for PublishVolume Request: %+v has failed. Error: %v", *req, err)
log.Error(msg)
return nil, csifault.CSIInvalidArgumentFault, status.Errorf(codes.Internal, msg)
}
// File volumes support
if isFileVolumeRequest {
volumeType = prometheus.PrometheusFileVolumeType
// Check the feature state for file volume support
if !commonco.ContainerOrchestratorUtility.IsFSSEnabled(ctx, common.FileVolume) {
// Feature is disabled on the cluster
return nil, csifault.CSIInternalFault,
status.Error(codes.InvalidArgument, "File volume not supported.")
}
return controllerPublishForFileVolume(ctx, req, c)
}
volumeType = prometheus.PrometheusBlockVolumeType
// Block volumes support
return controllerPublishForBlockVolume(ctx, req, c)
}
resp, faultType, err := controllerPublishVolumeInternal()
if err != nil {
log.Debugf("controllerPublishVolumeInternal: returns fault %q for volume %q", faultType, req.VolumeId)
log.Errorf("Operation failed, reporting failure status to Prometheus."+
" Operation Type: %q, Volume Type: %q, Fault Type: %q",
prometheus.PrometheusAttachVolumeOpType, volumeType, faultType)
prometheus.CsiControlOpsHistVec.WithLabelValues(volumeType, prometheus.PrometheusAttachVolumeOpType,
prometheus.PrometheusFailStatus, faultType).Observe(time.Since(start).Seconds())
} else {
log.Infof("Volume %q attached successfully to node %q", req.VolumeId, req.NodeId)
prometheus.CsiControlOpsHistVec.WithLabelValues(volumeType, prometheus.PrometheusAttachVolumeOpType,
prometheus.PrometheusPassStatus, faultType).Observe(time.Since(start).Seconds())
}
return resp, err
}
// controllerPublishForBlockVolume is a helper mthod for handling ControllerPublishVolume request for Block volumes
func controllerPublishForBlockVolume(ctx context.Context, req *csi.ControllerPublishVolumeRequest, c *controller) (
*csi.ControllerPublishVolumeResponse, string, error) {
log := logger.GetLogger(ctx)
var isVolumePresentInSpec, isVolumeAttached bool
var diskUUID string
var err error
virtualMachine := &vmoperatortypes.VirtualMachine{}
vmKey := types.NamespacedName{
Namespace: c.supervisorNamespace,
Name: req.NodeId,
}
timeoutSeconds := int64(getAttacherTimeoutInMin(ctx) * 60)
timeout := time.Now().Add(time.Duration(timeoutSeconds) * time.Second)
for {
if err = c.vmOperatorClient.Get(ctx, vmKey, virtualMachine); err != nil {
msg := fmt.Sprintf("failed to get VirtualMachines for the node: %q. Error: %+v", req.NodeId, err)
log.Error(msg)
return nil, csifault.CSIInternalFault, status.Errorf(codes.Internal, msg)
}
// Check if volume is already present in the virtualMachine.Spec.Volumes
for _, volume := range virtualMachine.Spec.Volumes {
if volume.PersistentVolumeClaim != nil && volume.Name == req.VolumeId {
log.Infof("Volume %q is already present in the virtualMachine.Spec.Volumes", volume.Name)
isVolumePresentInSpec = true
break
}
}
if isVolumePresentInSpec {
break
}
// Volume is not present in the virtualMachine.Spec.Volumes, so adding
// volume in the spec and patching virtualMachine instance.
vmvolumes := vmoperatortypes.VirtualMachineVolume{
Name: req.VolumeId,
PersistentVolumeClaim: &vmoperatortypes.PersistentVolumeClaimVolumeSource{
PersistentVolumeClaimVolumeSource: corev1.PersistentVolumeClaimVolumeSource{
ClaimName: req.VolumeId,
},
},
}
virtualMachine.Spec.Volumes = append(virtualMachine.Spec.Volumes, vmvolumes)
err = c.vmOperatorClient.Update(ctx, virtualMachine)
if err == nil {
break
} else {
log.Errorf("failed to update virtualmachine. Err: %v", err)
}
if time.Now().After(timeout) {
msg := fmt.Sprintf("timedout to update VirtualMachines %q", virtualMachine.Name)
log.Error(msg)
return nil, csifault.CSIInternalFault, status.Errorf(codes.Internal, msg)
}
virtualMachine = &vmoperatortypes.VirtualMachine{}
}
for _, volume := range virtualMachine.Status.Volumes {
if volume.Name == req.VolumeId && volume.Attached && volume.DiskUuid != "" {
diskUUID = volume.DiskUuid
isVolumeAttached = true
log.Infof("Volume %q is already attached in the virtualMachine.Spec.Volumes. Disk UUID: %q",
volume.Name, volume.DiskUuid)
break
}
}
// volume is not attached, so wait until volume is attached and DiskUuid is set
if !isVolumeAttached {
watchVirtualMachine, err := c.vmWatcher.Watch(metav1.ListOptions{
FieldSelector: fields.SelectorFromSet(fields.Set{"metadata.name": string(virtualMachine.Name)}).String(),
ResourceVersion: virtualMachine.ResourceVersion,
TimeoutSeconds: &timeoutSeconds,
})
if err != nil {
msg := fmt.Sprintf("failed to watch virtualMachine %q with Error: %v", virtualMachine.Name, err)
log.Error(msg)
return nil, csifault.CSIInternalFault, status.Errorf(codes.Internal, msg)
}
defer watchVirtualMachine.Stop()
// Watch all update events made on VirtualMachine instance until volume.DiskUuid is set
for diskUUID == "" {
// blocking wait for update event
log.Debugf("waiting for update on virtualmachine: %q", virtualMachine.Name)
event := <-watchVirtualMachine.ResultChan()
vm, ok := event.Object.(*vmoperatortypes.VirtualMachine)
if !ok {
msg := fmt.Sprintf("Watch on virtualmachine %q timed out", virtualMachine.Name)
log.Error(msg)
return nil, csifault.CSIInternalFault, status.Errorf(codes.Internal, msg)
}
if vm.Name != virtualMachine.Name {
log.Debugf("Observed vm name: %q, expecting vm name: %q, volumeID: %q",
vm.Name, virtualMachine.Name, req.VolumeId)
continue
}
log.Debugf("observed update on virtualmachine: %q. checking if disk UUID is set for volume: %q ",
virtualMachine.Name, req.VolumeId)
for _, volume := range vm.Status.Volumes {
if volume.Name == req.VolumeId {
if volume.Attached && volume.DiskUuid != "" && volume.Error == "" {
diskUUID = volume.DiskUuid
log.Infof("observed disk UUID %q is set for the volume %q on virtualmachine %q",
volume.DiskUuid, volume.Name, vm.Name)
} else {
if volume.Error != "" {
msg := fmt.Sprintf("observed Error: %q is set on the volume %q on virtualmachine %q",
volume.Error, volume.Name, vm.Name)
log.Error(msg)
return nil, csifault.CSIInternalFault, status.Errorf(codes.Internal, msg)
}
}
break
}
}
if diskUUID == "" {
log.Debugf("disk UUID is not set for volume: %q ", req.VolumeId)
}
}
log.Debugf("disk UUID %v is set for the volume: %q ", diskUUID, req.VolumeId)
}
//return PublishContext with diskUUID of the volume attached to node.
publishInfo := make(map[string]string)
publishInfo[common.AttributeDiskType] = common.DiskTypeBlockVolume
publishInfo[common.AttributeFirstClassDiskUUID] = common.FormatDiskUUID(diskUUID)
resp := &csi.ControllerPublishVolumeResponse{
PublishContext: publishInfo,
}
log.Infof("ControllerPublishVolume: Volume attached successfully %q", req.VolumeId)
return resp, "", nil
}
// controllerPublishForFileVolume is a helper mthod for handling ControllerPublishVolume request for File volumes
func controllerPublishForFileVolume(ctx context.Context, req *csi.ControllerPublishVolumeRequest, c *controller) (
*csi.ControllerPublishVolumeResponse, string, error) {
log := logger.GetLogger(ctx)
// Build the CnsFileAccessConfig instance name and namespace
cnsFileAccessConfigInstance := &cnsfileaccessconfigv1alpha1.CnsFileAccessConfig{}
cnsFileAccessConfigInstanceName := req.NodeId + "-" + req.VolumeId
cnsFileAccessConfigInstanceKey := types.NamespacedName{
Namespace: c.supervisorNamespace,
Name: cnsFileAccessConfigInstanceName,
}
// Check whether the CnsFileAccessConfig instance exist in the supervisor cluster
if err := c.cnsOperatorClient.Get(ctx, cnsFileAccessConfigInstanceKey, cnsFileAccessConfigInstance); err != nil {
if !errors.IsNotFound(err) {
// Get() on the CnsFileAccessConfig instance failed with different error
msg := fmt.Sprintf("failed to get CnsFileAccessConfig instance: %q/%q. Error: %+v",
c.supervisorNamespace, cnsFileAccessConfigInstance.Name, err)
log.Error(msg)
return nil, csifault.CSIInternalFault, status.Errorf(codes.Internal, msg)
}
// Create the CnsFileAccessConfig instance since it is not found
cnsFileAccessConfigInstance = &cnsfileaccessconfigv1alpha1.CnsFileAccessConfig{
ObjectMeta: metav1.ObjectMeta{
Name: cnsFileAccessConfigInstanceName,
Namespace: c.supervisorNamespace},
Spec: cnsfileaccessconfigv1alpha1.CnsFileAccessConfigSpec{
VMName: req.NodeId,
PvcName: req.VolumeId,
},
}
log.Debugf("Creating CnsFileAccessConfig instance: %+v", cnsFileAccessConfigInstance)
log.Infof("Creating CnsFileAccessConfig instance with name: %q", cnsFileAccessConfigInstance.Name)
if err := c.cnsOperatorClient.Create(ctx, cnsFileAccessConfigInstance); err != nil {
msg := fmt.Sprintf("failed to create cnsFileAccessConfig: %q/%q. Error: %v",
c.supervisorNamespace, cnsFileAccessConfigInstance.Name, err)
log.Error(msg)
return nil, csifault.CSIInternalFault, status.Errorf(codes.Internal, msg)
}
}
log.Debugf("Found CnsFileAccessConfig: %q/%q", c.supervisorNamespace, cnsFileAccessConfigInstance.Name)
if cnsFileAccessConfigInstance.DeletionTimestamp != nil {
// When deletionTimestamp is set, CnsOperator is in the process of
// removing access for this IP. When that operation is successful, the
// instance will be deleted. In a subsequent retry, a new instance will
// be created.
msg := fmt.Sprintf("cnsFileAccessConfigInstance %q/%q is getting deleted. "+
"A new instance will be created in the subsequent ControllerPublishVolume request",
c.supervisorNamespace, cnsFileAccessConfigInstance.Name)
log.Error(msg)
return nil, csifault.CSIInternalFault, status.Errorf(codes.Internal, msg)
}
publishInfo := make(map[string]string)
// Verify if the CnsFileAccessConfig instance has status with done set to true and error is empty
if cnsFileAccessConfigInstance.Status.Done && cnsFileAccessConfigInstance.Status.Error == "" {
for key, value := range cnsFileAccessConfigInstance.Status.AccessPoints {
if key == common.Nfsv4AccessPointKey {
publishInfo[common.Nfsv4AccessPoint] = value
break
}
}
publishInfo[common.AttributeDiskType] = common.DiskTypeFileVolume
resp := &csi.ControllerPublishVolumeResponse{
PublishContext: publishInfo,
}
log.Infof("ControllerPublishVolume: Volume %q attached successfully on the node: %q", req.VolumeId, req.NodeId)
return resp, "", nil
}
cnsFileAccessConfigWatcher, err := k8s.NewCnsFileAccessConfigWatcher(ctx, c.restClientConfig, c.supervisorNamespace)
if err != nil {
msg := fmt.Sprintf("failed to create cnsFileAccessConfigWatcher. Error: %+v", err)
log.Error(msg)
return nil, csifault.CSIInternalFault, status.Errorf(codes.Internal, msg)
}
// Attacher timeout, default is set to 4 minutes
timeoutSeconds := int64(getAttacherTimeoutInMin(ctx) * 60)
// Adding watch on the CnsFileAccessConfig instance to register for updates
watchCnsFileAccessConfig, err := cnsFileAccessConfigWatcher.Watch(metav1.ListOptions{
FieldSelector: fields.SelectorFromSet(fields.Set{"metadata.name": cnsFileAccessConfigInstance.Name}).String(),
ResourceVersion: cnsFileAccessConfigInstance.ResourceVersion,
TimeoutSeconds: &timeoutSeconds,
})
if err != nil {
msg := fmt.Sprintf("failed to watch cnsfileaccessconfig %q with Error: %v", cnsFileAccessConfigInstance.Name, err)
log.Error(msg)
return nil, csifault.CSIInternalFault, status.Errorf(codes.Internal, msg)
}
defer watchCnsFileAccessConfig.Stop()
var cnsFileAccessConfigInstanceErr string
// Watch all update events made on CnsFileAccessConfig instance until accessPoints is set
for {
log.Debugf("Waiting for update on cnsfileaccessconfigs: %q", cnsFileAccessConfigInstance.Name)
event := <-watchCnsFileAccessConfig.ResultChan()
cnsfileaccessconfig, ok := event.Object.(*cnsfileaccessconfigv1alpha1.CnsFileAccessConfig)
if !ok {
msg := fmt.Sprintf("Watch on cnsfileaccessconfig instance %q timed out. Last seen error on the instance=%q",
cnsFileAccessConfigInstance.Name, cnsFileAccessConfigInstanceErr)
log.Error(msg)
return nil, csifault.CSIInternalFault, status.Errorf(codes.Internal, msg)
}
if cnsfileaccessconfig.Name != cnsFileAccessConfigInstanceName {
log.Debugf("Observed cnsFileAccessConfig instance name: %q, expecting cnsFileAccessConfig instance name: %q",
cnsfileaccessconfig.Name, cnsFileAccessConfigInstanceName)
continue
}
// Check if SV PVC Name match with VolumeId from the request
if cnsfileaccessconfig.Spec.PvcName != req.VolumeId {
log.Debugf("Observed SV PVC Name: %q, expecting SV PVC Name: %q",
cnsfileaccessconfig.Spec.PvcName, req.VolumeId)
continue
}
// Check if VM name in the cnsfileaccessconfig instance match with NodeId from the request
if cnsfileaccessconfig.Spec.VMName != req.NodeId {
log.Debugf("Observed vm name: %q, expecting vm name: %q", cnsfileaccessconfig.Spec.VMName, req.NodeId)
continue
}
log.Debugf("Observed an update on cnsfileaccessconfig: %+v", cnsfileaccessconfig)
if cnsfileaccessconfig.Status.Done && cnsfileaccessconfig.Status.Error == "" &&
cnsfileaccessconfig.DeletionTimestamp == nil {
// Check if the updated instance has the AccessPoints
for key, value := range cnsfileaccessconfig.Status.AccessPoints {
if key == common.Nfsv4AccessPointKey {
publishInfo[common.AttributeDiskType] = common.DiskTypeFileVolume
publishInfo[common.Nfsv4AccessPoint] = value
break
}
}
if _, ok := publishInfo[common.Nfsv4AccessPoint]; ok {
log.Debugf("Found Nfsv4AccessPoint in publishInfo. publishInfo=%+v", publishInfo)
break
}
}
cnsFileAccessConfigInstanceErr = cnsfileaccessconfig.Status.Error
}
resp := &csi.ControllerPublishVolumeResponse{
PublishContext: publishInfo,
}
log.Infof("ControllerPublishVolume: Volume %q attached successfully on the node: %q", req.VolumeId, req.NodeId)
return resp, "", nil
}
// ControllerUnpublishVolume detaches a volume from the Node VM.
// volume id and node name is retrieved from ControllerUnpublishVolumeRequest
func (c *controller) ControllerUnpublishVolume(ctx context.Context, req *csi.ControllerUnpublishVolumeRequest) (
*csi.ControllerUnpublishVolumeResponse, error) {
start := time.Now()
ctx = logger.NewContextWithLogger(ctx)
log := logger.GetLogger(ctx)
volumeType := prometheus.PrometheusUnknownVolumeType
controllerUnpublishVolumeInternal := func() (
*csi.ControllerUnpublishVolumeResponse, string, error) {
log.Infof("ControllerUnpublishVolume: called with args %+v", *req)
//TODO: If the err is returned by invoking CNS API, then faultType should be
// populated by the underlying layer.
// If the request failed due to validate the request, "csi.fault.InvalidArgument" will be return.
// If thr reqeust failed due to object not found, "csi.fault.NotFound" will be return.
// For all other cases, the faultType will be set to "csi.fault.Internal" for now.
// Later we may need to define different csi faults.
err := validateGuestClusterControllerUnpublishVolumeRequest(ctx, req)
if err != nil {
msg := fmt.Sprintf("Validation for UnpublishVolume Request: %+v has failed. Error: %v", *req, err)
log.Error(msg)
return nil, csifault.CSIInvalidArgumentFault, err
}
// Retrieve Supervisor PVC
svPVC, err := c.supervisorClient.CoreV1().PersistentVolumeClaims(c.supervisorNamespace).Get(
ctx, req.VolumeId, metav1.GetOptions{})
if err != nil {
msg := fmt.Sprintf("failed to retrieve supervisor PVC %q in %q namespace. Error: %+v",
req.VolumeId, c.supervisorNamespace, err)
log.Error(msg)
return nil, csifault.CSIInternalFault, status.Error(codes.Internal, msg)
}
var isFileVolume bool
for _, accessMode := range svPVC.Spec.AccessModes {
if accessMode == corev1.ReadWriteMany || accessMode == corev1.ReadOnlyMany {
isFileVolume = true
}
}
if isFileVolume {
volumeType = prometheus.PrometheusFileVolumeType
if commonco.ContainerOrchestratorUtility.IsFSSEnabled(ctx, common.FileVolume) {
return controllerUnpublishForFileVolume(ctx, req, c)
}
// Feature is disabled on the cluster
return nil, csifault.CSIInvalidArgumentFault, status.Error(codes.InvalidArgument, "File volume not supported.")
}
volumeType = prometheus.PrometheusBlockVolumeType
return controllerUnpublishForBlockVolume(ctx, req, c)
}
resp, faultType, err := controllerUnpublishVolumeInternal()
log.Debugf("controllerUnpublishVolumeInternal: returns fault %q for volume %q", faultType, req.VolumeId)
if err != nil {
log.Errorf("Operation failed, reporting failure status to Prometheus."+
" Operation Type: %q, Volume Type: %q, Fault Type: %q",
prometheus.PrometheusDetachVolumeOpType, volumeType, faultType)
prometheus.CsiControlOpsHistVec.WithLabelValues(volumeType, prometheus.PrometheusDetachVolumeOpType,
prometheus.PrometheusFailStatus, faultType).Observe(time.Since(start).Seconds())
} else {
log.Infof("Volume %q detached successfully from node %q.", req.VolumeId, req.NodeId)
prometheus.CsiControlOpsHistVec.WithLabelValues(volumeType, prometheus.PrometheusDetachVolumeOpType,
prometheus.PrometheusPassStatus, faultType).Observe(time.Since(start).Seconds())
}
return resp, err
}
// controllerUnpublishForBlockVolume is helper method to handle ControllerPublishVolume for Block volumes
func controllerUnpublishForBlockVolume(ctx context.Context, req *csi.ControllerUnpublishVolumeRequest, c *controller) (
*csi.ControllerUnpublishVolumeResponse, string, error) {
log := logger.GetLogger(ctx)
virtualMachine := &vmoperatortypes.VirtualMachine{}
vmKey := types.NamespacedName{
Namespace: c.supervisorNamespace,
Name: req.NodeId,
}
var err error
timeoutSeconds := int64(getAttacherTimeoutInMin(ctx) * 60)
timeout := time.Now().Add(time.Duration(timeoutSeconds) * time.Second)
for {
if err := c.vmOperatorClient.Get(ctx, vmKey, virtualMachine); err != nil {
if errors.IsNotFound(err) {
log.Infof("VirtualMachine %s/%s not found. Assuming volume %s was detached.",
c.supervisorNamespace, req.NodeId, req.VolumeId)
return &csi.ControllerUnpublishVolumeResponse{}, "", nil
}
msg := fmt.Sprintf("failed to get VirtualMachines for node: %q. Error: %+v", req.NodeId, err)
log.Error(msg)
return nil, csifault.CSIInternalFault, status.Errorf(codes.Internal, msg)
}
log.Debugf("Found VirtualMachine for node: %q.", req.NodeId)
for index, volume := range virtualMachine.Spec.Volumes {
if volume.Name == req.VolumeId {
log.Debugf("Removing volume %q from VirtualMachine %q", volume.Name, virtualMachine.Name)
virtualMachine.Spec.Volumes = append(virtualMachine.Spec.Volumes[:index],
virtualMachine.Spec.Volumes[index+1:]...)
err = c.vmOperatorClient.Update(ctx, virtualMachine)
break
}
}
if err == nil {
break
} else {
log.Errorf("failed to update virtualmachine. Err: %v", err)
}
if time.Now().After(timeout) {
msg := fmt.Sprintf("timedout to update VirtualMachines %q", virtualMachine.Name)
log.Error(msg)
return nil, csifault.CSIInternalFault, status.Errorf(codes.Internal, msg)
}
virtualMachine = &vmoperatortypes.VirtualMachine{}
}
isVolumePresentInVMStatus := false
for _, volume := range virtualMachine.Status.Volumes {
if volume.Name == req.VolumeId {
isVolumePresentInVMStatus = true
}
}
if !isVolumePresentInVMStatus {
log.Infof("ControllerUnpublishVolume: Volume %q not found in VM %q status field. Assuming it's already detached",
req.VolumeId, req.NodeId)
} else {
// Watch virtual machine object and wait for volume name to be removed from the status field.
watchVirtualMachine, err := c.vmWatcher.Watch(metav1.ListOptions{
FieldSelector: fields.SelectorFromSet(fields.Set{"metadata.name": string(virtualMachine.Name)}).String(),
ResourceVersion: virtualMachine.ResourceVersion,
TimeoutSeconds: &timeoutSeconds,
})
if err != nil {
msg := fmt.Sprintf("failed to watch VirtualMachine %q with Error: %v", virtualMachine.Name, err)
log.Error(msg)
return nil, csifault.CSIInternalFault, status.Errorf(codes.Internal, msg)
}
if watchVirtualMachine == nil {
msg := fmt.Sprintf("watchVirtualMachine for %q is nil", virtualMachine.Name)
log.Error(msg)
return nil, csifault.CSIInternalFault, status.Errorf(codes.Internal, msg)
}
defer watchVirtualMachine.Stop()
// Loop until the volume is removed from virtualmachine status
isVolumeDetached := false
for !isVolumeDetached {
log.Debugf("Waiting for update on VirtualMachine: %q", virtualMachine.Name)
// Block on update events
event := <-watchVirtualMachine.ResultChan()
vm, ok := event.Object.(*vmoperatortypes.VirtualMachine)
if !ok {
msg := fmt.Sprintf("Watch on virtualmachine %q timed out", virtualMachine.Name)
log.Error(msg)
return nil, csifault.CSIInternalFault, status.Errorf(codes.Internal, msg)
}
if vm.Name != virtualMachine.Name {
log.Debugf("Observed vm name: %q, expecting vm name: %q, volumeID: %q",
vm.Name, virtualMachine.Name, req.VolumeId)
continue
}
switch event.Type {
case watch.Added, watch.Modified:
isVolumeDetached = true
for _, volume := range vm.Status.Volumes {
if volume.Name == req.VolumeId {
log.Debugf("Volume %q still exists in VirtualMachine %q status", volume.Name, virtualMachine.Name)
isVolumeDetached = false
if volume.Attached && volume.Error != "" {