forked from mtougeron/k8s-pvc-tagger
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkubernetes.go
462 lines (408 loc) · 14.5 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
// 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"
"io/ioutil"
"net/url"
"os"
"path/filepath"
"regexp"
"strings"
"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+)$`
)
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 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()
efsClient, _ := newEFSClient()
ec2Client, _ := newEC2Client()
_, err := informer.AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
pvc := getPVC(obj)
if !provisionedByAwsEfs(pvc) && !provisionedByAwsEbs(pvc) {
return
}
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
}
if provisionedByAwsEfs(pvc) {
efsClient.addEFSVolumeTags(volumeID, tags, *pvc.Spec.StorageClassName)
}
if provisionedByAwsEbs(pvc) {
ec2Client.addEBSVolumeTags(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 !provisionedByAwsEfs(newPVC) && !provisionedByAwsEbs(newPVC) {
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
}
if len(tags) > 0 {
if provisionedByAwsEfs(newPVC) {
efsClient.addEFSVolumeTags(volumeID, tags, *newPVC.Spec.StorageClassName)
}
if provisionedByAwsEbs(newPVC) {
ec2Client.addEBSVolumeTags(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 {
if provisionedByAwsEfs(newPVC) {
efsClient.deleteEFSVolumeTags(volumeID, deletedTags, *oldPVC.Spec.StorageClassName)
}
if provisionedByAwsEbs(newPVC) {
ec2Client.deleteEBSVolumeTags(volumeID, deletedTags, *oldPVC.Spec.StorageClassName)
}
}
},
})
if err != nil {
log.Errorln("Can't setup PVC informer! Check RBAC permissions")
return
}
informer.Run(ch)
}
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
}
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 == "efs.csi.aws.com" {
log.WithFields(log.Fields{"namespace": pvc.GetNamespace(), "pvc": pvc.GetName()}).Debugln("efs.csi.aws.com 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
}
if provisionedBy == "kubernetes.io/aws-ebs" {
log.WithFields(log.Fields{"namespace": pvc.GetNamespace(), "pvc": pvc.GetName()}).Debugln("kubernetes.io/aws-ebs volume")
return true
} else if provisionedBy == "ebs.csi.aws.com" {
log.WithFields(log.Fields{"namespace": pvc.GetNamespace(), "pvc": pvc.GetName()}).Debugln("ebs.csi.aws.com 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")
}
if provisionedBy == "ebs.csi.aws.com" {
if pv.Spec.CSI != nil {
volumeID = pv.Spec.CSI.VolumeHandle
} else {
volumeID = parseAWSEBSVolumeID(pv.Spec.AWSElasticBlockStore.VolumeID)
}
} else if provisionedBy == "efs.csi.aws.com" {
if pv.Spec.CSI != nil {
volumeID = parseAWSEFSVolumeID(pv.Spec.CSI.VolumeHandle)
}
} else if provisionedBy == "kubernetes.io/aws-ebs" {
volumeID = parseAWSEBSVolumeID(pv.Spec.AWSElasticBlockStore.VolumeID)
}
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 := ioutil.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
}