-
Notifications
You must be signed in to change notification settings - Fork 183
/
controllerserver.go
1052 lines (924 loc) · 40.6 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 azuredisk
import (
"context"
"fmt"
"path"
"sort"
"strconv"
"strings"
"github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-03-01/compute"
"github.com/container-storage-interface/spec/lib/go/csi"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
cloudprovider "k8s.io/cloud-provider"
volerr "k8s.io/cloud-provider/volume/errors"
"k8s.io/klog/v2"
consts "sigs.k8s.io/azuredisk-csi-driver/pkg/azureconstants"
"sigs.k8s.io/azuredisk-csi-driver/pkg/azureutils"
"sigs.k8s.io/azuredisk-csi-driver/pkg/optimization"
volumehelper "sigs.k8s.io/azuredisk-csi-driver/pkg/util"
azureconstants "sigs.k8s.io/cloud-provider-azure/pkg/consts"
"sigs.k8s.io/cloud-provider-azure/pkg/metrics"
azure "sigs.k8s.io/cloud-provider-azure/pkg/provider"
)
// listVolumeStatus explains the return status of `listVolumesByResourceGroup`
type listVolumeStatus struct {
numVisited int // the number of iterated azure disks
isCompleteRun bool // isCompleteRun is flagged true if the function iterated through all azure disks
entries []*csi.ListVolumesResponse_Entry
err error
}
// CreateVolume provisions an azure disk
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
}
params := req.GetParameters()
diskParams, err := azureutils.ParseDiskParameters(params)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "Failed parsing disk parameters: %v", err)
}
name := req.GetName()
if len(name) == 0 {
return nil, status.Error(codes.InvalidArgument, "CreateVolume Name must be provided")
}
volCaps := req.GetVolumeCapabilities()
if len(volCaps) == 0 {
return nil, status.Error(codes.InvalidArgument, "CreateVolume Volume capabilities must be provided")
}
if !azureutils.IsValidVolumeCapabilities(volCaps, diskParams.MaxShares) {
return nil, status.Error(codes.InvalidArgument, "Volume capability not supported")
}
isAdvancedPerfProfile := strings.EqualFold(diskParams.PerfProfile, consts.PerfProfileAdvanced)
// If perfProfile is set to advanced and no/invalid device settings are provided, fail the request
if d.getPerfOptimizationEnabled() && isAdvancedPerfProfile {
if err := optimization.AreDeviceSettingsValid(consts.DummyBlockDevicePathLinux, diskParams.DeviceSettings); err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error())
}
}
if acquired := d.volumeLocks.TryAcquire(name); !acquired {
return nil, status.Errorf(codes.Aborted, volumeOperationAlreadyExistsFmt, name)
}
defer d.volumeLocks.Release(name)
capacityBytes := req.GetCapacityRange().GetRequiredBytes()
volSizeBytes := int64(capacityBytes)
requestGiB := int(volumehelper.RoundUpGiB(volSizeBytes))
if requestGiB < consts.MinimumDiskSizeGiB {
requestGiB = consts.MinimumDiskSizeGiB
}
maxVolSize := int(volumehelper.RoundUpGiB(req.GetCapacityRange().GetLimitBytes()))
if (maxVolSize > 0) && (maxVolSize < requestGiB) {
return nil, status.Error(codes.InvalidArgument, "After round-up, volume size exceeds the limit specified")
}
if diskParams.Location == "" {
diskParams.Location = d.cloud.Location
}
localCloud := d.cloud
if diskParams.UserAgent != "" {
localCloud, err = azureutils.GetCloudProvider(ctx, d.kubeconfig, d.cloudConfigSecretName, d.cloudConfigSecretNamespace, diskParams.UserAgent, d.allowEmptyCloudConfig)
if err != nil {
return nil, status.Errorf(codes.Internal, "create cloud with UserAgent(%s) failed with: (%s)", diskParams.UserAgent, err)
}
}
if azureutils.IsAzureStackCloud(localCloud.Config.Cloud, localCloud.Config.DisableAzureStackCloud) {
if diskParams.MaxShares > 1 {
return nil, status.Error(codes.InvalidArgument, fmt.Sprintf("Invalid maxShares value: %d as Azure Stack does not support shared disk.", diskParams.MaxShares))
}
}
if diskParams.DiskName == "" {
diskParams.DiskName = name
}
diskParams.DiskName = azureutils.CreateValidDiskName(diskParams.DiskName)
if diskParams.ResourceGroup == "" {
diskParams.ResourceGroup = d.cloud.ResourceGroup
}
// normalize values
skuName, err := azureutils.NormalizeStorageAccountType(diskParams.AccountType, localCloud.Config.Cloud, localCloud.Config.DisableAzureStackCloud)
if err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error())
}
if _, err := azureutils.NormalizeCachingMode(diskParams.CachingMode); err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error())
}
if skuName == azureconstants.PremiumV2LRS {
// PremiumV2LRS only supports None caching mode
azureutils.SetKeyValueInMap(diskParams.VolumeContext, consts.CachingModeField, string(v1.AzureDataDiskCachingNone))
}
if err := azureutils.ValidateDiskEncryptionType(diskParams.DiskEncryptionType); err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error())
}
networkAccessPolicy, err := azureutils.NormalizeNetworkAccessPolicy(diskParams.NetworkAccessPolicy)
if err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error())
}
requirement := req.GetAccessibilityRequirements()
diskZone := azureutils.PickAvailabilityZone(requirement, diskParams.Location, topologyKey)
accessibleTopology := []*csi.Topology{}
if skuName == compute.StandardSSDZRS || skuName == compute.PremiumZRS {
klog.V(2).Infof("diskZone(%s) is reset as empty since disk(%s) is ZRS(%s)", diskZone, diskParams.DiskName, skuName)
diskZone = ""
// make volume scheduled on all 3 availability zones
for i := 1; i <= 3; i++ {
topology := &csi.Topology{
Segments: map[string]string{topologyKey: fmt.Sprintf("%s-%d", diskParams.Location, i)},
}
accessibleTopology = append(accessibleTopology, topology)
}
// make volume scheduled on all non-zone nodes
topology := &csi.Topology{
Segments: map[string]string{topologyKey: ""},
}
accessibleTopology = append(accessibleTopology, topology)
} else {
accessibleTopology = []*csi.Topology{
{
Segments: map[string]string{topologyKey: diskZone},
},
}
}
if d.enableDiskCapacityCheck {
if ok, err := d.checkDiskCapacity(ctx, diskParams.SubscriptionID, diskParams.ResourceGroup, diskParams.DiskName, requestGiB); !ok {
return nil, err
}
}
klog.V(2).Infof("begin to create azure disk(%s) account type(%s) rg(%s) location(%s) size(%d) diskZone(%v) maxShares(%d)",
diskParams.DiskName, skuName, diskParams.ResourceGroup, diskParams.Location, requestGiB, diskZone, diskParams.MaxShares)
contentSource := &csi.VolumeContentSource{}
if strings.EqualFold(diskParams.WriteAcceleratorEnabled, consts.TrueValue) {
diskParams.Tags[azure.WriteAcceleratorEnabled] = consts.TrueValue
}
sourceID := ""
sourceType := ""
content := req.GetVolumeContentSource()
if content != nil {
if content.GetSnapshot() != nil {
sourceID = content.GetSnapshot().GetSnapshotId()
sourceType = consts.SourceSnapshot
contentSource = &csi.VolumeContentSource{
Type: &csi.VolumeContentSource_Snapshot{
Snapshot: &csi.VolumeContentSource_SnapshotSource{
SnapshotId: sourceID,
},
},
}
} else {
sourceID = content.GetVolume().GetVolumeId()
sourceType = consts.SourceVolume
contentSource = &csi.VolumeContentSource{
Type: &csi.VolumeContentSource_Volume{
Volume: &csi.VolumeContentSource_VolumeSource{
VolumeId: sourceID,
},
},
}
subsID := azureutils.GetSubscriptionIDFromURI(sourceID)
if sourceGiB, _ := d.GetSourceDiskSize(ctx, subsID, diskParams.ResourceGroup, path.Base(sourceID), 0, consts.SourceDiskSearchMaxDepth); sourceGiB != nil && *sourceGiB < int32(requestGiB) {
diskParams.VolumeContext[consts.ResizeRequired] = strconv.FormatBool(true)
}
}
}
if skuName == compute.UltraSSDLRS {
if diskParams.DiskIOPSReadWrite == "" && diskParams.DiskMBPSReadWrite == "" {
// set default DiskIOPSReadWrite, DiskMBPSReadWrite per request size
diskParams.DiskIOPSReadWrite = strconv.Itoa(getDefaultDiskIOPSReadWrite(requestGiB))
diskParams.DiskMBPSReadWrite = strconv.Itoa(getDefaultDiskMBPSReadWrite(requestGiB))
klog.V(2).Infof("set default DiskIOPSReadWrite as %s, DiskMBPSReadWrite as %s on disk(%s)", diskParams.DiskIOPSReadWrite, diskParams.DiskMBPSReadWrite, diskParams.DiskName)
}
}
diskParams.VolumeContext[consts.RequestedSizeGib] = strconv.Itoa(requestGiB)
volumeOptions := &azure.ManagedDiskOptions{
AvailabilityZone: diskZone,
BurstingEnabled: diskParams.EnableBursting,
DiskEncryptionSetID: diskParams.DiskEncryptionSetID,
DiskEncryptionType: diskParams.DiskEncryptionType,
DiskIOPSReadWrite: diskParams.DiskIOPSReadWrite,
DiskMBpsReadWrite: diskParams.DiskMBPSReadWrite,
DiskName: diskParams.DiskName,
LogicalSectorSize: int32(diskParams.LogicalSectorSize),
MaxShares: int32(diskParams.MaxShares),
ResourceGroup: diskParams.ResourceGroup,
SubscriptionID: diskParams.SubscriptionID,
SizeGB: requestGiB,
StorageAccountType: skuName,
SourceResourceID: sourceID,
SourceType: sourceType,
Tags: diskParams.Tags,
Location: diskParams.Location,
}
volumeOptions.SkipGetDiskOperation = d.isGetDiskThrottled()
// Azure Stack Cloud does not support NetworkAccessPolicy
if !azureutils.IsAzureStackCloud(localCloud.Config.Cloud, localCloud.Config.DisableAzureStackCloud) {
volumeOptions.NetworkAccessPolicy = networkAccessPolicy
if diskParams.DiskAccessID != "" {
volumeOptions.DiskAccessID = &diskParams.DiskAccessID
}
}
var diskURI string
mc := metrics.NewMetricContext(consts.AzureDiskCSIDriverName, "controller_create_volume", d.cloud.ResourceGroup, d.cloud.SubscriptionID, d.Name)
isOperationSucceeded := false
defer func() {
mc.ObserveOperationWithResult(isOperationSucceeded, consts.VolumeID, diskURI)
}()
diskURI, err = localCloud.CreateManagedDisk(ctx, volumeOptions)
if err != nil {
if strings.Contains(err.Error(), consts.NotFound) {
return nil, status.Error(codes.NotFound, err.Error())
}
return nil, status.Errorf(codes.Internal, err.Error())
}
isOperationSucceeded = true
klog.V(2).Infof("create azure disk(%s) account type(%s) rg(%s) location(%s) size(%d) tags(%s) successfully", diskParams.DiskName, skuName, diskParams.ResourceGroup, diskParams.Location, requestGiB, diskParams.Tags)
return &csi.CreateVolumeResponse{
Volume: &csi.Volume{
VolumeId: diskURI,
CapacityBytes: volumehelper.GiBToBytes(int64(requestGiB)),
VolumeContext: diskParams.VolumeContext,
ContentSource: contentSource,
AccessibleTopology: accessibleTopology,
},
}, nil
}
// DeleteVolume delete an azure disk
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 the request")
}
if err := d.ValidateControllerServiceRequest(csi.ControllerServiceCapability_RPC_CREATE_DELETE_VOLUME); err != nil {
return nil, status.Errorf(codes.Internal, "invalid delete volume req: %v", req)
}
diskURI := volumeID
if err := azureutils.IsValidDiskURI(diskURI); err != nil {
klog.Errorf("validateDiskURI(%s) in DeleteVolume failed with error: %v", diskURI, err)
return &csi.DeleteVolumeResponse{}, nil
}
if acquired := d.volumeLocks.TryAcquire(volumeID); !acquired {
return nil, status.Errorf(codes.Aborted, volumeOperationAlreadyExistsFmt, volumeID)
}
defer d.volumeLocks.Release(volumeID)
mc := metrics.NewMetricContext(consts.AzureDiskCSIDriverName, "controller_delete_volume", d.cloud.ResourceGroup, d.cloud.SubscriptionID, d.Name)
isOperationSucceeded := false
defer func() {
mc.ObserveOperationWithResult(isOperationSucceeded, consts.VolumeID, diskURI)
}()
klog.V(2).Infof("deleting azure disk(%s)", diskURI)
err := d.cloud.DeleteManagedDisk(ctx, diskURI)
klog.V(2).Infof("delete azure disk(%s) returned with %v", diskURI, err)
isOperationSucceeded = (err == nil)
return &csi.DeleteVolumeResponse{}, err
}
// ControllerGetVolume get volume
func (d *Driver) ControllerGetVolume(context.Context, *csi.ControllerGetVolumeRequest) (*csi.ControllerGetVolumeResponse, error) {
return nil, status.Error(codes.Unimplemented, "")
}
// ControllerPublishVolume attach an azure disk to a required node
func (d *Driver) ControllerPublishVolume(ctx context.Context, req *csi.ControllerPublishVolumeRequest) (*csi.ControllerPublishVolumeResponse, error) {
diskURI := req.GetVolumeId()
if len(diskURI) == 0 {
return nil, status.Error(codes.InvalidArgument, "Volume ID not provided")
}
volCap := req.GetVolumeCapability()
if volCap == nil {
return nil, status.Error(codes.InvalidArgument, "Volume capability not provided")
}
caps := []*csi.VolumeCapability{volCap}
maxShares, err := azureutils.GetMaxShares(req.GetVolumeContext())
if err != nil {
return nil, status.Error(codes.InvalidArgument, "MaxShares value not supported")
}
if !azureutils.IsValidVolumeCapabilities(caps, maxShares) {
return nil, status.Error(codes.InvalidArgument, "Volume capability not supported")
}
disk, err := d.checkDiskExists(ctx, diskURI)
if err != nil {
return nil, status.Error(codes.NotFound, fmt.Sprintf("Volume not found, failed with error: %v", err))
}
nodeID := req.GetNodeId()
if len(nodeID) == 0 {
return nil, status.Error(codes.InvalidArgument, "Node ID not provided")
}
nodeName := types.NodeName(nodeID)
diskName, err := azureutils.GetDiskName(diskURI)
if err != nil {
return nil, status.Errorf(codes.Internal, err.Error())
}
mc := metrics.NewMetricContext(consts.AzureDiskCSIDriverName, "controller_publish_volume", d.cloud.ResourceGroup, d.cloud.SubscriptionID, d.Name)
isOperationSucceeded := false
defer func() {
mc.ObserveOperationWithResult(isOperationSucceeded, consts.VolumeID, diskURI, consts.Node, string(nodeName))
}()
lun, vmState, err := d.cloud.GetDiskLun(diskName, diskURI, nodeName)
if err == cloudprovider.InstanceNotFound {
return nil, status.Error(codes.NotFound, fmt.Sprintf("failed to get azure instance id for node %q (%v)", nodeName, err))
}
vmStateStr := "<nil>"
if vmState != nil {
vmStateStr = *vmState
}
klog.V(2).Infof("GetDiskLun returned: %v. Initiating attaching volume %s to node %s (vmState %s).", err, diskURI, nodeName, vmStateStr)
volumeContext := req.GetVolumeContext()
if volumeContext == nil {
volumeContext = map[string]string{}
}
if err == nil {
if vmState != nil && strings.ToLower(*vmState) == "failed" {
klog.Warningf("VM(%s) is in failed state, update VM first", nodeName)
if err := d.cloud.UpdateVM(ctx, nodeName); err != nil {
return nil, status.Errorf(codes.Internal, "update instance %q failed with %v", nodeName, err)
}
}
// Volume is already attached to node.
klog.V(2).Infof("Attach operation is successful. volume %s is already attached to node %s at lun %d.", diskURI, nodeName, lun)
} else {
if strings.Contains(strings.ToLower(err.Error()), strings.ToLower(consts.TooManyRequests)) ||
strings.Contains(strings.ToLower(err.Error()), consts.ClientThrottled) {
return nil, status.Errorf(codes.Internal, err.Error())
}
var cachingMode compute.CachingTypes
if cachingMode, err = azureutils.GetCachingMode(volumeContext); err != nil {
return nil, status.Errorf(codes.Internal, err.Error())
}
klog.V(2).Infof("Trying to attach volume %s to node %s", diskURI, nodeName)
asyncAttach := isAsyncAttachEnabled(d.enableAsyncAttach, volumeContext)
lun, err = d.cloud.AttachDisk(ctx, asyncAttach, diskName, diskURI, nodeName, cachingMode, disk)
if err == nil {
klog.V(2).Infof("Attach operation successful: volume %s attached to node %s.", diskURI, nodeName)
} else {
if derr, ok := err.(*volerr.DanglingAttachError); ok {
if strings.EqualFold(string(nodeName), string(derr.CurrentNode)) {
err := status.Errorf(codes.Internal, "volume %s is actually attached to current node %s, return error", diskURI, nodeName)
klog.Warningf("%v", err)
return nil, err
}
klog.Warningf("volume %s is already attached to node %s, try detach first", diskURI, derr.CurrentNode)
if err = d.cloud.DetachDisk(ctx, diskName, diskURI, derr.CurrentNode); err != nil {
return nil, status.Errorf(codes.Internal, "Could not detach volume %s from node %s: %v", diskURI, derr.CurrentNode, err)
}
klog.V(2).Infof("Trying to attach volume %s to node %s again", diskURI, nodeName)
lun, err = d.cloud.AttachDisk(ctx, asyncAttach, diskName, diskURI, nodeName, cachingMode, disk)
}
if err != nil {
klog.Errorf("Attach volume %s to instance %s failed with %v", diskURI, nodeName, err)
return nil, status.Errorf(codes.Internal, "Attach volume %s to instance %s failed with %v", diskURI, nodeName, err)
}
}
klog.V(2).Infof("attach volume %s to node %s successfully", diskURI, nodeName)
}
publishContext := map[string]string{consts.LUN: strconv.Itoa(int(lun))}
if disk != nil {
if _, ok := volumeContext[consts.RequestedSizeGib]; !ok {
klog.V(6).Infof("found static PV(%s), insert disk properties to volumeattachments", diskURI)
azureutils.InsertDiskProperties(disk, publishContext)
}
}
isOperationSucceeded = true
return &csi.ControllerPublishVolumeResponse{PublishContext: publishContext}, nil
}
// ControllerUnpublishVolume detach an azure disk from a required node
func (d *Driver) ControllerUnpublishVolume(ctx context.Context, req *csi.ControllerUnpublishVolumeRequest) (*csi.ControllerUnpublishVolumeResponse, error) {
diskURI := req.GetVolumeId()
if len(diskURI) == 0 {
return nil, status.Error(codes.InvalidArgument, "Volume ID not provided")
}
nodeID := req.GetNodeId()
if len(nodeID) == 0 {
return nil, status.Error(codes.InvalidArgument, "Node ID not provided")
}
nodeName := types.NodeName(nodeID)
diskName, err := azureutils.GetDiskName(diskURI)
if err != nil {
return nil, status.Errorf(codes.Internal, err.Error())
}
mc := metrics.NewMetricContext(consts.AzureDiskCSIDriverName, "controller_unpublish_volume", d.cloud.ResourceGroup, d.cloud.SubscriptionID, d.Name)
isOperationSucceeded := false
defer func() {
mc.ObserveOperationWithResult(isOperationSucceeded, consts.VolumeID, diskURI, consts.Node, string(nodeName))
}()
klog.V(2).Infof("Trying to detach volume %s from node %s", diskURI, nodeID)
if err := d.cloud.DetachDisk(ctx, diskName, diskURI, nodeName); err != nil {
if strings.Contains(err.Error(), consts.ErrDiskNotFound) {
klog.Warningf("volume %s already detached from node %s", diskURI, nodeID)
} else {
return nil, status.Errorf(codes.Internal, "Could not detach volume %s from node %s: %v", diskURI, nodeID, err)
}
}
klog.V(2).Infof("detach volume %s from node %s successfully", diskURI, nodeID)
isOperationSucceeded = true
return &csi.ControllerUnpublishVolumeResponse{}, nil
}
// ValidateVolumeCapabilities return the capabilities of the volume
func (d *Driver) ValidateVolumeCapabilities(ctx context.Context, req *csi.ValidateVolumeCapabilitiesRequest) (*csi.ValidateVolumeCapabilitiesResponse, error) {
diskURI := req.GetVolumeId()
if len(diskURI) == 0 {
return nil, status.Error(codes.InvalidArgument, "Volume ID missing in the request")
}
volumeCapabilities := req.GetVolumeCapabilities()
if volumeCapabilities == nil {
return nil, status.Error(codes.InvalidArgument, "VolumeCapabilities missing in the request")
}
params := req.GetParameters()
maxShares, err := azureutils.GetMaxShares(params)
if err != nil {
return nil, status.Error(codes.InvalidArgument, "MaxShares value not supported")
}
if !azureutils.IsValidVolumeCapabilities(volumeCapabilities, maxShares) {
return &csi.ValidateVolumeCapabilitiesResponse{Message: "VolumeCapabilities are invalid"}, nil
}
if _, err := d.checkDiskExists(ctx, diskURI); err != nil {
return nil, status.Error(codes.NotFound, fmt.Sprintf("Volume not found, failed with error: %v", err))
}
return &csi.ValidateVolumeCapabilitiesResponse{
Confirmed: &csi.ValidateVolumeCapabilitiesResponse_Confirmed{
VolumeCapabilities: volumeCapabilities,
}}, nil
}
// ControllerGetCapabilities returns the capabilities of the Controller plugin
func (d *Driver) ControllerGetCapabilities(ctx context.Context, req *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(ctx context.Context, req *csi.GetCapacityRequest) (*csi.GetCapacityResponse, error) {
return nil, status.Error(codes.Unimplemented, "")
}
// ListVolumes return all available volumes
func (d *Driver) ListVolumes(ctx context.Context, req *csi.ListVolumesRequest) (*csi.ListVolumesResponse, error) {
start := 0
if req.StartingToken != "" {
var err error
start, err = strconv.Atoi(req.StartingToken)
if err != nil {
return nil, status.Errorf(codes.Aborted, "ListVolumes starting token(%s) parsing with error: %v", req.StartingToken, err)
}
if start < 0 {
return nil, status.Errorf(codes.Aborted, "ListVolumes starting token(%d) can not be negative", start)
}
}
if d.cloud.KubeClient != nil && d.cloud.KubeClient.CoreV1() != nil && d.cloud.KubeClient.CoreV1().PersistentVolumes() != nil {
klog.V(6).Infof("List Volumes in Cluster:")
return d.listVolumesInCluster(ctx, start, int(req.MaxEntries))
}
klog.V(6).Infof("List Volumes in Node Resource Group: %s", d.cloud.ResourceGroup)
return d.listVolumesInNodeResourceGroup(ctx, start, int(req.MaxEntries))
}
// listVolumesInCluster is a helper function for ListVolumes used for when there is an available kubeclient
func (d *Driver) listVolumesInCluster(ctx context.Context, start, maxEntries int) (*csi.ListVolumesResponse, error) {
pvList, err := d.cloud.KubeClient.CoreV1().PersistentVolumes().List(ctx, metav1.ListOptions{})
if err != nil {
return nil, status.Errorf(codes.Internal, "ListVolumes failed while fetching PersistentVolumes List with error: %v", err.Error())
}
// get all resource groups and put them into a sorted slice
rgMap := make(map[string]bool)
volSet := make(map[string]bool)
for _, pv := range pvList.Items {
if pv.Spec.CSI != nil && pv.Spec.CSI.Driver == d.Name {
diskURI := pv.Spec.CSI.VolumeHandle
if err := azureutils.IsValidDiskURI(diskURI); err != nil {
klog.Warningf("invalid disk uri (%s) with error(%v)", diskURI, err)
continue
}
rg, err := azureutils.GetResourceGroupFromURI(diskURI)
if err != nil {
klog.Warningf("failed to get resource group from disk uri (%s) with error(%v)", diskURI, err)
continue
}
subsID := azureutils.GetSubscriptionIDFromURI(diskURI)
if !strings.EqualFold(subsID, d.cloud.SubscriptionID) {
klog.V(6).Infof("disk(%s) not in current subscription(%s), skip", diskURI, d.cloud.SubscriptionID)
continue
}
rg, diskURI = strings.ToLower(rg), strings.ToLower(diskURI)
volSet[diskURI] = true
if _, visited := rgMap[rg]; visited {
continue
}
rgMap[rg] = true
}
}
resourceGroups := make([]string, len(rgMap))
i := 0
for rg := range rgMap {
resourceGroups[i] = rg
i++
}
sort.Strings(resourceGroups)
// loop through each resourceGroup to get disk lists
entries := []*csi.ListVolumesResponse_Entry{}
numVisited := 0
isCompleteRun, startFound := true, false
for _, resourceGroup := range resourceGroups {
if !isCompleteRun || (maxEntries > 0 && len(entries) >= maxEntries) {
isCompleteRun = false
break
}
localStart := start - numVisited
if startFound {
localStart = 0
}
listStatus := d.listVolumesByResourceGroup(ctx, resourceGroup, entries, localStart, maxEntries-len(entries), volSet)
numVisited += listStatus.numVisited
if listStatus.err != nil {
if status.Code(listStatus.err) == codes.FailedPrecondition {
continue
}
return nil, listStatus.err
}
startFound = true
entries = listStatus.entries
isCompleteRun = isCompleteRun && listStatus.isCompleteRun
}
// if start was not found, start token was greater than total number of disks
if start > 0 && !startFound {
return nil, status.Errorf(codes.FailedPrecondition, "ListVolumes starting token(%d) is greater than total number of disks", start)
}
nextTokenString := ""
if !isCompleteRun {
nextTokenString = strconv.Itoa(start + numVisited)
}
listVolumesResp := &csi.ListVolumesResponse{
Entries: entries,
NextToken: nextTokenString,
}
return listVolumesResp, nil
}
// listVolumesInNodeResourceGroup is a helper function for ListVolumes used for when there is no available kubeclient
func (d *Driver) listVolumesInNodeResourceGroup(ctx context.Context, start, maxEntries int) (*csi.ListVolumesResponse, error) {
entries := []*csi.ListVolumesResponse_Entry{}
listStatus := d.listVolumesByResourceGroup(ctx, d.cloud.ResourceGroup, entries, start, maxEntries, nil)
if listStatus.err != nil {
return nil, listStatus.err
}
nextTokenString := ""
if !listStatus.isCompleteRun {
nextTokenString = strconv.Itoa(listStatus.numVisited)
}
listVolumesResp := &csi.ListVolumesResponse{
Entries: listStatus.entries,
NextToken: nextTokenString,
}
return listVolumesResp, nil
}
// listVolumesByResourceGroup is a helper function that updates the ListVolumeResponse_Entry slice and returns number of total visited volumes, number of volumes that needs to be visited and an error if found
func (d *Driver) listVolumesByResourceGroup(ctx context.Context, resourceGroup string, entries []*csi.ListVolumesResponse_Entry, start, maxEntries int, volSet map[string]bool) listVolumeStatus {
disks, derr := d.cloud.DisksClient.ListByResourceGroup(ctx, "", resourceGroup)
if derr != nil {
return listVolumeStatus{err: status.Errorf(codes.Internal, "ListVolumes on rg(%s) failed with error: %v", resourceGroup, derr.Error())}
}
// if volSet is initialized but is empty, return
if volSet != nil && len(volSet) == 0 {
return listVolumeStatus{
numVisited: len(disks),
isCompleteRun: true,
entries: entries,
}
}
if start > 0 && start >= len(disks) {
return listVolumeStatus{
numVisited: len(disks),
err: status.Errorf(codes.FailedPrecondition, "ListVolumes starting token(%d) on rg(%s) is greater than total number of volumes", start, d.cloud.ResourceGroup),
}
}
if start < 0 {
start = 0
}
i := start
isCompleteRun := true
// Loop until
for ; i < len(disks); i++ {
if maxEntries > 0 && len(entries) >= maxEntries {
isCompleteRun = false
break
}
disk := disks[i]
// if given a set of volumes from KubeClient, only continue if the disk can be found in the set
if volSet != nil && !volSet[strings.ToLower(*disk.ID)] {
continue
}
// HyperVGeneration property is only setup for os disks. Only the non os disks should be included in the list
if disk.DiskProperties == nil || disk.DiskProperties.HyperVGeneration == "" {
nodeList := []string{}
if disk.ManagedBy != nil {
attachedNode, err := d.cloud.VMSet.GetNodeNameByProviderID(*disk.ManagedBy)
if err != nil {
return listVolumeStatus{err: err}
}
nodeList = append(nodeList, string(attachedNode))
}
entries = append(entries, &csi.ListVolumesResponse_Entry{
Volume: &csi.Volume{
VolumeId: *disk.ID,
},
Status: &csi.ListVolumesResponse_VolumeStatus{
PublishedNodeIds: nodeList,
},
})
}
}
return listVolumeStatus{
numVisited: i - start,
isCompleteRun: isCompleteRun,
entries: entries,
}
}
// ControllerExpandVolume controller expand volume
func (d *Driver) ControllerExpandVolume(ctx context.Context, req *csi.ControllerExpandVolumeRequest) (*csi.ControllerExpandVolumeResponse, error) {
if len(req.GetVolumeId()) == 0 {
return nil, status.Error(codes.InvalidArgument, "Volume ID missing in the request")
}
if err := d.ValidateControllerServiceRequest(csi.ControllerServiceCapability_RPC_EXPAND_VOLUME); err != nil {
return nil, status.Errorf(codes.InvalidArgument, "invalid expand volume request: %v", req)
}
capacityBytes := req.GetCapacityRange().GetRequiredBytes()
if capacityBytes == 0 {
return nil, status.Error(codes.InvalidArgument, "volume capacity range missing in request")
}
requestSize := *resource.NewQuantity(capacityBytes, resource.BinarySI)
diskURI := req.GetVolumeId()
if err := azureutils.IsValidDiskURI(diskURI); err != nil {
return nil, status.Errorf(codes.InvalidArgument, "disk URI(%s) is not valid: %v", diskURI, err)
}
diskName, err := azureutils.GetDiskName(diskURI)
if err != nil {
return nil, status.Errorf(codes.Internal, "could not get disk name from diskURI(%s) with error(%v)", diskURI, err)
}
resourceGroup, err := azureutils.GetResourceGroupFromURI(diskURI)
if err != nil {
return nil, status.Errorf(codes.Internal, "could not get resource group from diskURI(%s) with error(%v)", diskURI, err)
}
subsID := azureutils.GetSubscriptionIDFromURI(diskURI)
result, rerr := d.cloud.DisksClient.Get(ctx, subsID, resourceGroup, diskName)
if rerr != nil {
return nil, status.Errorf(codes.Internal, "could not get the disk(%s) under rg(%s) with error(%v)", diskName, resourceGroup, rerr.Error())
}
if result.DiskProperties.DiskSizeGB == nil {
return nil, status.Errorf(codes.Internal, "could not get size of the disk(%s)", diskName)
}
oldSize := *resource.NewQuantity(int64(*result.DiskProperties.DiskSizeGB), resource.BinarySI)
mc := metrics.NewMetricContext(consts.AzureDiskCSIDriverName, "controller_expand_volume", d.cloud.ResourceGroup, d.cloud.SubscriptionID, d.Name)
isOperationSucceeded := false
defer func() {
mc.ObserveOperationWithResult(isOperationSucceeded, consts.VolumeID, diskURI)
}()
klog.V(2).Infof("begin to expand azure disk(%s) with new size(%d)", diskURI, requestSize.Value())
newSize, err := d.cloud.ResizeDisk(ctx, diskURI, oldSize, requestSize, d.enableDiskOnlineResize)
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to resize disk(%s) with error(%v)", diskURI, err)
}
currentSize, ok := newSize.AsInt64()
if !ok {
return nil, status.Errorf(codes.Internal, "failed to transform disk size with error(%v)", err)
}
isOperationSucceeded = true
klog.V(2).Infof("expand azure disk(%s) successfully, currentSize(%d)", diskURI, currentSize)
return &csi.ControllerExpandVolumeResponse{
CapacityBytes: currentSize,
NodeExpansionRequired: true,
}, nil
}
// CreateSnapshot create a snapshot
func (d *Driver) CreateSnapshot(ctx context.Context, req *csi.CreateSnapshotRequest) (*csi.CreateSnapshotResponse, error) {
sourceVolumeID := req.GetSourceVolumeId()
if len(sourceVolumeID) == 0 {
return nil, status.Error(codes.InvalidArgument, "CreateSnapshot Source Volume ID must be provided")
}
snapshotName := req.Name
if len(snapshotName) == 0 {
return nil, status.Error(codes.InvalidArgument, "snapshot name must be provided")
}
snapshotName = azureutils.CreateValidDiskName(snapshotName)
var customTags string
// set incremental snapshot as true by default
incremental := true
var subsID, resourceGroup, dataAccessAuthMode string
var err error
localCloud := d.cloud
location := d.cloud.Location
parameters := req.GetParameters()
for k, v := range parameters {
switch strings.ToLower(k) {
case consts.TagsField:
customTags = v
case consts.IncrementalField:
if v == "false" {
incremental = false
}
case consts.ResourceGroupField:
resourceGroup = v
case consts.LocationField:
location = v
case consts.UserAgentField:
newUserAgent := v
localCloud, err = azureutils.GetCloudProvider(ctx, d.kubeconfig, d.cloudConfigSecretName, d.cloudConfigSecretNamespace, newUserAgent, d.allowEmptyCloudConfig)
if err != nil {
return nil, status.Errorf(codes.Internal, "create cloud with UserAgent(%s) failed with: (%s)", newUserAgent, err)
}
case consts.SubscriptionIDField:
subsID = v
case consts.DataAccessAuthModeField:
dataAccessAuthMode = v
default:
return nil, status.Errorf(codes.Internal, "AzureDisk - invalid option %s in VolumeSnapshotClass", k)
}
}
if azureutils.IsAzureStackCloud(localCloud.Config.Cloud, localCloud.Config.DisableAzureStackCloud) {
klog.V(2).Info("Use full snapshot instead as Azure Stack does not support incremental snapshot.")
incremental = false
}
if resourceGroup == "" {
resourceGroup, err = azureutils.GetResourceGroupFromURI(sourceVolumeID)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "could not get resource group from diskURI(%s) with error(%v)", sourceVolumeID, err)
}
}
customTagsMap, err := volumehelper.ConvertTagsToMap(customTags)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, err.Error())
}
tags := make(map[string]*string)
for k, v := range customTagsMap {
value := v
tags[k] = &value
}
snapshot := compute.Snapshot{
SnapshotProperties: &compute.SnapshotProperties{
CreationData: &compute.CreationData{
CreateOption: compute.Copy,
SourceResourceID: &sourceVolumeID,
},
Incremental: &incremental,
},
Location: &location,
Tags: tags,
}
if dataAccessAuthMode != "" {
if err := azureutils.ValidateDataAccessAuthMode(dataAccessAuthMode); err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error())
}
snapshot.SnapshotProperties.DataAccessAuthMode = compute.DataAccessAuthMode(dataAccessAuthMode)
}
mc := metrics.NewMetricContext(consts.AzureDiskCSIDriverName, "controller_create_snapshot", d.cloud.ResourceGroup, d.cloud.SubscriptionID, d.Name)
isOperationSucceeded := false
defer func() {
mc.ObserveOperationWithResult(isOperationSucceeded, consts.SourceResourceID, sourceVolumeID, consts.SnapshotName, snapshotName)
}()
klog.V(2).Infof("begin to create snapshot(%s, incremental: %v) under rg(%s)", snapshotName, incremental, resourceGroup)
if rerr := d.cloud.SnapshotsClient.CreateOrUpdate(ctx, subsID, resourceGroup, snapshotName, snapshot); rerr != nil {
if strings.Contains(rerr.Error().Error(), "existing disk") {
return nil, status.Error(codes.AlreadyExists, fmt.Sprintf("request snapshot(%s) under rg(%s) already exists, but the SourceVolumeId is different, error details: %v", snapshotName, resourceGroup, rerr.Error()))
}
azureutils.SleepIfThrottled(rerr.Error(), consts.SnapshotOpThrottlingSleepSec)
return nil, status.Error(codes.Internal, fmt.Sprintf("create snapshot error: %v", rerr.Error()))
}
klog.V(2).Infof("create snapshot(%s) under rg(%s) successfully", snapshotName, resourceGroup)
csiSnapshot, err := d.getSnapshotByID(ctx, subsID, resourceGroup, snapshotName, sourceVolumeID)
if err != nil {
return nil, err
}
createResp := &csi.CreateSnapshotResponse{
Snapshot: csiSnapshot,
}
isOperationSucceeded = true
return createResp, nil
}
// DeleteSnapshot delete a snapshot
func (d *Driver) DeleteSnapshot(ctx context.Context, req *csi.DeleteSnapshotRequest) (*csi.DeleteSnapshotResponse, error) {
snapshotID := req.SnapshotId
if len(snapshotID) == 0 {
return nil, status.Error(codes.InvalidArgument, "Snapshot ID must be provided")
}
var err error
var subsID string
snapshotName := snapshotID
resourceGroup := d.cloud.ResourceGroup
if azureutils.IsARMResourceID(snapshotID) {
snapshotName, resourceGroup, subsID, err = d.getSnapshotInfo(snapshotID)
if err != nil {
return nil, status.Errorf(codes.Internal, err.Error())
}
}
mc := metrics.NewMetricContext(consts.AzureDiskCSIDriverName, "controller_delete_snapshot", d.cloud.ResourceGroup, d.cloud.SubscriptionID, d.Name)
isOperationSucceeded := false
defer func() {
mc.ObserveOperationWithResult(isOperationSucceeded, consts.SnapshotID, snapshotID)
}()
klog.V(2).Infof("begin to delete snapshot(%s) under rg(%s)", snapshotName, resourceGroup)
if rerr := d.cloud.SnapshotsClient.Delete(ctx, subsID, resourceGroup, snapshotName); rerr != nil {
azureutils.SleepIfThrottled(rerr.Error(), consts.SnapshotOpThrottlingSleepSec)
return nil, status.Error(codes.Internal, fmt.Sprintf("delete snapshot error: %v", rerr.Error()))
}
klog.V(2).Infof("delete snapshot(%s) under rg(%s) successfully", snapshotName, resourceGroup)
isOperationSucceeded = true
return &csi.DeleteSnapshotResponse{}, nil
}
// ListSnapshots list all snapshots
func (d *Driver) ListSnapshots(ctx context.Context, req *csi.ListSnapshotsRequest) (*csi.ListSnapshotsResponse, error) {
// SnapshotId is not empty, return snapshot that match the snapshot id.
if len(req.GetSnapshotId()) != 0 {
snapshot, err := d.getSnapshotByID(ctx, "", d.cloud.ResourceGroup, req.GetSnapshotId(), req.SourceVolumeId)
if err != nil {
if strings.Contains(err.Error(), consts.ResourceNotFound) {
return &csi.ListSnapshotsResponse{}, nil
}
return nil, err
}
entries := []*csi.ListSnapshotsResponse_Entry{
{
Snapshot: snapshot,
},
}
listSnapshotResp := &csi.ListSnapshotsResponse{
Entries: entries,
}
return listSnapshotResp, nil
}
// no SnapshotId is set, return all snapshots that satisfy the request.
snapshots, err := d.cloud.SnapshotsClient.ListByResourceGroup(ctx, "", d.cloud.ResourceGroup)
if err != nil {
return nil, status.Error(codes.Internal, fmt.Sprintf("Unknown list snapshot error: %v", err.Error()))
}
return azureutils.GetEntriesAndNextToken(req, snapshots)
}
func (d *Driver) getSnapshotByID(ctx context.Context, subsID, resourceGroup, snapshotID, sourceVolumeID string) (*csi.Snapshot, error) {
var err error
snapshotName := snapshotID
if azureutils.IsARMResourceID(snapshotID) {
snapshotName, resourceGroup, subsID, err = d.getSnapshotInfo(snapshotID)
if err != nil {
return nil, status.Errorf(codes.Internal, err.Error())
}
}
snapshot, rerr := d.cloud.SnapshotsClient.Get(ctx, subsID, resourceGroup, snapshotName)
if rerr != nil {
return nil, status.Error(codes.Internal, fmt.Sprintf("get snapshot %s from rg(%s) error: %v", snapshotName, resourceGroup, rerr.Error()))
}
return azureutils.GenerateCSISnapshot(sourceVolumeID, &snapshot)
}
// GetSourceDiskSize recursively searches for the sourceDisk and returns: sourceDisk disk size, error
func (d *Driver) GetSourceDiskSize(ctx context.Context, subsID, resourceGroup, diskName string, curDepth, maxDepth int) (*int32, error) {
if curDepth > maxDepth {