-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontroller.go
More file actions
497 lines (428 loc) · 14.1 KB
/
Copy pathcontroller.go
File metadata and controls
497 lines (428 loc) · 14.1 KB
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
package main
import (
"context"
"fmt"
"maps"
"path"
"strings"
"github.com/aws/aws-sdk-go-v2/aws"
awsconfig "github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/ec2"
"github.com/aws/aws-sdk-go-v2/service/ec2/types"
"github.com/go-logr/logr"
gce "google.golang.org/api/compute/v1"
corev1 "k8s.io/api/core/v1"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/event"
"sigs.k8s.io/controller-runtime/pkg/predicate"
)
type NodeLabelController struct {
client.Client
Logger logr.Logger
EC2Client ec2Client
GCEClient gceClient
AzureComputeClient azureComputeClient
// Labels is a list of label keys to sync from the node to the cloud provider
Labels []string
// Annotations is a list of annotation keys to sync from the node to the cloud provider
Annotations []string
// Cloud is the cloud provider (aws, gcp, or azure)
Cloud string
}
func (r *NodeLabelController) SetupCloudProvider(ctx context.Context) error {
switch r.Cloud {
case "aws":
cfg, err := awsconfig.LoadDefaultConfig(ctx)
if err != nil {
return fmt.Errorf("unable to load AWS config: %v", err)
}
r.EC2Client = ec2.NewFromConfig(cfg)
case "gcp":
c, err := gce.NewService(ctx)
if err != nil {
return fmt.Errorf("unable to create GCP client: %v", err)
}
r.GCEClient = newGCEComputeClient(c)
case "azure":
c, err := newAzureComputeClient(ctx)
if err != nil {
return fmt.Errorf("unable to create Azure compute client: %v", err)
}
r.AzureComputeClient = c
default:
return fmt.Errorf("unsupported cloud provider: %q", r.Cloud)
}
return nil
}
func (r *NodeLabelController) SetupWithManager(mgr ctrl.Manager) error {
// to reduce the number of API calls to AWS and GCP, filter out node events that
// do not involve changes to the monitored label or annotation sets.
changePredicate := predicate.Funcs{
UpdateFunc: func(e event.UpdateEvent) bool {
oldNode, ok := e.ObjectOld.(*corev1.Node)
if !ok {
return false
}
newNode, ok := e.ObjectNew.(*corev1.Node)
if !ok {
return false
}
// Process if any monitored label/annotation changed
if shouldProcessNodeUpdate(oldNode, newNode, r.Labels, r.Annotations) {
r.Logger.V(1).Info("Update event: label changed", "node", newNode.Name)
return true
}
// During periodic resync, controller-runtime emits Update events where
// oldObj and newObj are identical (same ResourceVersion). Allow these
// through for nodes with monitored labels to catch any missed events.
// But filter out real updates (different ResourceVersion) where only
// non-label fields changed (e.g., heartbeat, status updates).
if oldNode.ResourceVersion == newNode.ResourceVersion {
if shouldProcessNodeCreate(newNode, r.Labels, r.Annotations) {
r.Logger.V(1).Info("Update event: periodic resync", "node", newNode.Name)
return true
}
}
return false
},
CreateFunc: func(e event.CreateEvent) bool {
node, ok := e.Object.(*corev1.Node)
if !ok {
return false
}
shouldProcess := shouldProcessNodeCreate(node, r.Labels, r.Annotations)
r.Logger.V(1).Info("Create event",
"node", node.Name,
"shouldProcess", shouldProcess,
"labels", node.Labels,
"monitoredLabels", r.Labels,
)
return shouldProcess
},
DeleteFunc: func(e event.DeleteEvent) bool {
return false
},
GenericFunc: func(e event.GenericEvent) bool {
return false
},
}
return ctrl.NewControllerManagedBy(mgr).
For(&corev1.Node{}).
WithEventFilter(changePredicate).
Complete(r)
}
// shouldProcessNodeUpdate determines if a node update event should trigger reconciliation
// based on whether any monitored labels or annotations have changed.
func shouldProcessNodeUpdate(oldNode, newNode *corev1.Node, monitoredLabels, monitoredAnnotations []string) bool {
if oldNode == nil || newNode == nil {
return false
}
// Check if any monitored labels changed
for _, k := range monitoredLabels {
newVal, newExists := "", false
oldVal, oldExists := "", false
if newNode.Labels != nil {
newVal, newExists = newNode.Labels[k]
}
if oldNode.Labels != nil {
oldVal, oldExists = oldNode.Labels[k]
}
if newExists != oldExists || (newExists && newVal != oldVal) {
return true
}
}
// Check if any monitored annotations changed
for _, k := range monitoredAnnotations {
newVal, newExists := "", false
oldVal, oldExists := "", false
if newNode.Annotations != nil {
newVal, newExists = newNode.Annotations[k]
}
if oldNode.Annotations != nil {
oldVal, oldExists = oldNode.Annotations[k]
}
if newExists != oldExists || (newExists && newVal != oldVal) {
return true
}
}
return false
}
// shouldProcessNodeCreate determines if a newly created node should trigger reconciliation
// based on whether it has any of the monitored labels or annotations.
func shouldProcessNodeCreate(node *corev1.Node, monitoredLabels, monitoredAnnotations []string) bool {
if node == nil {
return false
}
// Check if node has any monitored labels
if node.Labels != nil {
for _, k := range monitoredLabels {
if _, ok := node.Labels[k]; ok {
return true
}
}
}
// Check if node has any monitored annotations
if node.Annotations != nil {
for _, k := range monitoredAnnotations {
if _, ok := node.Annotations[k]; ok {
return true
}
}
}
return false
}
func (r *NodeLabelController) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
logger := r.Logger.WithValues("node", req.NamespacedName)
var node corev1.Node
if err := r.Get(ctx, req.NamespacedName, &node); err != nil {
logger.Error(err, "unable to fetch Node")
return ctrl.Result{}, client.IgnoreNotFound(err)
}
providerID := node.Spec.ProviderID
if providerID == "" {
logger.Info("Node is missing a spec.ProviderID", "node", node.Name)
return ctrl.Result{}, nil
}
// Create a map for tags to sync with the cloud provider
tagsToSync := make(map[string]string)
var notFoundLabels, notFoundAnnotations []string
// First collect labels (may be overwritten by annotations with same key)
for _, k := range r.Labels {
if value, exists := node.Labels[k]; exists {
tagsToSync[k] = value
} else {
notFoundLabels = append(notFoundLabels, k)
}
}
// Then collect annotations (will overwrite labels with same key)
for _, k := range r.Annotations {
if value, exists := node.Annotations[k]; exists {
tagsToSync[k] = value
} else {
notFoundAnnotations = append(notFoundAnnotations, k)
}
}
logger.V(1).Info("Collected tags to sync",
"tagsToSync", tagsToSync,
"notFoundLabels", notFoundLabels,
"notFoundAnnotations", notFoundAnnotations,
)
var err error
switch r.Cloud {
case "aws":
err = r.syncAWSTags(ctx, providerID, tagsToSync)
case "gcp":
err = r.syncGCPLabels(ctx, providerID, tagsToSync)
case "azure":
err = r.syncAzureTags(ctx, providerID, tagsToSync)
}
if err != nil {
logger.Error(err, "failed to sync tags", "providerID", providerID)
return ctrl.Result{}, err
}
logger.Info("Successfully synced tags to cloud provider", "providerID", providerID, "tags", tagsToSync)
return ctrl.Result{}, nil
}
func (r *NodeLabelController) syncAWSTags(ctx context.Context, providerID string, desiredTags map[string]string) error {
instanceID := path.Base(providerID)
if instanceID == "" {
return fmt.Errorf("invalid AWS provider ID format: %q", providerID)
}
result, err := r.EC2Client.DescribeTags(ctx, &ec2.DescribeTagsInput{
Filters: []types.Filter{
{
Name: aws.String("resource-id"),
Values: []string{instanceID},
},
},
})
if err != nil {
return fmt.Errorf("failed to fetch node's current AWS tags: %v", err)
}
// Create a set of all monitored keys (both labels and annotations)
monitoredKeys := make(map[string]bool)
for _, k := range r.Labels {
monitoredKeys[k] = true
}
for _, k := range r.Annotations {
monitoredKeys[k] = true
}
currentTags := make(map[string]string)
for _, tag := range result.Tags {
key := aws.ToString(tag.Key)
if key != "" && monitoredKeys[key] {
currentTags[key] = aws.ToString(tag.Value)
}
}
toAdd := make([]types.Tag, 0)
toDelete := make([]types.Tag, 0)
// find tags to add or update
for k, v := range desiredTags {
if curr, exists := currentTags[k]; !exists || curr != v {
toAdd = append(toAdd, types.Tag{
Key: aws.String(k),
Value: aws.String(v),
})
}
}
// find monitored tags to remove
for k := range currentTags {
if monitoredKeys[k] {
if _, exists := desiredTags[k]; !exists {
toDelete = append(toDelete, types.Tag{
Key: aws.String(k),
})
}
}
}
if len(toAdd) > 0 {
_, err := r.EC2Client.CreateTags(ctx, &ec2.CreateTagsInput{
Resources: []string{instanceID},
Tags: toAdd,
})
if err != nil {
return fmt.Errorf("failed to create AWS tags: %v", err)
}
}
if len(toDelete) > 0 {
_, err := r.EC2Client.DeleteTags(ctx, &ec2.DeleteTagsInput{
Resources: []string{instanceID},
Tags: toDelete,
})
if err != nil {
return fmt.Errorf("failed to delete AWS tags: %v", err)
}
}
return nil
}
func (r *NodeLabelController) syncGCPLabels(ctx context.Context, providerID string, desiredTags map[string]string) error {
project, zone, name, err := parseGCPProviderID(providerID)
if err != nil {
return fmt.Errorf("failed to parse GCP provider ID: %v", err)
}
instance, err := r.GCEClient.GetInstance(ctx, project, zone, name)
if err != nil {
return fmt.Errorf("failed to get GCP instance: %v", err)
}
newLabels := maps.Clone(instance.Labels)
if newLabels == nil {
newLabels = make(map[string]string)
}
// Create a set of all monitored keys (both labels and annotations)
allMonitoredKeys := make([]string, 0, len(r.Labels)+len(r.Annotations))
allMonitoredKeys = append(allMonitoredKeys, r.Labels...)
allMonitoredKeys = append(allMonitoredKeys, r.Annotations...)
// create a set of sanitized monitored keys for easy lookup
monitoredKeys := make(map[string]string) // sanitized -> original
for _, k := range allMonitoredKeys {
monitoredKeys[sanitizeKeyForGCP(k)] = k
}
// remove any existing monitored labels that are no longer desired
for k := range newLabels {
if orig, isMonitored := monitoredKeys[k]; isMonitored {
if _, exists := desiredTags[orig]; !exists {
delete(newLabels, k)
}
}
}
// add or update desired tags
for k, v := range desiredTags {
newLabels[sanitizeKeyForGCP(k)] = sanitizeValueForGCP(v)
}
// skip update if no changes
if maps.Equal(instance.Labels, newLabels) {
return nil
}
err = r.GCEClient.SetLabels(ctx, project, zone, name, &gce.InstancesSetLabelsRequest{
Labels: newLabels,
LabelFingerprint: instance.LabelFingerprint,
})
if err != nil {
return fmt.Errorf("failed to update GCP instance labels: %v", err)
}
return nil
}
func parseGCPProviderID(providerID string) (string, string, string, error) {
if !strings.HasPrefix(providerID, "gce://") {
return "", "", "", fmt.Errorf("providerID missing \"gce://\" prefix, this might not be a GCE node? %q", providerID)
}
trimmed := strings.TrimPrefix(providerID, "gce://")
parts := strings.Split(trimmed, "/")
if len(parts) < 3 {
return "", "", "", fmt.Errorf("invalid GCP provider ID format: %q", providerID)
}
return parts[0], parts[1], parts[2], 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
}
// 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
}
// syncAzureTags syncs the desired tags to the Azure VM (or VMSS VM instance)
// backing the node. It mirrors syncAWSTags/syncGCPLabels: parse the provider
// ID, fetch the current tags, compute the diff against the monitored
// label/annotation keys, and replace the VM's tag set in one call. Azure tag
// keys disallow several characters that Kubernetes label keys commonly use
// (notably "/"), so monitored keys are sanitized; unmanaged tags are preserved
// verbatim.
func (r *NodeLabelController) syncAzureTags(ctx context.Context, providerID string, desiredTags map[string]string) error {
res, err := parseAzureProviderID(providerID)
if err != nil {
return fmt.Errorf("failed to parse Azure provider ID: %v", err)
}
currentTags, err := r.AzureComputeClient.GetInstanceTags(ctx, res)
if err != nil {
return fmt.Errorf("failed to fetch node's current Azure tags: %v", err)
}
// Create a set of all monitored keys (both labels and annotations), mapped
// from their sanitized form back to the original key.
allMonitoredKeys := make([]string, 0, len(r.Labels)+len(r.Annotations))
allMonitoredKeys = append(allMonitoredKeys, r.Labels...)
allMonitoredKeys = append(allMonitoredKeys, r.Annotations...)
monitoredKeys := make(map[string]string) // sanitized -> original
for _, k := range allMonitoredKeys {
monitoredKeys[sanitizeKeyForAzure(k)] = k
}
// Start from the current tags so unmanaged tags are preserved, then drop
// monitored tags that are no longer desired and add/update desired ones.
merged := make(map[string]string, len(currentTags)+len(desiredTags))
for k, v := range currentTags {
merged[k] = v
}
for sanKey, orig := range monitoredKeys {
if _, exists := desiredTags[orig]; !exists {
delete(merged, sanKey)
}
}
for k, v := range desiredTags {
merged[sanitizeKeyForAzure(k)] = sanitizeValueForAzure(v)
}
// Skip the round-trip if nothing changed.
if maps.Equal(currentTags, merged) {
return nil
}
if err := r.AzureComputeClient.SetInstanceTags(ctx, res, merged); err != nil {
return fmt.Errorf("failed to update Azure VM tags: %v", err)
}
return nil
}