/
controller.go
1896 lines (1781 loc) · 83 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 wcp
import (
"context"
"encoding/json"
"fmt"
"net/http"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
"github.com/container-storage-interface/spec/lib/go/csi"
"github.com/davecgh/go-spew/spew"
"github.com/fsnotify/fsnotify"
"github.com/prometheus/client_golang/prometheus/promhttp"
cnstypes "github.com/vmware/govmomi/cns/types"
"github.com/vmware/govmomi/units"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/timestamppb"
v1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/resource"
"k8s.io/apimachinery/pkg/util/wait"
cnsvolume "sigs.k8s.io/vsphere-csi-driver/v3/pkg/common/cns-lib/volume"
cnsvsphere "sigs.k8s.io/vsphere-csi-driver/v3/pkg/common/cns-lib/vsphere"
cnsconfig "sigs.k8s.io/vsphere-csi-driver/v3/pkg/common/config"
csifault "sigs.k8s.io/vsphere-csi-driver/v3/pkg/common/fault"
"sigs.k8s.io/vsphere-csi-driver/v3/pkg/common/prometheus"
"sigs.k8s.io/vsphere-csi-driver/v3/pkg/common/utils"
"sigs.k8s.io/vsphere-csi-driver/v3/pkg/csi/service/common"
"sigs.k8s.io/vsphere-csi-driver/v3/pkg/csi/service/common/commonco"
commoncotypes "sigs.k8s.io/vsphere-csi-driver/v3/pkg/csi/service/common/commonco/types"
"sigs.k8s.io/vsphere-csi-driver/v3/pkg/csi/service/logger"
csitypes "sigs.k8s.io/vsphere-csi-driver/v3/pkg/csi/types"
"sigs.k8s.io/vsphere-csi-driver/v3/pkg/internalapis/cnsvolumeinfo"
cnsvolumeinfov1alpha1 "sigs.k8s.io/vsphere-csi-driver/v3/pkg/internalapis/cnsvolumeinfo/v1alpha1"
"sigs.k8s.io/vsphere-csi-driver/v3/pkg/internalapis/cnsvolumeoperationrequest"
)
const (
vsanDirect = "vsanD"
vsanSna = "vsan-sna"
)
var (
// operationStore represents the client by which we can
// interact with VolumeOperationRequest interface.
operationStore cnsvolumeoperationrequest.VolumeOperationRequest
// 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,
csi.ControllerServiceCapability_RPC_CREATE_DELETE_SNAPSHOT,
csi.ControllerServiceCapability_RPC_LIST_SNAPSHOTS,
}
checkCompatibleDataStores = true
// volumeInfoService holds the pointer to VolumeInfo service instance
// This will hold mapping for VolumeID to Storage policy info for PodVMOnStretchedSupervisor deployments
volumeInfoService cnsvolumeinfo.VolumeInfoService
// isPodVMOnStretchSupervisorFSSEnabled is true when PodVMOnStretchedSupervisor FSS is enabled.
isPodVMOnStretchSupervisorFSSEnabled bool
)
var getCandidateDatastores = cnsvsphere.GetCandidateDatastoresInCluster
// Contains list of clusterComputeResourceMoIds on which supervisor cluster is deployed.
var clusterComputeResourceMoIds = make([]string, 0)
var (
expectedStartingIndex = 0
cnsVolumeIDs = make([]string, 0)
vmMoidToHostMoid, volumeIDToVMMap map[string]string
)
type controller struct {
manager *common.Manager
authMgr common.AuthorizationService
topologyMgr commoncotypes.ControllerTopologyService
}
// 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 WCP CSI controller")
var err error
if !config.Global.InsecureFlag && config.Global.CAFile != cnsconfig.SupervisorCAFilePath {
log.Warnf("Invalid CA file: %q is set in the vSphere Config Secret. "+
"Setting correct CA file: %q", config.Global.CAFile, cnsconfig.SupervisorCAFilePath)
config.Global.CAFile = cnsconfig.SupervisorCAFilePath
}
if commonco.ContainerOrchestratorUtility.IsFSSEnabled(ctx, common.TKGsHA) {
clusterComputeResourceMoIds, err = common.GetClusterComputeResourceMoIds(ctx)
if err != nil {
log.Errorf("failed to get clusterComputeResourceMoIds. err: %v", err)
return err
}
if len(clusterComputeResourceMoIds) > 0 {
if config.Global.SupervisorID == "" {
return logger.LogNewError(log, "supervisor-id is not set in the vsphere-config-secret")
}
} else {
// This will cover the case when VC is upgraded to 8.0+ but any of the existing pre-8.0 supervisor clusters
// are not upgraded along with it. Such supervisor clusters will not have a AZ CR in it.
clusterComputeResourceMoIds = append(clusterComputeResourceMoIds, config.Global.ClusterID)
}
}
// Get VirtualCenterManager instance and validate version.
vcenterconfig, err := cnsvsphere.GetVirtualCenterConfig(ctx, config)
if err != nil {
log.Errorf("failed to get VirtualCenterConfig. err=%v", err)
return err
}
vcenterconfig.ReloadVCConfigForNewClient = true
vcManager := cnsvsphere.GetVirtualCenterManager(ctx)
vcenter, err := vcManager.RegisterVirtualCenter(ctx, vcenterconfig)
if err != nil {
log.Errorf("failed to register VC with virtualCenterManager. err=%v", err)
return err
}
isPodVMOnStretchSupervisorFSSEnabled = commonco.ContainerOrchestratorUtility.IsFSSEnabled(ctx,
common.PodVMOnStretchedSupervisor)
idempotencyHandlingEnabled := commonco.ContainerOrchestratorUtility.IsFSSEnabled(ctx,
common.CSIVolumeManagerIdempotency)
if idempotencyHandlingEnabled {
log.Info("CSI Volume manager idempotency handling feature flag is enabled.")
operationStore, err = cnsvolumeoperationrequest.InitVolumeOperationRequestInterface(ctx,
config.Global.CnsVolumeOperationRequestCleanupIntervalInMin,
func() bool {
return commonco.ContainerOrchestratorUtility.IsFSSEnabled(ctx, common.BlockVolumeSnapshot)
}, isPodVMOnStretchSupervisorFSSEnabled)
if err != nil {
log.Errorf("failed to initialize VolumeOperationRequestInterface with error: %v", err)
return err
}
}
tasksListViewEnabled := commonco.ContainerOrchestratorUtility.IsFSSEnabled(ctx,
common.ListViewPerf)
volumeManager, err := cnsvolume.GetManager(ctx, vcenter, operationStore, idempotencyHandlingEnabled, false, false,
tasksListViewEnabled, cnstypes.CnsClusterFlavorWorkload)
if err != nil {
return logger.LogNewErrorf(log, "failed to create an instance of volume manager. err=%v", err)
}
c.manager = &common.Manager{
VcenterConfig: vcenterconfig,
CnsConfig: config,
VolumeManager: volumeManager,
VcenterManager: cnsvsphere.GetVirtualCenterManager(ctx),
}
vc, err := common.GetVCenter(ctx, c.manager)
if err != nil {
log.Errorf("failed to get vcenter. err=%v", err)
return err
}
// Check vCenter API Version against 6.7.3.
err = common.CheckAPI(ctx, vc.Client.ServiceContent.About.ApiVersion, common.MinSupportedVCenterMajor,
common.MinSupportedVCenterMinor, common.MinSupportedVCenterPatch)
if err != nil {
log.Errorf("checkAPI failed for vcenter API version: %s, err=%v", vc.Client.ServiceContent.About.ApiVersion, err)
return err
}
go cnsvolume.ClearTaskInfoObjects()
if tasksListViewEnabled {
go cnsvolume.ClearInvalidTasksFromListView(false)
}
cfgPath := cnsconfig.GetConfigPath(ctx)
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Errorf("failed to create fsnotify watcher. err=%v", err)
return err
}
log.Info("loading AuthorizationService")
authMgr, err := common.GetAuthorizationService(ctx, vc)
if err != nil {
log.Errorf("failed to initialize authMgr. err=%v", err)
return err
}
c.authMgr = authMgr
// TODO: Invoke similar method for block volumes.
go common.ComputeFSEnabledClustersToDsMap(authMgr.(*common.AuthManager), config.Global.CSIAuthCheckIntervalInMin)
// Create dynamic informer for AvailabilityZone instance if FSS is enabled
// and CR is present in environment.
if commonco.ContainerOrchestratorUtility.IsFSSEnabled(ctx, common.TKGsHA) {
// Initialize volume topology service.
c.topologyMgr, err = commonco.ContainerOrchestratorUtility.InitTopologyServiceInController(ctx)
if err != nil {
log.Errorf("failed to initialize topology service. Error: %+v", err)
return err
}
}
if isPodVMOnStretchSupervisorFSSEnabled {
log.Info("Loading CnsVolumeInfo Service to persist mapping for VolumeID to storage policy info")
volumeInfoService, err = cnsvolumeinfo.InitVolumeInfoService(ctx)
if err != nil {
return logger.LogNewErrorf(log, "error initializing volumeInfoService. Error: %+v", err)
}
log.Infof("Successfully initialized VolumeInfoService")
}
cfgDirPath := filepath.Dir(cfgPath)
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
}
caFileDirPath := filepath.Dir(cnsconfig.SupervisorCAFilePath)
log.Infof("Adding watch on path: %q", caFileDirPath)
err = watcher.Add(caFileDirPath)
if err != nil {
log.Errorf("failed to watch on path: %q. err=%v", caFileDirPath, 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())
expectedEvent :=
strings.Contains(event.Name, cfgDirPath) && !strings.Contains(event.Name, caFileDirPath)
if event.Op&fsnotify.Remove == fsnotify.Remove && expectedEvent {
for {
reloadConfigErr := c.ReloadConfiguration(false)
if reloadConfigErr == nil {
log.Infof("Successfully reloaded configuration from: %q", cfgPath)
break
}
log.Errorf("failed to reload configuration. will retry again in 60 seconds. err: %+v", reloadConfigErr)
time.Sleep(60 * time.Second)
}
}
// Handling create event for reconnecting to VC when ca file is
// rotated. In Supervisor cluster, ca file gets rotated at the path
// /etc/vmware/wcp/tls/vmca.pem. WCP is handling ca file rotation by
// creating a /etc/vmware/wcp/tls/vmca.pem.tmp file with new
// contents, and then renaming the file back to
// /etc/vmware/wcp/tls/vmca.pem. For such operations, fsnotify
// handles the event as a CREATE event. The condition below also
// ensures that the event is for the expected ca file path.
if event.Op&fsnotify.Create == fsnotify.Create && event.Name == cnsconfig.SupervisorCAFilePath {
log.Infof("Observed ca file rotation at: %q", cnsconfig.SupervisorCAFilePath)
for {
reconnectVCErr := c.ReloadConfiguration(true)
if reconnectVCErr == nil {
log.Infof("Successfully re-established connection with VC from: %q",
cnsconfig.SupervisorCAFilePath)
break
}
log.Errorf("failed to re-establish VC connection. Will retry again in 60 seconds. err: %+v",
reconnectVCErr)
time.Sleep(60 * time.Second)
}
}
case err, ok := <-watcher.Errors:
if !ok {
log.Errorf("fsnotify error: %+v", err)
return
}
}
log.Debugf("fsnotify event processed")
}
}()
// 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 update
// controller's config cache and VolumeManager's VC Config cache.
// The function takes a boolean reconnectToVCFromNewConfig as ainputs.
// If reconnectToVCFromNewConfig is set to true, the function re-establishes
// connection with VC, else based on the configuration data changed during
// reload, the function resets config, reloads VC connection when credentials
// are changed and returns appropriate error.
func (c *controller) ReloadConfiguration(reconnectToVCFromNewConfig bool) error {
ctx, log := logger.GetNewContextWithLogger()
log.Info("Reloading Configuration")
cfg, err := cnsconfig.GetConfig(ctx)
if err != nil {
log.Errorf("failed to read config. Error: %+v", err)
return err
}
if !cfg.Global.InsecureFlag && cfg.Global.CAFile != cnsconfig.SupervisorCAFilePath {
log.Warnf("Invalid CA file: %q is set in the vSphere Config Secret. "+
"Setting correct CA file: %q", cfg.Global.CAFile, cnsconfig.SupervisorCAFilePath)
cfg.Global.CAFile = cnsconfig.SupervisorCAFilePath
}
newVCConfig, err := cnsvsphere.GetVirtualCenterConfig(ctx, cfg)
if err != nil {
log.Errorf("failed to get VirtualCenterConfig. err=%v", err)
return err
}
if newVCConfig != nil {
newVCConfig.ReloadVCConfigForNewClient = true
var vcenter *cnsvsphere.VirtualCenter
if c.manager.VcenterConfig.Host != newVCConfig.Host ||
c.manager.VcenterConfig.Username != newVCConfig.Username ||
c.manager.VcenterConfig.Password != newVCConfig.Password || reconnectToVCFromNewConfig {
// Verify if new configuration has valid credentials by connecting to
// vCenter. Proceed only if the connection succeeds, else return error.
newVC := &cnsvsphere.VirtualCenter{Config: newVCConfig, ClientMutex: &sync.Mutex{}}
if err = newVC.Connect(ctx); err != nil {
return logger.LogNewErrorf(log, "failed to connect to VirtualCenter host: %q, Err: %+v",
newVCConfig.Host, err)
}
// Reset virtual center singleton instance by passing reload flag as
// true.
log.Info("Obtaining new vCenterInstance")
vcenter, err = cnsvsphere.GetVirtualCenterInstance(ctx, &cnsconfig.ConfigurationInfo{Cfg: cfg}, true)
if err != nil {
return logger.LogNewErrorf(log, "failed to get VirtualCenter. err=%v", err)
}
} else {
// If it's not a VC host or VC credentials update, same singleton
// instance can be used and it's Config field can be updated.
vcenter, err = cnsvsphere.GetVirtualCenterInstance(ctx, &cnsconfig.ConfigurationInfo{Cfg: cfg}, false)
if err != nil {
return logger.LogNewErrorf(log, "failed to get VirtualCenter. err=%v", err)
}
vcenter.Config = newVCConfig
}
idempotencyHandlingEnabled := commonco.ContainerOrchestratorUtility.IsFSSEnabled(ctx,
common.CSIVolumeManagerIdempotency)
if idempotencyHandlingEnabled {
log.Info("CSI Volume manager idempotency handling feature flag is enabled.")
operationStore, err = cnsvolumeoperationrequest.InitVolumeOperationRequestInterface(ctx,
c.manager.CnsConfig.Global.CnsVolumeOperationRequestCleanupIntervalInMin,
func() bool {
return commonco.ContainerOrchestratorUtility.IsFSSEnabled(ctx, common.BlockVolumeSnapshot)
}, isPodVMOnStretchSupervisorFSSEnabled)
if err != nil {
log.Errorf("failed to initialize VolumeOperationRequestInterface with error: %v", err)
return err
}
}
err := c.manager.VolumeManager.ResetManager(ctx, vcenter)
if err != nil {
return logger.LogNewErrorf(log, "failed to reset volume manager. err=%v", err)
}
c.manager.VcenterConfig = newVCConfig
tasksListViewEnabled := commonco.ContainerOrchestratorUtility.IsFSSEnabled(ctx,
common.ListViewPerf)
volumeManager, err := cnsvolume.GetManager(ctx, vcenter, operationStore, idempotencyHandlingEnabled, false,
false, tasksListViewEnabled, cnstypes.CnsClusterFlavorWorkload)
if err != nil {
return logger.LogNewErrorf(log, "failed to create an instance of volume manager. err=%v", err)
}
c.manager.VolumeManager = volumeManager
if c.authMgr != nil {
c.authMgr.ResetvCenterInstance(ctx, vcenter)
log.Debugf("Updated vCenter in auth manager")
}
}
if cfg != nil {
c.manager.CnsConfig = cfg
log.Debugf("Updated manager.CnsConfig")
}
log.Info("Successfully reloaded configuration")
return nil
}
// createBlockVolume creates a block volume based on the CreateVolumeRequest.
func (c *controller) createBlockVolume(ctx context.Context, req *csi.CreateVolumeRequest) (
*csi.CreateVolumeResponse, string, error) {
log := logger.GetLogger(ctx)
var (
storagePolicyID string
affineToHost string
storagePool string
selectedDatastoreURL string
storageTopologyType string
topologyRequirement *csi.TopologyRequirement
// accessibleNodes will be used to populate volumeAccessTopology.
accessibleNodes []string
sharedDatastores []*cnsvsphere.DatastoreInfo
vsanDirectDatastores []*cnsvsphere.DatastoreInfo
hostnameLabelPresent bool
zoneLabelPresent bool
err error
)
// Support case insensitive parameters.
for paramName := range req.Parameters {
param := strings.ToLower(paramName)
switch param {
case common.AttributeStoragePolicyID:
storagePolicyID = req.Parameters[paramName]
case common.AttributeStoragePool:
storagePool = req.Parameters[paramName]
case common.AttributeStorageTopologyType:
// TKGS-HA: validate storageTopologyType.
storageTopologyType = req.Parameters[paramName]
val := strings.ToLower(storageTopologyType)
if val != "zonal" {
return nil, csifault.CSIInvalidArgumentFault, logger.LogNewErrorCodef(log, codes.InvalidArgument,
"invalid value found for StorageClass parameter `storagetopologytype`: %q.",
storageTopologyType)
}
}
}
// Get VC instance.
vc, err := common.GetVCenter(ctx, c.manager)
// TODO: Need to extract fault from err returned by GetVirtualCenter.
// Currently, just return "csi.fault.Internal".
if err != nil {
return nil, csifault.CSIInternalFault, logger.LogNewErrorCodef(log, codes.Internal,
"failed to get vCenter from Manager. Error: %v", err)
}
// Fetch the accessibility requirements from the request.
topologyRequirement = req.GetAccessibilityRequirements()
filterSuspendedDatastores := commonco.ContainerOrchestratorUtility.IsFSSEnabled(ctx, common.CnsMgrSuspendCreateVolume)
isTKGSHAEnabled := commonco.ContainerOrchestratorUtility.IsFSSEnabled(ctx, common.TKGsHA)
topoSegToDatastoresMap := make(map[string][]*cnsvsphere.DatastoreInfo)
if isTKGSHAEnabled {
// TKGS-HA feature is enabled
// Identify the topology keys in Accessibility requirements.
hostnameLabelPresent, zoneLabelPresent = checkTopologyKeysFromAccessibilityReqs(topologyRequirement)
// TODO: TKGS-HA: This case will only arise when spherelet will add zone and hostname labels to CSINodes.
// Currently spherelet only accepts hostname. We will handle this case later.
if zoneLabelPresent && hostnameLabelPresent {
return nil, csifault.CSIUnimplementedFault, logger.LogNewErrorCodef(log, codes.Unimplemented,
"support for topology requirement with both zone and hostname labels is not yet implemented.")
} else if zoneLabelPresent {
// StorageTopologyType should be set if topology label is present
if storageTopologyType == "" {
return nil, csifault.CSIInvalidArgumentFault, logger.LogNewErrorCode(log, codes.InvalidArgument,
"StorageTopologyType is unset while topology label is present")
}
// topologyMgr can be nil if the AZ CR was not registered
// at the time of controller init. Handling that case in CreateVolume calls.
if c.topologyMgr == nil {
return nil, csifault.CSIInternalFault, logger.LogNewErrorCode(log, codes.Internal,
"topology manager not initialized.")
}
// Initiate TKGs HA workflow when the topology requirement contains zone labels only.
log.Infof("Topology aware environment detected with requirement: %+v", topologyRequirement)
sharedDatastores, err = c.topologyMgr.GetSharedDatastoresInTopology(ctx,
commoncotypes.WCPTopologyFetchDSParams{
TopologyRequirement: topologyRequirement,
Vc: vc,
TopoSegToDatastoresMap: topoSegToDatastoresMap})
if err != nil {
return nil, csifault.CSIInternalFault, logger.LogNewErrorCodef(log, codes.Internal,
"failed to find shared datastores for given topology requirement. Error: %v", err)
}
} else {
// zone labels not Present in the topologyRequirement
if len(clusterComputeResourceMoIds) > 1 {
return nil, csifault.CSIInternalFault, logger.LogNewErrorCodef(log, codes.FailedPrecondition,
"stretched supervisor cluster does not support creating volumes "+
"without zone keys in the topologyRequirement . Error: %v", err)
}
sharedDatastores, vsanDirectDatastores, err = getCandidateDatastores(ctx, vc,
clusterComputeResourceMoIds[0], true)
if err != nil {
return nil, csifault.CSIInternalFault, logger.LogNewErrorCodef(log, codes.Internal,
"failed finding candidate datastores to place volume. Error: %v", err)
}
}
} else {
// TKGS-HA feature is disabled
sharedDatastores, vsanDirectDatastores, err = getCandidateDatastores(ctx, vc,
c.manager.CnsConfig.Global.ClusterID, true)
if err != nil {
return nil, csifault.CSIInternalFault, logger.LogNewErrorCodef(log, codes.Internal,
"failed finding candidate datastores to place volume. Error: %v", err)
}
}
candidateDatastores := append(sharedDatastores, vsanDirectDatastores...)
if storagePool != "" {
if !isValidAccessibilityRequirement(topologyRequirement) {
return nil, csifault.CSIInvalidArgumentFault, logger.LogNewErrorCode(log, codes.InvalidArgument,
"invalid accessibility requirements")
}
spAccessibleNodes, storagePoolType, err := getStoragePoolInfo(ctx, storagePool)
if err != nil {
return nil, csifault.CSIInternalFault, logger.LogNewErrorCodef(log, codes.Internal,
"error in specified StoragePool %s. Error: %+v", storagePool, err)
}
overlappingNodes, err := getOverlappingNodes(spAccessibleNodes, topologyRequirement)
if err != nil || len(overlappingNodes) == 0 {
return nil, csifault.CSIInternalFault, logger.LogNewErrorCodef(log, codes.Internal,
"getOverlappingNodes failed: %v", err)
}
accessibleNodes = append(accessibleNodes, overlappingNodes...)
log.Infof("Storage pool Accessible nodes for volume topology: %+v", accessibleNodes)
if storagePoolType == vsanDirect {
selectedDatastoreURL, err = getDatastoreURLFromStoragePool(ctx, storagePool)
if err != nil {
return nil, csifault.CSIInternalFault, logger.LogNewErrorCodef(log, codes.Internal,
"error in specified StoragePool %s. Error: %+v", storagePool, err)
}
log.Infof("Will select datastore %s as per the provided storage pool %s", selectedDatastoreURL, storagePool)
} else if storagePoolType == vsanSna {
// Query API server to get ESX Host Moid from the hostLocalNodeName.
if len(accessibleNodes) != 1 {
return nil, csifault.CSIInternalFault, logger.LogNewErrorCode(log, codes.Internal,
"too many accessible nodes")
}
hostMoid, err := getHostMOIDFromK8sCloudOperatorService(ctx, accessibleNodes[0])
if err != nil {
return nil, csifault.CSIInternalFault, logger.LogNewErrorCodef(log, codes.Internal,
"failed to get ESX Host Moid from API server. Error: %+v", err)
}
affineToHost = hostMoid
log.Debugf("Setting the affineToHost value as %s", affineToHost)
}
}
// 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))
isBlockVolumeSnapshotEnabled := commonco.ContainerOrchestratorUtility.IsFSSEnabled(ctx, common.BlockVolumeSnapshot)
// Check if requested volume size and source snapshot size matches
volumeSource := req.GetVolumeContentSource()
var contentSourceSnapshotID string
if isBlockVolumeSnapshotEnabled && volumeSource != nil {
sourceSnapshot := volumeSource.GetSnapshot()
if sourceSnapshot == nil {
return nil, csifault.CSIInvalidArgumentFault,
logger.LogNewErrorCode(log, codes.InvalidArgument, "unsupported VolumeContentSource type")
}
contentSourceSnapshotID = sourceSnapshot.GetSnapshotId()
// Retrieving the original source CNS volume-id from the snapshot-id
cnsVolumeID, _, err := common.ParseCSISnapshotID(contentSourceSnapshotID)
if err != nil {
return nil, csifault.CSIInvalidArgumentFault,
logger.LogNewErrorCode(log, codes.InvalidArgument, err.Error())
}
// The requested volume size when creating a volume from snapshot should be the same as the
// snapshot size, since CNS does not support querying the exact snapshot size, we approximate
// it to the original source volume size, the check ensures that sufficient space is allocated
// for the restore.
// Query capacity in MB for block volume snapshot
volumeIds := []cnstypes.CnsVolumeId{{Id: cnsVolumeID}}
cnsVolumeDetailsMap, err := utils.QueryVolumeDetailsUtil(ctx, c.manager.VolumeManager, volumeIds)
if err != nil {
log.Errorf("failed to retrieve the volume: %s details. err: %+v", cnsVolumeID, err)
return nil, csifault.CSIInternalFault, err
}
if _, ok := cnsVolumeDetailsMap[cnsVolumeID]; !ok {
return nil, csifault.CSIInternalFault, logger.LogNewErrorCodef(log, codes.Internal,
"cns query volume did not return the volume: %s", cnsVolumeID)
}
snapshotSizeInMB := cnsVolumeDetailsMap[cnsVolumeID].SizeInMB
snapshotSizeInBytes := snapshotSizeInMB * common.MbInBytes
if volSizeBytes != snapshotSizeInBytes {
return nil, csifault.CSIInvalidArgumentFault, logger.LogNewErrorCodef(log, codes.InvalidArgument,
"requested volume size: %d must be the same as source snapshot size: %d",
volSizeBytes, snapshotSizeInBytes)
}
}
// Create CreateVolumeSpec and populate values.
var createVolumeSpec = common.CreateVolumeSpec{
CapacityMB: volSizeMB,
Name: req.Name,
StoragePolicyID: storagePolicyID,
ScParams: &common.StorageClassParams{},
AffineToHost: affineToHost,
VolumeType: common.BlockVolumeType,
VsanDirectDatastoreURL: selectedDatastoreURL,
ContentSourceSnapshotID: contentSourceSnapshotID,
}
var (
volumeInfo *cnsvolume.CnsVolumeInfo
faultType string
)
if isPodVMOnStretchSupervisorFSSEnabled {
volumeInfo, faultType, err = common.CreateBlockVolumeUtil(ctx, cnstypes.CnsClusterFlavorWorkload,
c.manager, &createVolumeSpec, candidateDatastores, filterSuspendedDatastores,
isTKGSHAEnabled, checkCompatibleDataStores,
&cnsvolume.CreateVolumeExtraParams{
VolSizeBytes: volSizeBytes,
StorageClassName: req.Parameters[common.AttributeStorageClassName],
Namespace: req.Parameters[common.AttributePvcNamespace],
IsPodVMOnStretchSupervisorFSSEnabled: isPodVMOnStretchSupervisorFSSEnabled,
})
} else {
volumeInfo, faultType, err = common.CreateBlockVolumeUtil(ctx, cnstypes.CnsClusterFlavorWorkload,
c.manager, &createVolumeSpec, candidateDatastores, filterSuspendedDatastores,
isTKGSHAEnabled, checkCompatibleDataStores, nil)
}
if err != nil {
return nil, faultType, logger.LogNewErrorCodef(log, codes.Internal,
"failed to create volume. Error: %+v", err)
}
// CreateVolume response.
attributes := make(map[string]string)
attributes[common.AttributeDiskType] = common.DiskTypeBlockVolume
resp := &csi.CreateVolumeResponse{
Volume: &csi.Volume{
VolumeId: volumeInfo.VolumeID.Id,
CapacityBytes: int64(units.FileSize(volSizeMB * common.MbInBytes)),
VolumeContext: attributes,
},
}
// Calculate accessible topology for the provisioned volume in case of topology aware environment.
if isTKGSHAEnabled {
if zoneLabelPresent && !hostnameLabelPresent {
selectedDatastore := volumeInfo.DatastoreURL
// CreateBlockVolumeUtil with idempotency enabled does not return datastore
// information when it uses the cached information from CR. In such cases,
// querying the volume to retrieve the datastore URL.
if selectedDatastore == "" {
queryFilter := cnstypes.CnsQueryFilter{
VolumeIds: []cnstypes.CnsVolumeId{
{
Id: volumeInfo.VolumeID.Id,
},
},
}
querySelection := cnstypes.CnsQuerySelection{
Names: []string{string(cnstypes.QuerySelectionNameTypeDataStoreUrl)},
}
queryResult, err := utils.QueryVolumeUtil(ctx, c.manager.VolumeManager, queryFilter, &querySelection,
true)
if err != nil || queryResult == nil || len(queryResult.Volumes) != 1 {
return nil, csifault.CSIInternalFault, logger.LogNewErrorCodef(log, codes.Internal,
"failed to find the datastore on which volume %q is provisioned. Error: %+v",
volumeInfo.VolumeID.Id, err)
}
selectedDatastore = queryResult.Volumes[0].DatastoreUrl
}
// Calculate accessible topology for the provisioned volume.
datastoreAccessibleTopology, err := c.topologyMgr.GetTopologyInfoFromNodes(ctx,
commoncotypes.WCPRetrieveTopologyInfoParams{
DatastoreURL: selectedDatastore,
StorageTopologyType: storageTopologyType,
TopologyRequirement: topologyRequirement,
Vc: vc,
TopoSegToDatastoresMap: topoSegToDatastoresMap})
if err != nil {
// If the error is of InvalidTopologyProvisioningError type, it means we cannot
// recover from this error with a retry, so cleanup the volume created above.
if _, ok := err.(*common.InvalidTopologyProvisioningError); ok {
log.Errorf("Encountered error after creating volume. Cleaning up...")
// Delete the CnsVolumeOperationRequest created for CreateVolume call above.
deleteOpReqError := operationStore.DeleteRequestDetails(ctx, req.Name)
if deleteOpReqError != nil {
log.Warnf("failed to cleanup CnsVolumeOperationRequest instance before erroring "+
"out. Error received: %+v", deleteOpReqError)
} else {
// As the CnsVolumeOperationRequest for this CreateVolume call is deleted
// successfully, we can go ahead and delete the volume created above.
_, deleteVolumeError := common.DeleteVolumeUtil(ctx, c.manager.VolumeManager,
volumeInfo.VolumeID.Id, true)
if deleteVolumeError != nil {
// This is a best effort deletion. We do not propagate the delete volume error to K8s.
// NOTE: This might leave behind an orphan volume.
log.Warnf("failed to delete volume: %q while cleaning up after CreateVolume failure. "+
"Error: %+v", volumeInfo.VolumeID.Id, deleteVolumeError)
}
}
return nil, csifault.CSIInternalFault, logger.LogNewErrorCodef(log, codes.Internal,
"encountered an error while fetching accessible topologies for volume %q. Error: %+v",
volumeInfo.VolumeID.Id, err)
}
// If error is not of InvalidTopologyProvisioningError type, do not delete volume created as idempotency
// feature will ensure we retry with the same volume.
return nil, csifault.CSIInternalFault, logger.LogNewErrorCodef(log, codes.Internal,
"failed to find accessible topologies for volume %q. Error: %+v",
volumeInfo.VolumeID.Id, err)
}
// Add topology segments to the CreateVolumeResponse.
for _, topoSegments := range datastoreAccessibleTopology {
volumeTopology := &csi.Topology{
Segments: topoSegments,
}
resp.Volume.AccessibleTopology = append(resp.Volume.AccessibleTopology, volumeTopology)
}
} else if hostnameLabelPresent {
// Configure the volumeTopology in the response so that the external
// provisioner will properly sets up the nodeAffinity for this volume.
for _, hostName := range accessibleNodes {
volumeTopology := &csi.Topology{
Segments: map[string]string{
v1.LabelHostname: hostName,
},
}
resp.Volume.AccessibleTopology = append(resp.Volume.AccessibleTopology, volumeTopology)
}
log.Debugf("Volume Accessible Topology: %+v", resp.Volume.AccessibleTopology)
}
} else {
// Configure the volumeTopology in the response so that the external
// provisioner will properly set up the nodeAffinity for this volume.
if isValidAccessibilityRequirement(topologyRequirement) {
for _, hostName := range accessibleNodes {
volumeTopology := &csi.Topology{
Segments: map[string]string{
v1.LabelHostname: hostName,
},
}
resp.Volume.AccessibleTopology = append(resp.Volume.AccessibleTopology, volumeTopology)
}
log.Debugf("Volume Accessible Topology: %+v", resp.Volume.AccessibleTopology)
}
}
// Set the Snapshot VolumeContentSource in the CreateVolumeResponse
if contentSourceSnapshotID != "" {
resp.Volume.ContentSource = &csi.VolumeContentSource{
Type: &csi.VolumeContentSource_Snapshot{
Snapshot: &csi.VolumeContentSource_SnapshotSource{
SnapshotId: contentSourceSnapshotID,
},
},
}
}
if isPodVMOnStretchSupervisorFSSEnabled {
if pvcNamespace, ok := req.Parameters[common.AttributePvcNamespace]; ok {
if scName, ok := req.Parameters[common.AttributeStorageClassName]; ok {
// Create CNSVolumeInfo CR for the volume ID.
capacity := resource.NewQuantity(volSizeBytes, resource.BinarySI)
err = volumeInfoService.CreateVolumeInfoWithPolicyInfo(ctx, volumeInfo.VolumeID.Id, pvcNamespace,
storagePolicyID, scName, vc.Config.Host, capacity)
if err != nil {
return nil, csifault.CSIInternalFault, logger.LogNewErrorCodef(log, codes.Internal,
"failed to store volumeID %q pvcNamespace %q StoragePolicyID %q StorageClassName %q "+
"and vCenter %q in CNSVolumeInfo CR. Error: %+v",
volumeInfo.VolumeID.Id, pvcNamespace, storagePolicyID, scName, vc.Config.Host, err)
}
} else {
return nil, csifault.CSIInternalFault, logger.LogNewErrorCodef(log, codes.Internal,
"failed to create CnsVolumeInfo CR for volumeID %q due to missing storage class name "+
"in the CreateVolume request parameters", volumeInfo.VolumeID.Id)
}
} else {
return nil, csifault.CSIInternalFault, logger.LogNewErrorCodef(log, codes.Internal,
"failed to create CnsVolumeInfo CR for volumeID %q due to missing pvc namespace "+
"in the CreateVolume request parameters", volumeInfo.VolumeID.Id)
}
}
return resp, "", nil
}
// createFileVolume creates a file volume based on the CreateVolumeRequest.
func (c *controller) createFileVolume(ctx context.Context, req *csi.CreateVolumeRequest) (
*csi.CreateVolumeResponse, string, error) {
log := logger.GetLogger(ctx)
// Ignore TopologyRequirement for file volume provisioning.
if req.GetAccessibilityRequirements() != nil {
log.Info("Ignoring TopologyRequirement for file volume")
}
// 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))
var storagePolicyID string
for paramName := range req.Parameters {
param := strings.ToLower(paramName)
if param == common.AttributeStoragePolicyID {
storagePolicyID = req.Parameters[paramName]
}
}
var createVolumeSpec = common.CreateVolumeSpec{
CapacityMB: volSizeMB,
Name: req.Name,
StoragePolicyID: storagePolicyID,
ScParams: &common.StorageClassParams{},
VolumeType: common.FileVolumeType,
}
var volumeID string
var err error
var faultType string
fsEnabledClusterToDsMap := c.authMgr.GetFsEnabledClusterToDsMap(ctx)
var filteredDatastores []*cnsvsphere.DatastoreInfo
// targetvSANFileShareClusters is set in CSI secret when file volume feature
// is enabled on WCP. So we get datastores with privileges to create file
// volumes for each specified vSAN cluster, and use those datastores to
// create file volumes.
for _, targetvSANcluster := range c.manager.VcenterConfig.TargetvSANFileShareClusters {
if datastores, ok := fsEnabledClusterToDsMap[targetvSANcluster]; ok {
for _, dsInfo := range datastores {
log.Debugf("Adding datastore %q to filtered datastores", dsInfo.Info.Url)
filteredDatastores = append(filteredDatastores, dsInfo)
}
}
}
if len(filteredDatastores) == 0 {
// when len(filteredDatastore)==0, it means vsan file service is not enabled on any vsan cluster specfified
// by VcenterConfig.TargetvSANFileShareClusters
return nil, csifault.CSIVSanFileServiceDisabledFault, logger.LogNewErrorCode(log, codes.FailedPrecondition,
"no datastores found to create file volume, vsan file service may be disabled")
}
filterSuspendedDatastores := commonco.ContainerOrchestratorUtility.IsFSSEnabled(ctx, common.CnsMgrSuspendCreateVolume)
isTKGSHAEnabled := commonco.ContainerOrchestratorUtility.IsFSSEnabled(ctx, common.TKGsHA)
vc, err := c.manager.VcenterManager.GetVirtualCenter(ctx, c.manager.VcenterConfig.Host)
if err != nil {
return nil, faultType, logger.LogNewErrorCodef(log, codes.Internal,
"failed to get vCenter. Error: %+v", err)
}
if isPodVMOnStretchSupervisorFSSEnabled {
volumeID, faultType, err = common.CreateFileVolumeUtil(ctx, cnstypes.CnsClusterFlavorWorkload, vc,
c.manager.VolumeManager, c.manager.CnsConfig, &createVolumeSpec, filteredDatastores,
filterSuspendedDatastores, isTKGSHAEnabled, &cnsvolume.CreateVolumeExtraParams{
VolSizeBytes: volSizeBytes,
StorageClassName: req.Parameters[common.AttributeStorageClassName],
Namespace: req.Parameters[common.AttributePvcNamespace],
IsPodVMOnStretchSupervisorFSSEnabled: isPodVMOnStretchSupervisorFSSEnabled,
})
} else {
volumeID, faultType, err = common.CreateFileVolumeUtil(ctx, cnstypes.CnsClusterFlavorWorkload, vc,
c.manager.VolumeManager, c.manager.CnsConfig, &createVolumeSpec, filteredDatastores,
filterSuspendedDatastores, isTKGSHAEnabled, nil)
}
if err != nil {
return nil, faultType, logger.LogNewErrorCodef(log, codes.Internal,
"failed to create volume. Error: %+v", err)
}
attributes := make(map[string]string)
attributes[common.AttributeDiskType] = common.DiskTypeFileVolume
resp := &csi.CreateVolumeResponse{
Volume: &csi.Volume{
VolumeId: volumeID,
CapacityBytes: int64(units.FileSize(volSizeMB * common.MbInBytes)),
VolumeContext: attributes,
},
}
return resp, "", 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)
if chkDataStoreCompatibility := req.Parameters["checkCompatibleDatastores"]; chkDataStoreCompatibility == "false" {
checkCompatibleDataStores = false
delete(req.Parameters, "checkCompatibleDatastores")
}
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.
isBlockRequest := !common.IsFileVolumeRequest(ctx, req.GetVolumeCapabilities())
if isBlockRequest {
volumeType = prometheus.PrometheusBlockVolumeType
} else {
volumeType = prometheus.PrometheusFileVolumeType
}
// Validate create request.
err := validateWCPCreateVolumeRequest(ctx, req, isBlockRequest)
if err != nil {
msg := fmt.Sprintf("Validation for CreateVolume Request: %+v has failed. Error: %+v", *req, err)
log.Error(msg)
return nil, csifault.CSIInvalidArgumentFault, err
}
if !isBlockRequest {
if !commonco.ContainerOrchestratorUtility.IsFSSEnabled(ctx, common.FileVolume) {
return nil, csifault.CSIUnimplementedFault, logger.LogNewErrorCode(log, codes.Unimplemented,
"file volume feature is disabled on the cluster")
}
if commonco.ContainerOrchestratorUtility.IsFSSEnabled(ctx, common.TKGsHA) {
if len(clusterComputeResourceMoIds) > 1 {
return nil, csifault.CSIUnimplementedFault, logger.LogNewErrorCode(log, codes.Unimplemented,
"file volume provisioning is not supported on a stretched supervisor cluster")
}
}
return c.createFileVolume(ctx, req)
}
return c.createBlockVolume(ctx, req)
}
resp, faultType, err := createVolumeInternal()
log.Debugf("createVolumeInternal: returns fault %q", faultType)
if err != nil {
if csifault.IsNonStorageFault(faultType) {
faultType = csifault.AddCsiNonStoragePrefix(ctx, faultType)
}
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())
}
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
cnsVolumeType := common.UnknownVolumeType
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.
// 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 := validateWCPDeleteVolumeRequest(ctx, req)
if err != nil {
msg := fmt.Sprintf("Validation for DeleteVolume Request: %+v has failed. Error: %+v", *req, err)
log.Error(msg)
return nil, csifault.CSIInvalidArgumentFault, err
}
if cnsVolumeType == common.UnknownVolumeType {
cnsVolumeType, err = common.GetCnsVolumeType(ctx, c.manager.VolumeManager, req.VolumeId)
if err != nil {
if err.Error() == common.ErrNotFound.Error() {
// The volume couldn't be found during query, assuming the delete operation as success
return &csi.DeleteVolumeResponse{}, "", nil
} else {
return nil, csifault.CSIInternalFault, logger.LogNewErrorCodef(log, codes.Internal,
"failed to determine CNS volume type for volume: %q. Error: %+v", req.VolumeId, err)
}
}
volumeType = convertCnsVolumeType(ctx, cnsVolumeType)