-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontroller_test.go
1033 lines (889 loc) · 39.1 KB
/
controller_test.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
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
/*
* Copyright (c) 2024. ECCO Data & AI Open-Source Project Maintainers.
*
* 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 main
import (
"context"
"github.com/SneaksAndData/nexus-core/pkg/generated/clientset/versioned/fake"
sharding "github.com/SneaksAndData/nexus-core/pkg/shards"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/diff"
kubeinformers "k8s.io/client-go/informers"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/tools/record"
ktesting "k8s.io/klog/v2/ktesting"
"reflect"
"testing"
"time"
nexuscontroller "github.com/SneaksAndData/nexus-core/pkg/apis/science/v1"
informers "github.com/SneaksAndData/nexus-core/pkg/generated/informers/externalversions"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
k8sfake "k8s.io/client-go/kubernetes/fake"
core "k8s.io/client-go/testing"
)
var (
alwaysReady = func() bool { return true }
noResyncPeriodFunc = func() time.Duration { return 0 }
)
type FakeInformers struct {
nexusInformers informers.SharedInformerFactory
k8sInformers kubeinformers.SharedInformerFactory
}
type FakeControllerInformers = FakeInformers
type FakeShardInformers = FakeInformers
type ApiFixture struct {
mlaListResults []*nexuscontroller.MachineLearningAlgorithm
secretListResults []*corev1.Secret
configMapListResults []*corev1.ConfigMap
existingCoreObjects []runtime.Object
existingMlaObjects []runtime.Object
}
type ControllerFixture = ApiFixture
type NexusFixture = ApiFixture
type fixture struct {
t *testing.T
controllerNexusClient *fake.Clientset
controllerKubeClient *k8sfake.Clientset
shardNexusClient *fake.Clientset
shardKubeClient *k8sfake.Clientset
// Objects to put in the store for controller cluster
mlaLister []*nexuscontroller.MachineLearningAlgorithm
secretLister []*corev1.Secret
configMapLister []*corev1.ConfigMap
// Objects to put in the store for shard cluster
shardMlaLister []*nexuscontroller.MachineLearningAlgorithm
shardSecretLister []*corev1.Secret
shardConfigLister []*corev1.ConfigMap
// Actions expected to happen on the controller and shard clients respectively.
controllerKubeActions []core.Action
controllerNexusActions []core.Action
shardKubeActions []core.Action
shardNexusActions []core.Action
// Objects from here preloaded into NewSimpleFake for controller and a shard.
controllerKubeObjects []runtime.Object
controllerObjects []runtime.Object
shardKubeObjects []runtime.Object
shardObjects []runtime.Object
}
func newFixture(t *testing.T) *fixture {
f := &fixture{}
f.t = t
f.mlaLister = []*nexuscontroller.MachineLearningAlgorithm{}
f.secretLister = []*corev1.Secret{}
f.configMapLister = []*corev1.ConfigMap{}
f.controllerObjects = []runtime.Object{}
f.controllerKubeObjects = []runtime.Object{}
f.shardMlaLister = []*nexuscontroller.MachineLearningAlgorithm{}
f.shardSecretLister = []*corev1.Secret{}
f.shardConfigLister = []*corev1.ConfigMap{}
f.shardObjects = []runtime.Object{}
f.shardKubeObjects = []runtime.Object{}
return f
}
// configure adds necessary mock return results for Kubernetes API calls for the respective listers
// and adds existing objects to the respective containers
func (f *fixture) configure(controllerFixture *ControllerFixture, nexusShardFixture *NexusFixture) *fixture {
f.mlaLister = append(f.mlaLister, controllerFixture.mlaListResults...)
f.secretLister = append(f.secretLister, controllerFixture.secretListResults...)
f.configMapLister = append(f.configMapLister, controllerFixture.configMapListResults...)
f.controllerObjects = append(f.controllerObjects, controllerFixture.existingMlaObjects...)
f.controllerKubeObjects = append(f.controllerKubeObjects, controllerFixture.existingCoreObjects...)
f.shardMlaLister = append(f.shardMlaLister, nexusShardFixture.mlaListResults...)
f.shardSecretLister = append(f.shardSecretLister, nexusShardFixture.secretListResults...)
f.shardConfigLister = append(f.shardConfigLister, nexusShardFixture.configMapListResults...)
f.shardObjects = append(f.shardObjects, nexusShardFixture.existingMlaObjects...)
f.shardKubeObjects = append(f.shardKubeObjects, nexusShardFixture.existingCoreObjects...)
return f
}
func int32Ptr(i int32) *int32 { return &i }
func expectedMla(mla *nexuscontroller.MachineLearningAlgorithm, secret *corev1.Secret, configMap *corev1.ConfigMap, syncedTo []string, conditions []metav1.Condition) *nexuscontroller.MachineLearningAlgorithm {
mlaCopy := mla.DeepCopy()
mlaCopy.Status.Conditions = conditions
if secret != nil {
mlaCopy.Status.SyncedSecrets = []string{secret.Name}
}
if configMap != nil {
mlaCopy.Status.SyncedConfigurations = []string{configMap.Name}
}
if syncedTo != nil {
mlaCopy.Status.SyncedToClusters = syncedTo
}
return mlaCopy
}
func expectedLabels() map[string]string {
return map[string]string{
"science.sneaksanddata.com/controller-app": "nexus-configuration-controller",
"science.sneaksanddata.com/configuration-owner": "test-controller-cluster",
}
}
func expectedShardMla(mla *nexuscontroller.MachineLearningAlgorithm, uid string) *nexuscontroller.MachineLearningAlgorithm {
mlaCopy := mla.DeepCopy()
mlaCopy.UID = types.UID(uid)
mlaCopy.Labels = expectedLabels()
return mlaCopy
}
func expectedShardSecret(secret *corev1.Secret, mlas []*nexuscontroller.MachineLearningAlgorithm) *corev1.Secret {
secretCopy := secret.DeepCopy()
secretCopy.Labels = expectedLabels()
secretCopy.OwnerReferences = make([]metav1.OwnerReference, 0)
for _, mla := range mlas {
secretCopy.OwnerReferences = append(secretCopy.OwnerReferences, metav1.OwnerReference{
APIVersion: nexuscontroller.SchemeGroupVersion.String(),
Kind: "MachineLearningAlgorithm",
Name: mla.Name,
UID: mla.UID,
})
}
return secretCopy
}
func expectedShardConfigMap(configMap *corev1.ConfigMap, mlas []*nexuscontroller.MachineLearningAlgorithm) *corev1.ConfigMap {
configMapCopy := configMap.DeepCopy()
configMapCopy.Labels = expectedLabels()
configMapCopy.OwnerReferences = make([]metav1.OwnerReference, 0)
for _, mla := range mlas {
configMapCopy.OwnerReferences = append(configMapCopy.OwnerReferences, metav1.OwnerReference{
APIVersion: nexuscontroller.SchemeGroupVersion.String(),
Kind: "MachineLearningAlgorithm",
Name: mla.Name,
UID: mla.UID,
})
}
return configMapCopy
}
func newMla(name string, secret *corev1.Secret, configMap *corev1.ConfigMap, onShard bool, status *nexuscontroller.MachineLearningAlgorithmStatus) *nexuscontroller.MachineLearningAlgorithm {
envFrom := make([]corev1.EnvFromSource, 2)
cargs := make([]string, 1)
var labels map[string]string
if onShard {
labels = expectedLabels()
}
cargs[0] = "job.py"
if secret != nil {
envFrom[0] = corev1.EnvFromSource{
SecretRef: &corev1.SecretEnvSource{
LocalObjectReference: corev1.LocalObjectReference{Name: secret.Name},
},
}
}
if configMap != nil {
envFrom[1] = corev1.EnvFromSource{
ConfigMapRef: &corev1.ConfigMapEnvSource{
LocalObjectReference: corev1.LocalObjectReference{Name: configMap.Name},
},
}
}
mla := &nexuscontroller.MachineLearningAlgorithm{
TypeMeta: metav1.TypeMeta{APIVersion: nexuscontroller.SchemeGroupVersion.String()},
ObjectMeta: metav1.ObjectMeta{
Name: name,
Namespace: metav1.NamespaceDefault,
Labels: labels,
UID: types.UID(name),
},
Spec: nexuscontroller.MachineLearningAlgorithmSpec{
ImageRegistry: "test",
ImageRepository: "test",
ImageTag: "v1.0.0",
DeadlineSeconds: int32Ptr(120),
MaximumRetries: int32Ptr(3),
Env: make([]corev1.EnvVar, 0),
EnvFrom: envFrom,
CpuLimit: "1000m",
MemoryLimit: "2000Mi",
WorkgroupHost: "test-cluster.io",
Workgroup: "default",
AdditionalWorkgroups: make(map[string]string),
MonitoringParameters: make([]string, 0),
CustomResources: make(map[string]string),
SpeculativeAttempts: int32Ptr(0),
TransientExitCodes: make([]int32, 0),
FatalExitCodes: make([]int32, 0),
Command: "python",
Args: cargs,
MountDatadogSocket: true,
},
}
if status != nil {
mla.Status = *status
}
return mla
}
func newSecret(name string, owner *nexuscontroller.MachineLearningAlgorithm) *corev1.Secret {
secret := corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Namespace: metav1.NamespaceDefault,
},
Data: make(map[string][]byte),
Type: "",
}
if owner != nil {
secret.SetOwnerReferences([]metav1.OwnerReference{
{
APIVersion: nexuscontroller.SchemeGroupVersion.String(),
Kind: "MachineLearningAlgorithm",
Name: owner.Name,
UID: owner.UID,
},
})
}
return &secret
}
func newConfigMap(name string, owner *nexuscontroller.MachineLearningAlgorithm) *corev1.ConfigMap {
configMap := corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Namespace: metav1.NamespaceDefault,
},
Data: make(map[string]string),
}
if owner != nil {
configMap.SetOwnerReferences([]metav1.OwnerReference{
{
APIVersion: nexuscontroller.SchemeGroupVersion.String(),
Kind: "MachineLearningAlgorithm",
Name: owner.Name,
UID: owner.UID,
},
})
}
return &configMap
}
// 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 reflect.TypeOf(actual) != reflect.TypeOf(expected) {
t.Errorf("Action has wrong type. Expected: %t. Got: %t", expected, actual)
return
}
switch a := actual.(type) {
case core.CreateActionImpl:
e, _ := expected.(core.CreateActionImpl)
expObject := e.GetObject()
object := a.GetObject()
if !reflect.DeepEqual(expObject, object) {
t.Errorf("Action %s %s has wrong object\nDiff:\n %s",
a.GetVerb(), a.GetResource().Resource, diff.ObjectGoPrintSideBySide(expObject, object))
}
case core.UpdateActionImpl:
e, _ := expected.(core.UpdateActionImpl)
expObject := e.GetObject()
object := a.GetObject()
switch expObject.(type) {
case *nexuscontroller.MachineLearningAlgorithm:
// avoid issues with time drift
currentTime := metav1.Now()
expCopy := expObject.DeepCopyObject().(*nexuscontroller.MachineLearningAlgorithm)
for ix := range expCopy.Status.Conditions {
expCopy.Status.Conditions[ix].LastTransitionTime = currentTime
}
objCopy := object.DeepCopyObject().(*nexuscontroller.MachineLearningAlgorithm)
for ix := range objCopy.Status.Conditions {
objCopy.Status.Conditions[ix].LastTransitionTime = currentTime
}
if !reflect.DeepEqual(expCopy, objCopy) {
t.Errorf("Action %s %s has wrong object\nDiff:\n %s",
a.GetVerb(), a.GetResource().Resource, diff.ObjectGoPrintSideBySide(expCopy, objCopy))
}
default:
if !reflect.DeepEqual(expObject, object) {
t.Errorf("Action %s %s has wrong object\nDiff:\n %s",
a.GetVerb(), a.GetResource().Resource, diff.ObjectGoPrintSideBySide(expObject, object))
}
}
case core.PatchActionImpl:
e, _ := expected.(core.PatchActionImpl)
expPatch := e.GetPatch()
patch := a.GetPatch()
if !reflect.DeepEqual(expPatch, patch) {
t.Errorf("Action %s %s has wrong patch\nDiff:\n %s",
a.GetVerb(), a.GetResource().Resource, diff.ObjectGoPrintSideBySide(expPatch, patch))
}
case core.DeleteActionImpl:
e, _ := expected.(core.DeleteActionImpl)
if e.GetName() != a.GetName() || e.GetNamespace() != a.GetNamespace() {
t.Errorf("Action %s targets wrong resource %s/%s, should target %s/%s", a.GetVerb(), a.GetNamespace(), a.GetName(), e.GetNamespace(), e.GetName())
}
default:
t.Errorf("Uncaptured Action %s %s, you should explicitly add a case to capture it",
actual.GetVerb(), actual.GetResource().Resource)
}
}
// 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", "machinelearningalgorithms") ||
action.Matches("watch", "machinelearningalgorithms") ||
action.Matches("list", "configmaps") ||
action.Matches("watch", "configmaps") ||
action.Matches("list", "secrets") ||
action.Matches("watch", "secrets")) {
continue
}
ret = append(ret, action)
}
return ret
}
func (f *fixture) newController(ctx context.Context) (*Controller, *FakeControllerInformers, *FakeShardInformers) {
f.controllerNexusClient = fake.NewSimpleClientset(f.controllerObjects...)
f.controllerKubeClient = k8sfake.NewSimpleClientset(f.controllerKubeObjects...)
f.shardNexusClient = fake.NewSimpleClientset(f.shardObjects...)
f.shardKubeClient = k8sfake.NewSimpleClientset(f.shardKubeObjects...)
controllerNexusInf := informers.NewSharedInformerFactory(f.controllerNexusClient, noResyncPeriodFunc())
controllerKubeInf := kubeinformers.NewSharedInformerFactory(f.controllerKubeClient, noResyncPeriodFunc())
shardNexusInf := informers.NewSharedInformerFactory(f.shardNexusClient, noResyncPeriodFunc())
shardKubeInf := kubeinformers.NewSharedInformerFactory(f.shardKubeClient, noResyncPeriodFunc())
shards := make([]*sharding.Shard, 0)
newShard := sharding.NewShard(
"test-controller-cluster",
"shard0",
f.shardKubeClient,
f.shardNexusClient,
shardNexusInf.Science().V1().MachineLearningAlgorithms(),
shardKubeInf.Core().V1().Secrets(),
shardKubeInf.Core().V1().ConfigMaps())
newShard.MlaSynced = alwaysReady
newShard.SecretsSynced = alwaysReady
newShard.ConfigMapsSynced = alwaysReady
shards = append(shards, newShard)
c, _ := NewController(
ctx,
"test",
f.controllerKubeClient,
f.controllerNexusClient,
shards,
controllerKubeInf.Core().V1().Secrets(),
controllerKubeInf.Core().V1().ConfigMaps(),
controllerNexusInf.Science().V1().MachineLearningAlgorithms(),
30*time.Millisecond,
5*time.Second,
50,
300,
)
c.mlaSynced = alwaysReady
c.secretsSynced = alwaysReady
c.configMapsSynced = alwaysReady
c.recorder = &record.FakeRecorder{}
for _, d := range f.mlaLister {
_ = controllerNexusInf.Science().V1().MachineLearningAlgorithms().Informer().GetIndexer().Add(d)
}
for _, d := range f.shardMlaLister {
_ = shardNexusInf.Science().V1().MachineLearningAlgorithms().Informer().GetIndexer().Add(d)
}
for _, d := range f.secretLister {
_ = controllerKubeInf.Core().V1().Secrets().Informer().GetIndexer().Add(d)
}
for _, d := range f.shardSecretLister {
_ = shardKubeInf.Core().V1().Secrets().Informer().GetIndexer().Add(d)
}
for _, d := range f.shardConfigLister {
_ = shardKubeInf.Core().V1().ConfigMaps().Informer().GetIndexer().Add(d)
}
for _, d := range f.configMapLister {
_ = controllerKubeInf.Core().V1().ConfigMaps().Informer().GetIndexer().Add(d)
}
return c, &FakeControllerInformers{
nexusInformers: controllerNexusInf,
k8sInformers: controllerKubeInf,
},
&FakeShardInformers{
nexusInformers: shardNexusInf,
k8sInformers: shardKubeInf,
}
}
func (f *fixture) checkActions(expected []core.Action, actual []core.Action) {
actions := filterInformerActions(actual)
for i, action := range actions {
if len(expected) < i+1 {
f.t.Errorf("%d unexpected actions: %+v", len(actions)-len(expected), actions[i:])
break
}
expectedAction := expected[i]
checkAction(expectedAction, action, f.t)
}
if len(expected) > len(actions) {
f.t.Errorf("%d additional expected actions:%+v", len(expected)-len(actions), expected[len(actions):])
}
}
func (f *fixture) runController(ctx context.Context, mlaRefs []cache.ObjectName, startInformers bool, expectError bool) {
controllerRef, controllerInformers, shardInformers := f.newController(ctx)
if startInformers {
controllerInformers.nexusInformers.Start(ctx.Done())
controllerInformers.k8sInformers.Start(ctx.Done())
shardInformers.nexusInformers.Start(ctx.Done())
shardInformers.k8sInformers.Start(ctx.Done())
}
for _, mlaRef := range mlaRefs {
err := controllerRef.syncHandler(ctx, mlaRef)
if !expectError && err != nil {
f.t.Errorf("error syncing mla: %v", err)
} else if expectError && err == nil {
f.t.Error("expected error syncing mla, got nil")
}
}
f.checkActions(f.controllerNexusActions, f.controllerNexusClient.Actions())
f.checkActions(f.shardNexusActions, f.shardNexusClient.Actions())
f.checkActions(f.shardKubeActions, f.shardKubeClient.Actions())
f.checkActions(f.controllerKubeActions, f.controllerKubeClient.Actions())
}
func (f *fixture) runObjectHandler(ctx context.Context, objs []interface{}, startInformers bool) {
controllerRef, controllerInformers, shardInformers := f.newController(ctx)
if startInformers {
controllerInformers.nexusInformers.Start(ctx.Done())
controllerInformers.k8sInformers.Start(ctx.Done())
shardInformers.nexusInformers.Start(ctx.Done())
shardInformers.k8sInformers.Start(ctx.Done())
}
for _, obj := range objs {
controllerRef.handleObject(obj)
}
f.checkActions(f.shardNexusActions, f.shardNexusClient.Actions())
f.checkActions(f.shardKubeActions, f.shardKubeClient.Actions())
}
func (f *fixture) run(ctx context.Context, mlaRefs []cache.ObjectName, expectError bool) {
f.runController(ctx, mlaRefs, true, expectError)
}
func getRef(mla *nexuscontroller.MachineLearningAlgorithm) cache.ObjectName {
ref := cache.MetaObjectToName(mla)
return ref
}
// expectControllerUpdateMlaStatusAction sets expectations for the resource actions in a controller cluster
// for MLA in the controller cluster we only expect a status update
func (f *fixture) expectControllerUpdateMlaStatusAction(mla *nexuscontroller.MachineLearningAlgorithm) {
updateMlaStatusAction := core.NewUpdateSubresourceAction(schema.GroupVersionResource{Resource: "machinelearningalgorithms"}, "status", mla.Namespace, mla)
f.controllerNexusActions = append(f.controllerNexusActions, updateMlaStatusAction)
}
// expectShardActions sets expectations for the resource actions in a shard cluster
// for resources in the shard cluster we expect the following: MLA is created, all referenced secrets and configmaps are created, with owner references assigned
func (f *fixture) expectShardActions(shardMla *nexuscontroller.MachineLearningAlgorithm, mlaSecret *corev1.Secret, mlaConfigMap *corev1.ConfigMap, mlaUpdated bool) {
if !mlaUpdated {
f.shardNexusActions = append(f.shardNexusActions, core.NewCreateAction(schema.GroupVersionResource{Resource: "machinelearningalgorithms"}, shardMla.Namespace, shardMla))
} else {
f.shardNexusActions = append(f.shardNexusActions, core.NewUpdateAction(schema.GroupVersionResource{Resource: "machinelearningalgorithms"}, shardMla.Namespace, shardMla))
}
if mlaSecret != nil {
f.shardKubeActions = append(f.shardKubeActions, core.NewCreateAction(schema.GroupVersionResource{Resource: "secrets", Version: "v1"}, mlaSecret.Namespace, mlaSecret))
}
if mlaConfigMap != nil {
f.shardKubeActions = append(f.shardKubeActions, core.NewCreateAction(schema.GroupVersionResource{Resource: "configmaps", Version: "v1"}, mlaConfigMap.Namespace, mlaConfigMap))
}
}
func (f *fixture) expectOwnershipUpdateActions(mlaSecret *corev1.Secret, mlaConfigMap *corev1.ConfigMap) {
if mlaSecret != nil {
f.shardKubeActions = append(f.shardKubeActions, core.NewUpdateAction(schema.GroupVersionResource{Resource: "secrets", Version: "v1"}, mlaSecret.Namespace, mlaSecret))
}
if mlaConfigMap != nil {
f.shardKubeActions = append(f.shardKubeActions, core.NewUpdateAction(schema.GroupVersionResource{Resource: "configmaps", Version: "v1"}, mlaConfigMap.Namespace, mlaConfigMap))
}
}
// expectedUpdateActions sets expectations for the resource actions in a shard cluster when a referenced secret or configmap in the controller cluster is updated
func (f *fixture) expectedUpdateActions(controllerMla *nexuscontroller.MachineLearningAlgorithm, shardMla *nexuscontroller.MachineLearningAlgorithm, mlaSecret *corev1.Secret, mlaConfigMap *corev1.ConfigMap, controllerStatusUpdated bool) {
updatedSecretAction := core.NewUpdateAction(schema.GroupVersionResource{Resource: "secrets", Version: "v1"}, shardMla.Namespace, mlaSecret)
updatedConfigAction := core.NewUpdateAction(schema.GroupVersionResource{Resource: "configmaps", Version: "v1"}, shardMla.Namespace, mlaConfigMap)
if controllerStatusUpdated {
f.controllerNexusActions = append(f.controllerNexusActions, core.NewUpdateSubresourceAction(schema.GroupVersionResource{Resource: "machinelearningalgorithms"}, "status", controllerMla.Namespace, controllerMla))
}
f.shardKubeActions = append(f.shardKubeActions, updatedSecretAction, updatedConfigAction)
}
// expectedUpdateActions sets expectations for the resource actions in a shard cluster when a referenced secret or configmap in the controller cluster is updated
func (f *fixture) expectedControllerUpdateActions(controllerMla *nexuscontroller.MachineLearningAlgorithm, mlaSecret *corev1.Secret, mlaConfigMap *corev1.ConfigMap, controllerStatusUpdated bool) {
updatedSecretAction := core.NewUpdateAction(schema.GroupVersionResource{Resource: "secrets", Version: "v1"}, controllerMla.Namespace, mlaSecret)
updatedConfigAction := core.NewUpdateAction(schema.GroupVersionResource{Resource: "configmaps", Version: "v1"}, controllerMla.Namespace, mlaConfigMap)
if controllerStatusUpdated {
f.controllerNexusActions = append(f.controllerNexusActions, core.NewUpdateSubresourceAction(schema.GroupVersionResource{Resource: "machinelearningalgorithms"}, "status", controllerMla.Namespace, controllerMla))
}
f.controllerKubeActions = append(f.controllerKubeActions, updatedSecretAction, updatedConfigAction)
}
// expectedDeleteActions sets expectations for resource deletions
func (f *fixture) expectedDeleteActions(shardMla *nexuscontroller.MachineLearningAlgorithm) {
f.shardNexusActions = append(f.shardNexusActions, core.NewDeleteAction(schema.GroupVersionResource{Resource: "machinelearningalgorithms"}, shardMla.Namespace, shardMla.Name))
}
func provisionControllerResources() (*corev1.Secret, *corev1.ConfigMap, *nexuscontroller.MachineLearningAlgorithm) {
mlaSecret := newSecret("test-secret", nil)
mlaConfigMap := newConfigMap("test-config", nil)
mla := newMla("test", mlaSecret, mlaConfigMap, false, nil)
return mlaSecret, mlaConfigMap, mla
}
func provisionOwnedControllerResources(mlaSecret *corev1.Secret, mlaConfigMap *corev1.ConfigMap, mla *nexuscontroller.MachineLearningAlgorithm) (*corev1.Secret, *corev1.ConfigMap) {
ownedMlaSecret := mlaSecret.DeepCopy()
ownedMlaSecret.OwnerReferences = []metav1.OwnerReference{
{
APIVersion: nexuscontroller.SchemeGroupVersion.String(),
Kind: "MachineLearningAlgorithm",
Name: mla.Name,
UID: mla.UID,
},
}
ownedMlaConfigMap := mlaConfigMap.DeepCopy()
ownedMlaConfigMap.OwnerReferences = []metav1.OwnerReference{
{
APIVersion: nexuscontroller.SchemeGroupVersion.String(),
Kind: "MachineLearningAlgorithm",
Name: mla.Name,
UID: mla.UID,
},
}
return ownedMlaSecret, ownedMlaConfigMap
}
// TestCreatesMla test that resource creation results in a correct status update event for the main resource and correct resource creations in the shard cluster
func TestCreatesMla(t *testing.T) {
f := newFixture(t)
mlaSecret, mlaConfigMap, mla := provisionControllerResources()
ownedMlaSecret, ownedMlaConfigMap := provisionOwnedControllerResources(mlaSecret, mlaConfigMap, mla)
_, ctx := ktesting.NewTestContext(t)
f = f.configure(
&ControllerFixture{
mlaListResults: []*nexuscontroller.MachineLearningAlgorithm{mla},
secretListResults: []*corev1.Secret{mlaSecret},
configMapListResults: []*corev1.ConfigMap{mlaConfigMap},
existingCoreObjects: []runtime.Object{mlaSecret, mlaConfigMap},
existingMlaObjects: []runtime.Object{mla},
},
&NexusFixture{},
)
f.expectControllerUpdateMlaStatusAction(expectedMla(mla, nil, nil, nil, []metav1.Condition{
*nexuscontroller.NewResourceReadyCondition(
metav1.Now(),
metav1.ConditionFalse,
"Algorithm \"test\" initializing",
),
}))
f.expectControllerUpdateMlaStatusAction(expectedMla(mla, mlaSecret, mlaConfigMap, []string{"shard0"}, []metav1.Condition{
*nexuscontroller.NewResourceReadyCondition(
metav1.Now(),
metav1.ConditionTrue,
"Algorithm \"test\" ready",
),
}))
f.expectedControllerUpdateActions(mla, ownedMlaSecret, ownedMlaConfigMap, false)
f.expectShardActions(
expectedShardMla(mla, ""),
expectedShardSecret(mlaSecret, []*nexuscontroller.MachineLearningAlgorithm{expectedShardMla(mla, "")}),
expectedShardConfigMap(mlaConfigMap, []*nexuscontroller.MachineLearningAlgorithm{expectedShardMla(mla, "")}),
false)
f.run(ctx, []cache.ObjectName{getRef(mla)}, false)
t.Log("Controller successfully created a new MachineLearningAlgorithm and related secrets and configurations on the shard cluster")
}
// TestDetectsRogue tests the rogue secrets or configs are detected and reported as errors correctly
func TestDetectsRogue(t *testing.T) {
f := newFixture(t)
mlaSecret, mlaConfigMap, mla := provisionControllerResources()
ownedMlaSecret, ownedMlaConfigMap := provisionOwnedControllerResources(mlaSecret, mlaConfigMap, mla)
_, ctx := ktesting.NewTestContext(t)
f = f.configure(
&ControllerFixture{
mlaListResults: []*nexuscontroller.MachineLearningAlgorithm{mla},
secretListResults: []*corev1.Secret{mlaSecret},
configMapListResults: []*corev1.ConfigMap{mlaConfigMap},
existingCoreObjects: []runtime.Object{mlaSecret, mlaConfigMap},
existingMlaObjects: []runtime.Object{mla},
},
&NexusFixture{
secretListResults: []*corev1.Secret{mlaSecret},
},
)
f.expectControllerUpdateMlaStatusAction(expectedMla(mla, nil, nil, nil, []metav1.Condition{
*nexuscontroller.NewResourceReadyCondition(
metav1.Now(),
metav1.ConditionFalse,
"Algorithm \"test\" initializing",
),
}))
// no actions expected due to fail-fast approach in sync
f.expectShardActions(
expectedShardMla(mla, ""),
nil,
nil,
false)
f.expectedControllerUpdateActions(mla, ownedMlaSecret, ownedMlaConfigMap, false)
f.run(ctx, []cache.ObjectName{getRef(mla)}, true)
t.Log("Controller successfully detected a rogue resource on the shard cluster")
}
// TestHandlesNotExistingResource tests that missing Mla case is handled by the controller
func TestHandlesNotExistingResource(t *testing.T) {
f := newFixture(t)
_, _, mla := provisionControllerResources()
_, ctx := ktesting.NewTestContext(t)
f = f.configure(
&ControllerFixture{
mlaListResults: []*nexuscontroller.MachineLearningAlgorithm{},
secretListResults: []*corev1.Secret{},
configMapListResults: []*corev1.ConfigMap{},
existingCoreObjects: []runtime.Object{},
existingMlaObjects: []runtime.Object{},
},
&NexusFixture{},
)
f.run(ctx, []cache.ObjectName{getRef(mla)}, false)
t.Log("Controller successfully reported an error for the missing Mla resource")
}
// TestSkipsInvalidMla tests that resource creation is skipped with a status update in case referenced configurations do not exist
func TestSkipsInvalidMla(t *testing.T) {
f := newFixture(t)
_, _, mla := provisionControllerResources()
_, ctx := ktesting.NewTestContext(t)
f = f.configure(
&ControllerFixture{
mlaListResults: []*nexuscontroller.MachineLearningAlgorithm{mla},
secretListResults: []*corev1.Secret{},
configMapListResults: []*corev1.ConfigMap{},
existingCoreObjects: []runtime.Object{},
existingMlaObjects: []runtime.Object{mla},
},
&NexusFixture{},
)
f.expectControllerUpdateMlaStatusAction(expectedMla(mla, nil, nil, nil, []metav1.Condition{
*nexuscontroller.NewResourceReadyCondition(
metav1.Now(),
metav1.ConditionFalse,
"Algorithm \"test\" initializing",
),
}))
f.run(ctx, []cache.ObjectName{getRef(mla)}, true)
t.Log("Controller skipped a misconfigured Mla resource")
}
// TestUpdatesMlaSecretAndConfig test that update to a secret referenced by the MLA is propagated to shard clusters
func TestUpdatesMlaSecretAndConfig(t *testing.T) {
f := newFixture(t)
mlaSecret, mlaConfigMap, mla := provisionControllerResources()
ownedMlaSecret, ownedMlaConfigMap := provisionOwnedControllerResources(mlaSecret, mlaConfigMap, mla)
mlaSecretUpdated := ownedMlaSecret.DeepCopy()
mlaSecretUpdated.Data = map[string][]byte{
"secret.file": []byte("updated-secret"),
}
mlaConfigMapUpdated := ownedMlaConfigMap.DeepCopy()
mlaConfigMapUpdated.Data = map[string]string{
"new.file": "updated-config",
}
mla = newMla("test", mlaSecretUpdated, mlaConfigMapUpdated, false, &nexuscontroller.MachineLearningAlgorithmStatus{
SyncedSecrets: []string{"test-secret"},
SyncedConfigurations: []string{"test-config"},
SyncedToClusters: []string{"shard0"},
Conditions: []metav1.Condition{
*nexuscontroller.NewResourceReadyCondition(
metav1.Now(),
metav1.ConditionTrue,
"Algorithm \"test\" ready",
),
},
})
mlaOnShard := newMla("test", mlaSecret, mlaConfigMap, true, nil)
mlaSecretOnShard := newSecret("test-secret", mlaOnShard)
mlaSecretOnShardUpdated := mlaSecretOnShard.DeepCopy()
mlaSecretOnShardUpdated.Data = map[string][]byte{
"secret.file": []byte("updated-secret"),
}
mlaConfigMapOnShard := newConfigMap("test-config", mlaOnShard)
mlaConfigMapOnShardUpdated := mlaConfigMapOnShard.DeepCopy()
mlaConfigMapOnShardUpdated.Data = map[string]string{
"new.file": "updated-config",
}
_, ctx := ktesting.NewTestContext(t)
f = f.configure(
// controller lister returns a new secret and a new configmap
&ControllerFixture{
mlaListResults: []*nexuscontroller.MachineLearningAlgorithm{mla},
secretListResults: []*corev1.Secret{mlaSecretUpdated},
configMapListResults: []*corev1.ConfigMap{mlaConfigMapUpdated},
existingCoreObjects: []runtime.Object{mlaSecretUpdated, mlaConfigMapUpdated},
existingMlaObjects: []runtime.Object{mla},
},
&NexusFixture{
mlaListResults: []*nexuscontroller.MachineLearningAlgorithm{mlaOnShard},
secretListResults: []*corev1.Secret{mlaSecretOnShard},
configMapListResults: []*corev1.ConfigMap{mlaConfigMapOnShard},
existingCoreObjects: []runtime.Object{mlaSecretOnShard, mlaConfigMapOnShard},
existingMlaObjects: []runtime.Object{mlaOnShard},
},
)
// secret or cfg updates are not show in resource conditions rn
f.expectedUpdateActions(
expectedMla(mla, mlaSecretUpdated, mlaConfigMapUpdated, []string{"shard0"}, nil),
mlaOnShard, mlaSecretOnShardUpdated, mlaConfigMapOnShardUpdated, false)
f.run(ctx, []cache.ObjectName{getRef(mla)}, false)
t.Log("Controller successfully updated a Secret and a ConfigMap in the shard cluster after those were updated in the controller cluster")
}
// TestCreatesSharedResources tests that the controller can successfully create an MLA that owns the secret and configmap created by another MLA
func TestCreatesSharedResources(t *testing.T) {
f := newFixture(t)
mlaSecret := newSecret("test-secret", nil)
mlaConfigMap := newConfigMap("test-config", nil)
mla1 := newMla("test1", mlaSecret, mlaConfigMap, false, &nexuscontroller.MachineLearningAlgorithmStatus{
SyncedSecrets: []string{"test-secret"},
SyncedConfigurations: []string{"test-config"},
SyncedToClusters: []string{"shard0"},
Conditions: []metav1.Condition{
*nexuscontroller.NewResourceReadyCondition(metav1.Now(), metav1.ConditionTrue, "Algorithm \"test1\" ready"),
},
})
ownedMla1Secret, ownedMla1ConfigMap := provisionOwnedControllerResources(mlaSecret, mlaConfigMap, mla1)
mla2 := newMla("test2", mlaSecret, mlaConfigMap, false, nil)
ownedMla12Secret := ownedMla1Secret.DeepCopy()
ownedMla12Secret.OwnerReferences = append(ownedMla12Secret.OwnerReferences, metav1.OwnerReference{
APIVersion: nexuscontroller.SchemeGroupVersion.String(),
Kind: "MachineLearningAlgorithm",
Name: mla2.Name,
UID: mla2.UID,
})
ownedMla12ConfigMap := ownedMla1ConfigMap.DeepCopy()
ownedMla12ConfigMap.OwnerReferences = append(ownedMla12ConfigMap.OwnerReferences, metav1.OwnerReference{
APIVersion: nexuscontroller.SchemeGroupVersion.String(),
Kind: "MachineLearningAlgorithm",
Name: mla2.Name,
UID: mla2.UID,
})
mlaSecretOnShard1 := expectedShardSecret(mlaSecret, []*nexuscontroller.MachineLearningAlgorithm{expectedShardMla(mla1, mla1.GetName())})
mlaConfigOnShard1 := expectedShardConfigMap(mlaConfigMap, []*nexuscontroller.MachineLearningAlgorithm{expectedShardMla(mla1, mla1.GetName())})
mlaOnShard1 := expectedShardMla(mla1, mla1.GetName())
_, ctx := ktesting.NewTestContext(t)
f = f.configure(
&ControllerFixture{
mlaListResults: []*nexuscontroller.MachineLearningAlgorithm{expectedMla(mla1, mlaSecret, mlaConfigMap, []string{"shard0"}, []metav1.Condition{
*nexuscontroller.NewResourceReadyCondition(metav1.Now(), metav1.ConditionTrue, "Algorithm \"test1\" ready"),
}), mla2},
secretListResults: []*corev1.Secret{ownedMla1Secret},
configMapListResults: []*corev1.ConfigMap{ownedMla1ConfigMap},
existingCoreObjects: []runtime.Object{ownedMla1Secret, ownedMla1ConfigMap},
existingMlaObjects: []runtime.Object{expectedMla(mla1, mlaSecret, mlaConfigMap, []string{"shard0"}, []metav1.Condition{
*nexuscontroller.NewResourceReadyCondition(metav1.Now(), metav1.ConditionTrue, "Algorithm \"test1\" ready"),
}), mla2},
},
// shard cluster now has an MLA, a secret and a configmap
&NexusFixture{
mlaListResults: []*nexuscontroller.MachineLearningAlgorithm{mlaOnShard1},
secretListResults: []*corev1.Secret{mlaSecretOnShard1},
configMapListResults: []*corev1.ConfigMap{mlaConfigOnShard1},
existingCoreObjects: []runtime.Object{mlaSecretOnShard1, mlaConfigOnShard1},
existingMlaObjects: []runtime.Object{mlaOnShard1},
},
)
f.expectControllerUpdateMlaStatusAction(expectedMla(mla2, nil, nil, nil, []metav1.Condition{
*nexuscontroller.NewResourceReadyCondition(
metav1.Now(),
metav1.ConditionFalse,
"Algorithm \"test2\" initializing",
)}))
f.expectControllerUpdateMlaStatusAction(expectedMla(mla2, mlaSecret, mlaConfigMap, []string{"shard0"}, []metav1.Condition{
*nexuscontroller.NewResourceReadyCondition(
metav1.Now(),
metav1.ConditionTrue,
"Algorithm \"test2\" ready",
),
}))
f.expectedControllerUpdateActions(mla2, ownedMla12Secret, ownedMla12ConfigMap, false)
f.expectShardActions(expectedShardMla(mla2, ""), nil, nil, false)
f.expectOwnershipUpdateActions(
expectedShardSecret(mlaSecretOnShard1, []*nexuscontroller.MachineLearningAlgorithm{mlaOnShard1, expectedShardMla(mla2, "")}),
expectedShardConfigMap(mlaConfigOnShard1, []*nexuscontroller.MachineLearningAlgorithm{mlaOnShard1, expectedShardMla(mla2, "")}))
f.run(ctx, []cache.ObjectName{getRef(mla2)}, false)
t.Log("Controller successfully created a second Mla resource referencing the same Secret and ConfigMap in the controller cluster")
}
// TestTakesOwnership test verifies that controller doesn't fail if it finds an existing MLA not created by it, and simply takes ownership
func TestTakesOwnership(t *testing.T) {
f := newFixture(t)
mlaSecret, mlaConfigMap, mla := provisionControllerResources()
ownedMlaSecret, ownedMlaConfigMap := provisionOwnedControllerResources(mlaSecret, mlaConfigMap, mla)
rogueMla := expectedShardMla(mla, "")
rogueMla.Spec.MountDatadogSocket = false
_, ctx := ktesting.NewTestContext(t)
f = f.configure(
&ControllerFixture{
mlaListResults: []*nexuscontroller.MachineLearningAlgorithm{mla},
secretListResults: []*corev1.Secret{mlaSecret},
configMapListResults: []*corev1.ConfigMap{mlaConfigMap},
existingCoreObjects: []runtime.Object{mlaSecret, mlaConfigMap},
existingMlaObjects: []runtime.Object{mla},
},
&NexusFixture{
mlaListResults: []*nexuscontroller.MachineLearningAlgorithm{rogueMla},
existingMlaObjects: []runtime.Object{rogueMla},
},
)
f.expectControllerUpdateMlaStatusAction(expectedMla(mla, nil, nil, nil, []metav1.Condition{
*nexuscontroller.NewResourceReadyCondition(
metav1.Now(),
metav1.ConditionFalse,
"Algorithm \"test\" initializing",
)}))
f.expectControllerUpdateMlaStatusAction(expectedMla(mla, mlaSecret, mlaConfigMap, []string{"shard0"}, []metav1.Condition{
*nexuscontroller.NewResourceReadyCondition(
metav1.Now(),
metav1.ConditionTrue,
"Algorithm \"test\" ready",
),
}))
f.expectedControllerUpdateActions(mla, ownedMlaSecret, ownedMlaConfigMap, false)
f.expectShardActions(
expectedShardMla(mla, ""),
expectedShardSecret(mlaSecret, []*nexuscontroller.MachineLearningAlgorithm{expectedShardMla(mla, "")}),
expectedShardConfigMap(mlaConfigMap, []*nexuscontroller.MachineLearningAlgorithm{expectedShardMla(mla, "")}),
true)
f.run(ctx, []cache.ObjectName{getRef(mla)}, false)
t.Log("Controller successfully took ownership of a MachineLearningAlgorithm and related secrets and configurations on the shard cluster")
}
// TestDeletesMla tests that MLA removal from controller cluster will propagate to shard clusters
func TestDeletesMla(t *testing.T) {
f := newFixture(t)
mlaSecret := newSecret("test-secret", nil)
mlaConfigMap := newConfigMap("test-config", nil)
mla := newMla("test", mlaSecret, mlaConfigMap, false, &nexuscontroller.MachineLearningAlgorithmStatus{
SyncedSecrets: []string{"test-secret"},
SyncedConfigurations: []string{"test-config"},
SyncedToClusters: []string{"shard0"},
Conditions: []metav1.Condition{
*nexuscontroller.NewResourceReadyCondition(
metav1.Now(),
metav1.ConditionTrue,
"Algorithm \"test\" ready",
),