-
Notifications
You must be signed in to change notification settings - Fork 808
/
cloud.go
1948 lines (1678 loc) · 64.3 KB
/
cloud.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 cloud
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"os"
"strconv"
"strings"
"sync"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/ec2"
"github.com/aws/aws-sdk-go-v2/service/ec2/types"
"github.com/aws/smithy-go"
"github.com/kubernetes-sigs/aws-ebs-csi-driver/pkg/batcher"
dm "github.com/kubernetes-sigs/aws-ebs-csi-driver/pkg/cloud/devicemanager"
"github.com/kubernetes-sigs/aws-ebs-csi-driver/pkg/expiringcache"
"github.com/kubernetes-sigs/aws-ebs-csi-driver/pkg/util"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/klog/v2"
)
// AWS volume types.
const (
// VolumeTypeIO1 represents a provisioned IOPS SSD type of volume.
VolumeTypeIO1 = "io1"
// VolumeTypeIO2 represents a provisioned IOPS SSD type of volume.
VolumeTypeIO2 = "io2"
// VolumeTypeGP2 represents a general purpose SSD type of volume.
VolumeTypeGP2 = "gp2"
// VolumeTypeGP3 represents a general purpose SSD type of volume.
VolumeTypeGP3 = "gp3"
// VolumeTypeSC1 represents a cold HDD (sc1) type of volume.
VolumeTypeSC1 = "sc1"
// VolumeTypeST1 represents a throughput-optimized HDD type of volume.
VolumeTypeST1 = "st1"
// VolumeTypeSBG1 represents a capacity-optimized HDD type of volume. Only for SBE devices.
VolumeTypeSBG1 = "sbg1"
// VolumeTypeSBP1 represents a performance-optimized SSD type of volume. Only for SBE devices.
VolumeTypeSBP1 = "sbp1"
// VolumeTypeStandard represents a previous type of volume.
VolumeTypeStandard = "standard"
)
// AWS provisioning limits.
// Source: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html
const (
io1MinTotalIOPS = 100
io1MaxTotalIOPS = 64000
io1MaxIOPSPerGB = 50
io2MinTotalIOPS = 100
io2MaxTotalIOPS = 64000
io2BlockExpressMaxTotalIOPS = 256000
io2MaxIOPSPerGB = 500
gp3MaxTotalIOPS = 16000
gp3MinTotalIOPS = 3000
gp3MaxIOPSPerGB = 500
)
var (
ValidVolumeTypes = []string{
VolumeTypeIO1,
VolumeTypeIO2,
VolumeTypeGP2,
VolumeTypeGP3,
VolumeTypeSC1,
VolumeTypeST1,
VolumeTypeStandard,
}
)
const (
volumeDetachedState = "detached"
volumeAttachedState = "attached"
cacheForgetDelay = 1 * time.Hour
)
// AWS provisioning limits.
// Source:
//
// https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html#tag-restrictions
const (
// MaxNumTagsPerResource represents the maximum number of tags per AWS resource.
MaxNumTagsPerResource = 50
// MinTagKeyLength represents the minimum key length for a tag.
MinTagKeyLength = 1
// MaxTagKeyLength represents the maximum key length for a tag.
MaxTagKeyLength = 128
// MaxTagValueLength represents the maximum value length for a tag.
MaxTagValueLength = 256
)
// Defaults.
const (
// DefaultVolumeSize represents the default volume size.
DefaultVolumeSize int64 = 100 * util.GiB
)
// Tags.
const (
// VolumeNameTagKey is the key value that refers to the volume's name.
VolumeNameTagKey = "CSIVolumeName"
// SnapshotNameTagKey is the key value that refers to the snapshot's name.
SnapshotNameTagKey = "CSIVolumeSnapshotName"
// KubernetesTagKeyPrefix is the prefix of the key value that is reserved for Kubernetes.
KubernetesTagKeyPrefix = "kubernetes.io"
// AWSTagKeyPrefix is the prefix of the key value that is reserved for AWS.
AWSTagKeyPrefix = "aws:"
// AwsEbsDriverTagKey is the tag to identify if a volume/snapshot is managed by ebs csi driver.
AwsEbsDriverTagKey = "ebs.csi.aws.com/cluster"
)
// Batcher.
const (
volumeIDBatcher volumeBatcherType = iota
volumeTagBatcher
snapshotIDBatcher snapshotBatcherType = iota
snapshotTagBatcher
batchDescribeTimeout = 30 * time.Second
batchMaxDelay = 500 * time.Millisecond // Minimizes RPC latency and EC2 API calls. Tuned via scalability tests.
)
var (
// ErrMultiDisks is an error that is returned when multiple
// disks are found with the same volume name.
ErrMultiDisks = errors.New("multiple disks with same name")
// ErrDiskExistsDiffSize is an error that is returned if a disk with a given
// name, but different size, is found.
ErrDiskExistsDiffSize = errors.New("there is already a disk with same name and different size")
// ErrNotFound is returned when a resource is not found.
ErrNotFound = errors.New("resource was not found")
// ErrIdempotentParameterMismatch is returned when another request with same idempotent token is in-flight.
ErrIdempotentParameterMismatch = errors.New("parameters on this idempotent request are inconsistent with parameters used in previous request(s)")
// ErrAlreadyExists is returned when a resource is already existent.
ErrAlreadyExists = errors.New("resource already exists")
// ErrMultiSnapshots is returned when multiple snapshots are found
// with the same ID.
ErrMultiSnapshots = errors.New("multiple snapshots with the same name found")
// ErrInvalidMaxResults is returned when a MaxResults pagination parameter is between 1 and 4.
ErrInvalidMaxResults = errors.New("maxResults parameter must be 0 or greater than or equal to 5")
// ErrVolumeNotBeingModified is returned if volume being described is not being modified.
ErrVolumeNotBeingModified = errors.New("volume is not being modified")
// ErrInvalidArgument is returned if parameters were rejected by cloud provider.
ErrInvalidArgument = errors.New("invalid argument")
// ErrInvalidRequest is returned if parameters were rejected by driver.
ErrInvalidRequest = errors.New("invalid request")
)
// Set during build time via -ldflags.
var driverVersion string
var invalidParameterErrorCodes = map[string]struct{}{
"InvalidParameter": {},
"InvalidParameterCombination": {},
"InvalidParameterDependency": {},
"InvalidParameterValue": {},
"UnknownParameter": {},
"UnknownVolumeType": {},
"UnsupportedOperation": {},
"ValidationError": {},
}
// Disk represents a EBS volume.
type Disk struct {
VolumeID string
CapacityGiB int32
AvailabilityZone string
SnapshotID string
OutpostArn string
Attachments []string
}
// DiskOptions represents parameters to create an EBS volume.
type DiskOptions struct {
CapacityBytes int64
Tags map[string]string
VolumeType string
IOPSPerGB int32
AllowIOPSPerGBIncrease bool
IOPS int32
Throughput int32
AvailabilityZone string
OutpostArn string
Encrypted bool
BlockExpress bool
MultiAttachEnabled bool
// KmsKeyID represents a fully qualified resource name to the key to use for encryption.
// example: arn:aws:kms:us-east-1:012345678910:key/abcd1234-a123-456a-a12b-a123b4cd56ef
KmsKeyID string
SnapshotID string
}
// ModifyDiskOptions represents parameters to modify an EBS volume.
type ModifyDiskOptions struct {
VolumeType string
IOPS int32
Throughput int32
}
// ModifyTagsOptions represents parameter to modify the tags of an existing EBS volume.
type ModifyTagsOptions struct {
TagsToAdd map[string]string
TagsToDelete []string
}
// Snapshot represents an EBS volume snapshot.
type Snapshot struct {
SnapshotID string
SourceVolumeID string
Size int32
CreationTime time.Time
ReadyToUse bool
}
// ListSnapshotsResponse is the container for our snapshots along with a pagination token to pass back to the caller.
type ListSnapshotsResponse struct {
Snapshots []*Snapshot
NextToken string
}
// SnapshotOptions represents parameters to create an EBS volume.
type SnapshotOptions struct {
Tags map[string]string
OutpostArn string
}
// ec2ListSnapshotsResponse is a helper struct returned from the AWS API calling function to the main ListSnapshots function.
type ec2ListSnapshotsResponse struct {
Snapshots []types.Snapshot
NextToken *string
}
// volumeWaitParameters dictates how to poll for volume events.
// E.g. how often to check if volume is created after an EC2 CreateVolume call.
type volumeWaitParameters struct {
creationInitialDelay time.Duration
creationBackoff wait.Backoff
modificationBackoff wait.Backoff
attachmentBackoff wait.Backoff
}
var (
vwp = volumeWaitParameters{
// Based on our testing in us-west-2 and ap-south-1, the median/p99 time until volume creation is ~1.5/~4 seconds.
// We have found that the following parameters are optimal for minimizing provisioning time and DescribeVolumes calls
// we queue DescribeVolume calls after [1.25, 0.5, 0.75, 1.125, 1.7, 2.5, 3] seconds.
// In total, we wait for ~60 seconds.
creationInitialDelay: 1250 * time.Millisecond,
creationBackoff: wait.Backoff{
Duration: 500 * time.Millisecond,
Factor: 1.5,
Steps: 25,
Cap: 3 * time.Second,
},
// Most attach/detach operations on AWS finish within 1-4 seconds.
// By using 1 second starting interval with a backoff of 1.8,
// we get [1, 1.8, 3.24, 5.832000000000001, 10.4976].
// In total, we wait for 2601 seconds.
attachmentBackoff: wait.Backoff{
Duration: 1 * time.Second,
Factor: 1.8,
Steps: 13,
},
modificationBackoff: wait.Backoff{
Duration: 1 * time.Second,
Factor: 1.7,
Steps: 10,
},
}
)
// volumeBatcherType is an enum representing the types of volume batchers available.
type volumeBatcherType int
// snapshotBatcherType is an enum representing the types of snapshot batchers available.
type snapshotBatcherType int
// batcherManager maintains a collection of batchers for different types of tasks.
type batcherManager struct {
volumeIDBatcher *batcher.Batcher[string, *types.Volume]
volumeTagBatcher *batcher.Batcher[string, *types.Volume]
instanceIDBatcher *batcher.Batcher[string, *types.Instance]
snapshotIDBatcher *batcher.Batcher[string, *types.Snapshot]
snapshotTagBatcher *batcher.Batcher[string, *types.Snapshot]
volumeModificationIDBatcher *batcher.Batcher[string, *types.VolumeModification]
}
type cloud struct {
region string
ec2 EC2API
dm dm.DeviceManager
bm *batcherManager
rm *retryManager
vwp volumeWaitParameters
likelyBadDeviceNames expiringcache.ExpiringCache[string, sync.Map]
latestClientTokens expiringcache.ExpiringCache[string, int]
}
var _ Cloud = &cloud{}
// NewCloud returns a new instance of AWS cloud
// It panics if session is invalid.
func NewCloud(region string, awsSdkDebugLog bool, userAgentExtra string, batching bool, deprecatedMetrics bool) (Cloud, error) {
c := newEC2Cloud(region, awsSdkDebugLog, userAgentExtra, batching, deprecatedMetrics)
return c, nil
}
func newEC2Cloud(region string, awsSdkDebugLog bool, userAgentExtra string, batchingEnabled bool, deprecatedMetrics bool) Cloud {
cfg, err := config.LoadDefaultConfig(context.Background(), config.WithRegion(region))
if err != nil {
panic(err)
}
if awsSdkDebugLog {
cfg.ClientLogMode = aws.LogRequestWithBody | aws.LogResponseWithBody
}
// Set the env var so that the session appends custom user agent string
if userAgentExtra != "" {
os.Setenv("AWS_EXECUTION_ENV", "aws-ebs-csi-driver-"+driverVersion+"-"+userAgentExtra)
} else {
os.Setenv("AWS_EXECUTION_ENV", "aws-ebs-csi-driver-"+driverVersion)
}
svc := ec2.NewFromConfig(cfg, func(o *ec2.Options) {
o.APIOptions = append(o.APIOptions,
RecordRequestsMiddleware(deprecatedMetrics),
LogServerErrorsMiddleware(), // This middlware should always be last so it sees an unmangled error
)
endpoint := os.Getenv("AWS_EC2_ENDPOINT")
if endpoint != "" {
o.BaseEndpoint = &endpoint
}
o.RetryMaxAttempts = retryMaxAttempt
})
var bm *batcherManager
if batchingEnabled {
klog.V(4).InfoS("newEC2Cloud: batching enabled")
bm = newBatcherManager(svc)
}
return &cloud{
region: region,
dm: dm.NewDeviceManager(),
ec2: svc,
bm: bm,
rm: newRetryManager(),
vwp: vwp,
likelyBadDeviceNames: expiringcache.New[string, sync.Map](cacheForgetDelay),
latestClientTokens: expiringcache.New[string, int](cacheForgetDelay),
}
}
// newBatcherManager initializes a new instance of batcherManager.
// Each batcher's `entries` set to maximum results returned by relevant EC2 API call without pagination.
// Each batcher's `delay` minimizes RPC latency and EC2 API calls. Tuned via scalability tests.
func newBatcherManager(svc EC2API) *batcherManager {
return &batcherManager{
volumeIDBatcher: batcher.New(500, batchMaxDelay, func(ids []string) (map[string]*types.Volume, error) {
return execBatchDescribeVolumes(svc, ids, volumeIDBatcher)
}),
volumeTagBatcher: batcher.New(500, batchMaxDelay, func(names []string) (map[string]*types.Volume, error) {
return execBatchDescribeVolumes(svc, names, volumeTagBatcher)
}),
instanceIDBatcher: batcher.New(50, batchMaxDelay, func(ids []string) (map[string]*types.Instance, error) {
return execBatchDescribeInstances(svc, ids)
}),
snapshotIDBatcher: batcher.New(1000, batchMaxDelay, func(ids []string) (map[string]*types.Snapshot, error) {
return execBatchDescribeSnapshots(svc, ids, snapshotIDBatcher)
}),
snapshotTagBatcher: batcher.New(1000, batchMaxDelay, func(names []string) (map[string]*types.Snapshot, error) {
return execBatchDescribeSnapshots(svc, names, snapshotTagBatcher)
}),
volumeModificationIDBatcher: batcher.New(500, batchMaxDelay, func(names []string) (map[string]*types.VolumeModification, error) {
return execBatchDescribeVolumesModifications(svc, names)
}),
}
}
// execBatchDescribeVolumes executes a batched DescribeVolumes API call depending on the type of batcher.
func execBatchDescribeVolumes(svc EC2API, input []string, batcher volumeBatcherType) (map[string]*types.Volume, error) {
var request *ec2.DescribeVolumesInput
switch batcher {
case volumeIDBatcher:
klog.V(7).InfoS("execBatchDescribeVolumes", "volumeIds", input)
request = &ec2.DescribeVolumesInput{
VolumeIds: input,
}
case volumeTagBatcher:
klog.V(7).InfoS("execBatchDescribeVolumes", "names", input)
filters := []types.Filter{
{
Name: aws.String("tag:" + VolumeNameTagKey),
Values: input,
},
}
request = &ec2.DescribeVolumesInput{
Filters: filters,
}
default:
return nil, errors.New("execBatchDescribeVolumes: unsupported request type")
}
ctx, cancel := context.WithTimeout(context.Background(), batchDescribeTimeout)
defer cancel()
resp, err := describeVolumes(ctx, svc, request)
if err != nil {
return nil, err
}
result := make(map[string]*types.Volume)
for _, v := range resp {
volume := v
key, err := extractVolumeKey(&volume, batcher)
if err != nil {
klog.Warningf("execBatchDescribeVolumes: skipping volume: %v, reason: %v", volume, err)
continue
}
result[key] = &volume
}
klog.V(7).InfoS("execBatchDescribeVolumes: success", "result", result)
return result, nil
}
// batchDescribeVolumes processes a DescribeVolumes request. Depending on the request,
// it determines the appropriate batcher to use, queues the task, and waits for the result.
func (c *cloud) batchDescribeVolumes(request *ec2.DescribeVolumesInput) (*types.Volume, error) {
var b *batcher.Batcher[string, *types.Volume]
var task string
switch {
case len(request.VolumeIds) == 1 && request.VolumeIds[0] != "":
b = c.bm.volumeIDBatcher
task = request.VolumeIds[0]
case len(request.Filters) == 1 && *request.Filters[0].Name == "tag:"+VolumeNameTagKey && len(request.Filters[0].Values) == 1:
b = c.bm.volumeTagBatcher
task = request.Filters[0].Values[0]
default:
return nil, fmt.Errorf("%w: batchDescribeVolumes: request: %v", ErrInvalidRequest, request)
}
ch := make(chan batcher.BatchResult[*types.Volume])
b.AddTask(task, ch)
r := <-ch
if r.Err != nil {
return nil, r.Err
}
if r.Result == nil {
return nil, ErrNotFound
}
return r.Result, nil
}
// extractVolumeKey retrieves the key associated with a given volume based on the batcher type.
// For the volumeIDBatcher type, it returns the volume's ID.
// For other types, it searches for the VolumeNameTagKey within the volume's tags.
func extractVolumeKey(v *types.Volume, batcher volumeBatcherType) (string, error) {
if batcher == volumeIDBatcher {
if v.VolumeId == nil {
return "", errors.New("extractVolumeKey: missing volume ID")
}
return *v.VolumeId, nil
}
for _, tag := range v.Tags {
klog.V(7).InfoS("extractVolumeKey: processing tag", "volume", v, "*tag.Key", *tag.Key, "VolumeNameTagKey", VolumeNameTagKey)
if tag.Key == nil || tag.Value == nil {
klog.V(7).InfoS("extractVolumeKey: skipping volume due to missing tag", "volume", v, "tag", tag)
continue
}
if *tag.Key == VolumeNameTagKey {
klog.V(7).InfoS("extractVolumeKey: found volume name tag", "volume", v, "tag", tag)
return *tag.Value, nil
}
}
return "", errors.New("extractVolumeKey: missing VolumeNameTagKey in volume tags")
}
func (c *cloud) CreateDisk(ctx context.Context, volumeName string, diskOptions *DiskOptions) (*Disk, error) {
var (
createType string
iops int32
throughput int32
err error
maxIops int32
minIops int32
maxIopsPerGb int32
requestedIops int32
)
capacityGiB := util.BytesToGiB(diskOptions.CapacityBytes)
if diskOptions.IOPS > 0 && diskOptions.IOPSPerGB > 0 {
return nil, errors.New("invalid StorageClass parameters; specify either IOPS or IOPSPerGb, not both")
}
createType = diskOptions.VolumeType
// If no volume type is specified, GP3 is used as default for newly created volumes.
if createType == "" {
createType = VolumeTypeGP3
}
switch createType {
case VolumeTypeGP2, VolumeTypeSC1, VolumeTypeST1, VolumeTypeSBG1, VolumeTypeSBP1, VolumeTypeStandard:
case VolumeTypeIO1:
maxIops = io1MaxTotalIOPS
minIops = io1MinTotalIOPS
maxIopsPerGb = io1MaxIOPSPerGB
case VolumeTypeIO2:
if diskOptions.BlockExpress {
maxIops = io2BlockExpressMaxTotalIOPS
} else {
maxIops = io2MaxTotalIOPS
}
minIops = io2MinTotalIOPS
maxIopsPerGb = io2MaxIOPSPerGB
case VolumeTypeGP3:
maxIops = gp3MaxTotalIOPS
minIops = gp3MinTotalIOPS
maxIopsPerGb = gp3MaxIOPSPerGB
throughput = diskOptions.Throughput
default:
return nil, fmt.Errorf("invalid AWS VolumeType %q", diskOptions.VolumeType)
}
if diskOptions.MultiAttachEnabled && createType != VolumeTypeIO2 {
return nil, errors.New("CreateDisk: multi-attach is only supported for io2 volumes")
}
if maxIops > 0 {
if diskOptions.IOPS > 0 {
requestedIops = diskOptions.IOPS
} else if diskOptions.IOPSPerGB > 0 {
requestedIops = diskOptions.IOPSPerGB * capacityGiB
}
iops = capIOPS(createType, capacityGiB, requestedIops, minIops, maxIops, maxIopsPerGb, diskOptions.AllowIOPSPerGBIncrease)
}
tags := make([]types.Tag, 0, len(diskOptions.Tags))
for key, value := range diskOptions.Tags {
tags = append(tags, types.Tag{Key: aws.String(key), Value: aws.String(value)})
}
tagSpec := types.TagSpecification{
ResourceType: types.ResourceTypeVolume,
Tags: tags,
}
zone := diskOptions.AvailabilityZone
if zone == "" {
zone, err = c.randomAvailabilityZone(ctx)
klog.V(5).InfoS("[Debug] AZ is not provided. Using node AZ", "zone", zone)
if err != nil {
return nil, fmt.Errorf("failed to get availability zone %w", err)
}
}
// The first client token used for any volume is the volume name as provided via CSI
// However, if a volume fails to create asyncronously (that is, the CreateVolume call
// succeeds but the volume ultimately fails to create), the client token is burned until
// EC2 forgets about its use (measured as 12 hours under normal conditions)
//
// To prevent becoming stuck for 12 hours when this occurs, we sequentially append "-2",
// "-3", "-4", etc to the volume name before hashing on the subsequent attempt after a
// volume fails to create because of an IdempotentParameterMismatch AWS error
// The most recent appended value is stored in an expiring cache to prevent memory leaks
tokenBase := volumeName
if tokenNumber, ok := c.latestClientTokens.Get(volumeName); ok {
tokenBase += "-" + strconv.Itoa(*tokenNumber)
}
// We use a sha256 hash to guarantee the token that is less than or equal to 64 characters
clientToken := sha256.Sum256([]byte(tokenBase))
requestInput := &ec2.CreateVolumeInput{
AvailabilityZone: aws.String(zone),
ClientToken: aws.String(hex.EncodeToString(clientToken[:])),
Size: aws.Int32(capacityGiB),
VolumeType: types.VolumeType(createType),
Encrypted: aws.Bool(diskOptions.Encrypted),
MultiAttachEnabled: aws.Bool(diskOptions.MultiAttachEnabled),
}
if !util.IsSBE(zone) {
requestInput.TagSpecifications = []types.TagSpecification{tagSpec}
}
// EBS doesn't handle empty outpost arn, so we have to include it only when it's non-empty
if len(diskOptions.OutpostArn) > 0 {
requestInput.OutpostArn = aws.String(diskOptions.OutpostArn)
}
if len(diskOptions.KmsKeyID) > 0 {
requestInput.KmsKeyId = aws.String(diskOptions.KmsKeyID)
requestInput.Encrypted = aws.Bool(true)
}
if iops > 0 {
requestInput.Iops = aws.Int32(iops)
}
if throughput > 0 {
requestInput.Throughput = aws.Int32(throughput)
}
snapshotID := diskOptions.SnapshotID
if len(snapshotID) > 0 {
requestInput.SnapshotId = aws.String(snapshotID)
}
response, err := c.ec2.CreateVolume(ctx, requestInput, func(o *ec2.Options) {
o.Retryer = c.rm.createVolumeRetryer
})
if err != nil {
if isAWSErrorSnapshotNotFound(err) {
return nil, ErrNotFound
}
if isAWSErrorIdempotentParameterMismatch(err) {
nextTokenNumber := 2
if tokenNumber, ok := c.latestClientTokens.Get(volumeName); ok {
nextTokenNumber = *tokenNumber + 1
}
c.latestClientTokens.Set(volumeName, &nextTokenNumber)
return nil, ErrIdempotentParameterMismatch
}
return nil, fmt.Errorf("could not create volume in EC2: %w", err)
}
volumeID := aws.ToString(response.VolumeId)
if len(volumeID) == 0 {
return nil, errors.New("volume ID was not returned by CreateVolume")
}
size := *response.Size
if size == 0 {
return nil, errors.New("disk size was not returned by CreateVolume")
}
if err := c.waitForVolume(ctx, volumeID); err != nil {
return nil, fmt.Errorf("timed out waiting for volume to create: %w", err)
}
outpostArn := aws.ToString(response.OutpostArn)
var resources []string
if util.IsSBE(zone) {
requestTagsInput := &ec2.CreateTagsInput{
Resources: append(resources, volumeID),
Tags: tags,
}
_, err := c.ec2.CreateTags(ctx, requestTagsInput)
if err != nil {
// To avoid leaking volume, we should delete the volume just created
// TODO: Need to figure out how to handle DeleteDisk failed scenario instead of just log the error
if _, deleteDiskErr := c.DeleteDisk(ctx, volumeID); deleteDiskErr != nil {
klog.ErrorS(deleteDiskErr, "failed to be deleted, this may cause volume leak", "volumeID", volumeID)
} else {
klog.V(5).InfoS("volume is deleted because there was an error while attaching the tags", "volumeID", volumeID)
}
return nil, fmt.Errorf("could not attach tags to volume: %v. %w", volumeID, err)
}
}
return &Disk{CapacityGiB: size, VolumeID: volumeID, AvailabilityZone: zone, SnapshotID: snapshotID, OutpostArn: outpostArn}, nil
}
// execBatchDescribeVolumesModifications executes a batched DescribeVolumesModifications API call.
func execBatchDescribeVolumesModifications(svc EC2API, input []string) (map[string]*types.VolumeModification, error) {
klog.V(7).InfoS("execBatchDescribeVolumeModifications", "volumeIds", input)
request := &ec2.DescribeVolumesModificationsInput{
VolumeIds: input,
}
ctx, cancel := context.WithTimeout(context.Background(), batchDescribeTimeout)
defer cancel()
resp, err := describeVolumesModifications(ctx, svc, request)
if err != nil {
return nil, err
}
result := make(map[string]*types.VolumeModification)
for _, m := range resp {
volumeModification := m
result[*volumeModification.VolumeId] = &volumeModification
}
klog.V(7).InfoS("execBatchDescribeVolumeModifications: success", "result", result)
return result, nil
}
// batchDescribeVolumesModifications processes a DescribeVolumesModifications request by queuing the task and waiting for the result.
func (c *cloud) batchDescribeVolumesModifications(request *ec2.DescribeVolumesModificationsInput) (*types.VolumeModification, error) {
var task string
if len(request.VolumeIds) == 1 && request.VolumeIds[0] != "" {
task = request.VolumeIds[0]
} else {
return nil, fmt.Errorf("%w: batchDescribeVolumesModifications: invalid request, request: %v", ErrInvalidRequest, request)
}
ch := make(chan batcher.BatchResult[*types.VolumeModification])
b := c.bm.volumeModificationIDBatcher
b.AddTask(task, ch)
r := <-ch
if r.Err != nil {
return nil, r.Err
}
return r.Result, nil
}
// ModifyTags adds, updates, and deletes tags for the specified EBS volume.
func (c *cloud) ModifyTags(ctx context.Context, volumeID string, tagOptions ModifyTagsOptions) error {
if len(tagOptions.TagsToDelete) > 0 {
deleteTagsInput := &ec2.DeleteTagsInput{
Resources: []string{volumeID},
Tags: make([]types.Tag, 0, len(tagOptions.TagsToDelete)),
}
for _, tagKey := range tagOptions.TagsToDelete {
deleteTagsInput.Tags = append(deleteTagsInput.Tags, types.Tag{Key: aws.String(tagKey)})
}
_, deleteErr := c.ec2.DeleteTags(ctx, deleteTagsInput)
if deleteErr != nil {
klog.ErrorS(deleteErr, "failed to delete tags", "volumeID", volumeID)
return deleteErr
}
}
if len(tagOptions.TagsToAdd) > 0 {
createTagsInput := &ec2.CreateTagsInput{
Resources: []string{volumeID},
Tags: make([]types.Tag, 0, len(tagOptions.TagsToAdd)),
}
for k, v := range tagOptions.TagsToAdd {
createTagsInput.Tags = append(createTagsInput.Tags, types.Tag{
Key: aws.String(k),
Value: aws.String(v),
})
}
_, addErr := c.ec2.CreateTags(ctx, createTagsInput)
if addErr != nil {
klog.ErrorS(addErr, "failed to create tags", "volumeID", volumeID)
return addErr
}
}
return nil
}
// ResizeOrModifyDisk resizes an EBS volume in GiB increments, rounding up to the next possible allocatable unit, and/or modifies an EBS
// volume with the parameters in ModifyDiskOptions.
// The resizing operation is performed only when newSizeBytes != 0.
// It returns the volume size after this call or an error if the size couldn't be determined or the volume couldn't be modified.
func (c *cloud) ResizeOrModifyDisk(ctx context.Context, volumeID string, newSizeBytes int64, options *ModifyDiskOptions) (int32, error) {
if newSizeBytes != 0 {
klog.V(4).InfoS("Received Resize and/or Modify Disk request", "volumeID", volumeID, "newSizeBytes", newSizeBytes, "options", options)
} else {
klog.V(4).InfoS("Received Modify Disk request", "volumeID", volumeID, "options", options)
}
newSizeGiB, err := util.RoundUpGiB(newSizeBytes)
if err != nil {
return 0, err
}
needsModification, volumeSize, err := c.validateModifyVolume(ctx, volumeID, newSizeGiB, options)
if err != nil || !needsModification {
return volumeSize, err
}
req := &ec2.ModifyVolumeInput{
VolumeId: aws.String(volumeID),
}
if newSizeBytes != 0 {
req.Size = aws.Int32(newSizeGiB)
}
if options.IOPS != 0 {
req.Iops = aws.Int32(options.IOPS)
}
if options.VolumeType != "" {
req.VolumeType = types.VolumeType(options.VolumeType)
}
if options.Throughput != 0 {
req.Throughput = aws.Int32(options.Throughput)
}
response, err := c.ec2.ModifyVolume(ctx, req, func(o *ec2.Options) {
o.Retryer = c.rm.modifyVolumeRetryer
})
if err != nil {
if isAWSErrorInvalidParameter(err) {
// Wrap error to preserve original message from AWS as to why this was an invalid argument
return 0, fmt.Errorf("%w: %w", ErrInvalidArgument, err)
}
return 0, err
}
// If the volume modification isn't immediately completed, wait for it to finish
state := string(response.VolumeModification.ModificationState)
if !volumeModificationDone(state) {
err = c.waitForVolumeModification(ctx, volumeID)
if err != nil {
return 0, err
}
}
// Perform one final check on the volume
return c.checkDesiredState(ctx, volumeID, newSizeGiB, options)
}
func (c *cloud) DeleteDisk(ctx context.Context, volumeID string) (bool, error) {
request := &ec2.DeleteVolumeInput{VolumeId: &volumeID}
if _, err := c.ec2.DeleteVolume(ctx, request, func(o *ec2.Options) {
o.Retryer = c.rm.deleteVolumeRetryer
}); err != nil {
if isAWSErrorVolumeNotFound(err) {
return false, ErrNotFound
}
return false, fmt.Errorf("DeleteDisk could not delete volume: %w", err)
}
return true, nil
}
// execBatchDescribeInstances executes a batched DescribeInstances API call.
func execBatchDescribeInstances(svc EC2API, input []string) (map[string]*types.Instance, error) {
klog.V(7).InfoS("execBatchDescribeInstances", "instanceIds", input)
request := &ec2.DescribeInstancesInput{
InstanceIds: input,
}
ctx, cancel := context.WithTimeout(context.Background(), batchDescribeTimeout)
defer cancel()
resp, err := describeInstances(ctx, svc, request)
if err != nil {
return nil, err
}
result := make(map[string]*types.Instance)
for _, i := range resp {
instance := i
if instance.InstanceId == nil {
klog.Warningf("execBatchDescribeInstances: skipping instance: %v, reason: missing instance ID", instance)
continue
}
result[*instance.InstanceId] = &instance
}
klog.V(7).InfoS("execBatchDescribeInstances: success", "result", result)
return result, nil
}
// batchDescribeInstances processes a DescribeInstances request by queuing the task and waiting for the result.
func (c *cloud) batchDescribeInstances(request *ec2.DescribeInstancesInput) (*types.Instance, error) {
var task string
if len(request.InstanceIds) == 1 && request.InstanceIds[0] != "" {
task = request.InstanceIds[0]
} else {
return nil, fmt.Errorf("%w: batchDescribeInstances: request: %v", ErrInvalidRequest, request)
}
ch := make(chan batcher.BatchResult[*types.Instance])
b := c.bm.instanceIDBatcher
b.AddTask(task, ch)
r := <-ch
if r.Err != nil {
return nil, r.Err
}
if r.Result == nil {
return nil, ErrNotFound
}
return r.Result, nil
}
func (c *cloud) AttachDisk(ctx context.Context, volumeID, nodeID string) (string, error) {
instance, err := c.getInstance(ctx, nodeID)
if err != nil {
return "", err
}
likelyBadDeviceNames, ok := c.likelyBadDeviceNames.Get(nodeID)
if !ok {
likelyBadDeviceNames = new(sync.Map)
c.likelyBadDeviceNames.Set(nodeID, likelyBadDeviceNames)
}
device, err := c.dm.NewDevice(instance, volumeID, likelyBadDeviceNames)
if err != nil {
return "", err
}
defer device.Release(false)
if !device.IsAlreadyAssigned {
request := &ec2.AttachVolumeInput{
Device: aws.String(device.Path),
InstanceId: aws.String(nodeID),
VolumeId: aws.String(volumeID),
}
resp, attachErr := c.ec2.AttachVolume(ctx, request, func(o *ec2.Options) {
o.Retryer = c.rm.attachVolumeRetryer
})
if attachErr != nil {
if isAWSErrorBlockDeviceInUse(attachErr) {
// If block device is "in use", that likely indicates a bad name that is in use by a block
// device that we do not know about (example: block devices attached in the AMI, which are
// not reported in DescribeInstance's block device map)
//
// Store such bad names in the "likely bad" map to be considered last in future attempts
likelyBadDeviceNames.Store(device.Path, struct{}{})
}
return "", fmt.Errorf("could not attach volume %q to node %q: %w", volumeID, nodeID, attachErr)
}
likelyBadDeviceNames.Delete(device.Path)
klog.V(5).InfoS("[Debug] AttachVolume", "volumeID", volumeID, "nodeID", nodeID, "resp", resp)
}
_, err = c.WaitForAttachmentState(ctx, volumeID, volumeAttachedState, *instance.InstanceId, device.Path, device.IsAlreadyAssigned)
// This is the only situation where we taint the device
if err != nil {
device.Taint()
return "", err
}
// TODO: Check volume capability matches for ALREADY_EXISTS
// This could happen when request volume already attached to request node,
// but is incompatible with the specified volume_capability or readonly flag
return device.Path, nil
}
func (c *cloud) DetachDisk(ctx context.Context, volumeID, nodeID string) error {
instance, err := c.getInstance(ctx, nodeID)
if err != nil {
return err
}
// TODO: check if attached
device, err := c.dm.GetDevice(instance, volumeID)
if err != nil {
return err
}
defer device.Release(true)
if !device.IsAlreadyAssigned {
klog.InfoS("DetachDisk: called on non-attached volume", "volumeID", volumeID)
}
request := &ec2.DetachVolumeInput{
InstanceId: aws.String(nodeID),
VolumeId: aws.String(volumeID),
}
_, err = c.ec2.DetachVolume(ctx, request, func(o *ec2.Options) {
o.Retryer = c.rm.detachVolumeRetryer