forked from mtougeron/k8s-pvc-tagger
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgcp.go
211 lines (185 loc) · 5.95 KB
/
gcp.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
package main
import (
"context"
"fmt"
"maps"
"strings"
"time"
"github.com/prometheus/client_golang/prometheus"
log "github.com/sirupsen/logrus"
"google.golang.org/api/compute/v1"
"k8s.io/apimachinery/pkg/util/wait"
)
type GCPClient interface {
GetDisk(project, zone, name string) (*compute.Disk, error)
SetDiskLabels(project, zone, name string, labelReq *compute.ZoneSetLabelsRequest) (*compute.Operation, error)
GetGCEOp(project, zone, name string) (*compute.Operation, error)
}
type gcpClient struct {
gce *compute.Service
}
func newGCPClient(ctx context.Context) (GCPClient, error) {
client, err := compute.NewService(ctx)
if err != nil {
return nil, err
}
return &gcpClient{gce: client}, nil
}
func (c *gcpClient) GetDisk(project, zone, name string) (*compute.Disk, error) {
return c.gce.Disks.Get(project, zone, name).Do()
}
func (c *gcpClient) SetDiskLabels(project, zone, name string, labelReq *compute.ZoneSetLabelsRequest) (*compute.Operation, error) {
return c.gce.Disks.SetLabels(project, zone, name, labelReq).Do()
}
func (c *gcpClient) GetGCEOp(project, zone, name string) (*compute.Operation, error) {
return c.gce.ZoneOperations.Get(project, zone, name).Do()
}
func addPDVolumeLabels(c GCPClient, volumeID string, labels map[string]string, storageclass string) {
sanitizedLabels := sanitizeLabelsForGCP(labels)
log.Debugf("labels to add to PD volume: %s: %s", volumeID, sanitizedLabels)
project, location, name, err := parseVolumeID(volumeID)
if err != nil {
log.Error(err)
return
}
disk, err := c.GetDisk(project, location, name)
if err != nil {
log.Error(err)
return
}
// merge existing disk labels with new labels:
updatedLabels := make(map[string]string)
if disk.Labels != nil {
updatedLabels = maps.Clone(disk.Labels)
}
maps.Copy(updatedLabels, sanitizedLabels)
if maps.Equal(disk.Labels, updatedLabels) {
log.Debug("labels already set on PD")
return
}
req := &compute.ZoneSetLabelsRequest{
Labels: updatedLabels,
LabelFingerprint: disk.LabelFingerprint,
}
op, err := c.SetDiskLabels(project, location, name, req)
if err != nil {
log.Errorf("failed to set labels on PD: %s", err)
promActionsTotal.With(prometheus.Labels{"status": "error", "storageclass": storageclass}).Inc()
return
}
waitForCompletion := func(_ context.Context) (bool, error) {
resp, err := c.GetGCEOp(project, location, op.Name)
if err != nil {
return false, fmt.Errorf("failed to set labels on PD %s: %s", disk.Name, err)
}
return resp.Status == "DONE", nil
}
if err := wait.PollUntilContextTimeout(context.TODO(),
time.Second,
time.Minute,
false,
waitForCompletion); err != nil {
log.Errorf("set label operation failed: %s", err)
promActionsTotal.With(prometheus.Labels{"status": "error", "storageclass": storageclass}).Inc()
return
}
log.Debug("successfully set labels on PD")
promActionsTotal.With(prometheus.Labels{"status": "success", "storageclass": storageclass}).Inc()
}
func deletePDVolumeLabels(c GCPClient, volumeID string, keys []string, storageclass string) {
if len(keys) == 0 {
return
}
sanitizedKeys := sanitizeKeysForGCP(keys)
log.Debugf("labels to delete from PD volume: %s: %s", volumeID, sanitizedKeys)
project, location, name, err := parseVolumeID(volumeID)
if err != nil {
log.Error(err)
return
}
disk, err := c.GetDisk(project, location, name)
if err != nil {
log.Error(err)
return
}
// if disk.Labels is nil, then there are no labels to delete
if disk.Labels == nil {
return
}
updatedLabels := maps.Clone(disk.Labels)
for _, k := range sanitizedKeys {
delete(updatedLabels, k)
}
if maps.Equal(disk.Labels, updatedLabels) {
return
}
req := &compute.ZoneSetLabelsRequest{
Labels: updatedLabels,
LabelFingerprint: disk.LabelFingerprint,
}
op, err := c.SetDiskLabels(project, location, name, req)
if err != nil {
log.Errorf("failed to delete labels from PD: %s", err)
promActionsTotal.With(prometheus.Labels{"status": "error", "storageclass": storageclass}).Inc()
return
}
waitForCompletion := func(_ context.Context) (bool, error) {
resp, err := c.GetGCEOp(project, location, op.Name)
if err != nil {
return false, fmt.Errorf("failed retrieve status of label update operation: %s", err)
}
return resp.Status == "DONE", nil
}
if err := wait.PollUntilContextTimeout(context.TODO(),
time.Second,
time.Minute,
false,
waitForCompletion); err != nil {
promActionsTotal.With(prometheus.Labels{"status": "error", "storageclass": storageclass}).Inc()
log.Errorf("delete label operation failed: %s", err)
return
}
log.Debug("successfully deleted labels from PD")
promActionsTotal.With(prometheus.Labels{"status": "success", "storageclass": storageclass}).Inc()
}
func parseVolumeID(id string) (string, string, string, error) {
parts := strings.Split(id, "/")
if len(parts) < 5 {
return "", "", "", fmt.Errorf("invalid volume handle format")
}
project := parts[1]
location := parts[3]
name := parts[5]
return project, location, name, nil
}
func sanitizeLabelsForGCP(labels map[string]string) map[string]string {
newLabels := make(map[string]string, len(labels))
for k, v := range labels {
newLabels[sanitizeKeyForGCP(k)] = sanitizeValueForGCP(v)
}
return newLabels
}
func sanitizeKeysForGCP(keys []string) []string {
newKeys := make([]string, len(keys))
for i, k := range keys {
newKeys[i] = sanitizeKeyForGCP(k)
}
return newKeys
}
// sanitizeKeyForGCP sanitizes a Kubernetes label key to fit GCP's label key constraints
func sanitizeKeyForGCP(key string) string {
key = strings.ToLower(key)
key = strings.NewReplacer("/", "_", ".", "-").Replace(key) // Replace disallowed characters
key = strings.TrimRight(key, "-_") // Ensure it does not end with '-' or '_'
if len(key) > 63 {
key = key[:63]
}
return key
}
// sanitizeKeyForGCP sanitizes a Kubernetes label value to fit GCP's label value constraints
func sanitizeValueForGCP(value string) string {
if len(value) > 63 {
value = value[:63]
}
return value
}