-
Notifications
You must be signed in to change notification settings - Fork 13
/
kubernetes.go
666 lines (592 loc) · 20.3 KB
/
kubernetes.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
// Licensed to Michael Tougeron <[email protected]> under
// one or more contributor license agreements. See the LICENSE
// file distributed with this work for additional information
// regarding copyright ownership.
// Michael Tougeron <[email protected]> licenses this file
// to you 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 main
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"html/template"
"net/url"
"os"
"path/filepath"
"regexp"
"slices"
"strings"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/fsx"
"github.com/prometheus/client_golang/prometheus"
log "github.com/sirupsen/logrus"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/informers"
"k8s.io/client-go/kubernetes"
_ "k8s.io/client-go/plugin/pkg/client/auth"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/tools/clientcmd"
)
var (
// DefaultKubeConfigFile local kubeconfig if not running in cluster
DefaultKubeConfigFile = filepath.Join(os.Getenv("HOME"), ".kube", "config")
k8sClient kubernetes.Interface
awsVolumeRegMatch = regexp.MustCompile("^vol-[^/]*$")
)
const (
// Matching strings for volume operations.
regexpEFSVolumeID = `^fs-\w+::(fsap-\w+)$`
// supported AWS storage provisioners:
AWS_EBS_CSI = "ebs.csi.aws.com"
AWS_EBS_LEGACY = "kubernetes.io/aws-ebs"
AWS_EFS_CSI = "efs.csi.aws.com"
AWS_FSX_CSI = "fsx.csi.aws.com"
// supported AZURE storage provisioners:
AZURE_DISK_CSI = "disk.csi.azure.com"
// supported GCP storage provisioners:
GCP_PD_CSI = "pd.csi.storage.gke.io"
GCP_PD_LEGACY = "kubernetes.io/gce-pd"
)
type TagTemplate struct {
Name string
Namespace string
Labels map[string]string
Annotations map[string]string
}
func BuildClient(kubeconfig string, kubeContext string) (*kubernetes.Clientset, error) {
config, err := rest.InClusterConfig()
if err != nil {
if kubeconfig == "" {
kubeconfig = DefaultKubeConfigFile
}
config, err = buildConfigFromFlags(kubeconfig, kubeContext)
if err != nil {
return nil, err
}
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
panic(err.Error())
}
return clientset, nil
}
func buildConfigFromFlags(kubeconfig string, context string) (*rest.Config, error) {
return clientcmd.NewNonInteractiveDeferredLoadingClientConfig(
&clientcmd.ClientConfigLoadingRules{ExplicitPath: kubeconfig},
&clientcmd.ConfigOverrides{
CurrentContext: context,
}).ClientConfig()
}
func watchForPersistentVolumeClaims(ch chan struct{}, watchNamespace string) {
var err error
var factory informers.SharedInformerFactory
log.WithFields(log.Fields{"namespace": watchNamespace}).Infoln("Starting informer")
if watchNamespace == "" {
factory = informers.NewSharedInformerFactory(k8sClient, 0)
} else {
factory = informers.NewSharedInformerFactoryWithOptions(k8sClient, 0, informers.WithNamespace(watchNamespace))
}
informer := factory.Core().V1().PersistentVolumeClaims().Informer()
var efsClient *EFSClient
var ec2Client *EBSClient
var fsxClient *FSxClient
var gcpClient GCPClient
var azureClient AzureClient
switch cloud {
case AWS:
efsClient, _ = newEFSClient()
ec2Client, _ = newEC2Client()
fsxClient, _ = newFSxClient()
case AZURE:
// see how to get the credentials with a service account and the subscription
azureClient, err = NewAzureClient()
if err != nil {
log.Fatalln("failed to create Azure client", err)
}
case GCP:
gcpClient, err = newGCPClient(context.Background())
if err != nil {
log.Fatalln("failed to create GCP client", err)
}
}
_, err = informer.AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
pvc := getPVC(obj)
log.WithFields(log.Fields{"namespace": pvc.GetNamespace(), "pvc": pvc.GetName()}).Infoln("New PVC Added to Store")
volumeID, tags, err := processPersistentVolumeClaim(pvc)
if err != nil || len(tags) == 0 {
return
}
switch cloud {
case AWS:
if !provisionedByAwsEfs(pvc) && !provisionedByAwsEbs(pvc) && !provisionedByAwsFsx(pvc) {
return
}
if provisionedByAwsEfs(pvc) {
efsClient.addEFSVolumeTags(volumeID, tags, *pvc.Spec.StorageClassName)
}
if provisionedByAwsEbs(pvc) {
ec2Client.addEBSVolumeTags(volumeID, tags, *pvc.Spec.StorageClassName)
}
if provisionedByAwsFsx(pvc) {
fsxClient.addFSxVolumeTags(volumeID, tags, *pvc.Spec.StorageClassName)
}
case AZURE:
if provisionedByAzureDisk(pvc) {
err = UpdateAzureVolumeTags(context.Background(), azureClient, volumeID, tags, []string{}, *pvc.Spec.StorageClassName)
if err != nil {
log.WithFields(log.Fields{"namespace": pvc.GetNamespace(), "pvc": pvc.GetName(), "error": err.Error()}).Error("failed to update persistent volume")
}
}
case GCP:
if !provisionedByGcpPD(pvc) {
return
}
addPDVolumeLabels(gcpClient, volumeID, tags, *pvc.Spec.StorageClassName)
}
},
UpdateFunc: func(old, new interface{}) {
newPVC := getPVC(new)
oldPVC := getPVC(old)
if newPVC.ResourceVersion == oldPVC.ResourceVersion {
log.WithFields(log.Fields{"namespace": newPVC.GetNamespace(), "pvc": newPVC.GetName()}).Debugln("ResourceVersion are the same")
return
}
if newPVC.Spec.VolumeName == "" {
log.WithFields(log.Fields{"namespace": newPVC.GetNamespace(), "pvc": newPVC.GetName()}).Debugln("PersistentVolume not created yet")
return
}
if newPVC.GetDeletionTimestamp() != nil {
log.WithFields(log.Fields{"namespace": newPVC.GetNamespace(), "pvc": newPVC.GetName()}).Debugln("PersistentVolumeClaim is being deleted")
return
}
log.WithFields(log.Fields{"namespace": newPVC.GetNamespace(), "pvc": newPVC.GetName()}).Infoln("Need to reconcile tags")
volumeID, tags, err := processPersistentVolumeClaim(newPVC)
if err != nil {
return
}
switch cloud {
case AWS:
if !provisionedByAwsEfs(newPVC) && !provisionedByAwsEbs(newPVC) && !provisionedByAwsFsx(newPVC) {
return
}
if len(tags) > 0 {
if provisionedByAwsEfs(newPVC) {
efsClient.addEFSVolumeTags(volumeID, tags, *newPVC.Spec.StorageClassName)
}
if provisionedByAwsEbs(newPVC) {
ec2Client.addEBSVolumeTags(volumeID, tags, *newPVC.Spec.StorageClassName)
}
if provisionedByAwsFsx(newPVC) {
fsxClient.addFSxVolumeTags(volumeID, tags, *newPVC.Spec.StorageClassName)
}
}
oldTags := buildTags(oldPVC)
var deletedTags []string
var deletedTagsPtr []*string
for k := range oldTags {
if _, ok := tags[k]; !ok {
deletedTags = append(deletedTags, k)
deletedTagsPtr = append(deletedTagsPtr, &k)
}
}
if len(deletedTags) > 0 {
if provisionedByAwsEfs(newPVC) {
efsClient.deleteEFSVolumeTags(volumeID, deletedTags, *oldPVC.Spec.StorageClassName)
}
if provisionedByAwsEbs(newPVC) {
ec2Client.deleteEBSVolumeTags(volumeID, deletedTags, *oldPVC.Spec.StorageClassName)
}
if provisionedByAwsFsx(newPVC) {
fsxClient.deleteFSxVolumeTags(volumeID, deletedTagsPtr, *oldPVC.Spec.StorageClassName)
}
}
case AZURE:
if !provisionedByAzureDisk(newPVC) {
var deletedTags []string
oldTags := buildTags(oldPVC)
for k := range oldTags {
if _, ok := tags[k]; !ok {
deletedTags = append(deletedTags, k)
}
}
err := UpdateAzureVolumeTags(context.Background(), azureClient, volumeID, tags, deletedTags, *newPVC.Spec.StorageClassName)
if err != nil {
log.WithFields(log.Fields{"namespace": newPVC.GetNamespace(), "pvc": newPVC.GetName()}).Error("failed to update persistent volume")
}
}
return
case GCP:
if !provisionedByGcpPD(newPVC) {
return
}
if len(tags) > 0 {
addPDVolumeLabels(gcpClient, volumeID, tags, *newPVC.Spec.StorageClassName)
}
oldTags := buildTags(oldPVC)
var deletedTags []string
for k := range oldTags {
if _, ok := tags[k]; !ok {
deletedTags = append(deletedTags, k)
}
}
if len(deletedTags) > 0 {
deletePDVolumeLabels(gcpClient, volumeID, deletedTags, *newPVC.Spec.StorageClassName)
}
}
},
})
if err != nil {
log.Errorln("Can't setup PVC informer! Check RBAC permissions")
return
}
informer.Run(ch)
}
func provisionedByAzureDisk(pvc *corev1.PersistentVolumeClaim) bool {
annotations := pvc.GetAnnotations()
if annotations == nil {
return false
}
provisionedBy, ok := getProvisionedBy(annotations)
if !ok {
log.WithFields(log.Fields{"namespace": pvc.GetNamespace(), "pvc": pvc.GetName()}).Debugln("no volume.kubernetes.io/storage-provisioner annotation")
return false
}
switch provisionedBy {
case AZURE_DISK_CSI:
log.WithFields(log.Fields{"namespace": pvc.GetNamespace(), "pvc": pvc.GetName()}).Debugln(AZURE_DISK_CSI + " volume")
return true
}
return false
}
func convertTagsToFSxTags(tags map[string]string) []*fsx.Tag {
convertedTags := []*fsx.Tag{}
for tagKey, tagValue := range tags {
convertedTags = append(convertedTags, &fsx.Tag{
Key: aws.String(tagKey),
Value: aws.String(tagValue),
})
}
return convertedTags
}
func parseAWSEBSVolumeID(kubernetesID string) string {
// Pulled from https://github.com/kubernetes/csi-translation-lib/blob/release-1.26/plugins/aws_ebs.go#L244
if !strings.HasPrefix(kubernetesID, "aws://") {
// Assume a bare aws volume id (vol-1234...)
return kubernetesID
}
url, err := url.Parse(kubernetesID)
if err != nil {
log.Errorln(fmt.Sprintf("Invalid disk name (%s): %v", kubernetesID, err))
return ""
}
if url.Scheme != "aws" {
log.Errorln(fmt.Sprintf("Invalid scheme for AWS volume (%s)", kubernetesID))
return ""
}
awsID := url.Path
awsID = strings.Trim(awsID, "/")
if !awsVolumeRegMatch.MatchString(awsID) {
log.Errorln(fmt.Sprintf("Invalid format for AWS volume (%s)", kubernetesID))
return ""
}
return awsID
}
func parseAWSEFSVolumeID(k8sVolumeID string) string {
re := regexp.MustCompile(regexpEFSVolumeID)
matches := re.FindSubmatch([]byte(k8sVolumeID))
if len(matches) <= 1 {
log.Errorln("Can't parse valid AWS EFS volumeID:", k8sVolumeID)
return ""
}
return string(matches[1])
}
func buildTags(pvc *corev1.PersistentVolumeClaim) map[string]string {
tags := map[string]string{}
customTags := map[string]string{}
var tagString string
var legacyTagString string
annotations := pvc.GetAnnotations()
// Skip if the annotation says to ignore this PVC
if _, ok := annotations[annotationPrefix+"/ignore"]; ok {
log.Debugln(annotationPrefix + "/ignore annotation is set")
promIgnoredTotal.With(prometheus.Labels{"storageclass": *pvc.Spec.StorageClassName}).Inc()
promIgnoredLegacyTotal.Inc()
return renderTagTemplates(pvc, tags)
}
// if the annotationPrefix has been changed, then we don't compare to the legacyAnnotationPrefix anymore
if annotationPrefix == defaultAnnotationPrefix {
if _, ok := annotations[legacyAnnotationPrefix+"/ignore"]; ok {
log.Debugln(legacyAnnotationPrefix + "/ignore annotation is set")
promIgnoredTotal.With(prometheus.Labels{"storageclass": *pvc.Spec.StorageClassName}).Inc()
promIgnoredLegacyTotal.Inc()
return renderTagTemplates(pvc, tags)
}
}
// Set the default tags
for k, v := range defaultTags {
if !isValidTagName(k) {
if !allowAllTags {
log.Warnln(k, "is a restricted tag. Skipping...")
promInvalidTagsTotal.With(prometheus.Labels{"storageclass": *pvc.Spec.StorageClassName}).Inc()
promInvalidTagsLegacyTotal.Inc()
continue
} else {
log.Warnln(k, "is a restricted tag but still allowing it to be set...")
}
}
tags[k] = v
}
if len(copyLabels) > 0 {
for k, v := range pvc.GetLabels() {
if copyLabels[0] == "*" || slices.Contains(copyLabels, k) {
if !isValidTagName(k) {
if !allowAllTags {
log.Warnln(k, "is a restricted tag. Skipping...")
promInvalidTagsTotal.With(prometheus.Labels{"storageclass": *pvc.Spec.StorageClassName}).Inc()
promInvalidTagsLegacyTotal.Inc()
continue
} else {
log.Warnln(k, "is a restricted tag but still allowing it to be set...")
}
}
tags[k] = v
}
}
}
var legacyOk bool
tagString, ok := annotations[annotationPrefix+"/tags"]
// if the annotationPrefix has been changed, then we don't compare to the legacyAnnotationPrefix anymore
if annotationPrefix == defaultAnnotationPrefix {
legacyTagString, legacyOk = annotations[legacyAnnotationPrefix+"/tags"]
} else {
legacyOk = false
legacyTagString = ""
}
if !ok && !legacyOk {
log.Debugln("Does not have " + annotationPrefix + "/tags or legacy " + legacyAnnotationPrefix + "/tags annotation")
return renderTagTemplates(pvc, tags)
} else if ok && legacyOk {
log.Warnln("Has both " + annotationPrefix + "/tags AND legacy " + legacyAnnotationPrefix + "/tags annotation. Using newer " + annotationPrefix + "/tags annotation")
} else if legacyOk && !ok {
tagString = legacyTagString
}
if tagFormat == "csv" {
customTags = parseCsv(tagString)
} else {
err := json.Unmarshal([]byte(tagString), &customTags)
if err != nil {
log.Errorln("Failed to Unmarshal JSON:", err)
}
}
for k, v := range customTags {
if !isValidTagName(k) {
if !allowAllTags {
log.Warnln(k, "is a restricted tag. Skipping...")
promInvalidTagsTotal.With(prometheus.Labels{"storageclass": *pvc.Spec.StorageClassName}).Inc()
promInvalidTagsLegacyTotal.Inc()
continue
} else {
log.Warnln(k, "is a restricted tag but still allowing it to be set...")
}
}
tags[k] = v
}
return renderTagTemplates(pvc, tags)
}
func renderTagTemplates(pvc *corev1.PersistentVolumeClaim, tags map[string]string) map[string]string {
tplData := TagTemplate{
Name: pvc.GetName(),
Namespace: pvc.GetNamespace(),
Labels: pvc.GetLabels(),
Annotations: pvc.GetAnnotations(),
}
for k, v := range tags {
tmpl, err := template.New("tag").Parse(v)
if err != nil {
continue
}
buf := new(bytes.Buffer)
err = tmpl.Execute(buf, tplData)
if err != nil {
continue
}
tags[k] = buf.String()
}
return tags
}
func isValidTagName(name string) bool {
if strings.HasPrefix(strings.ToLower(name), "kubernetes.io") {
return false
} else if strings.ToLower(name) == "name" {
return false
} else if strings.ToLower(name) == "kubernetescluster" {
return false
}
return true
}
func provisionedByAwsEfs(pvc *corev1.PersistentVolumeClaim) bool {
annotations := pvc.GetAnnotations()
if annotations == nil {
return false
}
provisionedBy, ok := getProvisionedBy(annotations)
if !ok {
log.WithFields(log.Fields{"namespace": pvc.GetNamespace(), "pvc": pvc.GetName()}).Debugln("no volume.kubernetes.io/storage-provisioner annotation")
return false
}
if provisionedBy == AWS_EFS_CSI {
log.WithFields(log.Fields{"namespace": pvc.GetNamespace(), "pvc": pvc.GetName()}).Debugln(AWS_EFS_CSI + " volume")
return true
}
return false
}
func provisionedByAwsEbs(pvc *corev1.PersistentVolumeClaim) bool {
annotations := pvc.GetAnnotations()
if annotations == nil {
return false
}
provisionedBy, ok := getProvisionedBy(annotations)
if !ok {
log.WithFields(log.Fields{"namespace": pvc.GetNamespace(), "pvc": pvc.GetName()}).Debugln("no volume.kubernetes.io/storage-provisioner annotation")
return false
}
switch provisionedBy {
case AWS_EBS_LEGACY:
log.WithFields(log.Fields{"namespace": pvc.GetNamespace(), "pvc": pvc.GetName()}).Debugln(AWS_EBS_LEGACY + " volume")
return true
case AWS_EBS_CSI:
log.WithFields(log.Fields{"namespace": pvc.GetNamespace(), "pvc": pvc.GetName()}).Debugln(AWS_EBS_CSI + " volume")
return true
}
return false
}
func provisionedByAwsFsx(pvc *corev1.PersistentVolumeClaim) bool {
annotations := pvc.GetAnnotations()
if annotations == nil {
return false
}
provisionedBy, ok := getProvisionedBy(annotations)
if !ok {
log.WithFields(log.Fields{"namespace": pvc.GetNamespace(), "pvc": pvc.GetName()}).Debugln("no volume.kubernetes.io/storage-provisioner annotation")
return false
}
if provisionedBy == AWS_FSX_CSI {
log.WithFields(log.Fields{"namespace": pvc.GetNamespace(), "pvc": pvc.GetName()}).Debugln(AWS_FSX_CSI + " volume")
return true
}
return false
}
func provisionedByGcpPD(pvc *corev1.PersistentVolumeClaim) bool {
annotations := pvc.GetAnnotations()
if annotations == nil {
return false
}
provisionedBy, ok := getProvisionedBy(annotations)
if !ok {
log.WithFields(log.Fields{"namespace": pvc.GetNamespace(), "pvc": pvc.GetName()}).Debugln("no volume.kubernetes.io/storage-provisioner annotation")
return false
}
switch provisionedBy {
case GCP_PD_LEGACY:
log.WithFields(log.Fields{"namespace": pvc.GetNamespace(), "pvc": pvc.GetName()}).Debugln(GCP_PD_LEGACY + " volume")
return true
case GCP_PD_CSI:
log.WithFields(log.Fields{"namespace": pvc.GetNamespace(), "pvc": pvc.GetName()}).Debugln(GCP_PD_CSI + " volume")
return true
}
return false
}
func processPersistentVolumeClaim(pvc *corev1.PersistentVolumeClaim) (string, map[string]string, error) {
tags := buildTags(pvc)
log.WithFields(log.Fields{"namespace": pvc.GetNamespace(), "pvc": pvc.GetName(), "tags": tags}).Debugln("PVC Tags")
pv, err := k8sClient.CoreV1().PersistentVolumes().Get(context.TODO(), pvc.Spec.VolumeName, metav1.GetOptions{})
if err != nil {
log.WithFields(log.Fields{"namespace": pvc.GetNamespace(), "pvc": pvc.GetName()}).Errorln("Get PV from kubernetes cluster error:", err)
return "", nil, err
}
var volumeID string
annotations := pvc.GetAnnotations()
if annotations == nil {
log.Errorf("cannot get PVC annotations")
return "", nil, errors.New("cannot get PVC annotations")
}
provisionedBy, ok := getProvisionedBy(annotations)
if !ok {
log.Errorf("cannot get volume.kubernetes.io/storage-provisioner annotation")
return "", nil, errors.New("cannot get volume.kubernetes.io/storage-provisioner annotation")
}
switch provisionedBy {
case AWS_EBS_CSI:
if pv.Spec.CSI != nil {
volumeID = pv.Spec.CSI.VolumeHandle
} else {
volumeID = parseAWSEBSVolumeID(pv.Spec.AWSElasticBlockStore.VolumeID)
}
case AWS_EFS_CSI:
if pv.Spec.CSI != nil {
volumeID = parseAWSEFSVolumeID(pv.Spec.CSI.VolumeHandle)
}
case AWS_EBS_LEGACY:
volumeID = parseAWSEBSVolumeID(pv.Spec.AWSElasticBlockStore.VolumeID)
case AWS_FSX_CSI:
volumeID = pv.Spec.CSI.VolumeHandle
case GCP_PD_LEGACY:
volumeID = pv.Spec.GCEPersistentDisk.PDName
case AZURE_DISK_CSI:
volumeID = pv.Spec.CSI.VolumeHandle
case GCP_PD_CSI:
volumeID = pv.Spec.CSI.VolumeHandle
}
log.WithFields(log.Fields{"namespace": pvc.GetNamespace(), "pvc": pvc.GetName(), "volumeID": volumeID}).Debugln("parsed volumeID:", volumeID)
if len(volumeID) == 0 {
log.Errorf("Cannot parse VolumeID")
return "", nil, errors.New("cannot parse VolumeID")
}
return volumeID, tags, nil
}
func getCurrentNamespace() string {
// Fall back to the namespace associated with the service account token, if available
if data, err := os.ReadFile("/var/run/secrets/kubernetes.io/serviceaccount/namespace"); err == nil {
if ns := strings.TrimSpace(string(data)); len(ns) > 0 {
return ns
}
}
return ""
}
func getProvisionedBy(annotations map[string]string) (string, bool) {
var provisionedBy string
provisionedBy, ok := annotations["volume.kubernetes.io/storage-provisioner"]
if !ok {
provisionedBy, ok = annotations["volume.beta.kubernetes.io/storage-provisioner"]
}
return provisionedBy, ok
}
func getPVC(obj interface{}) *corev1.PersistentVolumeClaim {
pvc := obj.(*corev1.PersistentVolumeClaim)
// https://kubernetes.io/docs/reference/labels-annotations-taints/#volume-beta-kubernetes-io-storage-class-deprecated
// The "volume.beta.kubernetes.io/storage-class" annotation is deprecated but can be used
// to specify the name of StorageClass in PVC. When both storageClassName attribute and
// volume.beta.kubernetes.io/storage-class annotation are specified, the annotation
// volume.beta.kubernetes.io/storage-class takes precedence over the storageClassName attribute.
storageClassName, ok := pvc.GetAnnotations()["volume.beta.kubernetes.io/storage-class"]
if ok {
pvc.Spec.StorageClassName = &storageClassName
}
return pvc
}