-
Notifications
You must be signed in to change notification settings - Fork 0
/
labelmaker_controller.go
148 lines (118 loc) · 3.91 KB
/
labelmaker_controller.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
/*
Copyright 2020 Alexander Vollschwitz
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 labelmaker
import (
"context"
"encoding/json"
"fmt"
"os"
"github.com/xelalexv/label-maker/pkg/controller/util"
core_v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/util/retry"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller"
"sigs.k8s.io/controller-runtime/pkg/handler"
"sigs.k8s.io/controller-runtime/pkg/manager"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"sigs.k8s.io/controller-runtime/pkg/source"
)
var controllerLog = util.NewControllerLogger("labelmaker.controller")
func Add(mgr manager.Manager) error {
return add(mgr, newReconciler(mgr))
}
func newReconciler(mgr manager.Manager) reconcile.Reconciler {
ret := &LabelMaker{client: mgr.GetClient()}
label, set := getRoleLabel()
if set {
controllerLog.Info("using explicitly set role label", "label", label)
} else {
controllerLog.Info("using default role label", "label", label)
}
ret.roleLabel = label
return ret
}
func add(mgr manager.Manager, r reconcile.Reconciler) error {
c, err := controller.New("labelmaker-controller", mgr,
controller.Options{Reconciler: r})
if err != nil {
return err
}
// Watch for changes to primary resource Node
if err := c.Watch(&source.Kind{Type: &core_v1.Node{}},
&handler.EnqueueRequestForObject{}); err != nil {
return err
}
return nil
}
var _ reconcile.Reconciler = &LabelMaker{}
type LabelMaker struct {
// This client, initialized using mgr.Client() above, is a split client
// that reads objects from the cache and writes to the API server
client client.Client
roleLabel string
}
func (lm *LabelMaker) Reconcile(req reconcile.Request) (reconcile.Result, error) {
log := controllerLog.LoggerForRequest("node", req)
res := reconcile.Result{}
log.Debug("reconciling")
node := &core_v1.Node{}
if err := lm.client.Get(
context.TODO(), req.NamespacedName, node); err != nil {
if errors.IsNotFound(err) {
return res, log.Info("node resource not found, ignoring")
}
return res, log.Error(err, "failed to get node")
}
return lm.handle(node)
}
func (lm *LabelMaker) handle(node *core_v1.Node) (reconcile.Result, error) {
log := controllerLog.LoggerForNode(node)
res := reconcile.Result{}
labels := node.GetLabels()
role, ok := labels[lm.roleLabel]
if !ok {
return res, log.Debug("no role label present")
}
// Check if the desired label already exists
if _, exists := labels[fmt.Sprintf("node-role.kubernetes.io/%s", role)]; exists {
return res, log.Debug("node-role already set")
}
log.Info("setting node-role", "role", role)
labels[fmt.Sprintf("node-role.kubernetes.io/%s", role)] = ""
// Server-side apply using strategic merge patch
err := retry.RetryOnConflict(retry.DefaultRetry, func() error {
nodeCopy := node.DeepCopy()
nodeCopy.SetLabels(labels)
// Marshal the modified nodeCopy to JSON for patching
patchBytes, err := json.Marshal(nodeCopy)
if err != nil {
return err
}
// Use client.Patch for types.StrategicMergePatchType
err = lm.client.Patch(context.TODO(), node, client.RawPatch(types.StrategicMergePatchType, patchBytes))
return err
})
if err != nil {
return res, log.Error(err, "failed to update labels")
}
return res, nil
}
func getRoleLabel() (string, bool) {
label := os.Getenv("ROLE_LABEL")
if label == "" {
return "node.kubernetes.io/role", false
}
return label, true
}