-
Notifications
You must be signed in to change notification settings - Fork 159
/
Copy pathgce-compute.go
1699 lines (1512 loc) · 59.8 KB
/
gce-compute.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 2018 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 gcecloudprovider
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"regexp"
"strings"
"time"
rscmgr "cloud.google.com/go/resourcemanager/apiv3"
rscmgrpb "cloud.google.com/go/resourcemanager/apiv3/resourcemanagerpb"
"github.com/GoogleCloudPlatform/k8s-cloud-provider/pkg/cloud/meta"
csi "github.com/container-storage-interface/spec/lib/go/csi"
"github.com/googleapis/gax-go/v2"
"github.com/googleapis/gax-go/v2/apierror"
"golang.org/x/oauth2"
computebeta "google.golang.org/api/compute/v0.beta"
computev1 "google.golang.org/api/compute/v1"
"google.golang.org/api/googleapi"
"google.golang.org/api/iterator"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/klog/v2"
"k8s.io/utils/strings/slices"
"sigs.k8s.io/gcp-compute-persistent-disk-csi-driver/pkg/common"
)
const (
operationStatusDone = "DONE"
waitForSnapshotCreationTimeOut = 2 * time.Minute
waitForImageCreationTimeOut = 5 * time.Minute
diskKind = "compute#disk"
cryptoKeyVerDelimiter = "/cryptoKeyVersions"
// Example message: "[pd-standard] features are not compatible for creating instance"
pdDiskTypeUnsupportedPattern = `\[([a-z-]+)\] features are not compatible for creating instance`
)
var pdDiskTypeUnsupportedRegex = regexp.MustCompile(pdDiskTypeUnsupportedPattern)
type GCEAPIVersion string
const (
// V1 key type
GCEAPIVersionV1 GCEAPIVersion = "v1"
// Beta key type
GCEAPIVersionBeta GCEAPIVersion = "beta"
)
var GCEAPIVersions = []GCEAPIVersion{GCEAPIVersionBeta, GCEAPIVersionV1}
// AttachDiskBackoff is backoff used to wait for AttachDisk to complete.
// Default values are similar to Poll every 5 seconds with 2 minute timeout.
var AttachDiskBackoff = wait.Backoff{
Duration: 5 * time.Second,
Factor: 0.0,
Jitter: 0.0,
Steps: 24,
Cap: 0}
// WaitForOpBackoff is backoff used to wait for Global, Regional or Zonal operation to complete.
// Default values are similar to Poll every 3 seconds with 5 minute timeout.
var WaitForOpBackoff = wait.Backoff{
Duration: 3 * time.Second,
Factor: 0.0,
Jitter: 0.0,
Steps: 100,
Cap: 0}
// Custom error type to propagate error messages up to clients.
type UnsupportedDiskError struct {
DiskType string
}
func (udErr *UnsupportedDiskError) Error() string {
return ""
}
type GCECompute interface {
// Metadata information
GetDefaultProject() string
GetDefaultZone() string
// Disk Methods
GetDisk(ctx context.Context, project string, volumeKey *meta.Key) (*CloudDisk, error)
RepairUnderspecifiedVolumeKey(ctx context.Context, project string, volumeKey *meta.Key) (string, *meta.Key, error)
InsertDisk(ctx context.Context, project string, volKey *meta.Key, params common.DiskParameters, capBytes int64, capacityRange *csi.CapacityRange, replicaZones []string, snapshotID string, volumeContentSourceVolumeID string, multiWriter bool, accessMode string) error
DeleteDisk(ctx context.Context, project string, volumeKey *meta.Key) error
UpdateDisk(ctx context.Context, project string, volKey *meta.Key, existingDisk *CloudDisk, params common.ModifyVolumeParameters) error
AttachDisk(ctx context.Context, project string, volKey *meta.Key, readWrite, diskType, instanceZone, instanceName string, forceAttach bool) error
DetachDisk(ctx context.Context, project, deviceName, instanceZone, instanceName string) error
SetDiskAccessMode(ctx context.Context, project string, volKey *meta.Key, accessMode string) error
ListCompatibleDiskTypeZones(ctx context.Context, project string, zones []string, diskType string) ([]string, error)
GetDiskSourceURI(project string, volKey *meta.Key) string
GetDiskTypeURI(project string, volKey *meta.Key, diskType string) string
WaitForAttach(ctx context.Context, project string, volKey *meta.Key, diskType, instanceZone, instanceName string) error
ResizeDisk(ctx context.Context, project string, volKey *meta.Key, requestBytes int64) (int64, error)
ListDisks(ctx context.Context, fields []googleapi.Field) ([]*computev1.Disk, string, error)
ListDisksWithFilter(ctx context.Context, fields []googleapi.Field, filter string) ([]*computev1.Disk, string, error)
ListInstances(ctx context.Context, fields []googleapi.Field) ([]*computev1.Instance, string, error)
// Regional Disk Methods
GetReplicaZoneURI(project string, zone string) string
// Instance Methods
GetInstanceOrError(ctx context.Context, instanceZone, instanceName string) (*computev1.Instance, error)
// Zone Methods
ListZones(ctx context.Context, region string) ([]string, error)
ListSnapshots(ctx context.Context, filter string) ([]*computev1.Snapshot, string, error)
GetSnapshot(ctx context.Context, project, snapshotName string) (*computev1.Snapshot, error)
CreateSnapshot(ctx context.Context, project string, volKey *meta.Key, snapshotName string, snapshotParams common.SnapshotParameters) (*computev1.Snapshot, error)
DeleteSnapshot(ctx context.Context, project, snapshotName string) error
ListImages(ctx context.Context, filter string) ([]*computev1.Image, string, error)
GetImage(ctx context.Context, project, imageName string) (*computev1.Image, error)
CreateImage(ctx context.Context, project string, volKey *meta.Key, imageName string, snapshotParams common.SnapshotParameters) (*computev1.Image, error)
DeleteImage(ctx context.Context, project, imageName string) error
}
// GetDefaultProject returns the project that was used to instantiate this GCE client.
func (cloud *CloudProvider) GetDefaultProject() string {
return cloud.project
}
// GetDefaultZone returns the zone that was used to instantiate this GCE client.
func (cloud *CloudProvider) GetDefaultZone() string {
return cloud.zone
}
// ListDisks lists disks based on maxEntries and pageToken only in the project
// and region that the driver is running in.
func (cloud *CloudProvider) ListDisks(ctx context.Context, fields []googleapi.Field) ([]*computev1.Disk, string, error) {
filter := ""
return cloud.listDisksInternal(ctx, fields, filter)
}
func (cloud *CloudProvider) ListDisksWithFilter(ctx context.Context, fields []googleapi.Field, filter string) ([]*computev1.Disk, string, error) {
return cloud.listDisksInternal(ctx, fields, filter)
}
func (cloud *CloudProvider) listDisksInternal(ctx context.Context, fields []googleapi.Field, filter string) ([]*computev1.Disk, string, error) {
region, err := common.GetRegionFromZones([]string{cloud.zone})
if err != nil {
return nil, "", fmt.Errorf("failed to get region from zones: %w", err)
}
zones, err := cloud.ListZones(ctx, region)
if err != nil {
return nil, "", err
}
items := []*computev1.Disk{}
// listing out regional disks in the region
rlCall := cloud.service.RegionDisks.List(cloud.project, region)
rlCall.Fields(fields...)
rlCall.Filter(filter)
nextPageToken := "pageToken"
for nextPageToken != "" {
rDiskList, err := rlCall.Do()
if err != nil {
return nil, "", err
}
items = append(items, rDiskList.Items...)
nextPageToken = rDiskList.NextPageToken
rlCall.PageToken(nextPageToken)
}
// listing out zonal disks in all zones of the region
for _, zone := range zones {
lCall := cloud.service.Disks.List(cloud.project, zone)
lCall.Fields(fields...)
lCall.Filter(filter)
nextPageToken := "pageToken"
for nextPageToken != "" {
diskList, err := lCall.Do()
if err != nil {
return nil, "", err
}
items = append(items, diskList.Items...)
nextPageToken = diskList.NextPageToken
lCall.PageToken(nextPageToken)
}
}
return items, "", nil
}
// ListInstances lists instances based on maxEntries and pageToken for the project and region
// that the driver is running in. Filters from cloud.listInstancesConfig.Filters are applied
// to the request.
func (cloud *CloudProvider) ListInstances(ctx context.Context, fields []googleapi.Field) ([]*computev1.Instance, string, error) {
region, err := common.GetRegionFromZones([]string{cloud.zone})
if err != nil {
return nil, "", fmt.Errorf("failed to get region from zones: %w", err)
}
zones, err := cloud.ListZones(ctx, region)
if err != nil {
return nil, "", err
}
items := []*computev1.Instance{}
for _, zone := range zones {
lCall := cloud.service.Instances.List(cloud.project, zone)
for _, filter := range cloud.listInstancesConfig.Filters {
lCall = lCall.Filter(filter)
}
lCall = lCall.Fields(fields...)
nextPageToken := "pageToken"
for nextPageToken != "" {
instancesList, err := lCall.Do()
if err != nil {
return nil, "", err
}
items = append(items, instancesList.Items...)
nextPageToken = instancesList.NextPageToken
lCall.PageToken(nextPageToken)
}
}
return items, "", nil
}
// RepairUnderspecifiedVolumeKey will query the cloud provider and check each zone for the disk specified
// by the volume key and return a volume key with a correct zone
func (cloud *CloudProvider) RepairUnderspecifiedVolumeKey(ctx context.Context, project string, volumeKey *meta.Key) (string, *meta.Key, error) {
klog.V(5).Infof("Repairing potentially underspecified volume key %v", volumeKey)
if project == common.UnspecifiedValue {
project = cloud.project
}
region, err := common.GetRegionFromZones([]string{cloud.zone})
if err != nil {
return "", nil, fmt.Errorf("failed to get region from zones: %w", err)
}
switch volumeKey.Type() {
case meta.Zonal:
foundZone := ""
if volumeKey.Zone == common.UnspecifiedValue {
// list all zones, try to get disk in each zone
zones, err := cloud.ListZones(ctx, region)
if err != nil {
return "", nil, err
}
for _, zone := range zones {
_, err := cloud.getZonalDiskOrError(ctx, project, zone, volumeKey.Name)
if err != nil {
if IsGCENotFoundError(err) {
// Couldn't find the disk in this zone so we keep
// looking
continue
}
// There is some miscellaneous error getting disk from zone
// so we return error immediately
return "", nil, err
}
if len(foundZone) > 0 {
return "", nil, fmt.Errorf("found disk %s in more than one zone: %s and %s", volumeKey.Name, foundZone, zone)
}
foundZone = zone
}
if len(foundZone) == 0 {
return "", nil, notFoundError()
}
volumeKey.Zone = foundZone
return project, volumeKey, nil
}
return project, volumeKey, nil
case meta.Regional:
if volumeKey.Region == common.UnspecifiedValue {
volumeKey.Region = region
}
return project, volumeKey, nil
default:
return "", nil, fmt.Errorf("key was neither zonal nor regional, got: %v", volumeKey.String())
}
}
func (cloud *CloudProvider) ListZones(ctx context.Context, region string) ([]string, error) {
klog.V(5).Infof("Listing zones in region: %v", region)
if len(cloud.zonesCache[region]) > 0 {
return cloud.zonesCache[region], nil
}
zones := []string{}
zoneList, err := cloud.service.Zones.List(cloud.project).Filter(fmt.Sprintf("region eq .*%s$", region)).Do()
if err != nil {
return nil, fmt.Errorf("failed to list zones in region %s: %w", region, err)
}
for _, zone := range zoneList.Items {
zones = append(zones, zone.Name)
}
cloud.zonesCache[region] = zones
return zones, nil
}
func (cloud *CloudProvider) ListSnapshots(ctx context.Context, filter string) ([]*computev1.Snapshot, string, error) {
klog.V(5).Infof("Listing snapshots with filter: %s", filter)
items := []*computev1.Snapshot{}
lCall := cloud.service.Snapshots.List(cloud.project).Filter(filter)
nextPageToken := "pageToken"
for nextPageToken != "" {
snapshotList, err := lCall.Do()
if err != nil {
return nil, "", err
}
items = append(items, snapshotList.Items...)
nextPageToken = snapshotList.NextPageToken
}
return items, "", nil
}
func (cloud *CloudProvider) GetDisk(ctx context.Context, project string, key *meta.Key) (*CloudDisk, error) {
klog.V(5).Infof("Getting disk %v", key)
switch key.Type() {
case meta.Zonal:
disk, err := cloud.getZonalBetaDiskOrError(ctx, project, key.Zone, key.Name)
return CloudDiskFromBeta(disk), err
case meta.Regional:
disk, err := cloud.getRegionalBetaDiskOrError(ctx, project, key.Region, key.Name)
return CloudDiskFromBeta(disk), err
default:
return nil, fmt.Errorf("key was neither zonal nor regional, got: %v", key.String())
}
}
func (cloud *CloudProvider) getZonalDiskOrError(ctx context.Context, project, volumeZone, volumeName string) (*computev1.Disk, error) {
disk, err := cloud.service.Disks.Get(project, volumeZone, volumeName).Context(ctx).Do()
if err != nil {
return nil, err
}
return disk, nil
}
func (cloud *CloudProvider) getRegionalDiskOrError(ctx context.Context, project, volumeRegion, volumeName string) (*computev1.Disk, error) {
disk, err := cloud.service.RegionDisks.Get(project, volumeRegion, volumeName).Context(ctx).Do()
if err != nil {
return nil, err
}
return disk, nil
}
func (cloud *CloudProvider) getZonalBetaDiskOrError(ctx context.Context, project, volumeZone, volumeName string) (*computebeta.Disk, error) {
disk, err := cloud.betaService.Disks.Get(project, volumeZone, volumeName).Context(ctx).Do()
if err != nil {
return nil, err
}
return disk, nil
}
func (cloud *CloudProvider) getRegionalBetaDiskOrError(ctx context.Context, project, volumeRegion, volumeName string) (*computebeta.Disk, error) {
disk, err := cloud.betaService.RegionDisks.Get(project, volumeRegion, volumeName).Context(ctx).Do()
if err != nil {
return nil, err
}
return disk, nil
}
func (cloud *CloudProvider) GetReplicaZoneURI(project, zone string) string {
return cloud.service.BasePath + fmt.Sprintf(
replicaZoneURITemplateSingleZone,
project,
zone)
}
func (cloud *CloudProvider) getRegionURI(project, region string) string {
return cloud.service.BasePath + fmt.Sprintf(
regionURITemplate,
project,
region)
}
func ValidateExistingDisk(ctx context.Context, resp *CloudDisk, params common.DiskParameters, reqBytes, limBytes int64, multiWriter bool, accessMode string) error {
klog.V(5).Infof("Validating existing disk %v with diskType: %s, reqested bytes: %v, limit bytes: %v", resp, params.DiskType, reqBytes, limBytes)
if resp == nil {
return fmt.Errorf("disk does not exist")
}
requestValid := common.GbToBytes(resp.GetSizeGb()) >= reqBytes || reqBytes == 0
responseValid := common.GbToBytes(resp.GetSizeGb()) <= limBytes || limBytes == 0
if !requestValid || !responseValid {
return fmt.Errorf(
"disk already exists with incompatible capacity. Need %v (Required) < %v (Existing) < %v (Limit)",
reqBytes, common.GbToBytes(resp.GetSizeGb()), limBytes)
}
if common.IsHyperdisk(params.DiskType) {
if !validAccessMode(accessMode, resp.GetAccessMode()) {
return fmt.Errorf("disk already exists with incompatible capability. Need %s. Got %s", accessMode, resp.GetAccessMode())
}
} else if multiWriter && !resp.GetMultiWriter() {
// We are assuming here that a multiWriter PD could be used as non-multiWriter
return fmt.Errorf("disk already exists with incompatible capability. Need MultiWriter. Got non-MultiWriter")
}
return ValidateDiskParameters(resp, params)
}
func validAccessMode(want, got string) bool {
if want == got {
return true
}
switch want {
case common.GCEReadOnlyManyAccessMode, common.GCEReadWriteOnceAccessMode:
return got == common.GCEReadWriteManyAccessMode
// For RWX, no other access mode is valid.
default:
return false
}
}
// ValidateDiskParameters takes a CloudDisk and returns true if the parameters
// specified validly describe the disk provided, and false otherwise.
func ValidateDiskParameters(disk *CloudDisk, params common.DiskParameters) error {
if disk.GetPDType() != params.DiskType {
return fmt.Errorf("actual pd type %s did not match the expected param %s", disk.GetPDType(), params.DiskType)
}
locationType := disk.LocationType()
if (params.ReplicationType == "none" && locationType != meta.Zonal) || (params.IsRegional() && locationType != meta.Regional) {
return fmt.Errorf("actual replication type %v did not match expected param %s and %s", locationType, params.ReplicationType, params.DiskType)
}
if !KmsKeyEqual(
disk.GetKMSKeyName(), /* fetchedKMSKey */
params.DiskEncryptionKMSKey /* storageClassKMSKey */) {
return fmt.Errorf("actual disk KMS key name %s did not match expected param %s", disk.GetKMSKeyName(), params.DiskEncryptionKMSKey)
}
return nil
}
func (cloud *CloudProvider) InsertDisk(ctx context.Context, project string, volKey *meta.Key, params common.DiskParameters, capBytes int64, capacityRange *csi.CapacityRange, replicaZones []string, snapshotID string, volumeContentSourceVolumeID string, multiWriter bool, accessMode string) error {
klog.V(5).Infof("Inserting disk %v", volKey)
description, err := encodeTags(params.Tags)
if err != nil {
return err
}
var isZonal bool
switch volKey.Type() {
case meta.Zonal:
if description == "" {
description = "Disk created by GCE-PD CSI Driver"
}
isZonal = true
case meta.Regional:
if description == "" {
description = "Regional disk created by GCE-PD CSI Driver"
}
isZonal = false
default:
return fmt.Errorf("could not insert disk, key was neither zonal nor regional, instead got: %v", volKey.String())
}
diskToCreate, err := cloud.constructDiskToCreate(ctx, project, volKey, params, capBytes, replicaZones, snapshotID, volumeContentSourceVolumeID, description, multiWriter, accessMode)
if err != nil {
return err
}
return cloud.insertConstructedDisk(ctx, diskToCreate, isZonal, project, volKey, params, capacityRange, multiWriter, accessMode)
}
func (cloud *CloudProvider) constructDiskToCreate(
ctx context.Context,
project string,
volKey *meta.Key,
params common.DiskParameters,
capBytes int64,
replicaZones []string,
snapshotID string,
volumeContentSourceVolumeID string,
description string,
multiWriter bool,
accessMode string) (*computebeta.Disk, error) {
diskToCreate := &computebeta.Disk{
Name: volKey.Name,
SizeGb: common.BytesToGbRoundUp(capBytes),
Description: description,
Type: cloud.GetDiskTypeURI(project, volKey, params.DiskType),
Labels: params.Labels,
}
if len(replicaZones) != 0 {
if volKey.Type() == meta.Zonal {
return nil, status.Errorf(codes.InvalidArgument, "cannot specify replica zones (%v) for zonal disks", replicaZones)
}
diskToCreate.ReplicaZones = replicaZones
}
if params.ProvisionedIOPSOnCreate > 0 {
diskToCreate.ProvisionedIops = params.ProvisionedIOPSOnCreate
}
if params.ProvisionedThroughputOnCreate > 0 {
diskToCreate.ProvisionedThroughput = params.ProvisionedThroughputOnCreate
}
if params.StoragePools != nil {
if volKey.Type() == meta.Regional {
return nil, status.Errorf(codes.InvalidArgument, "cannot create regional disks in a Storage Pool")
}
sp := common.StoragePoolInZone(params.StoragePools, volKey.Zone)
if sp == nil {
return nil, status.Errorf(codes.InvalidArgument, "cannot create disk in zone %q: no Storage Pools exist in zone", volKey.Zone)
}
diskToCreate.StoragePool = sp.ResourceName
}
if snapshotID != "" {
_, snapshotType, _, err := common.SnapshotIDToProjectKey(snapshotID)
if err != nil {
return nil, err
}
switch snapshotType {
case common.DiskSnapshotType:
diskToCreate.SourceSnapshot = snapshotID
case common.DiskImageType:
diskToCreate.SourceImage = snapshotID
default:
return nil, fmt.Errorf("invalid snapshot type in snapshot ID: %s", snapshotType)
}
}
if volumeContentSourceVolumeID != "" {
diskToCreate.SourceDisk = volumeContentSourceVolumeID
}
if params.DiskEncryptionKMSKey != "" {
diskToCreate.DiskEncryptionKey = &computebeta.CustomerEncryptionKey{
KmsKeyName: params.DiskEncryptionKMSKey,
}
}
diskToCreate.EnableConfidentialCompute = params.EnableConfidentialCompute
resourceTags, err := getResourceManagerTags(ctx, cloud.tokenSource, params.ResourceTags)
if err != nil {
return nil, err
}
if len(resourceTags) > 0 {
diskToCreate.Params = &computebeta.DiskParams{
ResourceManagerTags: resourceTags,
}
}
if common.IsHyperdisk(params.DiskType) {
diskToCreate.AccessMode = accessMode
} else {
diskToCreate.MultiWriter = multiWriter
}
return diskToCreate, nil
}
func (cloud *CloudProvider) processDiskAlreadyExistErr(ctx context.Context, err error, project string, volKey *meta.Key, params common.DiskParameters, capacityRange *csi.CapacityRange, multiWriter bool, accessMode string) error {
if err == nil {
return nil
}
if IsGCEError(err, "alreadyExists") {
disk, err := cloud.GetDisk(ctx, project, volKey)
if err != nil {
// failed to GetDisk, however the Disk may already exist
// the error code should be non-Final
return common.NewTemporaryError(codes.Unavailable, fmt.Errorf("error when getting disk: %w", err))
}
err = ValidateExistingDisk(ctx, disk, params,
int64(capacityRange.GetRequiredBytes()),
int64(capacityRange.GetLimitBytes()),
multiWriter, accessMode)
if err != nil {
return err
}
klog.Warningf("GCE PD %s already exists, reusing", volKey.Name)
return nil
}
return err
}
func (cloud *CloudProvider) insertConstructedDisk(ctx context.Context, disk *computebeta.Disk, isZonal bool, project string, volKey *meta.Key, params common.DiskParameters, capacityRange *csi.CapacityRange, multiWriter bool, accessMode string) error {
var (
insertOp *computebeta.Operation
opName string
err error
)
if isZonal {
insertOp, err = cloud.betaService.Disks.Insert(project, volKey.Zone, disk).Context(ctx).Do()
if insertOp != nil {
opName = insertOp.Name
}
} else {
insertOp, err = cloud.betaService.RegionDisks.Insert(project, volKey.Region, disk).Context(ctx).Do()
if insertOp != nil {
opName = insertOp.Name
}
}
if filterErr := cloud.processDiskAlreadyExistErr(ctx, err, project, volKey, params, capacityRange, multiWriter, accessMode); filterErr != nil {
// if the error code is considered "final", Disks.Insert might not be retried
return fmt.Errorf("unknown Insert disk error: %w", err)
}
klog.V(5).Infof("InsertDisk operation %s for disk %s", opName, disk.Name)
if isZonal {
err = cloud.waitForZonalOp(ctx, project, opName, volKey.Zone)
} else {
err = cloud.waitForRegionalOp(ctx, project, opName, volKey.Region)
}
if filterErr := cloud.processDiskAlreadyExistErr(ctx, err, project, volKey, params, capacityRange, multiWriter, accessMode); filterErr != nil {
return common.NewTemporaryError(codes.Unavailable, fmt.Errorf("unknown error when polling the operation: %w", err))
}
return nil
}
func (cloud *CloudProvider) UpdateDisk(ctx context.Context, project string, volKey *meta.Key, existingDisk *CloudDisk, params common.ModifyVolumeParameters) error {
// hyperdisks are zonal disks
// pd-disks do not support modification of IOPS and Throughput
if volKey.Type() == meta.Regional {
return status.Error(codes.InvalidArgument, "Cannot update regional disk")
}
klog.V(5).Infof("Updating disk %v", volKey)
return cloud.updateZonalDisk(ctx, project, volKey, existingDisk, params)
}
func (cloud *CloudProvider) updateZonalDisk(ctx context.Context, project string, volKey *meta.Key, existingDisk *CloudDisk, params common.ModifyVolumeParameters) error {
specifiedIops := params.IOPS != nil && *params.IOPS != 0
specifiedThroughput := params.Throughput != nil && *params.Throughput != 0
if !specifiedIops && !specifiedThroughput {
return fmt.Errorf("no IOPS or Throughput specified for disk %v", existingDisk.GetSelfLink())
}
updatedDisk := &computev1.Disk{
Name: existingDisk.GetName(),
}
paths := []string{}
if params.IOPS != nil && *params.IOPS != 0 {
updatedDisk.ProvisionedIops = *params.IOPS
paths = append(paths, "provisionedIops")
}
if params.Throughput != nil && *params.Throughput != 0 {
updatedDisk.ProvisionedThroughput = *params.Throughput
paths = append(paths, "provisionedThroughput")
}
diskUpdateOp := cloud.service.Disks.Update(project, volKey.Zone, volKey.Name, updatedDisk)
diskUpdateOp.Paths(paths...)
_, err := diskUpdateOp.Context(ctx).Do()
if err != nil {
return fmt.Errorf("error updating disk %v: %w", volKey, err)
}
return nil
}
func convertV1CustomerEncryptionKeyToBeta(v1Key *computev1.CustomerEncryptionKey) *computebeta.CustomerEncryptionKey {
return &computebeta.CustomerEncryptionKey{
KmsKeyName: v1Key.KmsKeyName,
RawKey: v1Key.RawKey,
Sha256: v1Key.Sha256,
ForceSendFields: v1Key.ForceSendFields,
NullFields: v1Key.NullFields,
}
}
func convertV1DiskParamsToBeta(v1DiskParams *computev1.DiskParams) *computebeta.DiskParams {
resourceManagerTags := make(map[string]string)
for k, v := range v1DiskParams.ResourceManagerTags {
resourceManagerTags[k] = v
}
return &computebeta.DiskParams{
ResourceManagerTags: resourceManagerTags,
}
}
func convertV1DiskToBetaDisk(v1Disk *computev1.Disk) *computebeta.Disk {
var dek *computebeta.CustomerEncryptionKey = nil
if v1Disk.DiskEncryptionKey != nil {
dek = convertV1CustomerEncryptionKeyToBeta(v1Disk.DiskEncryptionKey)
}
var params *computebeta.DiskParams = nil
if v1Disk.Params != nil {
params = convertV1DiskParamsToBeta(v1Disk.Params)
}
// Note: this is an incomplete list. It only includes the fields we use for disk creation.
betaDisk := &computebeta.Disk{
Name: v1Disk.Name,
SizeGb: v1Disk.SizeGb,
Description: v1Disk.Description,
Type: v1Disk.Type,
SourceSnapshot: v1Disk.SourceSnapshot,
SourceImage: v1Disk.SourceImage,
SourceImageId: v1Disk.SourceImageId,
SourceSnapshotId: v1Disk.SourceSnapshotId,
SourceDisk: v1Disk.SourceDisk,
ReplicaZones: v1Disk.ReplicaZones,
DiskEncryptionKey: dek,
Zone: v1Disk.Zone,
Region: v1Disk.Region,
Status: v1Disk.Status,
SelfLink: v1Disk.SelfLink,
Params: params,
AccessMode: v1Disk.AccessMode,
}
if v1Disk.ProvisionedIops > 0 {
betaDisk.ProvisionedIops = v1Disk.ProvisionedIops
}
if v1Disk.ProvisionedThroughput > 0 {
betaDisk.ProvisionedThroughput = v1Disk.ProvisionedThroughput
}
betaDisk.StoragePool = v1Disk.StoragePool
return betaDisk
}
func convertBetaCustomerEncryptionKeyToV1(betaKey *computebeta.CustomerEncryptionKey) *computev1.CustomerEncryptionKey {
return &computev1.CustomerEncryptionKey{
KmsKeyName: betaKey.KmsKeyName,
RawKey: betaKey.RawKey,
Sha256: betaKey.Sha256,
ForceSendFields: betaKey.ForceSendFields,
NullFields: betaKey.NullFields,
}
}
func convertBetaDiskParamsToV1(betaDiskParams *computebeta.DiskParams) *computev1.DiskParams {
resourceManagerTags := make(map[string]string)
for k, v := range betaDiskParams.ResourceManagerTags {
resourceManagerTags[k] = v
}
return &computev1.DiskParams{
ResourceManagerTags: resourceManagerTags,
}
}
func convertBetaDiskToV1Disk(betaDisk *computebeta.Disk) *computev1.Disk {
var dek *computev1.CustomerEncryptionKey = nil
if betaDisk.DiskEncryptionKey != nil {
dek = convertBetaCustomerEncryptionKeyToV1(betaDisk.DiskEncryptionKey)
}
var params *computev1.DiskParams = nil
if betaDisk.Params != nil {
params = convertBetaDiskParamsToV1(betaDisk.Params)
}
// Note: this is an incomplete list. It only includes the fields we use for disk creation.
v1Disk := &computev1.Disk{
Name: betaDisk.Name,
SizeGb: betaDisk.SizeGb,
Description: betaDisk.Description,
Type: betaDisk.Type,
SourceSnapshot: betaDisk.SourceSnapshot,
SourceImage: betaDisk.SourceImage,
SourceImageId: betaDisk.SourceImageId,
SourceSnapshotId: betaDisk.SourceSnapshotId,
SourceDisk: betaDisk.SourceDisk,
ReplicaZones: betaDisk.ReplicaZones,
DiskEncryptionKey: dek,
Zone: betaDisk.Zone,
Region: betaDisk.Region,
Status: betaDisk.Status,
SelfLink: betaDisk.SelfLink,
Params: params,
AccessMode: betaDisk.AccessMode,
}
if betaDisk.ProvisionedIops > 0 {
v1Disk.ProvisionedIops = betaDisk.ProvisionedIops
}
if betaDisk.ProvisionedThroughput > 0 {
v1Disk.ProvisionedThroughput = betaDisk.ProvisionedThroughput
}
v1Disk.StoragePool = betaDisk.StoragePool
return v1Disk
}
func (cloud *CloudProvider) DeleteDisk(ctx context.Context, project string, volKey *meta.Key) error {
klog.V(5).Infof("Deleting disk: %v", volKey)
switch volKey.Type() {
case meta.Zonal:
return cloud.deleteZonalDisk(ctx, project, volKey.Zone, volKey.Name)
case meta.Regional:
return cloud.deleteRegionalDisk(ctx, project, volKey.Region, volKey.Name)
default:
return fmt.Errorf("could not delete disk, key was neither zonal nor regional, instead got: %v", volKey.String())
}
}
func (cloud *CloudProvider) deleteZonalDisk(ctx context.Context, project, zone, name string) error {
op, err := cloud.service.Disks.Delete(project, zone, name).Context(ctx).Do()
if err != nil {
if IsGCEError(err, "notFound") {
// Already deleted
return nil
}
return err
}
klog.V(5).Infof("DeleteDisk operation %s for disk %s", op.Name, name)
err = cloud.waitForZonalOp(ctx, project, op.Name, zone)
if err != nil {
return err
}
return nil
}
func (cloud *CloudProvider) deleteRegionalDisk(ctx context.Context, project, region, name string) error {
op, err := cloud.service.RegionDisks.Delete(project, region, name).Context(ctx).Do()
if err != nil {
if IsGCEError(err, "notFound") {
// Already deleted
return nil
}
return err
}
klog.V(5).Infof("DeleteDisk operation %s for disk %s", op.Name, name)
err = cloud.waitForRegionalOp(ctx, project, op.Name, region)
if err != nil {
return err
}
return nil
}
func (cloud *CloudProvider) AttachDisk(ctx context.Context, project string, volKey *meta.Key, readWrite, diskType, instanceZone, instanceName string, forceAttach bool) error {
klog.V(5).Infof("Attaching disk %v to %s", volKey, instanceName)
source := cloud.GetDiskSourceURI(project, volKey)
deviceName, err := common.GetDeviceName(volKey)
if err != nil {
return fmt.Errorf("failed to get device name: %w", err)
}
attachedDiskV1 := &computev1.AttachedDisk{
DeviceName: deviceName,
Kind: diskKind,
Mode: readWrite,
Source: source,
Type: diskType,
// This parameter is ignored in the call, the ForceAttach decorator
// (query parameter) is the important one. We'll set it in both places
// in case that behavior changes.
ForceAttach: forceAttach,
}
op, err := cloud.service.Instances.AttachDisk(project, instanceZone, instanceName, attachedDiskV1).Context(ctx).ForceAttach(forceAttach).Do()
if err != nil {
return fmt.Errorf("failed cloud service attach disk call: %w", err)
}
klog.V(5).Infof("AttachDisk operation %s for disk %s", op.Name, attachedDiskV1.DeviceName)
err = cloud.waitForZonalOp(ctx, project, op.Name, instanceZone)
if err != nil {
return fmt.Errorf("failed when waiting for zonal op: %w", err)
}
return nil
}
func (cloud *CloudProvider) DetachDisk(ctx context.Context, project, deviceName, instanceZone, instanceName string) error {
klog.V(5).Infof("Detaching disk %v from %v", deviceName, instanceName)
op, err := cloud.service.Instances.DetachDisk(project, instanceZone, instanceName, deviceName).Context(ctx).Do()
if err != nil {
return err
}
klog.V(5).Infof("DetachDisk operation %s for disk %s", op.Name, deviceName)
err = cloud.waitForZonalOp(ctx, project, op.Name, instanceZone)
if err != nil {
return err
}
return nil
}
func (cloud *CloudProvider) SetDiskAccessMode(ctx context.Context, project string, volKey *meta.Key, accessMode string) error {
diskMask := &computev1.Disk{
AccessMode: accessMode,
Name: volKey.Name,
}
switch volKey.Type() {
case meta.Zonal:
op, err := cloud.service.Disks.Update(project, volKey.Zone, volKey.Name, diskMask).Context(ctx).Paths("accessMode").Do()
if err != nil {
return fmt.Errorf("failed to set access mode for zonal volume %v: %w", volKey, err)
}
klog.V(5).Infof("SetDiskAccessMode operation %s for disk %s", op.Name, volKey.Name)
err = cloud.waitForZonalOp(ctx, project, op.Name, volKey.Zone)
if err != nil {
return fmt.Errorf("failed waiting for op for zonal disk update for %v: %w", volKey, err)
}
case meta.Regional:
op, err := cloud.service.RegionDisks.Update(project, volKey.Region, volKey.Name, diskMask).Context(ctx).Paths("accessMode").Do()
if err != nil {
return fmt.Errorf("failed to set access mode for regional volume %v: %w", volKey, err)
}
klog.V(5).Infof("SetDiskAccessMode operation %s for disk %s", op.Name, volKey.Name)
err = cloud.waitForRegionalOp(ctx, project, op.Name, volKey.Region)
if err != nil {
return fmt.Errorf("failed waiting for op for regional disk update for %v: %w", volKey, err)
}
default:
return fmt.Errorf("volume key %v not zonal nor regional", volKey.Name)
}
return nil
}
func (cloud *CloudProvider) ListCompatibleDiskTypeZones(ctx context.Context, project string, zones []string, diskType string) ([]string, error) {
diskTypeFilter := fmt.Sprintf("name=%s", diskType)
filters := []string{diskTypeFilter}
diskTypeListCall := cloud.service.DiskTypes.AggregatedList(project).Context(ctx).Filter(strings.Join(filters, " "))
supportedZones := []string{}
nextPageToken := "pageToken"
for nextPageToken != "" {
diskTypeList, err := diskTypeListCall.Do()
if err != nil {
return nil, err
}
for _, item := range diskTypeList.Items {
for _, diskType := range item.DiskTypes {
zone, err := common.ParseZoneFromURI(diskType.Zone)
if err != nil {
klog.Warningf("Failed to parse zone %q from diskTypes API: %v", diskType.Zone, err)
continue
}
if slices.Contains(zones, zone) {
supportedZones = append(supportedZones, zone)
}
}
}
nextPageToken = diskTypeList.NextPageToken
diskTypeListCall.PageToken(nextPageToken)
}
return supportedZones, nil
}
func (cloud *CloudProvider) GetDiskSourceURI(project string, volKey *meta.Key) string {
switch volKey.Type() {
case meta.Zonal:
return cloud.getZonalDiskSourceURI(project, volKey.Name, volKey.Zone)
case meta.Regional:
return cloud.getRegionalDiskSourceURI(project, volKey.Name, volKey.Region)
default:
return ""
}
}
func (cloud *CloudProvider) getZonalDiskSourceURI(project, diskName, zone string) string {
return cloud.service.BasePath + fmt.Sprintf(
diskSourceURITemplateSingleZone,
project,
zone,
diskName)
}
func (cloud *CloudProvider) getRegionalDiskSourceURI(project, diskName, region string) string {
return cloud.service.BasePath + fmt.Sprintf(
diskSourceURITemplateRegional,
project,
region,
diskName)
}
func (cloud *CloudProvider) GetDiskTypeURI(project string, volKey *meta.Key, diskType string) string {
switch volKey.Type() {
case meta.Zonal:
return cloud.getZonalDiskTypeURI(project, volKey.Zone, diskType)
case meta.Regional:
return cloud.getRegionalDiskTypeURI(project, volKey.Region, diskType)
default:
return fmt.Sprintf("could get disk type URI, key was neither zonal nor regional, instead got: %v", volKey.String())
}
}
func (cloud *CloudProvider) getZonalDiskTypeURI(project string, zone, diskType string) string {
return cloud.service.BasePath + fmt.Sprintf(diskTypeURITemplateSingleZone, project, zone, diskType)
}
func (cloud *CloudProvider) getRegionalDiskTypeURI(project string, region, diskType string) string {
return cloud.service.BasePath + fmt.Sprintf(diskTypeURITemplateRegional, project, region, diskType)
}