-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
195 lines (161 loc) · 4.82 KB
/
main.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
package main
import (
"context"
"flag"
"fmt"
"github.com/spf13/afero"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/kubernetes"
"os"
"reflect"
"sigs.k8s.io/controller-runtime/pkg/client/config"
"sigs.k8s.io/controller-runtime/pkg/controller"
"sigs.k8s.io/controller-runtime/pkg/event"
"sigs.k8s.io/controller-runtime/pkg/handler"
logf "sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/controller-runtime/pkg/log/zap"
"sigs.k8s.io/controller-runtime/pkg/manager"
"sigs.k8s.io/controller-runtime/pkg/predicate"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"sigs.k8s.io/controller-runtime/pkg/runtime/signals"
"sigs.k8s.io/controller-runtime/pkg/source"
"sync"
)
const (
controllerName = "k8s-auto-labeller"
)
var (
appfs afero.Fs
fsutil *afero.Afero
labelDir = "labels"
log = logf.Log.WithName(controllerName)
// possibleLabelMap contains the global state of all possible labels gleaned from the label dirs. It is dynamically
// rebuilt when the filesystem watchers observe changes to the label files. It is implemented in the form of
// label: [dependendent labels...]
possibleLabelMap map[string][]string
possibleLabelLock sync.RWMutex
// nodeLabelMap contains the global node label state reflecting set (true) and recently cleared (false) labels
// for the reconciler to act on, in the form of node name -> label -> true/false.
nodeLabelMap *NodeLabelMap
)
func init() {
appfs = afero.NewOsFs()
fsutil = &afero.Afero{Fs: appfs}
}
func main() {
flag.StringVar(&labelDir, "label-dir", labelDir, "Label directory to monitor")
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "Node Auto Labeller for Kubernetes\n")
fmt.Fprintf(os.Stderr, "Usage: %s [flags]\n", os.Args[0])
flag.PrintDefaults()
}
flag.Parse()
logf.SetLogger(zap.New(zap.UseDevMode(false)))
entryLog := log.WithName("entrypoint")
labelWatcher, err := NewLabelWatcher(labelDir)
if err != nil {
entryLog.Error(err, "failed to initialize label watcher")
os.Exit(1)
}
defer labelWatcher.Close()
nodeLabelMap = NewNodeLabelMap()
possibleLabelMap, err = buildPossibleLabelMap()
if err != nil {
entryLog.Error(err, "unable to build initial label map")
os.Exit(1)
}
cfg := config.GetConfigOrDie()
clientset := kubernetes.NewForConfigOrDie(cfg)
mgr, err := manager.New(cfg, manager.Options{})
if err != nil {
entryLog.Error(err, "unable to instantiate manager")
os.Exit(1)
}
c, err := controller.New(controllerName, mgr, controller.Options{
Reconciler: &reconcileNodeLabels{
client: mgr.GetClient(),
log: log.WithName("reconciler"),
},
})
if err != nil {
entryLog.Error(err, "unable to set up individual controller")
os.Exit(1)
}
pred := predicate.Funcs{
CreateFunc: func(e event.CreateEvent) bool {
name := e.Meta.GetName()
nodeLabels := e.Meta.GetLabels()
nodeLabelMap.Lock()
defer nodeLabelMap.Unlock()
nodeLabelMap.Add(name)
nodeLabelMap.SetPossible(name, nodeLabels)
return nodeLabelMap.Valid(name)
},
DeleteFunc: func(e event.DeleteEvent) bool {
nodeLabelMap.Lock()
nodeLabelMap.Remove(e.Meta.GetName())
nodeLabelMap.Unlock()
return false
},
UpdateFunc: func(e event.UpdateEvent) bool {
oldName := e.MetaOld.GetName()
newName := e.MetaNew.GetName()
oldLabels := e.MetaOld.GetLabels()
newLabels := e.MetaNew.GetLabels()
eq := reflect.DeepEqual(oldLabels, newLabels)
if !eq {
nodeLabelMap.Lock()
nodeLabelMap.ResetLabels(oldName)
nodeLabelMap.Add(newName)
nodeLabelMap.SetPossible(newName, newLabels)
nodeLabelMap.Unlock()
return true
}
return false
},
GenericFunc: func(e event.GenericEvent) bool {
return false
},
}
// Watch Nodes and enqueue Nodes object key
if err := c.Watch(&source.Kind{Type: &corev1.Node{}}, &handler.EnqueueRequestForObject{}, &pred); err != nil {
entryLog.Error(err, "unable to watch Node")
os.Exit(1)
}
done := make(chan bool)
refresh := make(chan bool)
go func() {
entryLog.Info("starting manager")
if err := mgr.Start(signals.SetupSignalHandler()); err != nil {
entryLog.Error(err, "unable to run manager")
os.Exit(1)
}
}()
go labelWatcher.Watch(done, refresh)
for {
select {
case <-refresh:
entryLog.Info("Refreshing node labels")
nodeList, _ := clientset.CoreV1().Nodes().List(context.TODO(), metav1.ListOptions{})
for _, node := range nodeList.Items {
nodeLabelMap.Lock()
nodeLabelMap.ResetLabels(node.Name)
nodeLabelMap.Add(node.Name)
nodeLabelMap.SetPossible(node.Name, node.Labels)
nodeLabelMap.Unlock()
// Kick-off node reconciliation
c.Reconcile(reconcile.Request{
NamespacedName: types.NamespacedName{
Name: node.Name,
Namespace: node.Namespace,
},
})
}
case <-done:
entryLog.Info("Exiting..")
return
}
}
}