-
Notifications
You must be signed in to change notification settings - Fork 488
Expand file tree
/
Copy pathnode_controller_test.go
More file actions
2266 lines (2069 loc) · 79.3 KB
/
node_controller_test.go
File metadata and controls
2266 lines (2069 loc) · 79.3 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
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
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package node
import (
"context"
"encoding/json"
"fmt"
"reflect"
"testing"
"time"
"github.com/openshift/library-go/pkg/operator/configobserver/featuregates"
"github.com/openshift/machine-config-operator/pkg/apihelpers"
pkghelpers "github.com/openshift/machine-config-operator/pkg/helpers"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/intstr"
"k8s.io/apimachinery/pkg/util/strategicpatch"
"k8s.io/apimachinery/pkg/util/uuid"
kubeinformers "k8s.io/client-go/informers"
k8sfake "k8s.io/client-go/kubernetes/fake"
core "k8s.io/client-go/testing"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/tools/record"
"github.com/davecgh/go-spew/spew"
configv1 "github.com/openshift/api/config/v1"
mcfgv1 "github.com/openshift/api/machineconfiguration/v1"
fakeconfigv1client "github.com/openshift/client-go/config/clientset/versioned/fake"
configv1informer "github.com/openshift/client-go/config/informers/externalversions"
"github.com/openshift/client-go/machineconfiguration/clientset/versioned/fake"
informers "github.com/openshift/client-go/machineconfiguration/informers/externalversions"
fakeoperatorclient "github.com/openshift/client-go/operator/clientset/versioned/fake"
operatorinformer "github.com/openshift/client-go/operator/informers/externalversions"
"github.com/openshift/machine-config-operator/pkg/constants"
ctrlcommon "github.com/openshift/machine-config-operator/pkg/controller/common"
daemonconsts "github.com/openshift/machine-config-operator/pkg/daemon/constants"
"github.com/openshift/machine-config-operator/pkg/version"
"github.com/openshift/machine-config-operator/test/helpers"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
utilrand "k8s.io/apimachinery/pkg/util/rand"
)
const (
machineConfigV0 string = "rendered-machine-config-v0"
machineConfigV1 string = "rendered-machine-config-v1"
machineConfigV2 string = "rendered-machine-config-v2"
imageV0 string = "registry.com/org/repo@sha256:12345"
imageV1 string = "registry.com/org/repo@sha256:54321"
)
var (
alwaysReady = func() bool { return true }
noResyncPeriodFunc = func() time.Duration { return 0 }
)
type fixture struct {
t *testing.T
client *fake.Clientset
kubeclient *k8sfake.Clientset
schedulerClient *fakeconfigv1client.Clientset
ccLister []*mcfgv1.ControllerConfig
mcpLister []*mcfgv1.MachineConfigPool
nodeLister []*corev1.Node
kubeactions []core.Action
actions []core.Action
kubeobjects []runtime.Object
objects []runtime.Object
schedulerObjects []runtime.Object
schedulerLister []*configv1.Scheduler
fgHandler ctrlcommon.FeatureGatesHandler
}
func newFixtureWithFeatureGates(t *testing.T, enabled, disabled []configv1.FeatureGateName) *fixture {
f := &fixture{}
f.t = t
f.objects = []runtime.Object{}
f.kubeobjects = []runtime.Object{}
fgAccess := featuregates.NewHardcodedFeatureGateAccess(
enabled,
disabled,
)
f.fgHandler = ctrlcommon.NewFeatureGatesAccessHandler(fgAccess)
if err := f.fgHandler.Connect(context.Background()); err != nil {
f.t.Fatal(err)
}
return f
}
func newFixture(t *testing.T) *fixture {
return newFixtureWithFeatureGates(t, []configv1.FeatureGateName{}, []configv1.FeatureGateName{})
}
func (f *fixture) newControllerWithStopChan(stopCh <-chan struct{}) *Controller {
f.client = fake.NewSimpleClientset(f.objects...)
f.kubeclient = k8sfake.NewSimpleClientset(f.kubeobjects...)
f.schedulerClient = fakeconfigv1client.NewSimpleClientset(f.schedulerObjects...)
operatorClient := fakeoperatorclient.NewSimpleClientset()
i := informers.NewSharedInformerFactory(f.client, noResyncPeriodFunc())
k8sI := kubeinformers.NewSharedInformerFactory(f.kubeclient, noResyncPeriodFunc())
ci := configv1informer.NewSharedInformerFactory(f.schedulerClient, noResyncPeriodFunc())
oi := operatorinformer.NewSharedInformerFactory(operatorClient, noResyncPeriodFunc())
c := NewWithCustomUpdateDelay(i.Machineconfiguration().V1().ControllerConfigs(), i.Machineconfiguration().V1().MachineConfigs(), i.Machineconfiguration().V1().MachineConfigPools(), k8sI.Core().V1().Nodes(),
k8sI.Core().V1().Pods(), i.Machineconfiguration().V1().MachineOSConfigs(), i.Machineconfiguration().V1().MachineOSBuilds(), i.Machineconfiguration().V1().MachineConfigNodes(), ci.Config().V1().Schedulers(), oi.Operator().V1().MachineConfigurations(), f.kubeclient, f.client, time.Millisecond, f.fgHandler)
c.ccListerSynced = alwaysReady
c.mcpListerSynced = alwaysReady
c.nodeListerSynced = alwaysReady
c.schedulerListerSynced = alwaysReady
c.mcopListerSynced = alwaysReady
c.eventRecorder = &record.FakeRecorder{}
i.Start(stopCh)
i.WaitForCacheSync(stopCh)
k8sI.Start(stopCh)
k8sI.WaitForCacheSync(stopCh)
for _, c := range f.ccLister {
i.Machineconfiguration().V1().ControllerConfigs().Informer().GetIndexer().Add(c)
}
for _, c := range f.mcpLister {
i.Machineconfiguration().V1().MachineConfigPools().Informer().GetIndexer().Add(c)
}
for _, m := range f.nodeLister {
k8sI.Core().V1().Nodes().Informer().GetIndexer().Add(m)
}
for _, c := range f.schedulerLister {
ci.Config().V1().Schedulers().Informer().GetIndexer().Add(c)
}
return c
}
func (f *fixture) newController() *Controller {
stopCh := make(chan struct{})
defer close(stopCh)
return f.newControllerWithStopChan(stopCh)
}
func (f *fixture) newControllerWithContext(ctx context.Context) *Controller {
return f.newControllerWithStopChan(ctx.Done())
}
func (f *fixture) run(pool string) {
f.runController(pool, false)
}
func (f *fixture) runExpectError(pool string) {
f.runController(pool, true)
}
func (f *fixture) runController(pool string, expectError bool) {
c := f.newController()
err := c.syncHandler(pool)
if !expectError && err != nil {
f.t.Errorf("error syncing machineconfigpool: %v", err)
} else if expectError && err == nil {
f.t.Error("expected error syncing machineconfigpool, got nil")
}
actions := filterInformerActions(f.client.Actions())
for i, action := range actions {
if len(f.actions) < i+1 {
f.t.Errorf("%d unexpected actions: %+v", len(actions)-len(f.actions), actions[i:])
break
}
expectedAction := f.actions[i]
checkAction(expectedAction, action, f.t)
}
if len(f.actions) > len(actions) {
f.t.Errorf("%d additional expected actions:%+v", len(f.actions)-len(actions), f.actions[len(actions):])
}
k8sActions := filterInformerActions(f.kubeclient.Actions())
for i, action := range k8sActions {
if len(f.kubeactions) < i+1 {
f.t.Errorf("%d unexpected kube actions: %+v", len(k8sActions)-len(f.kubeactions), k8sActions[i:])
break
}
expectedAction := f.kubeactions[i]
checkAction(expectedAction, action, f.t)
}
if len(f.kubeactions) > len(k8sActions) {
f.t.Errorf("%d additional expected actions:%+v", len(f.kubeactions)-len(k8sActions), f.kubeactions[len(k8sActions):])
f.t.Log(k8sActions)
f.t.Log("------")
f.t.Log(f.kubeactions)
}
}
func newControllerConfig(name string, topology configv1.TopologyMode) *mcfgv1.ControllerConfig {
return &mcfgv1.ControllerConfig{
TypeMeta: metav1.TypeMeta{APIVersion: mcfgv1.SchemeGroupVersion.String()},
ObjectMeta: metav1.ObjectMeta{Annotations: map[string]string{daemonconsts.GeneratedByVersionAnnotationKey: version.Raw}, Name: name, UID: types.UID(utilrand.String(5))},
Spec: mcfgv1.ControllerConfigSpec{
Infra: &configv1.Infrastructure{
Status: configv1.InfrastructureStatus{
ControlPlaneTopology: topology,
},
},
},
}
}
// checkAction verifies that expected and actual actions are equal and both have
// same attached resources
func checkAction(expected, actual core.Action, t *testing.T) {
if !(expected.Matches(actual.GetVerb(), actual.GetResource().Resource) && actual.GetSubresource() == expected.GetSubresource()) {
t.Errorf("Expected\n\t%#v\ngot\n\t%#v", expected, actual)
return
}
if !assert.Equal(t, reflect.TypeOf(expected), reflect.TypeOf(actual)) {
return
}
switch a := actual.(type) {
case core.CreateAction:
e, _ := expected.(core.CreateAction)
expObject := filterLastTransitionTime(e.GetObject())
object := filterLastTransitionTime(a.GetObject())
assert.Equal(t, expObject, object)
case core.UpdateAction:
e, _ := expected.(core.UpdateAction)
expObject := filterLastTransitionTime(e.GetObject())
object := filterLastTransitionTime(a.GetObject())
assert.Equal(t, expObject, object)
case core.PatchAction:
e, _ := expected.(core.PatchAction)
expPatch := e.GetPatch()
patch := a.GetPatch()
assert.Equal(t, expPatch, patch)
}
}
// filterInformerActions filters list and watch actions for testing resources.
// Since list and watch don't change resource state we can filter it to lower
// nose level in our tests.
func filterInformerActions(actions []core.Action) []core.Action {
ret := []core.Action{}
for _, action := range actions {
if len(action.GetNamespace()) == 0 &&
(action.Matches("list", "machineconfigpools") ||
action.Matches("watch", "machineconfigpools") ||
action.Matches("list", "machineconfigs") ||
action.Matches("watch", "machineconfigs") ||
action.Matches("list", "controllerconfigs") ||
action.Matches("watch", "controllerconfigs") ||
action.Matches("list", "nodes") ||
action.Matches("watch", "nodes") ||
action.Matches("list", "pods") ||
action.Matches("watch", "pods") ||
action.Matches("list", "machineosbuilds") ||
action.Matches("watch", "machineosbuilds") ||
action.Matches("list", "machineosconfigs") ||
action.Matches("watch", "machineosconfigs") ||
action.Matches("get", "machineconfignodes") ||
action.Matches("list", "machineconfignodes") ||
action.Matches("watch", "machineconfignodes")) {
continue
}
ret = append(ret, action)
}
return ret
}
func (f *fixture) expectUpdateMachineConfigPoolStatus(pool *mcfgv1.MachineConfigPool) {
f.actions = append(f.actions, core.NewRootUpdateSubresourceAction(schema.GroupVersionResource{Resource: "machineconfigpools"}, "status", pool))
}
func (f *fixture) expectGetNodeAction(node *corev1.Node) {
f.kubeactions = append(f.kubeactions, core.NewGetAction(schema.GroupVersionResource{Resource: "nodes"}, node.Namespace, node.Name))
}
func (f *fixture) expectPatchNodeAction(node *corev1.Node, patch []byte) {
f.kubeactions = append(f.kubeactions, core.NewPatchAction(schema.GroupVersionResource{Resource: "nodes"}, node.Namespace, node.Name, types.MergePatchType, patch))
}
func TestGetNodesForPool(t *testing.T) {
t.Parallel()
tests := []struct {
pool *mcfgv1.MachineConfigPool
nodes []*corev1.Node
expected int
err bool
}{
{
pool: helpers.NewMachineConfigPool("master", nil, helpers.MasterSelector, machineConfigV0),
nodes: newMixedNodeSet(3, map[string]string{"node-role": ""}, map[string]string{"node-role/worker": ""}),
expected: 0,
err: false,
},
{
pool: helpers.NewMachineConfigPool("master", nil, helpers.MasterSelector, machineConfigV0),
nodes: newMixedNodeSet(2, map[string]string{"node-role/master": ""}, map[string]string{"node-role/worker": ""}),
expected: 2,
err: false,
},
{
pool: helpers.NewMachineConfigPool("ïnfra", nil, helpers.InfraSelector, machineConfigV0),
nodes: newMixedNodeSet(3, map[string]string{"node-role/master": ""}, map[string]string{"node-role/worker": "", "node-role/infra": ""}),
expected: 3,
err: false,
},
{
// Mixed cluster with both Windows and Linux worker nodes. Only Linux nodes should be managed by MCO
pool: helpers.NewMachineConfigPool("worker", nil, helpers.WorkerSelector, machineConfigV0),
nodes: append(newMixedNodeSet(3, map[string]string{"node-role/master": ""}, map[string]string{"node-role/worker": "", "node-role/infra": ""}), newNodeWithLabels("windowsNode", map[string]string{pkghelpers.OSLabel: "windows"})),
expected: 3,
err: false,
},
{
// Single Windows node is the cluster, so shouldn't be managed by MCO
pool: helpers.NewMachineConfigPool("worker", nil, helpers.WorkerSelector, machineConfigV0),
nodes: []*corev1.Node{newNodeWithLabels("windowsNode", map[string]string{osLabel: "windows"})},
expected: 0,
err: false,
},
}
for idx, test := range tests {
idx := idx
test := test
t.Run(fmt.Sprintf("case#%d", idx), func(t *testing.T) {
t.Parallel()
f := newFixture(t)
f.nodeLister = append(f.nodeLister, test.nodes...)
f.mcpLister = append(f.mcpLister, test.pool)
c := f.newController()
got, err := c.getNodesForPool(test.pool)
if err != nil && !test.err {
t.Fatal("expected non-nil error")
}
assert.Equal(t, test.expected, len(got))
})
}
}
func TestGetPrimaryPoolForNode(t *testing.T) {
t.Parallel()
tests := []struct {
pools []*mcfgv1.MachineConfigPool
nodeLabel map[string]string
expected *mcfgv1.MachineConfigPool
err bool
}{{
pools: []*mcfgv1.MachineConfigPool{
helpers.NewMachineConfigPool("master", nil, helpers.MasterSelector, machineConfigV0),
helpers.NewMachineConfigPool("worker", nil, helpers.WorkerSelector, machineConfigV0),
},
nodeLabel: map[string]string{"node-role": ""},
expected: nil,
err: false,
}, {
pools: []*mcfgv1.MachineConfigPool{
helpers.NewMachineConfigPool("master", nil, helpers.MasterSelector, machineConfigV0),
helpers.NewMachineConfigPool("worker", nil, helpers.WorkerSelector, machineConfigV0),
},
nodeLabel: map[string]string{"node-role/master": ""},
expected: helpers.NewMachineConfigPool("master", nil, helpers.MasterSelector, machineConfigV0),
err: false,
}, {
pools: []*mcfgv1.MachineConfigPool{
helpers.NewMachineConfigPool("master", nil, helpers.MasterSelector, machineConfigV0),
helpers.NewMachineConfigPool("worker", nil, helpers.WorkerSelector, machineConfigV0),
},
nodeLabel: map[string]string{"node-role/master": "", "node-role/worker": ""},
expected: helpers.NewMachineConfigPool("master", nil, helpers.MasterSelector, machineConfigV0),
err: false,
}, {
pools: []*mcfgv1.MachineConfigPool{
helpers.NewMachineConfigPool("master", nil, helpers.MasterSelector, machineConfigV0),
helpers.NewMachineConfigPool("worker", nil, helpers.WorkerSelector, machineConfigV0),
helpers.NewMachineConfigPool("infra", nil, helpers.InfraSelector, machineConfigV0),
},
nodeLabel: map[string]string{"node-role/worker": "", "node-role/infra": ""},
expected: helpers.NewMachineConfigPool("infra", nil, helpers.InfraSelector, machineConfigV0),
err: false,
}, {
pools: []*mcfgv1.MachineConfigPool{
helpers.NewMachineConfigPool("master", nil, helpers.MasterSelector, machineConfigV0),
helpers.NewMachineConfigPool("worker", nil, helpers.WorkerSelector, machineConfigV0),
helpers.NewMachineConfigPool("infra", nil, helpers.InfraSelector, machineConfigV0),
},
nodeLabel: map[string]string{"node-role/master": "", "node-role/infra": ""},
// https://issues.redhat.com/browse/OCPBUGS-2177 a user should
// be able to label something as infra but retain master if it exists
expected: helpers.NewMachineConfigPool("master", nil, helpers.MasterSelector, machineConfigV0),
err: false,
}, {
pools: []*mcfgv1.MachineConfigPool{
helpers.NewMachineConfigPool("master", nil, helpers.MasterSelector, machineConfigV0),
helpers.NewMachineConfigPool("worker", nil, helpers.WorkerSelector, machineConfigV0),
helpers.NewMachineConfigPool("infra", nil, helpers.InfraSelector, machineConfigV0),
helpers.NewMachineConfigPool("infra2", nil, metav1.AddLabelToSelector(&metav1.LabelSelector{}, "node-role/infra2", ""), machineConfigV0),
},
nodeLabel: map[string]string{"node-role/infra": "", "node-role/infra2": ""},
expected: nil,
err: true,
}, {
pools: []*mcfgv1.MachineConfigPool{
helpers.NewMachineConfigPool("test-cluster-pool-1", nil, helpers.MasterSelector, machineConfigV0),
helpers.NewMachineConfigPool("test-cluster-pool-2", nil, helpers.MasterSelector, machineConfigV0),
},
nodeLabel: map[string]string{"node-role": "master"},
expected: nil,
err: true,
}, {
// MCP with Widows worker, it should not be assigned a pool
pools: []*mcfgv1.MachineConfigPool{
helpers.NewMachineConfigPool("worker", nil, helpers.WorkerSelector, machineConfigV0),
},
nodeLabel: map[string]string{"node-role/master": "", "node-role/worker": "", osLabel: "windows"},
expected: nil,
err: false,
},
}
for idx, test := range tests {
idx := idx
test := test
t.Run(fmt.Sprintf("case#%d", idx), func(t *testing.T) {
t.Parallel()
f := newFixture(t)
node := newNode("node-0", machineConfigV0, machineConfigV0)
node.Labels = test.nodeLabel
f.nodeLister = append(f.nodeLister, node)
f.kubeobjects = append(f.kubeobjects, node)
f.mcpLister = append(f.mcpLister, test.pools...)
for idx := range test.pools {
f.objects = append(f.objects, test.pools[idx])
}
c := f.newController()
got, err := c.getPrimaryPoolForNode(node)
if err != nil && !test.err {
t.Fatal("expected non-nil error")
}
if got != nil {
got.ObjectMeta.UID = ""
}
if test.expected != nil {
test.expected.ObjectMeta.UID = ""
}
assert.Equal(t, test.expected, got)
})
}
}
func intStrPtr(obj intstr.IntOrString) *intstr.IntOrString { return &obj }
// newMixedNodeSet generates a slice of nodes for each role specified of length setlen.
func newMixedNodeSet(setlen int, roles ...map[string]string) []*corev1.Node {
var nodeSet []*corev1.Node
for _, role := range roles {
nodes := newRoleNodeSet(setlen, role)
nodeSet = append(nodeSet, nodes...)
}
return nodeSet
}
func newRoleNodeSet(len int, roles map[string]string) []*corev1.Node {
nodes := []*corev1.Node{}
for i := 0; i < len; i++ {
nodes = append(nodes, newNodeWithLabels(fmt.Sprintf("node-%s", uuid.NewUUID()), roles))
}
return nodes
}
func newNodeSet(len int) []*corev1.Node {
nodes := []*corev1.Node{}
for i := 0; i < len; i++ {
nodes = append(nodes, newNode(fmt.Sprintf("node-%d", i), "", ""))
}
return nodes
}
func TestMaxUnavailable(t *testing.T) {
t.Parallel()
tests := []struct {
poolName string
maxUnavail *intstr.IntOrString
nodes []*corev1.Node
expected int
err bool
}{
{
maxUnavail: nil,
nodes: newNodeSet(4),
expected: 1,
err: false,
}, {
maxUnavail: intStrPtr(intstr.FromInt(2)),
nodes: newNodeSet(4),
expected: 2,
err: false,
}, {
maxUnavail: intStrPtr(intstr.FromInt(0)),
nodes: newNodeSet(4),
expected: 1,
err: false,
}, {
maxUnavail: intStrPtr(intstr.FromString("50%")),
nodes: newNodeSet(4),
expected: 2,
err: false,
}, {
maxUnavail: intStrPtr(intstr.FromString("60%")),
nodes: newNodeSet(4),
expected: 2,
err: false,
}, {
maxUnavail: intStrPtr(intstr.FromString("50 percent")),
nodes: newNodeSet(4),
expected: 0,
err: true,
}, {
maxUnavail: intStrPtr(intstr.FromString("60")),
nodes: newNodeSet(4),
expected: 0,
err: true,
}, {
maxUnavail: intStrPtr(intstr.FromString("40 %")),
nodes: newNodeSet(4),
expected: 0,
err: true,
},
}
for idx, test := range tests {
idx := idx
test := test
t.Run(fmt.Sprintf("case#%d", idx), func(t *testing.T) {
pool := &mcfgv1.MachineConfigPool{
ObjectMeta: metav1.ObjectMeta{
Name: test.poolName,
},
Spec: mcfgv1.MachineConfigPoolSpec{
MaxUnavailable: test.maxUnavail,
},
}
got, err := maxUnavailable(pool, test.nodes)
if err != nil && !test.err {
t.Fatal("expected non-nil error")
}
assert.Equal(t, test.expected, got)
})
}
}
func TestGetCandidateMachines(t *testing.T) {
t.Parallel()
tests := []struct {
name string
nodes []*corev1.Node
progress int
mosc *mcfgv1.MachineOSConfig
mosb *mcfgv1.MachineOSBuild
expected []string
// otherCandidates is nodes that *could* be updated but we chose not to
otherCandidates []string
// capacity is the maximum number of nodes we could update
capacity uint
layered bool
}{{
name: "no progress - capacity 1",
progress: 1,
nodes: []*corev1.Node{
helpers.NewNodeWithReady("node-0", machineConfigV1, machineConfigV1, corev1.ConditionTrue),
helpers.NewNodeWithReady("node-1", machineConfigV1, machineConfigV1, corev1.ConditionTrue),
helpers.NewNodeWithReady("node-2", machineConfigV1, machineConfigV1, corev1.ConditionTrue),
},
expected: []string{},
otherCandidates: nil,
capacity: 1,
}, {
name: "no progress - capacity 0",
progress: 1,
nodes: []*corev1.Node{
helpers.NewNodeWithReady("node-0", machineConfigV1, machineConfigV1, corev1.ConditionTrue),
helpers.NewNodeWithReady("node-1", machineConfigV1, machineConfigV1, corev1.ConditionTrue),
helpers.NewNodeWithReady("node-2", machineConfigV1, machineConfigV1, corev1.ConditionFalse),
},
expected: []string{},
otherCandidates: nil,
capacity: 0,
}, {
name: "no progress because we have an unavailable node",
progress: 1,
nodes: []*corev1.Node{
helpers.NewNodeWithReady("node-0", machineConfigV1, machineConfigV1, corev1.ConditionTrue),
helpers.NewNodeWithReady("node-1", machineConfigV1, machineConfigV1, corev1.ConditionFalse),
helpers.NewNodeWithReady("node-2", machineConfigV0, machineConfigV1, corev1.ConditionTrue),
},
expected: []string{},
otherCandidates: nil,
capacity: 0,
}, {
name: "node-0 is unavailable and should be skipped over",
progress: 2,
nodes: []*corev1.Node{
helpers.NewNodeWithReady("node-0", machineConfigV0, machineConfigV0, corev1.ConditionFalse),
helpers.NewNodeWithReady("node-1", machineConfigV0, machineConfigV0, corev1.ConditionTrue),
helpers.NewNodeWithReady("node-2", machineConfigV0, machineConfigV0, corev1.ConditionTrue),
},
expected: []string{"node-1"},
otherCandidates: []string{"node-2"},
capacity: 1,
}, {
name: "node-2 is going to change config, so we can only progress one more",
progress: 3,
nodes: []*corev1.Node{
helpers.NewNodeWithReady("node-0", machineConfigV1, machineConfigV1, corev1.ConditionTrue),
helpers.NewNodeWithReady("node-1", machineConfigV1, machineConfigV1, corev1.ConditionFalse),
helpers.NewNodeWithReady("node-2", machineConfigV0, machineConfigV1, corev1.ConditionTrue),
helpers.NewNodeWithReady("node-3", machineConfigV0, machineConfigV0, corev1.ConditionTrue),
helpers.NewNodeWithReady("node-4", machineConfigV0, machineConfigV0, corev1.ConditionTrue),
},
expected: []string{"node-3"},
otherCandidates: []string{"node-4"},
capacity: 1,
}, {
name: "We have a node working, don't start anything else",
progress: 1,
nodes: []*corev1.Node{
helpers.NewNodeWithReady("node-0", machineConfigV1, machineConfigV1, corev1.ConditionTrue),
helpers.NewNodeWithReady("node-1", machineConfigV1, machineConfigV1, corev1.ConditionTrue),
helpers.NewNodeWithReady("node-2", machineConfigV0, machineConfigV1, corev1.ConditionTrue),
helpers.NewNodeWithReady("node-3", machineConfigV0, machineConfigV0, corev1.ConditionTrue),
helpers.NewNodeWithReady("node-4", machineConfigV0, machineConfigV0, corev1.ConditionTrue),
},
expected: []string{},
otherCandidates: nil,
capacity: 0,
}, {
name: "progress on old stuck node",
progress: 1,
nodes: []*corev1.Node{
helpers.NewNodeWithReady("node-0", machineConfigV1, machineConfigV1, corev1.ConditionTrue),
newNodeWithReadyAndDaemonState("node-1", "v0.1", "v0.2", corev1.ConditionTrue, daemonconsts.MachineConfigDaemonStateDegraded),
helpers.NewNodeWithReady("node-2", machineConfigV0, machineConfigV0, corev1.ConditionTrue),
},
expected: []string{"node-1"},
otherCandidates: []string{"node-2"},
capacity: 1,
}, {
name: "Don't change a degraded node to same config, but also don't start another",
progress: 1,
nodes: []*corev1.Node{
helpers.NewNodeWithReady("node-0", machineConfigV1, machineConfigV1, corev1.ConditionTrue),
newNodeWithReadyAndDaemonState("node-1", machineConfigV1, machineConfigV1, corev1.ConditionTrue, daemonconsts.MachineConfigDaemonStateDegraded),
helpers.NewNodeWithReady("node-2", machineConfigV0, machineConfigV0, corev1.ConditionTrue),
},
expected: []string{},
otherCandidates: nil,
capacity: 0,
}, {
name: "Must be able to roll back",
progress: 1,
nodes: []*corev1.Node{
helpers.NewNodeWithReady("node-0", machineConfigV1, machineConfigV1, corev1.ConditionTrue),
helpers.NewNodeWithReady("node-1", machineConfigV1, machineConfigV1, corev1.ConditionTrue),
newNodeWithReadyAndDaemonState("node-2", machineConfigV1, machineConfigV2, corev1.ConditionTrue, daemonconsts.MachineConfigDaemonStateDegraded),
helpers.NewNodeWithReady("node-3", machineConfigV1, machineConfigV1, corev1.ConditionTrue),
},
expected: []string{"node-2"},
otherCandidates: nil,
capacity: 1,
}, {
name: "Validate we also don't affect nodes which haven't started work",
progress: 1,
nodes: []*corev1.Node{
helpers.NewNodeWithReady("node-0", machineConfigV1, machineConfigV1, corev1.ConditionTrue),
newNodeWithReadyAndDaemonState("node-2", machineConfigV1, machineConfigV2, corev1.ConditionTrue, daemonconsts.MachineConfigDaemonStateDone),
helpers.NewNodeWithReady("node-3", machineConfigV1, machineConfigV1, corev1.ConditionTrue),
},
expected: []string{},
otherCandidates: nil,
capacity: 0,
}, {
name: "More nodes in mixed order",
progress: 4,
nodes: []*corev1.Node{
helpers.NewNodeWithReady("node-0", machineConfigV1, machineConfigV1, corev1.ConditionTrue),
helpers.NewNodeWithReady("node-1", machineConfigV1, machineConfigV1, corev1.ConditionFalse),
helpers.NewNodeWithReady("node-2", machineConfigV0, machineConfigV1, corev1.ConditionTrue),
helpers.NewNodeWithReady("node-3", machineConfigV0, machineConfigV0, corev1.ConditionTrue),
helpers.NewNodeWithReady("node-4", machineConfigV0, machineConfigV0, corev1.ConditionTrue),
helpers.NewNodeWithReady("node-5", machineConfigV0, machineConfigV0, corev1.ConditionTrue),
helpers.NewNodeWithReady("node-6", machineConfigV0, machineConfigV0, corev1.ConditionTrue),
helpers.NewNodeWithReady("node-7", machineConfigV1, machineConfigV1, corev1.ConditionTrue),
helpers.NewNodeWithReady("node-8", machineConfigV1, machineConfigV1, corev1.ConditionTrue),
},
expected: []string{"node-3", "node-4"},
otherCandidates: []string{"node-5", "node-6"},
capacity: 2,
}, {
name: "Layered nodes in mixed order",
progress: 4,
nodes: []*corev1.Node{
helpers.NewNodeBuilder("node-0").WithEqualConfigsAndImages(machineConfigV1, imageV1).WithNodeReady().Node(),
helpers.NewNodeBuilder("node-1").WithEqualConfigsAndImages(machineConfigV1, imageV1).WithNodeNotReady().Node(),
helpers.NewNodeBuilder("node-2").WithConfigs(machineConfigV0, machineConfigV1).WithImages(imageV0, imageV1).WithNodeReady().Node(),
helpers.NewNodeBuilder("node-3").WithEqualConfigsAndImages(machineConfigV0, imageV0).WithNodeNotReady().Node(),
helpers.NewNodeBuilder("node-4").WithEqualConfigsAndImages(machineConfigV0, imageV0).WithNodeReady().Node(),
helpers.NewNodeBuilder("node-5").WithEqualConfigsAndImages(machineConfigV0, imageV0).WithNodeReady().Node(),
helpers.NewNodeBuilder("node-6").WithEqualConfigsAndImages(machineConfigV0, imageV0).WithNodeReady().Node(),
helpers.NewNodeBuilder("node-7").WithEqualConfigsAndImages(machineConfigV1, imageV1).WithNodeReady().Node(),
helpers.NewNodeBuilder("node-8").WithEqualConfigsAndImages(machineConfigV1, imageV1).WithNodeReady().Node(),
},
expected: []string{"node-4"},
otherCandidates: []string{"node-5", "node-6"},
capacity: 1,
layered: true,
mosc: helpers.NewMachineOSConfigBuilder("mosc-1").WithCurrentImagePullspec(imageV1).MachineOSConfig(),
mosb: helpers.NewMachineOSBuildBuilder("mosb-1").WithDesiredConfig(machineConfigV1).MachineOSBuild(),
}, {
// Targets https://issues.redhat.com/browse/OCPBUGS-24705.
name: "Node has received desiredImage annotation but MCD has not yet started working",
progress: 1,
nodes: []*corev1.Node{
// Need to set WithNodeReady() on all nodes to avoid short-circuiting.
helpers.NewNodeBuilder("node-0").
WithEqualConfigs(machineConfigV1).
WithDesiredImage(imageV1).
WithNodeReady().
WithMCDState(daemonconsts.MachineConfigDaemonStateDone).
Node(),
helpers.NewNodeBuilder("node-1").
WithEqualConfigs(machineConfigV1).
WithNodeReady().
WithMCDState(daemonconsts.MachineConfigDaemonStateDone).
Node(),
helpers.NewNodeBuilder("node-2").
WithEqualConfigs(machineConfigV1).
WithNodeReady().
WithMCDState(daemonconsts.MachineConfigDaemonStateDone).
Node(),
},
expected: []string{},
otherCandidates: nil,
capacity: 0,
layered: true,
mosc: helpers.NewMachineOSConfigBuilder("mosc-1").WithCurrentImagePullspec(imageV1).MachineOSConfig(),
mosb: helpers.NewMachineOSBuildBuilder("mosb-1").WithDesiredConfig(machineConfigV1).MachineOSBuild(),
}, {
// Targets https://issues.redhat.com/browse/OCPBUGS-24705.
name: "Node has received desiredImage annotation and the MCD has started working",
progress: 1,
nodes: []*corev1.Node{
// Need to set WithNodeReady() on all nodes to avoid short-circuiting.
helpers.NewNodeBuilder("node-0").
WithEqualConfigs(machineConfigV1).
WithDesiredImage(imageV1).
WithNodeReady().
WithMCDState(daemonconsts.MachineConfigDaemonStateWorking).
Node(),
helpers.NewNodeBuilder("node-1").
WithEqualConfigs(machineConfigV1).
WithNodeReady().
WithMCDState(daemonconsts.MachineConfigDaemonStateDone).
Node(),
helpers.NewNodeBuilder("node-2").
WithEqualConfigs(machineConfigV1).
WithNodeReady().
WithMCDState(daemonconsts.MachineConfigDaemonStateDone).
Node(),
},
expected: []string{},
otherCandidates: nil,
capacity: 0,
layered: true,
mosc: helpers.NewMachineOSConfigBuilder("mosc-1").WithCurrentImagePullspec(imageV1).MachineOSConfig(),
mosb: helpers.NewMachineOSBuildBuilder("mosb-1").WithDesiredConfig(machineConfigV1).MachineOSBuild(),
}, {
// Targets https://issues.redhat.com//browse/OCPBUGS-43552.
name: "Node is rolling back from layered mode but MCD has not yet started working",
progress: 1,
nodes: []*corev1.Node{
// Need to set WithNodeReady() on all nodes to avoid short-circuiting.
helpers.NewNodeBuilder("node-0").WithEqualConfigs(machineConfigV1).
WithCurrentImage(imageV1).
WithNodeReady().
WithMCDState(daemonconsts.MachineConfigDaemonStateDone).
Node(),
helpers.NewNodeBuilder("node-1").
WithEqualConfigs(machineConfigV1).
WithNodeReady().
WithMCDState(daemonconsts.MachineConfigDaemonStateDone).
Node(),
helpers.NewNodeBuilder("node-2").
WithEqualConfigs(machineConfigV1).
WithNodeReady().
WithMCDState(daemonconsts.MachineConfigDaemonStateDone).
Node(),
},
expected: []string{},
otherCandidates: nil,
capacity: 0,
layered: false,
}, {
// Targets https://issues.redhat.com//browse/OCPBUGS-43552.
name: "Node is rolling back from layered mode and the MCD has started working",
progress: 1,
nodes: []*corev1.Node{
// Need to set WithNodeReady() on all nodes to avoid short-circuiting.
helpers.NewNodeBuilder("node-0").
WithEqualConfigs(machineConfigV1).
WithCurrentImage(imageV1).
WithNodeReady().
WithMCDState(daemonconsts.MachineConfigDaemonStateWorking).
Node(),
helpers.NewNodeBuilder("node-1").
WithEqualConfigs(machineConfigV1).
WithNodeReady().
WithMCDState(daemonconsts.MachineConfigDaemonStateDone).
Node(),
helpers.NewNodeBuilder("node-2").
WithEqualConfigs(machineConfigV1).
WithNodeReady().
WithMCDState(daemonconsts.MachineConfigDaemonStateDone).
Node(),
},
expected: []string{},
otherCandidates: nil,
capacity: 0,
layered: false,
},
}
for _, test := range tests {
test := test
t.Run(test.name, func(t *testing.T) {
t.Parallel()
pool := helpers.NewMachineConfigPoolBuilder("").WithMachineConfig(machineConfigV1).MachineConfigPool()
allCandidates, capacity := getAllCandidateMachines(test.layered, test.mosc, test.mosb, pool, test.nodes, test.progress)
assert.Equal(t, test.capacity, capacity)
var candidates, currentCandidates, otherCandidates []string
candidates = helpers.GetNamesFromNodes(allCandidates)
// Divide candidates list by capacity if there are more candidates than capacity count
if capacity < uint(len(allCandidates)) {
currentCandidates = candidates[:capacity]
otherCandidates = candidates[capacity:]
} else {
currentCandidates = candidates
otherCandidates = nil
}
assert.Equal(t, test.expected, currentCandidates)
assert.Equal(t, test.otherCandidates, otherCandidates)
})
}
}
func assertNodeDoesNotHaveAnnotations(t *testing.T, client *k8sfake.Clientset, nodeName string, annoKeys []string) {
t.Helper()
node, err := client.CoreV1().Nodes().Get(context.TODO(), nodeName, metav1.GetOptions{})
require.NoError(t, err)
for _, key := range annoKeys {
assert.NotContains(t, node.Annotations, key)
}
}
func assertNodeHasAnnotations(t *testing.T, client *k8sfake.Clientset, nodeName string, annos map[string]string) {
t.Helper()
node, err := client.CoreV1().Nodes().Get(context.TODO(), nodeName, metav1.GetOptions{})
require.NoError(t, err)
for k, v := range annos {
assert.Contains(t, node.Annotations, k)
assert.Equal(t, v, node.Annotations[k])
}
if t.Failed() {
helpers.DumpNodesAndPools(t, []*corev1.Node{node}, nil)
}
}
func assertNodeGetsAnnotations(t *testing.T, actions []core.Action, annos map[string]string) {
if !assert.Equal(t, 2, len(actions)) {
t.Fatal("actions")
}
if !actions[0].Matches("get", "nodes") || actions[0].(core.GetAction).GetName() != "node-0" {
t.Fatal(actions)
}
if !actions[1].Matches("patch", "nodes") {
t.Fatal(actions)
}
expected := map[string]interface{}{
"metadata": map[string]interface{}{
"annotations": annos,
},
}
expectedBytes, err := json.Marshal(expected)
require.NoError(t, err)
actual := actions[1].(core.PatchAction).GetPatch()
assert.JSONEq(t, string(expectedBytes), string(actual))
}
func assertPatchesNode0ToV1(t *testing.T, actions []core.Action) {
assertNodeGetsAnnotations(t, actions, map[string]string{
daemonconsts.DesiredMachineConfigAnnotationKey: machineConfigV1,
})
}
func TestUpdateCandidates(t *testing.T) {
t.Parallel()
tests := []struct {
name string
node *corev1.Node
pool *mcfgv1.MachineConfigPool
extraannos map[string]string
mosc *mcfgv1.MachineOSConfig
mosb *mcfgv1.MachineOSBuild
layered bool
verify func([]core.Action, *testing.T)
verifyAPI func(*testing.T, *k8sfake.Clientset)
}{{
name: "Node has no annotations",
node: newNode("node-0", "", ""),
verify: func(actions []core.Action, t *testing.T) {
assertPatchesNode0ToV1(t, actions)
},
}, {
name: "Node has no MachineConfig annotations",
node: newNode("node-0", "", ""),
extraannos: map[string]string{"test": "extra-annotation"},
verify: func(actions []core.Action, t *testing.T) {
assertPatchesNode0ToV1(t, actions)
},
}, {
name: "Node has current MachineConfig annotation only",
node: newNode("node-0", machineConfigV0, ""),
verify: func(actions []core.Action, t *testing.T) {
assertPatchesNode0ToV1(t, actions)
},
}, {
name: "Node has current MachineConfig annotation and extra ones",
node: newNode("node-0", machineConfigV0, ""),
extraannos: map[string]string{"test": "extra-annotation"},
verify: func(actions []core.Action, t *testing.T) {
assertPatchesNode0ToV1(t, actions)
},
}, {
name: "Node has both current and desired MachineConfig annotations",
node: newNode("node-0", machineConfigV0, machineConfigV0),
verify: func(actions []core.Action, t *testing.T) {
assertPatchesNode0ToV1(t, actions)
},
}, {
name: "Node has current and desired MachineConfig annotations and extra annotations",
node: newNode("node-0", machineConfigV0, machineConfigV0),