-
Notifications
You must be signed in to change notification settings - Fork 150
/
gce-compute.go
1212 lines (1083 loc) · 41.1 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"
"fmt"
"regexp"
"strings"
"time"
"github.com/GoogleCloudPlatform/k8s-cloud-provider/pkg/cloud/meta"
csi "github.com/container-storage-interface/spec/lib/go/csi"
computebeta "google.golang.org/api/compute/v0.beta"
computev1 "google.golang.org/api/compute/v1"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/klog/v2"
"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)
var hyperdiskTypes = []string{"hyperdisk-extreme", "hyperdisk-throughput"}
type GCEAPIVersion string
const (
// V1 key type
GCEAPIVersionV1 GCEAPIVersion = "v1"
// Alpha key type
GCEAPIVersionBeta GCEAPIVersion = "beta"
)
// 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, gceAPIVersion GCEAPIVersion) (*CloudDisk, error)
RepairUnderspecifiedVolumeKey(ctx context.Context, project string, volumeKey *meta.Key) (string, *meta.Key, error)
ValidateExistingDisk(ctx context.Context, disk *CloudDisk, params common.DiskParameters, reqBytes, limBytes int64, multiWriter bool) 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) error
DeleteDisk(ctx context.Context, project string, volumeKey *meta.Key) error
AttachDisk(ctx context.Context, project string, volKey *meta.Key, readWrite, diskType, instanceZone, instanceName string) error
DetachDisk(ctx context.Context, project, deviceName, instanceZone, instanceName 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, instanceZone, instanceName string) error
ResizeDisk(ctx context.Context, project string, volKey *meta.Key, requestBytes int64) (int64, error)
ListDisks(ctx context.Context) ([]*computev1.Disk, 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) ([]*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)
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)
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
}
// 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...)
}
return items, "", nil
}
func (cloud *CloudProvider) GetDisk(ctx context.Context, project string, key *meta.Key, gceAPIVersion GCEAPIVersion) (*CloudDisk, error) {
klog.V(5).Infof("Getting disk %v", key)
switch key.Type() {
case meta.Zonal:
if gceAPIVersion == GCEAPIVersionBeta {
disk, err := cloud.getZonalBetaDiskOrError(ctx, project, key.Zone, key.Name)
return CloudDiskFromBeta(disk), err
} else {
disk, err := cloud.getZonalDiskOrError(ctx, project, key.Zone, key.Name)
return CloudDiskFromV1(disk), err
}
case meta.Regional:
if gceAPIVersion == GCEAPIVersionBeta {
disk, err := cloud.getRegionalAlphaDiskOrError(ctx, project, key.Region, key.Name)
return CloudDiskFromBeta(disk), err
} else {
disk, err := cloud.getRegionalDiskOrError(ctx, project, key.Region, key.Name)
return CloudDiskFromV1(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) getRegionalAlphaDiskOrError(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 (cloud *CloudProvider) ValidateExistingDisk(ctx context.Context, resp *CloudDisk, params common.DiskParameters, reqBytes, limBytes int64, multiWriter bool) 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)
}
// We are assuming here that a multiWriter disk could be used as non-multiWriter
if multiWriter && !resp.GetMultiWriter() {
return fmt.Errorf("disk already exists with incompatible capability. Need MultiWriter. Got non-MultiWriter")
}
return ValidateDiskParameters(resp, params)
}
// 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.ReplicationType == "regional-pd" && locationType != meta.Regional) {
return fmt.Errorf("actual disk replication type %v did not match expected param %s", locationType, params.ReplicationType)
}
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) error {
klog.V(5).Infof("Inserting disk %v", volKey)
description, err := encodeTags(params.Tags)
if err != nil {
return err
}
switch volKey.Type() {
case meta.Zonal:
if description == "" {
description = "Disk created by GCE-PD CSI Driver"
}
return cloud.insertZonalDisk(ctx, project, volKey, params, capBytes, capacityRange, snapshotID, volumeContentSourceVolumeID, description, multiWriter)
case meta.Regional:
if description == "" {
description = "Regional disk created by GCE-PD CSI Driver"
}
return cloud.insertRegionalDisk(ctx, project, volKey, params, capBytes, capacityRange, replicaZones, snapshotID, volumeContentSourceVolumeID, description, multiWriter)
default:
return fmt.Errorf("could not insert disk, key was neither zonal nor regional, instead got: %v", volKey.String())
}
}
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 convertV1DiskToBetaDisk(v1Disk *computev1.Disk, provisionedThroughputOnCreate int64) *computebeta.Disk {
var dek *computebeta.CustomerEncryptionKey = nil
if v1Disk.DiskEncryptionKey != nil {
dek = convertV1CustomerEncryptionKeyToBeta(v1Disk.DiskEncryptionKey)
}
// 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,
ReplicaZones: v1Disk.ReplicaZones,
DiskEncryptionKey: dek,
}
if v1Disk.ProvisionedIops > 0 {
betaDisk.ProvisionedIops = v1Disk.ProvisionedIops
}
if provisionedThroughputOnCreate > 0 {
betaDisk.ProvisionedThroughput = provisionedThroughputOnCreate
}
return betaDisk
}
func (cloud *CloudProvider) insertRegionalDisk(
ctx context.Context,
project string,
volKey *meta.Key,
params common.DiskParameters,
capBytes int64,
capacityRange *csi.CapacityRange,
replicaZones []string,
snapshotID string,
volumeContentSourceVolumeID string,
description string,
multiWriter bool) error {
var (
err error
opName string
gceAPIVersion = GCEAPIVersionV1
)
if multiWriter {
gceAPIVersion = GCEAPIVersionBeta
}
diskToCreate := &computev1.Disk{
Name: volKey.Name,
SizeGb: common.BytesToGbRoundUp(capBytes),
Description: description,
Type: cloud.GetDiskTypeURI(cloud.project, volKey, params.DiskType),
Labels: params.Labels,
}
if snapshotID != "" {
_, snapshotType, _, err := common.SnapshotIDToProjectKey(snapshotID)
if err != nil {
return err
}
switch snapshotType {
case common.DiskSnapshotType:
diskToCreate.SourceSnapshot = snapshotID
case common.DiskImageType:
diskToCreate.SourceImage = snapshotID
default:
return fmt.Errorf("invalid snapshot type in snapshot ID: %s", snapshotType)
}
}
if volumeContentSourceVolumeID != "" {
diskToCreate.SourceDisk = volumeContentSourceVolumeID
}
if len(replicaZones) != 0 {
diskToCreate.ReplicaZones = replicaZones
}
if params.DiskEncryptionKMSKey != "" {
diskToCreate.DiskEncryptionKey = &computev1.CustomerEncryptionKey{
KmsKeyName: params.DiskEncryptionKMSKey,
}
}
if gceAPIVersion == GCEAPIVersionBeta {
var insertOp *computebeta.Operation
betaDiskToCreate := convertV1DiskToBetaDisk(diskToCreate, 0)
betaDiskToCreate.MultiWriter = multiWriter
insertOp, err = cloud.betaService.RegionDisks.Insert(project, volKey.Region, betaDiskToCreate).Context(ctx).Do()
if insertOp != nil {
opName = insertOp.Name
}
} else {
var insertOp *computev1.Operation
insertOp, err = cloud.service.RegionDisks.Insert(project, volKey.Region, diskToCreate).Context(ctx).Do()
if insertOp != nil {
opName = insertOp.Name
}
}
if err != nil {
if IsGCEError(err, "alreadyExists") {
disk, err := cloud.GetDisk(ctx, project, volKey, gceAPIVersion)
if err != nil {
return err
}
err = cloud.ValidateExistingDisk(ctx, disk, params,
int64(capacityRange.GetRequiredBytes()),
int64(capacityRange.GetLimitBytes()),
multiWriter)
if err != nil {
return err
}
klog.Warningf("GCE PD %s already exists, reusing", volKey.Name)
return nil
}
return status.Error(codes.Internal, fmt.Sprintf("unknown Insert disk error: %v", err.Error()))
}
klog.V(5).Infof("InsertDisk operation %s for disk %s", opName, diskToCreate.Name)
err = cloud.waitForRegionalOp(ctx, project, opName, volKey.Region)
if err != nil {
if IsGCEError(err, "alreadyExists") {
disk, err := cloud.GetDisk(ctx, project, volKey, gceAPIVersion)
if err != nil {
return err
}
err = cloud.ValidateExistingDisk(ctx, disk, params,
int64(capacityRange.GetRequiredBytes()),
int64(capacityRange.GetLimitBytes()),
multiWriter)
if err != nil {
return err
}
klog.Warningf("GCE PD %s already exists after wait, reusing", volKey.Name)
return nil
}
return fmt.Errorf("unknown Insert disk operation error: %w", err)
}
return nil
}
func (cloud *CloudProvider) insertZonalDisk(
ctx context.Context,
project string,
volKey *meta.Key,
params common.DiskParameters,
capBytes int64,
capacityRange *csi.CapacityRange,
snapshotID string,
volumeContentSourceVolumeID string,
description string,
multiWriter bool) error {
var (
err error
opName string
gceAPIVersion = GCEAPIVersionV1
)
if multiWriter || containsBetaDiskType(hyperdiskTypes, params.DiskType) {
gceAPIVersion = GCEAPIVersionBeta
}
diskToCreate := &computev1.Disk{
Name: volKey.Name,
SizeGb: common.BytesToGbRoundUp(capBytes),
Description: description,
Type: cloud.GetDiskTypeURI(project, volKey, params.DiskType),
Labels: params.Labels,
ProvisionedIops: params.ProvisionedIOPSOnCreate,
}
if snapshotID != "" {
_, snapshotType, _, err := common.SnapshotIDToProjectKey(snapshotID)
if err != nil {
return err
}
switch snapshotType {
case common.DiskSnapshotType:
diskToCreate.SourceSnapshot = snapshotID
case common.DiskImageType:
diskToCreate.SourceImage = snapshotID
default:
return fmt.Errorf("invalid snapshot type in snapshot ID: %s", snapshotType)
}
}
if volumeContentSourceVolumeID != "" {
diskToCreate.SourceDisk = volumeContentSourceVolumeID
}
if params.DiskEncryptionKMSKey != "" {
diskToCreate.DiskEncryptionKey = &computev1.CustomerEncryptionKey{
KmsKeyName: params.DiskEncryptionKMSKey,
}
}
if gceAPIVersion == GCEAPIVersionBeta {
var insertOp *computebeta.Operation
betaDiskToCreate := convertV1DiskToBetaDisk(diskToCreate, params.ProvisionedThroughputOnCreate)
betaDiskToCreate.MultiWriter = multiWriter
insertOp, err = cloud.betaService.Disks.Insert(project, volKey.Zone, betaDiskToCreate).Context(ctx).Do()
if insertOp != nil {
opName = insertOp.Name
}
} else {
var insertOp *computev1.Operation
insertOp, err = cloud.service.Disks.Insert(project, volKey.Zone, diskToCreate).Context(ctx).Do()
if insertOp != nil {
opName = insertOp.Name
}
}
if err != nil {
if IsGCEError(err, "alreadyExists") {
disk, err := cloud.GetDisk(ctx, project, volKey, gceAPIVersion)
if err != nil {
return err
}
err = cloud.ValidateExistingDisk(ctx, disk, params,
int64(capacityRange.GetRequiredBytes()),
int64(capacityRange.GetLimitBytes()),
multiWriter)
if err != nil {
return err
}
klog.Warningf("GCE PD %s already exists, reusing", volKey.Name)
return nil
}
return fmt.Errorf("unknown Insert disk error: %w", err)
}
klog.V(5).Infof("InsertDisk operation %s for disk %s", opName, diskToCreate.Name)
err = cloud.waitForZonalOp(ctx, project, opName, volKey.Zone)
if err != nil {
if IsGCEError(err, "alreadyExists") {
disk, err := cloud.GetDisk(ctx, project, volKey, gceAPIVersion)
if err != nil {
return err
}
err = cloud.ValidateExistingDisk(ctx, disk, params,
int64(capacityRange.GetRequiredBytes()),
int64(capacityRange.GetLimitBytes()),
multiWriter)
if err != nil {
return err
}
klog.Warningf("GCE PD %s already exists after wait, reusing", volKey.Name)
return nil
}
return fmt.Errorf("unknown Insert disk operation error: %w", err)
}
return nil
}
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) 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,
}
op, err := cloud.service.Instances.AttachDisk(project, instanceZone, instanceName, attachedDiskV1).Context(ctx).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) 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)
}
func (cloud *CloudProvider) waitForZonalOp(ctx context.Context, project, opName string, zone string) error {
// The v1 API can query for v1, alpha, or beta operations.
return wait.ExponentialBackoff(WaitForOpBackoff, func() (bool, error) {
pollOp, err := cloud.service.ZoneOperations.Get(project, zone, opName).Context(ctx).Do()
if err != nil {
klog.Errorf("WaitForOp(op: %s, zone: %#v) failed to poll the operation", opName, zone)
return false, err
}
done, err := opIsDone(pollOp)
return done, err
})
}
func (cloud *CloudProvider) waitForRegionalOp(ctx context.Context, project, opName string, region string) error {
// The v1 API can query for v1, alpha, or beta operations.
return wait.ExponentialBackoff(WaitForOpBackoff, func() (bool, error) {
pollOp, err := cloud.service.RegionOperations.Get(project, region, opName).Context(ctx).Do()
if err != nil {
klog.Errorf("WaitForOp(op: %s, region: %#v) failed to poll the operation", opName, region)
return false, err
}
done, err := opIsDone(pollOp)
return done, err
})
}
func (cloud *CloudProvider) waitForGlobalOp(ctx context.Context, project, opName string) error {
return wait.ExponentialBackoff(WaitForOpBackoff, func() (bool, error) {
pollOp, err := cloud.service.GlobalOperations.Get(project, opName).Context(ctx).Do()
if err != nil {
klog.Errorf("waitForGlobalOp(op: %s) failed to poll the operation", opName)
return false, err
}
done, err := opIsDone(pollOp)
return done, err
})
}
func (cloud *CloudProvider) WaitForAttach(ctx context.Context, project string, volKey *meta.Key, instanceZone, instanceName string) error {
klog.V(5).Infof("Waiting for attach of disk %v to instance %v to complete...", volKey.Name, instanceName)
start := time.Now()
return wait.ExponentialBackoff(AttachDiskBackoff, func() (bool, error) {
klog.V(6).Infof("Polling for attach of disk %v to instance %v to complete for %v", volKey.Name, instanceName, time.Since(start))
disk, err := cloud.GetDisk(ctx, project, volKey, GCEAPIVersionV1)
if err != nil {
return false, fmt.Errorf("GetDisk failed to get disk: %w", err)
}
if disk == nil {
return false, fmt.Errorf("Disk %v could not be found", volKey.Name)
}
for _, user := range disk.GetUsers() {
if strings.Contains(user, instanceName) && strings.Contains(user, instanceZone) {
return true, nil
}
}
return false, nil
})
}
func wrapOpErr(name string, opErr *computev1.OperationErrorErrors) error {
if opErr.Code == "UNSUPPORTED_OPERATION" {
if diskType := pdDiskTypeUnsupportedRegex.FindStringSubmatch(opErr.Message); diskType != nil {
return &UnsupportedDiskError{
DiskType: diskType[1],
}
}
}
return fmt.Errorf("operation %v failed (%v): %v", name, opErr.Code, opErr.Message)
}
func opIsDone(op *computev1.Operation) (bool, error) {
if op == nil || op.Status != operationStatusDone {
return false, nil
}
if op.Error != nil && len(op.Error.Errors) > 0 && op.Error.Errors[0] != nil {
return true, wrapOpErr(op.Name, op.Error.Errors[0])
}
return true, nil
}
func (cloud *CloudProvider) GetInstanceOrError(ctx context.Context, instanceZone, instanceName string) (*computev1.Instance, error) {
klog.V(5).Infof("Getting instance %v from zone %v", instanceName, instanceZone)
svc := cloud.service
project := cloud.project
instance, err := svc.Instances.Get(project, instanceZone, instanceName).Do()
if err != nil {
return nil, err
}
return instance, nil
}
func (cloud *CloudProvider) GetSnapshot(ctx context.Context, project, snapshotName string) (*computev1.Snapshot, error) {
klog.V(5).Infof("Getting snapshot %v", snapshotName)
svc := cloud.service
snapshot, err := svc.Snapshots.Get(project, snapshotName).Context(ctx).Do()
if err != nil {
return nil, err
}
return snapshot, nil
}
func (cloud *CloudProvider) DeleteSnapshot(ctx context.Context, project, snapshotName string) error {
klog.V(5).Infof("Deleting snapshot %v", snapshotName)
op, err := cloud.service.Snapshots.Delete(project, snapshotName).Context(ctx).Do()
if err != nil {
if IsGCEError(err, "notFound") {
// Already deleted
return nil
}
return err
}
err = cloud.waitForGlobalOp(ctx, project, op.Name)
if err != nil {
return err
}
return nil
}
func (cloud *CloudProvider) CreateSnapshot(ctx context.Context, project string, volKey *meta.Key, snapshotName string, snapshotParams common.SnapshotParameters) (*computev1.Snapshot, error) {
klog.V(5).Infof("Creating snapshot %s for volume %v", snapshotName, volKey)
description, err := encodeTags(snapshotParams.Tags)
if err != nil {
return nil, err
}
switch volKey.Type() {
case meta.Zonal:
if description == "" {
description = "Snapshot created by GCE-PD CSI Driver"
}
return cloud.createZonalDiskSnapshot(ctx, project, volKey, snapshotName, snapshotParams, description)
case meta.Regional:
if description == "" {
description = "Regional Snapshot created by GCE-PD CSI Driver"
}
return cloud.createRegionalDiskSnapshot(ctx, project, volKey, snapshotName, snapshotParams, description)
default:
return nil, fmt.Errorf("could not create snapshot, key was neither zonal nor regional, instead got: %v", volKey.String())
}
}
func (cloud *CloudProvider) CreateImage(ctx context.Context, project string, volKey *meta.Key, imageName string, snapshotParams common.SnapshotParameters) (*computev1.Image, error) {
klog.V(5).Infof("Creating image %s for source %v", imageName, volKey)
description, err := encodeTags(snapshotParams.Tags)
if err != nil {
return nil, err
}
if description == "" {
description = "Image created by GCE-PD CSI Driver"
}
diskID, err := common.KeyToVolumeID(volKey, project)
if err != nil {
return nil, err
}
image := &computev1.Image{
SourceDisk: diskID,
Family: snapshotParams.ImageFamily,
Name: imageName,
StorageLocations: snapshotParams.StorageLocations,
Description: description,
}
_, err = cloud.service.Images.Insert(project, image).Context(ctx).ForceCreate(true).Do()
if err != nil {
return nil, err
}
return cloud.waitForImageCreation(ctx, project, imageName)
}
func (cloud *CloudProvider) waitForImageCreation(ctx context.Context, project, imageName string) (*computev1.Image, error) {
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
timer := time.NewTimer(waitForImageCreationTimeOut)
defer timer.Stop()
for {
select {
case <-ticker.C:
klog.V(6).Infof("Checking GCE Image %s.", imageName)
image, err := cloud.GetImage(ctx, project, imageName)
if err != nil {
klog.Warningf("Error in getting image %s, %v", imageName, err.Error())
} else if image != nil {
if image.Status != "PENDING" {
klog.V(6).Infof("Image %s status is %s", imageName, image.Status)
return image, nil
} else {
klog.V(6).Infof("Image %s is still pending", imageName)
}
}
case <-timer.C:
return nil, fmt.Errorf("timeout waiting for image %s to be created", imageName)
}
}
}
func (cloud *CloudProvider) GetImage(ctx context.Context, project, imageName string) (*computev1.Image, error) {
klog.V(5).Infof("Getting image %v", imageName)