-
Notifications
You must be signed in to change notification settings - Fork 110
/
update_approval.go
572 lines (475 loc) · 14.8 KB
/
update_approval.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
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
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
/*
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 (
"os"
"strconv"
"strings"
"time"
"github.com/flant/addon-operator/pkg/module_manager/go_hook"
"github.com/flant/addon-operator/sdk"
corev1 "k8s.io/api/core/v1"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/util/intstr"
"k8s.io/utils/pointer"
"github.com/deckhouse/deckhouse/modules/040-node-manager/hooks/internal/shared"
ngv1 "github.com/deckhouse/deckhouse/modules/040-node-manager/hooks/internal/v1"
)
var _ = sdk.RegisterFunc(&go_hook.HookConfig{
Settings: &go_hook.HookConfigSettings{
ExecutionMinInterval: 5 * time.Second,
ExecutionBurst: 3,
},
Queue: "/modules/node-manager/update_approval",
Kubernetes: []go_hook.KubernetesConfig{
// snapshot: "configuration_checksums_secret"
// api: "v1",
// kind: "Secret",
// ns: "d8-cloud-instance-manager"
// name: "configuration-checksums"
shared.ConfigurationChecksumHookConfig(),
{
Name: "ngs",
WaitForSynchronization: pointer.BoolPtr(false),
ApiVersion: "deckhouse.io/v1",
Kind: "NodeGroup",
FilterFunc: updateApprovalNodeGroupFilter,
},
{
Name: "nodes",
WaitForSynchronization: pointer.BoolPtr(false),
ApiVersion: "v1",
Kind: "Node",
LabelSelector: &v1.LabelSelector{
MatchExpressions: []v1.LabelSelectorRequirement{
{
Key: "node.deckhouse.io/group",
Operator: v1.LabelSelectorOpExists,
},
},
},
FilterFunc: updateApprovalFilterNode,
},
},
}, handleUpdateApproval)
func handleUpdateApproval(input *go_hook.HookInput) error {
approver := &updateApprover{
finished: false,
nodes: make(map[string]updateApprovalNode),
nodeGroups: make(map[string]updateNodeGroup),
}
snap := input.Snapshots["configuration_checksums_secret"]
if len(snap) == 0 {
input.LogEntry.Warn("no configuration_checksums_secret snapshot found. Skipping run")
return nil
}
approver.ngChecksums = snap[0].(shared.ConfigurationChecksum)
snap = input.Snapshots["ngs"]
for _, s := range snap {
ng := s.(updateNodeGroup)
approver.nodeGroups[ng.Name] = ng
}
snap = input.Snapshots["nodes"]
for _, s := range snap {
n := s.(updateApprovalNode)
approver.nodes[n.Name] = n
setNodeMetric(input, n, approver.nodeGroups[n.NodeGroup], approver.ngChecksums[n.NodeGroup])
}
err := approver.processUpdatedNodes(input)
if err != nil {
return err
}
if approver.finished {
return nil
}
err = approver.approveDisruptions(input)
if err != nil {
return err
}
if approver.finished {
return nil
}
err = approver.approveUpdates(input)
if err != nil {
return err
}
return nil
}
type updateApprover struct {
finished bool
ngChecksums shared.ConfigurationChecksum
nodes map[string]updateApprovalNode
nodeGroups map[string]updateNodeGroup
}
func calculateConcurrency(ngCon *intstr.IntOrString, totalNodes int) int {
var concurrency = 1
switch ngCon.Type {
case intstr.Int:
concurrency = ngCon.IntValue()
case intstr.String:
if strings.HasSuffix(ngCon.String(), "%") {
percentStr := strings.TrimSuffix(ngCon.String(), "%")
percent, _ := strconv.Atoi(percentStr)
concurrency = totalNodes * percent / 100
if concurrency == 0 {
concurrency = 1
}
} else {
concurrency = ngCon.IntValue()
}
}
return concurrency
}
// Approve updates
// * Only one node from node group can be approved for update
// * If there are not ready nodes in the group, they'll be updated first
func (ar *updateApprover) approveUpdates(input *go_hook.HookInput) error {
for _, ng := range ar.nodeGroups {
nodeGroupNodes := make([]updateApprovalNode, 0)
currentUpdates := 0
for _, node := range ar.nodes {
if node.NodeGroup == ng.Name {
nodeGroupNodes = append(nodeGroupNodes, node)
}
}
concurrency := calculateConcurrency(ng.Concurrency, len(nodeGroupNodes))
var hasWaitingForApproval bool
// Count already approved nodes
for _, ngn := range nodeGroupNodes {
if ngn.IsApproved {
currentUpdates++
}
if !hasWaitingForApproval && ngn.IsWaitingForApproval {
hasWaitingForApproval = true
}
}
// Skip ng, if maxConcurrent is already reached
if currentUpdates >= concurrency {
continue
}
// Skip ng, if it has no waiting nodes
if !hasWaitingForApproval {
continue
}
countToApprove := concurrency - currentUpdates
approvedNodeNames := make(map[string]struct{}, countToApprove)
// Allow one node, if 100% nodes in NodeGroup are ready
if ng.Status.Desired == ng.Status.Ready || ng.NodeType != ngv1.NodeTypeCloudEphemeral {
var allReady = true
for _, ngn := range nodeGroupNodes {
if !ngn.IsReady {
allReady = false
break
}
}
if allReady {
for _, ngn := range nodeGroupNodes {
if ngn.IsWaitingForApproval {
approvedNodeNames[ngn.Name] = struct{}{}
if len(approvedNodeNames) == countToApprove {
break
}
}
}
}
}
if len(approvedNodeNames) < countToApprove {
// Allow one of not ready nodes, if any
for _, ngn := range nodeGroupNodes {
if !ngn.IsReady && ngn.IsWaitingForApproval {
approvedNodeNames[ngn.Name] = struct{}{}
if len(approvedNodeNames) == countToApprove {
break
}
}
}
}
if len(approvedNodeNames) == 0 {
continue
}
for approvedNodeName := range approvedNodeNames {
input.PatchCollector.MergePatch(approvedPatch, "v1", "Node", "", approvedNodeName)
setNodeStatusesMetrics(input, approvedNodeName, ng.Name, "Approved")
}
ar.finished = true
}
return nil
}
var (
approvedPatch = map[string]interface{}{
"metadata": map[string]interface{}{
"annotations": map[string]interface{}{
"update.node.deckhouse.io/approved": "",
"update.node.deckhouse.io/waiting-for-approval": nil,
},
},
}
)
// Approve disruption updates for NodeGroups with approvalMode == Automatic
// We don't limit number of Nodes here, because it's already limited
func (ar *updateApprover) approveDisruptions(input *go_hook.HookInput) error {
now := time.Now()
if os.Getenv("D8_IS_TESTS_ENVIRONMENT") != "" {
now = time.Date(2021, 01, 01, 13, 30, 00, 00, time.UTC)
}
for _, node := range ar.nodes {
if !(node.IsDisruptionRequired && !node.IsDraining) {
continue
}
ngName := node.NodeGroup
ng := ar.nodeGroups[ngName]
// Skip nodes in NodeGroup not allowing disruptive updates
if !(ng.Disruptions.ApprovalMode == "Automatic") {
continue
}
// Skip node if update is not permitted in the current time window
if !ng.Disruptions.Automatic.Windows.IsAllowed(now) {
continue
}
ar.finished = true
var patch map[string]interface{}
var metricStatus string
switch {
case !*ng.Disruptions.Automatic.DrainBeforeApproval:
// Skip draining if it's disabled in the NodeGroup
patch = map[string]interface{}{
"metadata": map[string]interface{}{
"annotations": map[string]interface{}{
"update.node.deckhouse.io/disruption-approved": "",
"update.node.deckhouse.io/disruption-required": nil,
},
},
}
metricStatus = "DisruptionApproved"
case !node.IsUnschedulable:
// If node is not unschedulable – mark it for draining
patch = map[string]interface{}{
"metadata": map[string]interface{}{
"annotations": map[string]interface{}{
"update.node.deckhouse.io/draining": "",
},
},
}
metricStatus = "DrainingForDisruption"
default:
// Node is unschedulable (is drained by us, or was marked as unschedulable by someone before), skip draining
patch = map[string]interface{}{
"metadata": map[string]interface{}{
"annotations": map[string]interface{}{
"update.node.deckhouse.io/disruption-approved": "",
"update.node.deckhouse.io/disruption-required": nil,
},
},
}
metricStatus = "DisruptionApproved"
}
input.PatchCollector.MergePatch(patch, "v1", "Node", "", node.Name)
setNodeStatusesMetrics(input, node.Name, node.NodeGroup, metricStatus)
}
return nil
}
// Process updated nodes: remove approved and disruption-approved annotations, if:
// * Node is ready
// * Node checksum is equal to NodeGroup checksum
func (ar *updateApprover) processUpdatedNodes(input *go_hook.HookInput) error {
for _, node := range ar.nodes {
if !node.IsApproved {
continue
}
nodeChecksum := node.ConfigurationChecksum
ngName := node.NodeGroup
ngChecksum := ar.ngChecksums[ngName]
if nodeChecksum == "" || ngChecksum == "" {
continue
}
if nodeChecksum != ngChecksum {
continue
}
if !node.IsReady {
continue
}
patch := map[string]interface{}{
"metadata": map[string]interface{}{
"annotations": map[string]interface{}{
"update.node.deckhouse.io/approved": nil,
"update.node.deckhouse.io/waiting-for-approval": nil,
"update.node.deckhouse.io/disruption-required": nil,
"update.node.deckhouse.io/disruption-approved": nil,
"update.node.deckhouse.io/drained": nil,
},
},
}
if node.IsDrained {
patch["spec"] = map[string]interface{}{
"unschedulable": nil,
}
}
input.PatchCollector.MergePatch(patch, "v1", "Node", "", node.Name)
setNodeStatusesMetrics(input, node.Name, node.NodeGroup, "UpToDate")
ar.finished = true
}
return nil
}
type updateApprovalNode struct {
Name string
NodeGroup string
ConfigurationChecksum string
IsReady bool
IsApproved bool
IsDisruptionApproved bool
IsWaitingForApproval bool
IsDisruptionRequired bool
IsUnschedulable bool
IsDraining bool
IsDrained bool
}
type updateNodeGroup struct {
Name string
NodeType ngv1.NodeType
Disruptions ngv1.Disruptions
Status ngv1.NodeGroupStatus
Concurrency *intstr.IntOrString
}
func updateApprovalNodeGroupFilter(obj *unstructured.Unstructured) (go_hook.FilterResult, error) {
var ng ngv1.NodeGroup
err := sdk.FromUnstructured(obj, &ng)
if err != nil {
return nil, err
}
ung := updateNodeGroup{
Name: ng.Name,
NodeType: ng.Spec.NodeType,
}
if ng.Spec.Update.MaxConcurrent != nil {
ung.Concurrency = ng.Spec.Update.MaxConcurrent
} else {
concurrency := intstr.FromInt(1)
ung.Concurrency = &concurrency
}
if len(ng.Spec.Disruptions.Automatic.Windows) > 0 {
ung.Disruptions.Automatic.Windows = ng.Spec.Disruptions.Automatic.Windows
}
if ng.Spec.Disruptions.ApprovalMode != "" {
ung.Disruptions.ApprovalMode = ng.Spec.Disruptions.ApprovalMode
} else {
ung.Disruptions.ApprovalMode = "Automatic"
}
ung.Status = ng.Status
if ung.Disruptions.ApprovalMode == "Automatic" {
if ng.Spec.Disruptions.Automatic.DrainBeforeApproval != nil {
ung.Disruptions.Automatic.DrainBeforeApproval = ng.Spec.Disruptions.Automatic.DrainBeforeApproval
} else {
ung.Disruptions.Automatic.DrainBeforeApproval = pointer.BoolPtr(true)
}
}
return ung, nil
}
func updateApprovalFilterNode(obj *unstructured.Unstructured) (go_hook.FilterResult, error) {
var node corev1.Node
err := sdk.FromUnstructured(obj, &node)
if err != nil {
return nil, err
}
var isApproved, isWaitingForApproval, isDisruptionRequired, isDraining, isReady, isDrained, isDisruptionApproved bool
if _, ok := node.Annotations["update.node.deckhouse.io/approved"]; ok {
isApproved = true
}
if _, ok := node.Annotations["update.node.deckhouse.io/waiting-for-approval"]; ok {
isWaitingForApproval = true
}
if _, ok := node.Annotations["update.node.deckhouse.io/disruption-required"]; ok {
isDisruptionRequired = true
}
if _, ok := node.Annotations["update.node.deckhouse.io/draining"]; ok {
isDraining = true
}
if _, ok := node.Annotations["update.node.deckhouse.io/disruption-approved"]; ok {
isDisruptionApproved = true
}
configChecksum, ok := node.Annotations["node.deckhouse.io/configuration-checksum"]
if !ok {
configChecksum = ""
}
nodeGroup, ok := node.Labels["node.deckhouse.io/group"]
if !ok {
nodeGroup = ""
}
if _, ok := node.Annotations["update.node.deckhouse.io/drained"]; ok {
isDrained = true
}
for _, cond := range node.Status.Conditions {
if cond.Type == corev1.NodeReady && cond.Status == corev1.ConditionTrue {
isReady = true
break
}
}
n := updateApprovalNode{
Name: node.Name,
IsApproved: isApproved,
IsDisruptionApproved: isDisruptionApproved,
ConfigurationChecksum: configChecksum,
NodeGroup: nodeGroup,
IsReady: isReady,
IsDisruptionRequired: isDisruptionRequired,
IsDraining: isDraining,
IsUnschedulable: node.Spec.Unschedulable,
IsWaitingForApproval: isWaitingForApproval,
IsDrained: isDrained,
}
return n, nil
}
func setNodeMetric(input *go_hook.HookInput, node updateApprovalNode, ng updateNodeGroup, desiredChecksum string) {
nodeStatus := calculateNodeStatus(node, ng, desiredChecksum)
setNodeStatusesMetrics(input, node.Name, node.NodeGroup, nodeStatus)
}
func calculateNodeStatus(node updateApprovalNode, ng updateNodeGroup, desiredChecksum string) string {
switch {
case node.IsWaitingForApproval:
return "WaitingForApproval"
case node.IsApproved && node.IsDisruptionRequired && node.IsDraining:
return "DrainingForDisruption"
case node.IsApproved && node.IsDisruptionRequired && ng.Disruptions.ApprovalMode == "Automatic":
return "WaitingForDisruptionApproval"
case node.IsApproved && node.IsDisruptionRequired && ng.Disruptions.ApprovalMode == "Manual":
return "WaitingForManualDisruptionApproval"
case node.IsApproved && node.IsDisruptionApproved:
return "DisruptionApproved"
case node.IsApproved:
return "Approved"
case node.ConfigurationChecksum != desiredChecksum:
return "ToBeUpdated"
case node.ConfigurationChecksum == desiredChecksum:
return "UpToDate"
default:
return "Unknown"
}
}
var metricStatuses = []string{
"WaitingForApproval", "Approved", "DrainingForDisruption", "WaitingForDisruptionApproval",
"WaitingForManualDisruptionApproval", "DisruptionApproved", "ToBeUpdated", "UpToDate",
}
func setNodeStatusesMetrics(input *go_hook.HookInput, nodeName, nodeGroup, nodeStatus string) {
for _, status := range metricStatuses {
var value float64 = 0
if status == nodeStatus {
value = 1
}
labels := map[string]string{
"node": nodeName,
"node_group": nodeGroup,
"status": status,
}
input.MetricsCollector.Set("node_group_node_status", value, labels)
}
}