-
Notifications
You must be signed in to change notification settings - Fork 110
/
handle_node_templates.go
347 lines (302 loc) · 10 KB
/
handle_node_templates.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
/*
Copyright 2021 Flant JSC
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 hooks
import (
"encoding/json"
"fmt"
"time"
"github.com/flant/addon-operator/pkg/module_manager/go_hook"
"github.com/flant/addon-operator/sdk"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"github.com/deckhouse/deckhouse/go_lib/set"
"github.com/deckhouse/deckhouse/go_lib/taints"
ngv1 "github.com/deckhouse/deckhouse/modules/040-node-manager/hooks/internal/v1"
)
/**
HandleNodeTemplates hook applies annotations, taints and labels to CloudStatic, CloudPermanent and Static nodes
and deletes "node.deckhouse.io/uninitialized" taint.
*/
const (
NodeGroupNameLabel = "node.deckhouse.io/group"
LastAppliedNodeTemplateAnnotation = "node-manager.deckhouse.io/last-applied-node-template"
NodeUnininitalizedTaintKey = "node.deckhouse.io/uninitialized"
)
type NodeSettings struct {
Name string
NodeType ngv1.NodeType
NodeGroup string
Annotations map[string]string
Labels map[string]string
Taints []v1.Taint
LastAppliedNodeTemplate *NodeSettings
}
// Hook will be executed when NodeType or NodeTemplate are changed.
func desiredNodeSettingsFromNodeGroupFilter(obj *unstructured.Unstructured) (go_hook.FilterResult, error) {
nodeGroup := new(ngv1.NodeGroup)
err := sdk.FromUnstructured(obj, nodeGroup)
if err != nil {
return nil, err
}
settings := NodeSettings{
Name: nodeGroup.Name,
NodeType: nodeGroup.Spec.NodeType,
Annotations: nodeGroup.Spec.NodeTemplate.Annotations,
Labels: nodeGroup.Spec.NodeTemplate.Labels,
Taints: nodeGroup.Spec.NodeTemplate.Taints,
}
// base64 decoding is not needed in Go.
return settings, nil
}
// actualNodeSettingsFilter gets annotations, labels, taints, and nodeGroup
// from the Node. nodeGroup is used as a key to find desired settings.
// Hook will be executed when NodeGroup, annotations, labels or taints are changed.
func actualNodeSettingsFilter(obj *unstructured.Unstructured) (go_hook.FilterResult, error) {
nodeObj := new(v1.Node)
err := sdk.FromUnstructured(obj, nodeObj)
if err != nil {
return nil, err
}
settings := NodeSettings{
Name: nodeObj.Name,
NodeGroup: nodeObj.Labels[NodeGroupNameLabel],
Labels: nodeObj.Labels,
Annotations: nodeObj.Annotations,
Taints: nodeObj.Spec.Taints,
}
lastApplied, ok := settings.Annotations[LastAppliedNodeTemplateAnnotation]
if ok {
settings.LastAppliedNodeTemplate = new(NodeSettings)
err = json.Unmarshal([]byte(lastApplied), settings.LastAppliedNodeTemplate)
if err != nil {
return nil, fmt.Errorf("parse last applied node template: %v", err)
}
}
return settings, nil
}
var _ = sdk.RegisterFunc(&go_hook.HookConfig{
Queue: "/modules/node-manager/handle_node_templates",
Settings: &go_hook.HookConfigSettings{
ExecutionMinInterval: 5 * time.Second,
ExecutionBurst: 3,
},
Kubernetes: []go_hook.KubernetesConfig{
{
Name: "ngs",
ApiVersion: "deckhouse.io/v1",
Kind: "NodeGroup",
FilterFunc: desiredNodeSettingsFromNodeGroupFilter,
WaitForSynchronization: go_hook.Bool(false),
},
{
Name: "nodes",
ApiVersion: "v1",
Kind: "Node",
FilterFunc: actualNodeSettingsFilter,
WaitForSynchronization: go_hook.Bool(false),
},
},
}, nodeTemplatesHandler)
// nodeTemplatesHandler applies annotations, labels and taints to Hybrid and Static nodes from NodeGroup's nodeTemplate.
// Also, "node.deckhouse.io/uninitialized" taint is deleted.
func nodeTemplatesHandler(input *go_hook.HookInput) error {
nodes := input.Snapshots["nodes"]
// Expire d8_unmanaged_nodes_on_cluster metric and register unmanaged nodes.
// This is a separate loop because template applying may return an error.
input.MetricsCollector.Expire("")
for _, nodeObj := range nodes {
node := nodeObj.(NodeSettings)
if node.NodeGroup == "" {
input.MetricsCollector.Set("d8_unmanaged_nodes_on_cluster", 1, map[string]string{
"node": node.Name,
})
}
}
if len(nodes) == 0 {
return nil
}
nodeGroups := input.Snapshots["ngs"]
if len(nodeGroups) == 0 {
return nil
}
// Prepare index of node groups.
ngs := map[string]NodeSettings{}
for _, nodeGroup := range nodeGroups {
ng := nodeGroup.(NodeSettings)
ngs[ng.Name] = ng
}
for _, nodeObj := range nodes {
node := nodeObj.(NodeSettings)
// Skip nodes not managed by us (not having node.deckhouse.io/group label)
if node.NodeGroup == "" {
continue
}
// Skip nodes from unknown node groups
nodeGroup, ok := ngs[node.NodeGroup]
if !ok {
continue
}
input.PatchCollector.Filter(func(obj *unstructured.Unstructured) (*unstructured.Unstructured, error) {
nodeObj := new(v1.Node)
err := sdk.FromUnstructured(obj, nodeObj)
if err != nil {
return nil, err
}
if nodeGroup.NodeType == ngv1.NodeTypeCloudEphemeral {
err = fixCloudNodeTaints(nodeObj, node, nodeGroup)
} else {
err = applyNodeTemplate(nodeObj, node, nodeGroup)
}
if err != nil {
return nil, err
}
nodeObj.Status = v1.NodeStatus{}
return sdk.ToUnstructured(nodeObj)
}, "v1", "Node", "", node.Name)
}
return nil
}
// fixCloudNodeTaints removes "node.deckhouse.io/uninitialized" taint when
// NodeTemplate for Cloud node is applied by MCM.
// TODO Taint deletion should be moved to a separate hook in the future.
func fixCloudNodeTaints(nodeObj *v1.Node, node NodeSettings, nodeGroup NodeSettings) error {
newTaints := taints.Slice(nodeObj.Spec.Taints).Merge(nodeGroup.Taints)
if !newTaints.Equal(nodeObj.Spec.Taints) {
return nil
}
newTaints = newTaints.WithoutKey(NodeUnininitalizedTaintKey)
if len(newTaints) == 0 {
// MergePatch: delete .spec.taints
nodeObj.Spec.Taints = nil
} else {
// MergePatch: delete "node.deckhouse.io/uninitialized"
nodeObj.Spec.Taints = newTaints
}
return nil
}
func applyNodeTemplate(nodeObj *v1.Node, node NodeSettings, nodeGroup NodeSettings) error {
// 1. Labels
// 1.1. Merge node.labels with nodeTemplate.labels and remove excess keys.
var lastLabels map[string]string
if node.LastAppliedNodeTemplate != nil {
lastLabels = node.LastAppliedNodeTemplate.Labels
}
newLabels, labelsChanged := ApplyTemplateMap(node.Labels, nodeGroup.Labels, lastLabels)
// 1.2. Add label with nodeGroup name.
_, ok := newLabels["node-role.kubernetes.io/"+nodeGroup.Name]
if !ok {
labelsChanged = true
}
newLabels["node-role.kubernetes.io/"+nodeGroup.Name] = ""
// 1.3. Add label with nodeGroup type
nodeGroupType, ok := newLabels["node.deckhouse.io/type"]
if !ok || nodeGroupType != nodeGroup.NodeType.String() {
labelsChanged = true
}
newLabels["node.deckhouse.io/type"] = nodeGroup.NodeType.String()
// 2. Annotations
// 2.1. Merge node.annotations with nodeTemplate.annotations and remove excess keys.
var lastAnnotations map[string]string
if node.LastAppliedNodeTemplate != nil {
lastAnnotations = node.LastAppliedNodeTemplate.Annotations
}
newAnnotations, annotationsChanged := ApplyTemplateMap(node.Annotations, nodeGroup.Annotations, lastAnnotations)
// 2.2. Save last applied node template in annotation.
// Mimic shell-operator behaviour with empty fields.
lastAppliedMap := map[string]interface{}{
"annotations": make(map[string]string),
"labels": make(map[string]string),
"taints": make([]v1.Taint, 0),
}
if len(nodeGroup.Annotations) > 0 {
lastAppliedMap["annotations"] = nodeGroup.Annotations
}
if len(nodeGroup.Labels) > 0 {
lastAppliedMap["labels"] = nodeGroup.Labels
}
if len(nodeGroup.Taints) > 0 {
lastAppliedMap["taints"] = nodeGroup.Taints
}
newLastApplied, err := json.Marshal(lastAppliedMap)
if err != nil {
return fmt.Errorf("marshal last-applied-node-template: %v", err)
}
_, ok = newAnnotations[LastAppliedNodeTemplateAnnotation]
if !ok {
annotationsChanged = true
}
newAnnotations[LastAppliedNodeTemplateAnnotation] = string(newLastApplied)
// 3. Taints
// 3.1. Merge taints, remove excess.
var lastTaints []v1.Taint
if node.LastAppliedNodeTemplate != nil {
lastTaints = node.LastAppliedNodeTemplate.Taints
}
newTaints, taintsChanged := taints.Slice(node.Taints).ApplyTemplate(nodeGroup.Taints, lastTaints)
// 3.2. Delete uninitialized taint.
if newTaints.HasKey(NodeUnininitalizedTaintKey) {
taintsChanged = true
newTaints = newTaints.WithoutKey(NodeUnininitalizedTaintKey)
}
if labelsChanged || annotationsChanged {
if labelsChanged {
nodeObj.SetLabels(newLabels)
}
if labelsChanged {
nodeObj.SetAnnotations(newAnnotations)
}
}
if taintsChanged {
if len(newTaints) == 0 {
// 3.3. Remove taint key if no taints left.
nodeObj.Spec.Taints = nil
} else {
nodeObj.Spec.Taints = newTaints
}
}
return nil
}
// ApplyTemplateMap return actual merged with template without excess keys.
func ApplyTemplateMap(actual, template, lastApplied map[string]string) (map[string]string, bool) {
changed := false
excess := ExcessMapKeys(lastApplied, template)
newLabels := map[string]string{}
for k, v := range actual {
// Ignore keys removed from template.
if excess.Has(k) {
changed = true
continue
}
newLabels[k] = v
}
// Merge with values from template.
for k, v := range template {
oldVal, ok := newLabels[k]
if !ok || oldVal != v {
changed = true
}
newLabels[k] = v
}
return newLabels, changed
}
// ExcessMapKeys returns keys from a without keys from b.
func ExcessMapKeys(a, b map[string]string) set.Set {
onlyA := set.New()
for k := range a {
onlyA.Add(k)
}
for k := range b {
onlyA.Delete(k)
}
return onlyA
}