forked from kubernetes-sigs/azurefile-csi-driver
-
Notifications
You must be signed in to change notification settings - Fork 7
/
controllerserver.go
1426 lines (1297 loc) · 62.9 KB
/
controllerserver.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 2017 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 azurefile
import (
"context"
"fmt"
"net/url"
"os"
"os/exec"
"strconv"
"strings"
"time"
volumehelper "sigs.k8s.io/azurefile-csi-driver/pkg/util"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azfile/sas"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azfile/service"
"github.com/Azure/azure-sdk-for-go/services/storage/mgmt/2021-09-01/storage"
"github.com/Azure/azure-storage-file-go/azfile"
"github.com/container-storage-interface/spec/lib/go/csi"
"github.com/pborman/uuid"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"k8s.io/klog/v2"
"k8s.io/utils/pointer"
timestamppb "google.golang.org/protobuf/types/known/timestamppb"
"sigs.k8s.io/cloud-provider-azure/pkg/azureclients/fileclient"
azcache "sigs.k8s.io/cloud-provider-azure/pkg/cache"
"sigs.k8s.io/cloud-provider-azure/pkg/metrics"
"sigs.k8s.io/cloud-provider-azure/pkg/provider"
azure "sigs.k8s.io/cloud-provider-azure/pkg/provider"
)
const (
azureFileCSIDriverName = "azurefile_csi_driver"
privateEndpoint = "privateendpoint"
snapshotTimeFormat = "2006-01-02T15:04:05.0000000Z07:00"
snapshotsExpand = "snapshots"
azcopyAutoLoginType = "AZCOPY_AUTO_LOGIN_TYPE"
azcopySPAApplicationID = "AZCOPY_SPA_APPLICATION_ID"
azcopySPAClientSecret = "AZCOPY_SPA_CLIENT_SECRET"
azcopyTenantID = "AZCOPY_TENANT_ID"
azcopyMSIClientID = "AZCOPY_MSI_CLIENT_ID"
MSI = "MSI"
SPN = "SPN"
authorizationPermissionMismatch = "AuthorizationPermissionMismatch"
)
var (
volumeCaps = []csi.VolumeCapability_AccessMode{
{
Mode: csi.VolumeCapability_AccessMode_SINGLE_NODE_WRITER,
},
{
Mode: csi.VolumeCapability_AccessMode_SINGLE_NODE_READER_ONLY,
},
{
Mode: csi.VolumeCapability_AccessMode_SINGLE_NODE_SINGLE_WRITER,
},
{
Mode: csi.VolumeCapability_AccessMode_SINGLE_NODE_MULTI_WRITER,
},
{
Mode: csi.VolumeCapability_AccessMode_MULTI_NODE_READER_ONLY,
},
{
Mode: csi.VolumeCapability_AccessMode_MULTI_NODE_SINGLE_WRITER,
},
{
Mode: csi.VolumeCapability_AccessMode_MULTI_NODE_MULTI_WRITER,
},
}
skipMatchingTag = map[string]*string{azure.SkipMatchingTag: pointer.String("")}
)
// CreateVolume provisions an azure file
func (d *Driver) CreateVolume(ctx context.Context, req *csi.CreateVolumeRequest) (*csi.CreateVolumeResponse, error) {
if err := d.ValidateControllerServiceRequest(csi.ControllerServiceCapability_RPC_CREATE_DELETE_VOLUME); err != nil {
klog.Errorf("invalid create volume req: %v", req)
return nil, err
}
volName := req.GetName()
if len(volName) == 0 {
return nil, status.Error(codes.InvalidArgument, "CreateVolume Name must be provided")
}
volumeCapabilities := req.GetVolumeCapabilities()
if err := isValidVolumeCapabilities(volumeCapabilities); err != nil {
return nil, status.Error(codes.InvalidArgument, fmt.Sprintf("CreateVolume Volume capabilities not valid: %v", err))
}
capacityBytes := req.GetCapacityRange().GetRequiredBytes()
requestGiB := volumehelper.RoundUpGiB(capacityBytes)
if requestGiB == 0 {
requestGiB = defaultAzureFileQuota
klog.Warningf("no quota specified, set as default value(%d GiB)", defaultAzureFileQuota)
}
if acquired := d.volumeLocks.TryAcquire(volName); !acquired {
// logging the job status if it's volume cloning
if req.GetVolumeContentSource() != nil {
jobState, percent, err := d.azcopy.GetAzcopyJob(volName, []string{})
return nil, status.Errorf(codes.Aborted, volumeOperationAlreadyExistsWithAzcopyFmt, volName, jobState, percent, err)
}
return nil, status.Errorf(codes.Aborted, volumeOperationAlreadyExistsFmt, volName)
}
defer d.volumeLocks.Release(volName)
parameters := req.GetParameters()
if parameters == nil {
parameters = make(map[string]string)
}
var sku, subsID, resourceGroup, location, account, fileShareName, diskName, fsType, secretName string
var secretNamespace, pvcNamespace, protocol, customTags, storageEndpointSuffix, networkEndpointType, shareAccessTier, accountAccessTier, rootSquashType string
var createAccount, useDataPlaneAPI, useSeretCache, matchTags, selectRandomMatchingAccount, getLatestAccountKey bool
var vnetResourceGroup, vnetName, subnetName, shareNamePrefix, fsGroupChangePolicy string
var requireInfraEncryption, disableDeleteRetentionPolicy, enableLFS, isMultichannelEnabled *bool
// set allowBlobPublicAccess as false by default
allowBlobPublicAccess := pointer.Bool(false)
fileShareNameReplaceMap := map[string]string{}
// store account key to k8s secret by default
storeAccountKey := true
var accountQuota int32
// Apply ProvisionerParameters (case-insensitive). We leave validation of
// the values to the cloud provider.
for k, v := range parameters {
switch strings.ToLower(k) {
case skuNameField:
sku = v
case storageAccountTypeField:
sku = v
case locationField:
location = v
case storageAccountField:
account = v
case subscriptionIDField:
subsID = v
case resourceGroupField:
resourceGroup = v
case shareNameField:
fileShareName = v
case diskNameField:
diskName = v
case fsTypeField:
fsType = v
case storeAccountKeyField:
if strings.EqualFold(v, falseValue) {
storeAccountKey = false
}
case selectRandomMatchingAccountField:
value, err := strconv.ParseBool(v)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, fmt.Sprintf("invalid %s: %s in storage class", selectRandomMatchingAccountField, v))
}
selectRandomMatchingAccount = value
case secretNameField:
secretName = v
case secretNamespaceField:
secretNamespace = v
case protocolField:
protocol = v
case matchTagsField:
matchTags = strings.EqualFold(v, trueValue)
case tagsField:
customTags = v
case createAccountField:
createAccount = strings.EqualFold(v, trueValue)
case useSecretCacheField:
useSeretCache = strings.EqualFold(v, trueValue)
case enableLargeFileSharesField:
value, err := strconv.ParseBool(v)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, fmt.Sprintf("invalid %s: %s in storage class", enableLargeFileSharesField, v))
}
enableLFS = &value
case useDataPlaneAPIField:
useDataPlaneAPI = strings.EqualFold(v, trueValue)
case disableDeleteRetentionPolicyField:
value, err := strconv.ParseBool(v)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, fmt.Sprintf("invalid %s: %s in storage class", disableDeleteRetentionPolicyField, v))
}
disableDeleteRetentionPolicy = &value
case pvcNamespaceKey:
pvcNamespace = v
fileShareNameReplaceMap[pvcNamespaceMetadata] = v
case storageEndpointSuffixField:
storageEndpointSuffix = v
case networkEndpointTypeField:
networkEndpointType = v
case accessTierField:
shareAccessTier = v
case shareAccessTierField:
shareAccessTier = v
case accountAccessTierField:
accountAccessTier = v
case rootSquashTypeField:
rootSquashType = v
case allowBlobPublicAccessField:
value, err := strconv.ParseBool(v)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, fmt.Sprintf("invalid %s: %s in storage class", allowBlobPublicAccessField, v))
}
allowBlobPublicAccess = &value
case pvcNameKey:
fileShareNameReplaceMap[pvcNameMetadata] = v
case pvNameKey:
fileShareNameReplaceMap[pvNameMetadata] = v
case serverNameField:
// no op, only used in NodeStageVolume
case folderNameField:
// no op, only used in NodeStageVolume
case fsGroupChangePolicyField:
fsGroupChangePolicy = v
case mountPermissionsField:
// only do validations here, used in NodeStageVolume, NodePublishVolume
if _, err := strconv.ParseUint(v, 8, 32); err != nil {
return nil, status.Errorf(codes.InvalidArgument, fmt.Sprintf("invalid mountPermissions %s in storage class", v))
}
case vnetResourceGroupField:
vnetResourceGroup = v
case vnetNameField:
vnetName = v
case subnetNameField:
subnetName = v
case shareNamePrefixField:
shareNamePrefix = v
case requireInfraEncryptionField:
value, err := strconv.ParseBool(v)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, fmt.Sprintf("invalid %s: %s in storage class", requireInfraEncryptionField, v))
}
requireInfraEncryption = &value
case enableMultichannelField:
value, err := strconv.ParseBool(v)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, fmt.Sprintf("invalid %s: %s in storage class", enableMultichannelField, v))
}
isMultichannelEnabled = &value
case getLatestAccountKeyField:
value, err := strconv.ParseBool(v)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, fmt.Sprintf("invalid %s: %s in storage class", getLatestAccountKeyField, v))
}
getLatestAccountKey = value
case accountQuotaField:
value, err := strconv.ParseInt(v, 10, 32)
if err != nil || value < minimumAccountQuota {
return nil, status.Errorf(codes.InvalidArgument, fmt.Sprintf("invalid accountQuota %s in storage class, minimum quota: %d", v, minimumAccountQuota))
}
accountQuota = int32(value)
default:
return nil, status.Errorf(codes.InvalidArgument, fmt.Sprintf("invalid parameter %q in storage class", k))
}
}
if matchTags && account != "" {
return nil, status.Errorf(codes.InvalidArgument, fmt.Sprintf("matchTags must set as false when storageAccount(%s) is provided", account))
}
if subsID != "" && subsID != d.cloud.SubscriptionID {
if resourceGroup == "" {
return nil, status.Errorf(codes.InvalidArgument, fmt.Sprintf("resourceGroup must be provided in cross subscription(%s)", subsID))
}
}
if secretNamespace == "" {
if pvcNamespace == "" {
secretNamespace = defaultNamespace
} else {
secretNamespace = pvcNamespace
}
}
if !d.enableVHDDiskFeature && fsType != "" {
return nil, status.Errorf(codes.InvalidArgument, "fsType storage class parameter enables experimental VDH disk feature which is currently disabled, use --enable-vhd driver option to enable it")
}
if !isSupportedFsType(fsType) {
return nil, status.Errorf(codes.InvalidArgument, "fsType(%s) is not supported, supported fsType list: %v", fsType, supportedFsTypeList)
}
if !isSupportedProtocol(protocol) {
return nil, status.Errorf(codes.InvalidArgument, "protocol(%s) is not supported, supported protocol list: %v", protocol, supportedProtocolList)
}
if !isSupportedShareAccessTier(shareAccessTier) {
return nil, status.Errorf(codes.InvalidArgument, "shareAccessTier(%s) is not supported, supported ShareAccessTier list: %v", shareAccessTier, storage.PossibleShareAccessTierValues())
}
if !isSupportedAccountAccessTier(accountAccessTier) {
return nil, status.Errorf(codes.InvalidArgument, "accountAccessTier(%s) is not supported, supported AccountAccessTier list: %v", accountAccessTier, storage.PossibleAccessTierValues())
}
if !isSupportedRootSquashType(rootSquashType) {
return nil, status.Errorf(codes.InvalidArgument, "rootSquashType(%s) is not supported, supported RootSquashType list: %v", rootSquashType, storage.PossibleRootSquashTypeValues())
}
if !isSupportedFSGroupChangePolicy(fsGroupChangePolicy) {
return nil, status.Errorf(codes.InvalidArgument, "fsGroupChangePolicy(%s) is not supported, supported fsGroupChangePolicy list: %v", fsGroupChangePolicy, supportedFSGroupChangePolicyList)
}
if !isSupportedShareNamePrefix(shareNamePrefix) {
return nil, status.Errorf(codes.InvalidArgument, "shareNamePrefix(%s) can only contain lowercase letters, numbers, hyphens, and length should be less than 21", shareNamePrefix)
}
if protocol == nfs && fsType != "" && fsType != nfs {
return nil, status.Errorf(codes.InvalidArgument, "fsType(%s) is not supported with protocol(%s)", fsType, protocol)
}
enableHTTPSTrafficOnly := true
shareProtocol := storage.EnabledProtocolsSMB
var createPrivateEndpoint *bool
if strings.EqualFold(networkEndpointType, privateEndpoint) {
if strings.Contains(subnetName, ",") {
return nil, status.Errorf(codes.InvalidArgument, "subnetName(%s) can only contain one subnet for private endpoint", subnetName)
}
createPrivateEndpoint = pointer.BoolPtr(true)
}
var vnetResourceIDs []string
if fsType == nfs || protocol == nfs {
if sku == "" {
// NFS protocol only supports Premium storage
sku = string(storage.SkuNamePremiumLRS)
} else if strings.HasPrefix(strings.ToLower(sku), standard) {
return nil, status.Errorf(codes.InvalidArgument, "nfs protocol only supports premium storage, current account type: %s", sku)
}
protocol = nfs
enableHTTPSTrafficOnly = false
shareProtocol = storage.EnabledProtocolsNFS
// NFS protocol does not need account key
storeAccountKey = false
// reset protocol field (compatible with "fsType: nfs")
setKeyValueInMap(parameters, protocolField, protocol)
if !pointer.BoolDeref(createPrivateEndpoint, false) {
// set VirtualNetworkResourceIDs for storage account firewall setting
subnets := strings.Split(subnetName, ",")
for _, subnet := range subnets {
subnet = strings.TrimSpace(subnet)
vnetResourceID := d.getSubnetResourceID(vnetResourceGroup, vnetName, subnet)
klog.V(2).Infof("set vnetResourceID(%s) for NFS protocol", vnetResourceID)
vnetResourceIDs = []string{vnetResourceID}
if err := d.updateSubnetServiceEndpoints(ctx, vnetResourceGroup, vnetName, subnet); err != nil {
return nil, status.Errorf(codes.Internal, "update service endpoints failed with error: %v", err)
}
}
}
}
if pointer.BoolDeref(isMultichannelEnabled, false) {
if sku != "" && !strings.HasPrefix(strings.ToLower(sku), premium) {
return nil, status.Errorf(codes.InvalidArgument, "smb multichannel is only supported with premium account, current account type: %s", sku)
}
if fsType == nfs || protocol == nfs {
return nil, status.Errorf(codes.InvalidArgument, "smb multichannel is only supported with smb protocol, current protocol: %s", protocol)
}
}
if resourceGroup == "" {
resourceGroup = d.cloud.ResourceGroup
}
fileShareSize := int(requestGiB)
if account != "" && resourceGroup != "" && sku == "" && fileShareSize < minimumPremiumShareSize {
accountProperties, err := d.cloud.StorageAccountClient.GetProperties(ctx, subsID, resourceGroup, account)
if err != nil {
klog.Warningf("failed to get properties on storage account account(%s) rg(%s), error: %v", account, resourceGroup, err)
}
if accountProperties.Sku != nil {
sku = string(accountProperties.Sku.Name)
}
}
// account kind should be FileStorage for Premium File
accountKind := string(storage.KindStorageV2)
if strings.HasPrefix(strings.ToLower(sku), premium) {
accountKind = string(storage.KindFileStorage)
if fileShareSize < minimumPremiumShareSize {
fileShareSize = minimumPremiumShareSize
}
}
// replace pv/pvc name namespace metadata in fileShareName
validFileShareName := replaceWithMap(fileShareName, fileShareNameReplaceMap)
if validFileShareName == "" {
name := volName
if shareNamePrefix != "" {
name = shareNamePrefix + "-" + volName
} else {
if protocol == nfs {
// use "pvcn" prefix for nfs protocol file share
name = strings.Replace(name, "pvc", "pvcn", 1)
} else if isDiskFsType(fsType) {
// use "pvcd" prefix for vhd disk file share
name = strings.Replace(name, "pvc", "pvcd", 1)
}
}
validFileShareName = getValidFileShareName(name)
}
tags, err := ConvertTagsToMap(customTags)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, err.Error())
}
if strings.TrimSpace(storageEndpointSuffix) == "" {
storageEndpointSuffix = d.getStorageEndPointSuffix()
}
accountOptions := &azure.AccountOptions{
Name: account,
Type: sku,
Kind: accountKind,
SubscriptionID: subsID,
ResourceGroup: resourceGroup,
Location: location,
EnableHTTPSTrafficOnly: enableHTTPSTrafficOnly,
MatchTags: matchTags,
Tags: tags,
VirtualNetworkResourceIDs: vnetResourceIDs,
CreateAccount: createAccount,
CreatePrivateEndpoint: createPrivateEndpoint,
EnableLargeFileShare: enableLFS,
DisableFileServiceDeleteRetentionPolicy: disableDeleteRetentionPolicy,
AllowBlobPublicAccess: allowBlobPublicAccess,
VNetResourceGroup: vnetResourceGroup,
VNetName: vnetName,
SubnetName: subnetName,
RequireInfrastructureEncryption: requireInfraEncryption,
AccessTier: accountAccessTier,
StorageType: provider.StorageTypeFile,
StorageEndpointSuffix: storageEndpointSuffix,
IsMultichannelEnabled: isMultichannelEnabled,
PickRandomMatchingAccount: selectRandomMatchingAccount,
GetLatestAccountKey: getLatestAccountKey,
}
var volumeID string
requestName := "controller_create_volume"
if req.GetVolumeContentSource() != nil {
switch req.VolumeContentSource.Type.(type) {
case *csi.VolumeContentSource_Snapshot:
requestName = "controller_create_volume_from_snapshot"
case *csi.VolumeContentSource_Volume:
requestName = "controller_create_volume_from_volume"
}
}
mc := metrics.NewMetricContext(azureFileCSIDriverName, requestName, d.cloud.ResourceGroup, subsID, d.Name)
isOperationSucceeded := false
defer func() {
mc.ObserveOperationWithResult(isOperationSucceeded, VolumeID, volumeID)
}()
var accountKey, lockKey string
accountName := account
if len(req.GetSecrets()) == 0 && accountName == "" {
if v, ok := d.volMap.Load(volName); ok {
accountName = v.(string)
} else {
lockKey = fmt.Sprintf("%s%s%s%s%s%s%s%v%v%v%v%v", sku, accountKind, resourceGroup, location, protocol, subsID, accountAccessTier,
pointer.BoolDeref(createPrivateEndpoint, false), pointer.BoolDeref(allowBlobPublicAccess, false), pointer.BoolDeref(requireInfraEncryption, false),
pointer.BoolDeref(enableLFS, false), pointer.BoolDeref(disableDeleteRetentionPolicy, false))
// search in cache first
cache, err := d.accountSearchCache.Get(lockKey, azcache.CacheReadTypeDefault)
if err != nil {
return nil, status.Errorf(codes.Internal, err.Error())
}
if cache != nil {
accountName = cache.(string)
} else {
d.volLockMap.LockEntry(lockKey)
accountName, accountKey, err = d.cloud.EnsureStorageAccount(ctx, accountOptions, defaultAccountNamePrefix)
if isRetriableError(err) {
klog.Warningf("EnsureStorageAccount(%s) failed with error(%v), waiting for retrying", account, err)
sleepIfThrottled(err, accountOpThrottlingSleepSec)
}
d.volLockMap.UnlockEntry(lockKey)
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to ensure storage account: %v", err)
}
if accountQuota > minimumAccountQuota {
totalQuotaGB, fileshareNum, err := d.GetTotalAccountQuota(ctx, subsID, resourceGroup, accountName)
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to get total quota on account(%s), error: %v", accountName, err)
}
klog.V(2).Infof("total used quota on account(%s) is %d GB, file share number: %d", accountName, totalQuotaGB, fileshareNum)
if totalQuotaGB > accountQuota {
klog.Warningf("account(%s) used quota(%d GB) is over %d GB, skip matching current account", accountName, totalQuotaGB, accountQuota)
if rerr := d.cloud.AddStorageAccountTags(ctx, subsID, resourceGroup, accountName, skipMatchingTag); rerr != nil {
klog.Warningf("AddStorageAccountTags(%v) on account(%s) subsID(%s) rg(%s) failed with error: %v", tags, accountName, subsID, resourceGroup, rerr.Error())
}
// release volume lock first to prevent deadlock
d.volumeLocks.Release(volName)
return d.CreateVolume(ctx, req)
}
}
d.accountSearchCache.Set(lockKey, accountName)
d.volMap.Store(volName, accountName)
if accountKey != "" {
d.accountCacheMap.Set(accountName, accountKey)
}
}
}
}
if pointer.BoolDeref(createPrivateEndpoint, false) {
setKeyValueInMap(parameters, serverNameField, fmt.Sprintf("%s.privatelink.file.%s", accountName, storageEndpointSuffix))
}
accountOptions.Name = accountName
secret := req.GetSecrets()
if len(secret) == 0 && useDataPlaneAPI {
if accountKey == "" {
if accountKey, err = d.GetStorageAccesskey(ctx, accountOptions, secret, secretName, secretNamespace); err != nil {
return nil, status.Errorf(codes.Internal, "failed to GetStorageAccesskey on account(%s) rg(%s), error: %v", accountOptions.Name, accountOptions.ResourceGroup, err)
}
}
secret = createStorageAccountSecret(accountName, accountKey)
// skip validating file share quota if useDataPlaneAPI
} else {
if quota, err := d.getFileShareQuota(ctx, subsID, resourceGroup, accountName, validFileShareName, secret); err != nil {
return nil, status.Errorf(codes.Internal, err.Error())
} else if quota != -1 && quota < fileShareSize {
return nil, status.Errorf(codes.AlreadyExists, "request file share(%s) already exists, but its capacity %d is smaller than %d", validFileShareName, quota, fileShareSize)
}
}
shareOptions := &fileclient.ShareOptions{
Name: validFileShareName,
Protocol: shareProtocol,
RequestGiB: fileShareSize,
AccessTier: shareAccessTier,
RootSquash: rootSquashType,
}
klog.V(2).Infof("begin to create file share(%s) on account(%s) type(%s) subID(%s) rg(%s) location(%s) size(%d) protocol(%s)", validFileShareName, accountName, sku, subsID, resourceGroup, location, fileShareSize, shareProtocol)
if err := d.CreateFileShare(ctx, accountOptions, shareOptions, secret); err != nil {
if strings.Contains(err.Error(), accountLimitExceedManagementAPI) || strings.Contains(err.Error(), accountLimitExceedDataPlaneAPI) {
klog.Warningf("create file share(%s) on account(%s) type(%s) subID(%s) rg(%s) location(%s) size(%d), error: %v, skip matching current account", validFileShareName, accountName, sku, subsID, resourceGroup, location, fileShareSize, err)
if rerr := d.cloud.AddStorageAccountTags(ctx, subsID, resourceGroup, accountName, skipMatchingTag); rerr != nil {
klog.Warningf("AddStorageAccountTags(%v) on account(%s) subsID(%s) rg(%s) failed with error: %v", tags, accountName, subsID, resourceGroup, rerr.Error())
}
// do not remove skipMatchingTag in a period of time
d.skipMatchingTagCache.Set(accountName, "")
// release volume lock first to prevent deadlock
d.volumeLocks.Release(volName)
// clean search cache
if err := d.accountSearchCache.Delete(lockKey); err != nil {
return nil, status.Errorf(codes.Internal, err.Error())
}
// remove the volName from the volMap to stop matching the same storage account
d.volMap.Delete(volName)
return d.CreateVolume(ctx, req)
}
return nil, status.Errorf(codes.Internal, "failed to create file share(%s) on account(%s) type(%s) subsID(%s) rg(%s) location(%s) size(%d), error: %v", validFileShareName, account, sku, subsID, resourceGroup, location, fileShareSize, err)
}
if req.GetVolumeContentSource() != nil {
accountSASToken, authAzcopyEnv, err := d.getAzcopyAuth(ctx, accountName, accountKey, storageEndpointSuffix, accountOptions, secret, secretName, secretNamespace, false)
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to getAzcopyAuth on account(%s) rg(%s), error: %v", accountOptions.Name, accountOptions.ResourceGroup, err)
}
if err := d.copyVolume(ctx, req, accountName, accountSASToken, authAzcopyEnv, secretName, secretNamespace, secret, shareOptions, accountOptions, storageEndpointSuffix); err != nil {
return nil, err
}
// storeAccountKey is not needed here since copy volume is only using SAS token
storeAccountKey = false
}
klog.V(2).Infof("create file share %s on storage account %s successfully", validFileShareName, accountName)
if isDiskFsType(fsType) && !strings.HasSuffix(diskName, vhdSuffix) && req.GetVolumeContentSource() == nil {
if accountKey == "" {
if accountKey, err = d.GetStorageAccesskey(ctx, accountOptions, req.GetSecrets(), secretName, secretNamespace); err != nil {
return nil, status.Errorf(codes.Internal, "failed to GetStorageAccesskey on account(%s) rg(%s), error: %v", accountOptions.Name, accountOptions.ResourceGroup, err)
}
}
if fileShareName == "" {
// use pvc name as vhd disk name if file share not specified
diskName = validFileShareName + vhdSuffix
} else {
// use uuid as vhd disk name if file share specified
diskName = uuid.NewUUID().String() + vhdSuffix
}
diskSizeBytes := volumehelper.GiBToBytes(requestGiB)
klog.V(2).Infof("begin to create vhd file(%s) size(%d) on share(%s) on account(%s) type(%s) rg(%s) location(%s)",
diskName, diskSizeBytes, validFileShareName, account, sku, resourceGroup, location)
if err := createDisk(ctx, accountName, accountKey, d.getStorageEndPointSuffix(), validFileShareName, diskName, diskSizeBytes); err != nil {
return nil, status.Errorf(codes.Internal, "failed to create VHD disk: %v", err)
}
klog.V(2).Infof("create vhd file(%s) size(%d) on share(%s) on account(%s) type(%s) rg(%s) location(%s) successfully",
diskName, diskSizeBytes, validFileShareName, account, sku, resourceGroup, location)
setKeyValueInMap(parameters, diskNameField, diskName)
}
if storeAccountKey && len(req.GetSecrets()) == 0 {
secretCacheKey := accountName + secretName + secretNamespace
if useSeretCache {
cache, err := d.secretCacheMap.Get(secretCacheKey, azcache.CacheReadTypeDefault)
if err != nil {
return nil, status.Errorf(codes.Internal, "get cache key(%s) failed with %v", secretCacheKey, err)
}
useSeretCache = (cache != nil)
}
if !useSeretCache {
if accountKey == "" {
if accountKey, err = d.GetStorageAccesskey(ctx, accountOptions, req.GetSecrets(), secretName, secretNamespace); err != nil {
return nil, status.Errorf(codes.Internal, "failed to GetStorageAccesskey on account(%s) rg(%s), error: %v", accountOptions.Name, accountOptions.ResourceGroup, err)
}
}
storeSecretName, err := d.SetAzureCredentials(ctx, accountName, accountKey, secretName, secretNamespace)
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to store storage account key: %v", err)
}
if storeSecretName != "" {
klog.V(2).Infof("store account key to k8s secret(%v) in %s namespace", storeSecretName, secretNamespace)
}
d.secretCacheMap.Set(secretCacheKey, "")
}
}
var uuid string
if fileShareName != "" {
// add volume name as suffix to differentiate volumeID since "shareName" is specified
// not necessary for dynamic file share name creation since volumeID already contains volume name
uuid = volName
}
volumeID = fmt.Sprintf(volumeIDTemplate, resourceGroup, accountName, validFileShareName, diskName, uuid, secretNamespace)
if subsID != "" && subsID != d.cloud.SubscriptionID {
volumeID = volumeID + "#" + subsID
}
if useDataPlaneAPI {
d.dataPlaneAPIVolMap.Store(volumeID, "")
}
isOperationSucceeded = true
// reset secretNamespace field in VolumeContext
setKeyValueInMap(parameters, secretNamespaceField, secretNamespace)
return &csi.CreateVolumeResponse{
Volume: &csi.Volume{
VolumeId: volumeID,
CapacityBytes: capacityBytes,
VolumeContext: parameters,
ContentSource: req.GetVolumeContentSource(),
},
}, nil
}
// DeleteVolume delete an azure file
func (d *Driver) DeleteVolume(ctx context.Context, req *csi.DeleteVolumeRequest) (*csi.DeleteVolumeResponse, error) {
volumeID := req.GetVolumeId()
if len(volumeID) == 0 {
return nil, status.Error(codes.InvalidArgument, "Volume ID missing in request")
}
if err := d.ValidateControllerServiceRequest(csi.ControllerServiceCapability_RPC_CREATE_DELETE_VOLUME); err != nil {
return nil, status.Errorf(codes.InvalidArgument, "invalid delete volume request: %v", req)
}
if acquired := d.volumeLocks.TryAcquire(volumeID); !acquired {
return nil, status.Errorf(codes.Aborted, volumeOperationAlreadyExistsFmt, volumeID)
}
defer d.volumeLocks.Release(volumeID)
resourceGroupName, accountName, fileShareName, _, secretNamespace, subsID, err := GetFileShareInfo(volumeID)
if err != nil {
// According to CSI Driver Sanity Tester, should succeed when an invalid volume id is used
klog.Errorf("GetFileShareInfo(%s) in DeleteVolume failed with error: %v", volumeID, err)
return &csi.DeleteVolumeResponse{}, nil
}
if resourceGroupName == "" {
resourceGroupName = d.cloud.ResourceGroup
}
if subsID == "" {
subsID = d.cloud.SubscriptionID
}
secret := req.GetSecrets()
if len(secret) == 0 && d.useDataPlaneAPI(volumeID, accountName) {
reqContext := map[string]string{}
if secretNamespace != "" {
setKeyValueInMap(reqContext, secretNamespaceField, secretNamespace)
}
// use data plane api, get account key first
_, _, accountKey, _, _, _, err := d.GetAccountInfo(ctx, volumeID, req.GetSecrets(), reqContext)
if err != nil {
return nil, status.Errorf(codes.NotFound, "get account info from(%s) failed with error: %v", volumeID, err)
}
secret = createStorageAccountSecret(accountName, accountKey)
}
mc := metrics.NewMetricContext(azureFileCSIDriverName, "controller_delete_volume", resourceGroupName, subsID, d.Name)
isOperationSucceeded := false
defer func() {
mc.ObserveOperationWithResult(isOperationSucceeded, VolumeID, volumeID)
}()
if err := d.DeleteFileShare(ctx, subsID, resourceGroupName, accountName, fileShareName, secret); err != nil {
return nil, status.Errorf(codes.Internal, "DeleteFileShare %s under account(%s) rg(%s) failed with error: %v", fileShareName, accountName, resourceGroupName, err)
}
klog.V(2).Infof("azure file(%s) under subsID(%s) rg(%s) account(%s) volume(%s) is deleted successfully", fileShareName, subsID, resourceGroupName, accountName, volumeID)
if err := d.RemoveStorageAccountTag(ctx, subsID, resourceGroupName, accountName, azure.SkipMatchingTag); err != nil {
klog.Warningf("RemoveStorageAccountTag(%s) under rg(%s) account(%s) failed with %v", azure.SkipMatchingTag, resourceGroupName, accountName, err)
}
isOperationSucceeded = true
return &csi.DeleteVolumeResponse{}, nil
}
// copyVolume copy an azure file
func (d *Driver) copyVolume(ctx context.Context, req *csi.CreateVolumeRequest, accountName, accountSASToken string, authAzcopyEnv []string, secretName, secretNamespace string, secrets map[string]string, shareOptions *fileclient.ShareOptions, accountOptions *azure.AccountOptions, storageEndpointSuffix string) error {
vs := req.VolumeContentSource
switch vs.Type.(type) {
case *csi.VolumeContentSource_Snapshot:
return d.restoreSnapshot(ctx, req, accountName, accountSASToken, authAzcopyEnv, secretName, secretNamespace, secrets, shareOptions, accountOptions, storageEndpointSuffix)
case *csi.VolumeContentSource_Volume:
return d.copyFileShare(ctx, req, accountSASToken, authAzcopyEnv, secretName, secretNamespace, secrets, shareOptions, accountOptions, storageEndpointSuffix)
default:
return status.Errorf(codes.InvalidArgument, "%v is not a proper volume source", vs)
}
}
// ControllerGetVolume get volume
func (d *Driver) ControllerGetVolume(context.Context, *csi.ControllerGetVolumeRequest) (*csi.ControllerGetVolumeResponse, error) {
return nil, status.Error(codes.Unimplemented, "")
}
// ValidateVolumeCapabilities return the capabilities of the volume
func (d *Driver) ValidateVolumeCapabilities(ctx context.Context, req *csi.ValidateVolumeCapabilitiesRequest) (*csi.ValidateVolumeCapabilitiesResponse, error) {
volumeID := req.GetVolumeId()
if len(volumeID) == 0 {
return nil, status.Error(codes.InvalidArgument, "Volume ID not provided")
}
volCaps := req.GetVolumeCapabilities()
if len(volCaps) == 0 {
return nil, status.Error(codes.InvalidArgument, "Volume capabilities not provided")
}
resourceGroupName, accountName, _, fileShareName, diskName, subsID, err := d.GetAccountInfo(ctx, volumeID, req.GetSecrets(), req.GetVolumeContext())
if err != nil || accountName == "" || fileShareName == "" {
return nil, status.Errorf(codes.NotFound, "get account info from(%s) failed with error: %v", volumeID, err)
}
if resourceGroupName == "" {
resourceGroupName = d.cloud.ResourceGroup
}
if subsID == "" {
subsID = d.cloud.SubscriptionID
}
if quota, err := d.getFileShareQuota(ctx, subsID, resourceGroupName, accountName, fileShareName, req.GetSecrets()); err != nil {
return nil, status.Errorf(codes.Internal, "error checking if volume(%s) exists: %v", volumeID, err)
} else if quota == -1 {
return nil, status.Errorf(codes.NotFound, "the requested volume(%s) does not exist.", volumeID)
}
confirmed := &csi.ValidateVolumeCapabilitiesResponse_Confirmed{VolumeCapabilities: volCaps}
if !strings.HasSuffix(diskName, vhdSuffix) {
return &csi.ValidateVolumeCapabilitiesResponse{Confirmed: confirmed}, nil
}
for _, c := range volCaps {
if c.GetAccessMode().Mode == csi.VolumeCapability_AccessMode_MULTI_NODE_SINGLE_WRITER {
return &csi.ValidateVolumeCapabilitiesResponse{}, nil
}
}
return &csi.ValidateVolumeCapabilitiesResponse{Confirmed: confirmed}, nil
}
// ControllerGetCapabilities returns the capabilities of the Controller plugin
func (d *Driver) ControllerGetCapabilities(_ context.Context, _ *csi.ControllerGetCapabilitiesRequest) (*csi.ControllerGetCapabilitiesResponse, error) {
return &csi.ControllerGetCapabilitiesResponse{
Capabilities: d.Cap,
}, nil
}
// GetCapacity returns the capacity of the total available storage pool
func (d *Driver) GetCapacity(_ context.Context, _ *csi.GetCapacityRequest) (*csi.GetCapacityResponse, error) {
return nil, status.Error(codes.Unimplemented, "")
}
// ListVolumes return all available volumes
func (d *Driver) ListVolumes(_ context.Context, _ *csi.ListVolumesRequest) (*csi.ListVolumesResponse, error) {
return nil, status.Error(codes.Unimplemented, "")
}
// ControllerPublishVolume make a volume available on some required node
func (d *Driver) ControllerPublishVolume(_ context.Context, _ *csi.ControllerPublishVolumeRequest) (*csi.ControllerPublishVolumeResponse, error) {
return nil, status.Error(codes.Unimplemented, "")
}
// ControllerUnpublishVolume detach the volume on a specified node
func (d *Driver) ControllerUnpublishVolume(_ context.Context, _ *csi.ControllerUnpublishVolumeRequest) (*csi.ControllerUnpublishVolumeResponse, error) {
return nil, status.Error(codes.Unimplemented, "")
}
// CreateSnapshot create a snapshot
func (d *Driver) CreateSnapshot(ctx context.Context, req *csi.CreateSnapshotRequest) (*csi.CreateSnapshotResponse, error) {
sourceVolumeID := req.GetSourceVolumeId()
snapshotName := req.Name
if len(snapshotName) == 0 {
return nil, status.Error(codes.InvalidArgument, "Snapshot name must be provided")
}
if len(sourceVolumeID) == 0 {
return nil, status.Error(codes.InvalidArgument, "CreateSnapshot Source Volume ID must be provided")
}
rgName, accountName, fileShareName, _, _, subsID, err := GetFileShareInfo(sourceVolumeID) //nolint:dogsled
if err != nil {
return nil, status.Error(codes.Internal, fmt.Sprintf("GetFileShareInfo(%s) failed with error: %v", sourceVolumeID, err))
}
if rgName == "" {
rgName = d.cloud.ResourceGroup
}
if subsID == "" {
subsID = d.cloud.SubscriptionID
}
var useDataPlaneAPI bool
for k, v := range req.GetParameters() {
switch strings.ToLower(k) {
case useDataPlaneAPIField:
useDataPlaneAPI = strings.EqualFold(v, trueValue)
default:
return nil, status.Errorf(codes.InvalidArgument, fmt.Sprintf("invalid parameter %q in storage class", k))
}
}
mc := metrics.NewMetricContext(azureFileCSIDriverName, "controller_create_snapshot", rgName, subsID, d.Name)
isOperationSucceeded := false
defer func() {
mc.ObserveOperationWithResult(isOperationSucceeded, SourceResourceID, sourceVolumeID, SnapshotName, snapshotName)
}()
exists, itemSnapshot, itemSnapshotTime, itemSnapshotQuota, err := d.snapshotExists(ctx, sourceVolumeID, snapshotName, req.GetSecrets(), useDataPlaneAPI)
if err != nil {
if exists {
return nil, status.Errorf(codes.AlreadyExists, "%v", err)
}
return nil, status.Errorf(codes.Internal, "failed to check if snapshot(%v) exists: %v", snapshotName, err)
}
if exists {
klog.V(2).Infof("snapshot(%s) already exists", snapshotName)
return &csi.CreateSnapshotResponse{
Snapshot: &csi.Snapshot{
SizeBytes: volumehelper.GiBToBytes(int64(itemSnapshotQuota)),
SnapshotId: sourceVolumeID + "#" + itemSnapshot,
SourceVolumeId: sourceVolumeID,
CreationTime: timestamppb.New(itemSnapshotTime),
// Since the snapshot of azurefile has no field of ReadyToUse, here ReadyToUse is always set to true.
ReadyToUse: true,
},
}, nil
}
if len(req.GetSecrets()) > 0 || useDataPlaneAPI {
shareURL, err := d.getShareURL(ctx, sourceVolumeID, req.GetSecrets())
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to get share url with (%s): %v", sourceVolumeID, err)
}
snapshotShare, err := shareURL.CreateSnapshot(ctx, azfile.Metadata{snapshotNameKey: snapshotName})
if err != nil {
return nil, status.Errorf(codes.Internal, "create snapshot from(%s) failed with %v, shareURL: %q", sourceVolumeID, err, shareURL)
}
properties, err := shareURL.GetProperties(ctx)
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to get snapshot properties from (%s): %v", snapshotShare.Snapshot(), err)
}
itemSnapshot = snapshotShare.Snapshot()
itemSnapshotTime = properties.LastModified()
itemSnapshotQuota = properties.Quota()
} else {
snapshotShare, err := d.cloud.FileClient.WithSubscriptionID(subsID).CreateFileShare(ctx, rgName, accountName, &fileclient.ShareOptions{Name: fileShareName, Metadata: map[string]*string{snapshotNameKey: &snapshotName}}, snapshotsExpand)
if err != nil {
return nil, status.Errorf(codes.Internal, "create snapshot from(%s) failed with %v, accountName: %q", sourceVolumeID, err, accountName)
}
if snapshotShare.SnapshotTime == nil {
return nil, status.Errorf(codes.Internal, "Last modified time of snapshot is null")
}
itemSnapshot = snapshotShare.SnapshotTime.Format(snapshotTimeFormat)
itemSnapshotTime = snapshotShare.SnapshotTime.Time
itemSnapshotQuota = pointer.Int32Deref(snapshotShare.ShareQuota, 0)
}
klog.V(2).Infof("created share snapshot: %s, time: %v, quota: %dGiB", itemSnapshot, itemSnapshotTime, itemSnapshotQuota)
if itemSnapshotQuota == 0 {
itemSnapshotQuota = defaultAzureFileQuota
}
createResp := &csi.CreateSnapshotResponse{
Snapshot: &csi.Snapshot{
SizeBytes: volumehelper.GiBToBytes(int64(itemSnapshotQuota)),
SnapshotId: sourceVolumeID + "#" + itemSnapshot,
SourceVolumeId: sourceVolumeID,
CreationTime: timestamppb.New(itemSnapshotTime),
// Since the snapshot of azurefile has no field of ReadyToUse, here ReadyToUse is always set to true.
ReadyToUse: true,
},
}
isOperationSucceeded = true
return createResp, nil
}
// DeleteSnapshot delete a snapshot (todo)
func (d *Driver) DeleteSnapshot(ctx context.Context, req *csi.DeleteSnapshotRequest) (*csi.DeleteSnapshotResponse, error) {
if len(req.SnapshotId) == 0 {
return nil, status.Error(codes.InvalidArgument, "Snapshot ID must be provided")
}
rgName, accountName, fileShareName, _, _, _, err := GetFileShareInfo(req.SnapshotId) //nolint:dogsled
if fileShareName == "" || err != nil {
// According to CSI Driver Sanity Tester, should succeed when an invalid snapshot id is used
klog.V(4).Infof("failed to get share url with (%s): %v, returning with success", req.SnapshotId, err)
return &csi.DeleteSnapshotResponse{}, nil
}
snapshot, err := getSnapshot(req.SnapshotId)
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to get snapshot name with (%s): %v", req.SnapshotId, err)
}
if rgName == "" {
rgName = d.cloud.ResourceGroup
}
subsID := d.cloud.SubscriptionID
mc := metrics.NewMetricContext(azureFileCSIDriverName, "controller_delete_snapshot", rgName, subsID, d.Name)
isOperationSucceeded := false
defer func() {
mc.ObserveOperationWithResult(isOperationSucceeded, SnapshotID, req.SnapshotId)
}()
var deleteErr error
if len(req.GetSecrets()) > 0 {
shareURL, err := d.getShareURL(ctx, req.SnapshotId, req.GetSecrets())
if err != nil {
// According to CSI Driver Sanity Tester, should succeed when an invalid snapshot id is used
klog.V(4).Infof("failed to get share url with (%s): %v, returning with success", req.SnapshotId, err)
return &csi.DeleteSnapshotResponse{}, nil
}
_, deleteErr = shareURL.WithSnapshot(snapshot).Delete(ctx, azfile.DeleteSnapshotsOptionNone)
} else {
deleteErr = d.cloud.FileClient.WithSubscriptionID(subsID).DeleteFileShare(ctx, rgName, accountName, fileShareName, snapshot)
}
if deleteErr != nil {
if strings.Contains(deleteErr.Error(), "ShareSnapshotNotFound") {
klog.Warningf("the specify snapshot(%s) was not found", snapshot)
return &csi.DeleteSnapshotResponse{}, nil
}
return nil, status.Errorf(codes.Internal, "failed to delete snapshot(%s): %v", snapshot, deleteErr)
}
klog.V(2).Infof("delete snapshot(%s) successfully", snapshot)
isOperationSucceeded = true
return &csi.DeleteSnapshotResponse{}, nil
}
// ListSnapshots list all snapshots (todo)
func (d *Driver) ListSnapshots(_ context.Context, _ *csi.ListSnapshotsRequest) (*csi.ListSnapshotsResponse, error) {
return nil, status.Error(codes.Unimplemented, "")
}
// restoreSnapshot restores from a snapshot
func (d *Driver) restoreSnapshot(ctx context.Context, req *csi.CreateVolumeRequest, dstAccountName, dstAccountSasToken string, authAzcopyEnv []string, secretName, secretNamespace string, secrets map[string]string, shareOptions *fileclient.ShareOptions, accountOptions *azure.AccountOptions, storageEndpointSuffix string) error {
if shareOptions.Protocol == storage.EnabledProtocolsNFS {
return fmt.Errorf("protocol nfs is not supported for snapshot restore")
}
var sourceSnapshotID string
if req.GetVolumeContentSource() != nil && req.GetVolumeContentSource().GetSnapshot() != nil {
sourceSnapshotID = req.GetVolumeContentSource().GetSnapshot().GetSnapshotId()
}