forked from googleforgames/agones
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfleet_test.go
1415 lines (1202 loc) · 50.5 KB
/
fleet_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 2018 Google LLC All Rights Reserved.
//
// 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 e2e
import (
"fmt"
"math"
"strings"
"sync"
"testing"
"time"
"agones.dev/agones/pkg/apis"
agonesv1 "agones.dev/agones/pkg/apis/agones/v1"
allocationv1 "agones.dev/agones/pkg/apis/allocation/v1"
typedagonesv1 "agones.dev/agones/pkg/client/clientset/versioned/typed/agones/v1"
"agones.dev/agones/pkg/util/runtime"
e2e "agones.dev/agones/test/e2e/framework"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/stretchr/testify/assert"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
v1betaext "k8s.io/api/extensions/v1beta1"
k8serrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/intstr"
"k8s.io/apimachinery/pkg/util/rand"
"k8s.io/apimachinery/pkg/util/validation"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/util/retry"
)
const (
key = "test-state"
red = "red"
green = "green"
replicasCount = 3
)
// TestFleetRequestsLimits reproduces an issue when 1000m and 1 CPU is not equal, but should be equal
// Every fleet should create no more than 2 GameServerSet at once on a simple fleet patch
func TestFleetRequestsLimits(t *testing.T) {
t.Parallel()
flt := defaultFleet(framework.Namespace)
flt.Spec.Template.Spec.Template.Spec.Containers[0].Resources.Limits[corev1.ResourceCPU] = *resource.NewScaledQuantity(1000, -3)
client := framework.AgonesClient.AgonesV1()
flt, err := client.Fleets(framework.Namespace).Create(flt)
if assert.Nil(t, err) {
defer client.Fleets(framework.Namespace).Delete(flt.ObjectMeta.Name, nil) // nolint:errcheck
}
framework.AssertFleetCondition(t, flt, e2e.FleetReadyCount(flt.Spec.Replicas))
newReplicas := int32(5)
patch := fmt.Sprintf(`[{ "op": "replace", "path": "/spec/template/spec/template/spec/containers/0/resources/requests/cpu", "value": "1000m"},
{ "op": "replace", "path": "/spec/replicas", "value": %d}]`, newReplicas)
_, err = framework.AgonesClient.AgonesV1().Fleets(framework.Namespace).Patch(flt.ObjectMeta.Name, types.JSONPatchType, []byte(patch))
assert.Nil(t, err)
// In bug scenario fleet was infinitely creating new GSSets (5 at a time), because 1000m CPU was changed to 1 CPU
// internally - thought as new wrong GSSet in a Fleet Controller
framework.AssertFleetCondition(t, flt, e2e.FleetReadyCount(newReplicas))
}
// TestFleetStrategyValidation reproduces an issue when we are trying
// to update a fleet with no strategy in a new one
func TestFleetStrategyValidation(t *testing.T) {
t.Parallel()
flt := defaultFleet(framework.Namespace)
client := framework.AgonesClient.AgonesV1()
flt, err := client.Fleets(framework.Namespace).Create(flt)
if assert.Nil(t, err) {
defer client.Fleets(framework.Namespace).Delete(flt.ObjectMeta.Name, nil) // nolint:errcheck
}
framework.AssertFleetCondition(t, flt, e2e.FleetReadyCount(flt.Spec.Replicas))
flt, err = client.Fleets(framework.Namespace).Get(flt.ObjectMeta.GetName(), metav1.GetOptions{})
assert.NoError(t, err)
// func to check that we receive an expected error
verifyErr := func(err error) {
assert.NotNil(t, err)
statusErr, ok := err.(*k8serrors.StatusError)
assert.True(t, ok)
fmt.Println(statusErr)
CausesMessages := []string{"Strategy Type should be one of: RollingUpdate, Recreate."}
assert.Len(t, statusErr.Status().Details.Causes, 1)
assert.Equal(t, metav1.CauseTypeFieldValueInvalid, statusErr.Status().Details.Causes[0].Type)
assert.Contains(t, CausesMessages, statusErr.Status().Details.Causes[0].Message)
}
// Change DeploymentStrategy Type, set it to empty string, which is forbidden
fltCopy := flt.DeepCopy()
fltCopy.Spec.Strategy.Type = appsv1.DeploymentStrategyType("")
_, err = client.Fleets(framework.Namespace).Update(fltCopy)
verifyErr(err)
// Try to remove whole DeploymentStrategy in a patch
patch := `[{ "op": "remove", "path": "/spec/strategy"},
{ "op": "replace", "path": "/spec/replicas", "value": 3}]`
_, err = framework.AgonesClient.AgonesV1().Fleets(framework.Namespace).Patch(flt.ObjectMeta.Name, types.JSONPatchType, []byte(patch))
verifyErr(err)
}
func TestFleetScaleUpEditAndScaleDown(t *testing.T) {
t.Parallel()
//Use scaleFleetPatch (true) or scaleFleetSubresource (false)
fixtures := []bool{true, false}
for _, usePatch := range fixtures {
usePatch := usePatch
t.Run("Use fleet Patch "+fmt.Sprint(usePatch), func(t *testing.T) {
t.Parallel()
client := framework.AgonesClient.AgonesV1()
flt := defaultFleet(framework.Namespace)
flt.Spec.Replicas = 1
flt, err := client.Fleets(framework.Namespace).Create(flt)
if assert.Nil(t, err) {
defer client.Fleets(framework.Namespace).Delete(flt.ObjectMeta.Name, nil) // nolint:errcheck
}
assert.Equal(t, int32(1), flt.Spec.Replicas)
framework.AssertFleetCondition(t, flt, e2e.FleetReadyCount(flt.Spec.Replicas))
// scale up
const targetScale = 3
if usePatch {
flt = scaleFleetPatch(t, flt, targetScale)
assert.Equal(t, int32(targetScale), flt.Spec.Replicas)
} else {
flt = scaleFleetSubresource(t, flt, targetScale)
}
framework.AssertFleetCondition(t, flt, e2e.FleetReadyCount(targetScale))
gsa := framework.CreateAndApplyAllocation(t, flt)
framework.AssertFleetCondition(t, flt, func(fleet *agonesv1.Fleet) bool {
return fleet.Status.AllocatedReplicas == 1
})
flt, err = client.Fleets(framework.Namespace).Get(flt.ObjectMeta.GetName(), metav1.GetOptions{})
assert.Nil(t, err)
// Change ContainerPort to trigger creating a new GSSet
fltCopy := flt.DeepCopy()
fltCopy.Spec.Template.Spec.Ports[0].ContainerPort++
flt, err = client.Fleets(framework.Namespace).Update(fltCopy)
assert.Nil(t, err)
// Wait for one more GSSet to be created and ReadyReplicas created in new GSS
err = wait.PollImmediate(1*time.Second, time.Minute, func() (bool, error) {
selector := labels.SelectorFromSet(labels.Set{agonesv1.FleetNameLabel: flt.ObjectMeta.Name})
list, err := framework.AgonesClient.AgonesV1().GameServerSets(framework.Namespace).List(
metav1.ListOptions{LabelSelector: selector.String()})
if err != nil {
return false, err
}
ready := false
if len(list.Items) == 2 {
for _, v := range list.Items {
if v.Status.ReadyReplicas > 0 && v.Status.AllocatedReplicas == 0 {
ready = true
}
}
}
return ready, nil
})
assert.Nil(t, err)
// scale down, with allocation
const scaleDownTarget = 1
if usePatch {
flt = scaleFleetPatch(t, flt, scaleDownTarget)
} else {
flt = scaleFleetSubresource(t, flt, scaleDownTarget)
}
framework.AssertFleetCondition(t, flt, e2e.FleetReadyCount(0))
// delete the allocated GameServer
gp := int64(1)
err = client.GameServers(framework.Namespace).Delete(gsa.Status.GameServerName, &metav1.DeleteOptions{GracePeriodSeconds: &gp})
assert.Nil(t, err)
framework.AssertFleetCondition(t, flt, e2e.FleetReadyCount(1))
framework.AssertFleetCondition(t, flt, func(fleet *agonesv1.Fleet) bool {
return fleet.Status.AllocatedReplicas == 0
})
})
}
}
// TestFleetRollingUpdate - test that the limited number of gameservers are created and deleted at a time
// maxUnavailable and maxSurge parameters check.
func TestFleetRollingUpdate(t *testing.T) {
t.Parallel()
//Use scaleFleetPatch (true) or scaleFleetSubresource (false)
fixtures := []bool{true, false}
maxSurge := []string{"25%", "10%"}
for _, usePatch := range fixtures {
for _, maxSurgeParam := range maxSurge {
usePatch := usePatch
maxSurgeParam := maxSurgeParam
t.Run(fmt.Sprintf("Use fleet Patch %t %s", usePatch, maxSurgeParam), func(t *testing.T) {
t.Parallel()
client := framework.AgonesClient.AgonesV1()
flt := defaultFleet(framework.Namespace)
flt.ApplyDefaults()
flt.Spec.Replicas = 1
rollingUpdatePercent := intstr.FromString(maxSurgeParam)
flt.Spec.Strategy.RollingUpdate.MaxSurge = &rollingUpdatePercent
flt.Spec.Strategy.RollingUpdate.MaxUnavailable = &rollingUpdatePercent
flt, err := client.Fleets(framework.Namespace).Create(flt)
if assert.Nil(t, err) {
defer client.Fleets(framework.Namespace).Delete(flt.ObjectMeta.Name, nil) // nolint:errcheck
}
assert.Equal(t, int32(1), flt.Spec.Replicas)
framework.AssertFleetCondition(t, flt, e2e.FleetReadyCount(flt.Spec.Replicas))
// scale up
const targetScale = 8
if usePatch {
flt = scaleFleetPatch(t, flt, targetScale)
assert.Equal(t, int32(targetScale), flt.Spec.Replicas)
} else {
flt = scaleFleetSubresource(t, flt, targetScale)
}
framework.AssertFleetCondition(t, flt, e2e.FleetReadyCount(targetScale))
flt, err = client.Fleets(framework.Namespace).Get(flt.ObjectMeta.GetName(), metav1.GetOptions{})
assert.NoError(t, err)
// Change ContainerPort to trigger creating a new GSSet
fltCopy := flt.DeepCopy()
fltCopy.Spec.Template.Spec.Ports[0].ContainerPort++
flt, err = client.Fleets(framework.Namespace).Update(fltCopy)
assert.NoError(t, err)
selector := labels.SelectorFromSet(labels.Set{agonesv1.FleetNameLabel: flt.ObjectMeta.Name})
// New GSS was created
err = wait.PollImmediate(1*time.Second, 30*time.Second, func() (bool, error) {
gssList, err := framework.AgonesClient.AgonesV1().GameServerSets(framework.Namespace).List(
metav1.ListOptions{LabelSelector: selector.String()})
if err != nil {
return false, err
}
return len(gssList.Items) == 2, nil
})
assert.NoError(t, err)
// Check that total number of gameservers in the system does not exceed the RollingUpdate
// parameters (creating no more than maxSurge, deleting maxUnavailable servers at a time)
// Wait for old GSSet to be deleted
err = wait.PollImmediate(1*time.Second, 5*time.Minute, func() (bool, error) {
list, err := framework.AgonesClient.AgonesV1().GameServers(framework.Namespace).List(
metav1.ListOptions{LabelSelector: selector.String()})
if err != nil {
return false, err
}
maxSurge, err := intstr.GetValueFromIntOrPercent(flt.Spec.Strategy.RollingUpdate.MaxSurge, 100, true)
assert.Nil(t, err)
maxUnavailable, err := intstr.GetValueFromIntOrPercent(flt.Spec.Strategy.RollingUpdate.MaxUnavailable, 100, true)
assert.Nil(t, err)
target := float64(targetScale)
if len(list.Items) > int(target+math.Ceil(target*float64(maxSurge)/100.)+math.Ceil(target*float64(maxUnavailable)/100.)) {
err = errors.New("New replicas should be less than target + maxSurge + maxUnavailable")
}
if err != nil {
return false, err
}
gssList, err := framework.AgonesClient.AgonesV1().GameServerSets(framework.Namespace).List(
metav1.ListOptions{LabelSelector: selector.String()})
if err != nil {
return false, err
}
return len(gssList.Items) == 1, nil
})
assert.NoError(t, err)
// scale down, with allocation
const scaleDownTarget = 1
if usePatch {
flt = scaleFleetPatch(t, flt, scaleDownTarget)
} else {
flt = scaleFleetSubresource(t, flt, scaleDownTarget)
}
framework.AssertFleetCondition(t, flt, e2e.FleetReadyCount(1))
framework.AssertFleetCondition(t, flt, func(fleet *agonesv1.Fleet) bool {
return fleet.Status.AllocatedReplicas == 0
})
})
}
}
}
func TestScaleFleetUpAndDownWithGameServerAllocation(t *testing.T) {
t.Parallel()
fixtures := []bool{false, true}
for _, usePatch := range fixtures {
usePatch := usePatch
t.Run("Use fleet Patch "+fmt.Sprint(usePatch), func(t *testing.T) {
t.Parallel()
client := framework.AgonesClient.AgonesV1()
flt := defaultFleet(framework.Namespace)
flt.Spec.Replicas = 1
flt, err := client.Fleets(framework.Namespace).Create(flt)
if assert.Nil(t, err) {
defer client.Fleets(framework.Namespace).Delete(flt.ObjectMeta.Name, nil) // nolint:errcheck
}
assert.Equal(t, int32(1), flt.Spec.Replicas)
framework.AssertFleetCondition(t, flt, e2e.FleetReadyCount(flt.Spec.Replicas))
// scale up
const targetScale = 3
if usePatch {
flt = scaleFleetPatch(t, flt, targetScale)
assert.Equal(t, int32(targetScale), flt.Spec.Replicas)
} else {
flt = scaleFleetSubresource(t, flt, targetScale)
}
framework.AssertFleetCondition(t, flt, e2e.FleetReadyCount(targetScale))
// get an allocation
gsa := &allocationv1.GameServerAllocation{ObjectMeta: metav1.ObjectMeta{GenerateName: "allocation-"},
Spec: allocationv1.GameServerAllocationSpec{
Required: metav1.LabelSelector{MatchLabels: map[string]string{agonesv1.FleetNameLabel: flt.ObjectMeta.Name}},
}}
gsa, err = framework.AgonesClient.AllocationV1().GameServerAllocations(framework.Namespace).Create(gsa)
assert.Nil(t, err)
assert.Equal(t, allocationv1.GameServerAllocationAllocated, gsa.Status.State)
framework.AssertFleetCondition(t, flt, func(fleet *agonesv1.Fleet) bool {
return fleet.Status.AllocatedReplicas == 1
})
// scale down, with allocation
const scaleDownTarget = 1
if usePatch {
flt = scaleFleetPatch(t, flt, scaleDownTarget)
} else {
flt = scaleFleetSubresource(t, flt, scaleDownTarget)
}
framework.AssertFleetCondition(t, flt, e2e.FleetReadyCount(0))
// delete the allocated GameServer
gp := int64(1)
err = client.GameServers(framework.Namespace).Delete(gsa.Status.GameServerName, &metav1.DeleteOptions{GracePeriodSeconds: &gp})
assert.Nil(t, err)
framework.AssertFleetCondition(t, flt, e2e.FleetReadyCount(1))
framework.AssertFleetCondition(t, flt, func(fleet *agonesv1.Fleet) bool {
return fleet.Status.AllocatedReplicas == 0
})
})
}
}
func TestFleetUpdates(t *testing.T) {
t.Parallel()
fixtures := map[string]func() *agonesv1.Fleet{
"recreate": func() *agonesv1.Fleet {
flt := defaultFleet(framework.Namespace)
flt.Spec.Strategy.Type = appsv1.RecreateDeploymentStrategyType
return flt
},
"rolling": func() *agonesv1.Fleet {
flt := defaultFleet(framework.Namespace)
flt.Spec.Strategy.Type = appsv1.RollingUpdateDeploymentStrategyType
return flt
},
}
for k, v := range fixtures {
k := k
v := v
t.Run(k, func(t *testing.T) {
t.Parallel()
client := framework.AgonesClient.AgonesV1()
flt := v()
flt.Spec.Template.ObjectMeta.Annotations = map[string]string{key: red}
flt, err := client.Fleets(framework.Namespace).Create(flt)
if assert.Nil(t, err) {
defer client.Fleets(framework.Namespace).Delete(flt.ObjectMeta.Name, nil) // nolint:errcheck
}
err = framework.WaitForFleetGameServersCondition(flt, func(gs *agonesv1.GameServer) bool {
return gs.ObjectMeta.Annotations[key] == red
})
assert.Nil(t, err)
// if the generation has been updated, it's time to try again.
err = wait.PollImmediate(time.Second, 10*time.Second, func() (bool, error) {
flt, err = framework.AgonesClient.AgonesV1().Fleets(framework.Namespace).Get(flt.ObjectMeta.Name, metav1.GetOptions{})
if err != nil {
return false, err
}
fltCopy := flt.DeepCopy()
fltCopy.Spec.Template.ObjectMeta.Annotations[key] = green
_, err = framework.AgonesClient.AgonesV1().Fleets(framework.Namespace).Update(fltCopy)
if err != nil {
logrus.WithError(err).Warn("Could not update fleet, trying again")
return false, nil
}
return true, nil
})
assert.Nil(t, err)
err = framework.WaitForFleetGameServersCondition(flt, func(gs *agonesv1.GameServer) bool {
return gs.ObjectMeta.Annotations[key] == green
})
assert.Nil(t, err)
})
}
}
func TestUpdateGameServerConfigurationInFleet(t *testing.T) {
t.Parallel()
client := framework.AgonesClient.AgonesV1()
gsSpec := framework.DefaultGameServer(framework.Namespace).Spec
oldPort := int32(7111)
gsSpec.Ports = []agonesv1.GameServerPort{{
ContainerPort: oldPort,
Name: "gameport",
PortPolicy: agonesv1.Dynamic,
Protocol: corev1.ProtocolUDP,
}}
flt := fleetWithGameServerSpec(&gsSpec, framework.Namespace)
flt, err := client.Fleets(framework.Namespace).Create(flt)
assert.Nil(t, err, "could not create fleet")
defer client.Fleets(framework.Namespace).Delete(flt.ObjectMeta.Name, nil) // nolint:errcheck
assert.Equal(t, int32(replicasCount), flt.Spec.Replicas)
framework.AssertFleetCondition(t, flt, e2e.FleetReadyCount(flt.Spec.Replicas))
// get an allocation
gsa := &allocationv1.GameServerAllocation{ObjectMeta: metav1.ObjectMeta{GenerateName: "allocation-"},
Spec: allocationv1.GameServerAllocationSpec{
Required: metav1.LabelSelector{MatchLabels: map[string]string{agonesv1.FleetNameLabel: flt.ObjectMeta.Name}},
}}
gsa, err = framework.AgonesClient.AllocationV1().GameServerAllocations(framework.Namespace).Create(gsa)
assert.Nil(t, err, "cloud not create gameserver allocation")
assert.Equal(t, allocationv1.GameServerAllocationAllocated, gsa.Status.State)
framework.AssertFleetCondition(t, flt, func(fleet *agonesv1.Fleet) bool {
return fleet.Status.AllocatedReplicas == 1
})
flt, err = framework.AgonesClient.AgonesV1().Fleets(framework.Namespace).Get(flt.Name, metav1.GetOptions{})
assert.Nil(t, err, "could not get fleet")
// Update the configuration of the gameservers of the fleet, i.e. container port.
// The changes should only be rolled out to gameservers in ready state, but not the allocated gameserver.
newPort := int32(7222)
fltCopy := flt.DeepCopy()
fltCopy.Spec.Template.Spec.Ports[0].ContainerPort = newPort
_, err = framework.AgonesClient.AgonesV1().Fleets(framework.Namespace).Update(fltCopy)
assert.Nil(t, err, "could not update fleet")
err = framework.WaitForFleetGameServersCondition(flt, func(gs *agonesv1.GameServer) bool {
containerPort := gs.Spec.Ports[0].ContainerPort
return (gs.Name == gsa.Status.GameServerName && containerPort == oldPort) ||
(gs.Name != gsa.Status.GameServerName && containerPort == newPort)
})
assert.Nil(t, err, "gameservers don't have expected container port")
}
func TestReservedGameServerInFleet(t *testing.T) {
t.Parallel()
client := framework.AgonesClient.AgonesV1()
flt := defaultFleet(framework.Namespace)
flt.Spec.Replicas = 3
flt, err := client.Fleets(framework.Namespace).Create(flt)
if assert.NoError(t, err) {
defer client.Fleets(framework.Namespace).Delete(flt.ObjectMeta.Name, nil) // nolint:errcheck
}
framework.AssertFleetCondition(t, flt, e2e.FleetReadyCount(flt.Spec.Replicas))
gsList, err := framework.ListGameServersFromFleet(flt)
assert.NoError(t, err)
assert.Len(t, gsList, int(flt.Spec.Replicas))
// mark one as reserved
gsCopy := gsList[0].DeepCopy()
gsCopy.Status.State = agonesv1.GameServerStateReserved
_, err = client.GameServers(framework.Namespace).Update(gsCopy)
assert.NoError(t, err)
// make sure counts are correct
framework.AssertFleetCondition(t, flt, func(fleet *agonesv1.Fleet) bool {
return fleet.Status.ReadyReplicas == 2 && fleet.Status.ReservedReplicas == 1
})
// scale down to 0
flt = scaleFleetSubresource(t, flt, 0)
framework.AssertFleetCondition(t, flt, e2e.FleetReadyCount(0))
// one should be left behind
framework.AssertFleetCondition(t, flt, func(fleet *agonesv1.Fleet) bool {
result := fleet.Status.ReservedReplicas == 1
logrus.WithField("reserved", fleet.Status.ReservedReplicas).WithField("result", result).Info("waiting for 1 reserved replica")
return result
})
// check against gameservers directly too, just to be extra sure
err = wait.PollImmediate(2*time.Second, 5*time.Minute, func() (done bool, err error) {
list, err := framework.ListGameServersFromFleet(flt)
if err != nil {
return true, err
}
l := len(list)
logrus.WithField("len", l).WithField("state", list[0].Status.State).Info("waiting for 1 reserved gs")
return l == 1 && list[0].Status.State == agonesv1.GameServerStateReserved, nil
})
assert.NoError(t, err)
}
// TestFleetGSSpecValidation is built to test Fleet's underlying Gameserver template
// validation. Gameserver Spec contained in a Fleet should be valid to create a fleet.
func TestFleetGSSpecValidation(t *testing.T) {
t.Parallel()
client := framework.AgonesClient.AgonesV1()
// check two Containers in Gameserver Spec Template validation
flt := defaultFleet(framework.Namespace)
containerName := "container2"
flt.Spec.Template.Spec.Template =
corev1.PodTemplateSpec{
Spec: corev1.PodSpec{
Containers: []corev1.Container{{Name: "container", Image: "myImage"}, {Name: containerName, Image: "myImage2"}},
},
}
flt.Spec.Template.Spec.Container = "testing"
_, err := client.Fleets(framework.Namespace).Create(flt)
assert.NotNil(t, err)
statusErr, ok := err.(*k8serrors.StatusError)
assert.True(t, ok)
if runtime.FeatureEnabled(runtime.FeatureContainerPortAllocation) && assert.Len(t, statusErr.Status().Details.Causes, 2) {
assert.Equal(t, "Container must be empty or the name of a container in the pod template", statusErr.Status().Details.Causes[1].Message)
} else {
assert.Len(t, statusErr.Status().Details.Causes, 1)
}
assert.Equal(t, metav1.CauseTypeFieldValueInvalid, statusErr.Status().Details.Causes[0].Type)
assert.Equal(t, "Could not find a container named testing", statusErr.Status().Details.Causes[0].Message)
flt.Spec.Template.Spec.Container = ""
_, err = client.Fleets(framework.Namespace).Create(flt)
assert.NotNil(t, err)
statusErr, ok = err.(*k8serrors.StatusError)
assert.True(t, ok)
CausesMessages := []string{agonesv1.ErrContainerRequired, "Could not find a container named "}
if assert.Len(t, statusErr.Status().Details.Causes, 2) {
assert.Equal(t, metav1.CauseTypeFieldValueInvalid, statusErr.Status().Details.Causes[1].Type)
assert.Contains(t, CausesMessages, statusErr.Status().Details.Causes[1].Message)
}
assert.Equal(t, metav1.CauseTypeFieldValueInvalid, statusErr.Status().Details.Causes[0].Type)
assert.Contains(t, CausesMessages, statusErr.Status().Details.Causes[0].Message)
// use valid name for a container, one of two defined above
flt.Spec.Template.Spec.Container = containerName
_, err = client.Fleets(framework.Namespace).Create(flt)
if assert.Nil(t, err) {
defer client.Fleets(framework.Namespace).Delete(flt.ObjectMeta.Name, nil) // nolint:errcheck
}
// check port configuration validation
fltPort := defaultFleet(framework.Namespace)
fltPort.Spec.Template.Spec.Ports = []agonesv1.GameServerPort{{Name: "Dyn", HostPort: 5555, PortPolicy: agonesv1.Dynamic, ContainerPort: 5555}}
_, err = client.Fleets(framework.Namespace).Create(fltPort)
assert.NotNil(t, err)
statusErr, ok = err.(*k8serrors.StatusError)
assert.True(t, ok)
assert.Len(t, statusErr.Status().Details.Causes, 1)
assert.Equal(t, agonesv1.ErrHostPort, statusErr.Status().Details.Causes[0].Message)
fltPort.Spec.Template.Spec.Ports[0].PortPolicy = agonesv1.Static
fltPort.Spec.Template.Spec.Ports[0].HostPort = 0
fltPort.Spec.Template.Spec.Ports[0].ContainerPort = 5555
_, err = client.Fleets(framework.Namespace).Create(fltPort)
if assert.Nil(t, err) {
defer client.Fleets(framework.Namespace).Delete(fltPort.ObjectMeta.Name, nil) // nolint:errcheck
}
}
// TestFleetNameValidation is built to test Fleet Name length validation,
// Fleet Name should have at most 63 chars.
func TestFleetNameValidation(t *testing.T) {
t.Parallel()
client := framework.AgonesClient.AgonesV1()
flt := defaultFleet(framework.Namespace)
nameLen := validation.LabelValueMaxLength + 1
bytes := make([]byte, nameLen)
for i := 0; i < nameLen; i++ {
bytes[i] = 'f'
}
flt.Name = string(bytes)
_, err := client.Fleets(framework.Namespace).Create(flt)
assert.NotNil(t, err)
statusErr, ok := err.(*k8serrors.StatusError)
assert.True(t, ok)
assert.True(t, len(statusErr.Status().Details.Causes) > 0)
assert.Equal(t, metav1.CauseTypeFieldValueInvalid, statusErr.Status().Details.Causes[0].Type)
goodFlt := defaultFleet(framework.Namespace)
goodFlt.Name = string(bytes[0 : nameLen-1])
goodFlt, err = client.Fleets(framework.Namespace).Create(goodFlt)
if assert.Nil(t, err) {
defer client.Fleets(framework.Namespace).Delete(goodFlt.ObjectMeta.Name, nil) // nolint:errcheck
}
}
func assertSuccessOrUpdateConflict(t *testing.T, err error) {
if !k8serrors.IsConflict(err) {
// update conflicts are sometimes ok, we simply lost the race.
assert.Nil(t, err)
}
}
// TestGameServerAllocationDuringGameServerDeletion is built to specifically
// test for race conditions of allocations when doing scale up/down,
// rolling updates, etc. Failures may not happen ALL the time -- as that is the
// nature of race conditions.
func TestGameServerAllocationDuringGameServerDeletion(t *testing.T) {
t.Parallel()
testAllocationRaceCondition := func(t *testing.T, fleet func(string) *agonesv1.Fleet, deltaSleep time.Duration, delta func(t *testing.T, flt *agonesv1.Fleet)) {
client := framework.AgonesClient.AgonesV1()
flt := fleet(framework.Namespace)
flt.ApplyDefaults()
size := int32(10)
flt.Spec.Replicas = size
flt, err := client.Fleets(framework.Namespace).Create(flt)
if assert.Nil(t, err) {
defer client.Fleets(framework.Namespace).Delete(flt.ObjectMeta.Name, nil) // nolint:errcheck
}
assert.Equal(t, size, flt.Spec.Replicas)
framework.AssertFleetCondition(t, flt, e2e.FleetReadyCount(flt.Spec.Replicas))
var allocs []string
wg := sync.WaitGroup{}
wg.Add(2)
go func() {
for {
// this gives room for fleet scaling to go down - makes it more likely for the race condition to fire
time.Sleep(100 * time.Millisecond)
gsa := &allocationv1.GameServerAllocation{ObjectMeta: metav1.ObjectMeta{GenerateName: "allocation-"},
Spec: allocationv1.GameServerAllocationSpec{
Required: metav1.LabelSelector{MatchLabels: map[string]string{agonesv1.FleetNameLabel: flt.ObjectMeta.Name}},
}}
gsa, err = framework.AgonesClient.AllocationV1().GameServerAllocations(framework.Namespace).Create(gsa)
if err != nil || gsa.Status.State == allocationv1.GameServerAllocationUnAllocated {
logrus.WithError(err).Info("Allocation ended")
break
}
logrus.WithField("gs", gsa.Status.GameServerName).Info("Allocated")
allocs = append(allocs, gsa.Status.GameServerName)
}
wg.Done()
}()
go func() {
// this tends to force the scaling to happen as we are fleet allocating
time.Sleep(deltaSleep)
// call the function that makes the change to the fleet
logrus.Info("Applying delta function")
delta(t, flt)
wg.Done()
}()
wg.Wait()
assert.NotEmpty(t, allocs)
for _, name := range allocs {
gsCheck, err := client.GameServers(framework.Namespace).Get(name, metav1.GetOptions{})
assert.Nil(t, err)
assert.True(t, gsCheck.ObjectMeta.DeletionTimestamp.IsZero())
}
}
t.Run("scale down", func(t *testing.T) {
t.Parallel()
testAllocationRaceCondition(t, defaultFleet, time.Second,
func(t *testing.T, flt *agonesv1.Fleet) {
const targetScale = int32(0)
flt = scaleFleetPatch(t, flt, targetScale)
assert.Equal(t, targetScale, flt.Spec.Replicas)
})
})
t.Run("recreate update", func(t *testing.T) {
t.Parallel()
fleet := func(ns string) *agonesv1.Fleet {
flt := defaultFleet(ns)
flt.Spec.Strategy.Type = appsv1.RecreateDeploymentStrategyType
flt.Spec.Template.ObjectMeta.Annotations = map[string]string{key: red}
return flt
}
testAllocationRaceCondition(t, fleet, time.Second,
func(t *testing.T, flt *agonesv1.Fleet) {
flt, err := framework.AgonesClient.AgonesV1().Fleets(framework.Namespace).Get(flt.ObjectMeta.Name, metav1.GetOptions{})
assert.Nil(t, err)
fltCopy := flt.DeepCopy()
fltCopy.Spec.Template.ObjectMeta.Annotations[key] = green
_, err = framework.AgonesClient.AgonesV1().Fleets(framework.Namespace).Update(fltCopy)
assertSuccessOrUpdateConflict(t, err)
})
})
t.Run("rolling update", func(t *testing.T) {
t.Parallel()
fleet := func(ns string) *agonesv1.Fleet {
flt := defaultFleet(ns)
flt.Spec.Strategy.Type = appsv1.RollingUpdateDeploymentStrategyType
flt.Spec.Template.ObjectMeta.Annotations = map[string]string{key: red}
return flt
}
testAllocationRaceCondition(t, fleet, time.Duration(0),
func(t *testing.T, flt *agonesv1.Fleet) {
flt, err := framework.AgonesClient.AgonesV1().Fleets(framework.Namespace).Get(flt.ObjectMeta.Name, metav1.GetOptions{})
assert.Nil(t, err)
fltCopy := flt.DeepCopy()
fltCopy.Spec.Template.ObjectMeta.Annotations[key] = green
_, err = framework.AgonesClient.AgonesV1().Fleets(framework.Namespace).Update(fltCopy)
assertSuccessOrUpdateConflict(t, err)
})
})
}
// TestCreateFleetAndUpdateScaleSubresource is built to
// test scale subresource usage and its ability to change Fleet Replica size.
// Both scaling up and down.
func TestCreateFleetAndUpdateScaleSubresource(t *testing.T) {
t.Parallel()
client := framework.AgonesClient.AgonesV1()
flt := defaultFleet(framework.Namespace)
const initialReplicas int32 = 1
flt.Spec.Replicas = initialReplicas
flt, err := client.Fleets(framework.Namespace).Create(flt)
if assert.Nil(t, err) {
defer client.Fleets(framework.Namespace).Delete(flt.ObjectMeta.Name, nil) // nolint:errcheck
}
assert.Equal(t, initialReplicas, flt.Spec.Replicas)
framework.AssertFleetCondition(t, flt, e2e.FleetReadyCount(flt.Spec.Replicas))
newReplicas := initialReplicas * 2
scaleFleetSubresource(t, flt, newReplicas)
framework.AssertFleetCondition(t, flt, e2e.FleetReadyCount(newReplicas))
scaleFleetSubresource(t, flt, initialReplicas)
framework.AssertFleetCondition(t, flt, e2e.FleetReadyCount(initialReplicas))
}
// TestScaleUpAndDownInParallelStressTest creates N fleets, half of which start with replicas=0
// and the other half with 0 and scales them up/down 3 times in parallel expecting it to reach
// the desired number of ready replicas each time.
// This test is also used as a stress test with 'make stress-test-e2e', in which case it creates
// many more fleets of bigger sizes and runs many more repetitions.
func TestScaleUpAndDownInParallelStressTest(t *testing.T) {
t.Parallel()
client := framework.AgonesClient.AgonesV1()
fleetCount := 2
fleetSize := int32(10)
defaultReplicas := int32(1)
repeatCount := 3
deadline := time.Now().Add(1 * time.Minute)
logrus.WithField("fleetCount", fleetCount).
WithField("fleetSize", fleetSize).
WithField("repeatCount", repeatCount).
WithField("deadline", deadline).
Info("starting scale up/down test")
if framework.StressTestLevel > 0 {
fleetSize = 10 * int32(framework.StressTestLevel)
repeatCount = 10
fleetCount = 10
deadline = time.Now().Add(45 * time.Minute)
}
var fleets []*agonesv1.Fleet
scaleUpStats := framework.NewStatsCollector(fmt.Sprintf("fleet_%v_scale_up", fleetSize), framework.Version)
scaleDownStats := framework.NewStatsCollector(fmt.Sprintf("fleet_%v_scale_down", fleetSize), framework.Version)
defer scaleUpStats.Report()
defer scaleDownStats.Report()
for fleetNumber := 0; fleetNumber < fleetCount; fleetNumber++ {
flt := defaultFleet(framework.Namespace)
flt.ObjectMeta.GenerateName = fmt.Sprintf("scale-fleet-%v-", fleetNumber)
if fleetNumber%2 == 0 {
// even-numbered fleets starts at fleetSize and are scaled down to zero and back.
flt.Spec.Replicas = fleetSize
} else {
// odd-numbered fleets starts at default 1 replica and are scaled up to fleetSize and back.
flt.Spec.Replicas = defaultReplicas
}
flt, err := client.Fleets(framework.Namespace).Create(flt)
if assert.Nil(t, err) {
defer client.Fleets(framework.Namespace).Delete(flt.ObjectMeta.Name, nil) // nolint:errcheck
}
fleets = append(fleets, flt)
}
// wait for initial fleet conditions.
for fleetNumber, flt := range fleets {
if fleetNumber%2 == 0 {
framework.AssertFleetCondition(t, flt, e2e.FleetReadyCount(fleetSize))
} else {
framework.AssertFleetCondition(t, flt, e2e.FleetReadyCount(defaultReplicas))
}
}
errorsChan := make(chan error)
var wg sync.WaitGroup
finished := make(chan bool, 1)
for fleetNumber, flt := range fleets {
wg.Add(1)
go func(fleetNumber int, flt *agonesv1.Fleet) {
defer wg.Done()
defer func() {
if err := recover(); err != nil {
t.Errorf("recovered panic: %v", err)
}
}()
if fleetNumber%2 == 0 {
duration, err := scaleAndWait(t, flt, 0)
if err != nil {
fmt.Println(err)
errorsChan <- err
return
}
scaleDownStats.ReportDuration(duration, nil)
}
for i := 0; i < repeatCount; i++ {
if time.Now().After(deadline) {
break
}
duration, err := scaleAndWait(t, flt, fleetSize)
if err != nil {
fmt.Println(err)
errorsChan <- err
return
}
scaleUpStats.ReportDuration(duration, nil)
duration, err = scaleAndWait(t, flt, 0)
if err != nil {
fmt.Println(err)
errorsChan <- err
return
}
scaleDownStats.ReportDuration(duration, nil)
}
}(fleetNumber, flt)
}
go func() {
wg.Wait()
close(finished)
}()
select {
case <-finished:
case err := <-errorsChan:
t.Fatalf("Error in waiting for a fleet to scale: %s", err)
}
fmt.Println("We are Done")
}
// Creates a fleet and one GameServer with Packed scheduling.
// Scale to two GameServers with Distributed scheduling.
// The old GameServer has Scheduling set to 5 and the new one has it set to Distributed.
func TestUpdateFleetScheduling(t *testing.T) {
t.Parallel()
t.Run("Updating Spec.Scheduling on fleet should be updated in GameServer",
func(t *testing.T) {
client := framework.AgonesClient.AgonesV1()
flt := defaultFleet(framework.Namespace)
flt.Spec.Replicas = 1
flt.Spec.Scheduling = apis.Packed
flt, err := client.Fleets(framework.Namespace).Create(flt)
if assert.Nil(t, err) {
defer client.Fleets(framework.Namespace).Delete(flt.ObjectMeta.Name, nil) // nolint:errcheck
}
assert.Equal(t, int32(1), flt.Spec.Replicas)
assert.Equal(t, apis.Packed, flt.Spec.Scheduling)
framework.AssertFleetCondition(t, flt, e2e.FleetReadyCount(flt.Spec.Replicas))
const targetScale = 2
flt = schedulingFleetPatch(t, flt, apis.Distributed, targetScale)
framework.AssertFleetCondition(t, flt, e2e.FleetReadyCount(targetScale))
assert.Equal(t, int32(targetScale), flt.Spec.Replicas)
assert.Equal(t, apis.Distributed, flt.Spec.Scheduling)
err = framework.WaitForFleetGameServerListCondition(flt,
func(gsList []agonesv1.GameServer) bool {
return countFleetScheduling(gsList, apis.Distributed) == 1 &&
countFleetScheduling(gsList, apis.Packed) == 1
})
assert.Nil(t, err)
})
}
// TestFleetWithZeroReplicas ensures that we can always create 0 replica
// fleets, which is useful!
func TestFleetWithZeroReplicas(t *testing.T) {
t.Parallel()
client := framework.AgonesClient.AgonesV1()
flt := defaultFleet(framework.Namespace)
flt.Spec.Replicas = 0
flt, err := client.Fleets(framework.Namespace).Create(flt)
assert.NoError(t, err)
// can't think of a better way to wait for a bit before checking.
time.Sleep(time.Second)
list, err := framework.ListGameServersFromFleet(flt)
assert.NoError(t, err)
assert.Empty(t, list)
}
// TestFleetWithLongLabelsAnnotations ensures that we can not create a fleet
// with label over 64 chars and Annotations key over 64