forked from googleforgames/agones
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfleet_test.go
2004 lines (1695 loc) · 75.1 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 (
"context"
"fmt"
"sort"
"strings"
"sync"
"testing"
"time"
"github.com/sirupsen/logrus"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
appsv1 "k8s.io/api/apps/v1"
autoscalingv1 "k8s.io/api/autoscaling/v1"
corev1 "k8s.io/api/core/v1"
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"
"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"
)
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()
ctx := context.Background()
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(ctx, flt, metav1.CreateOptions{})
if assert.NoError(t, err) {
defer client.Fleets(framework.Namespace).Delete(ctx, flt.ObjectMeta.Name, metav1.DeleteOptions{}) // 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(ctx, flt.ObjectMeta.Name, types.JSONPatchType, []byte(patch), metav1.PatchOptions{})
require.NoError(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()
ctx := context.Background()
flt := defaultFleet(framework.Namespace)
client := framework.AgonesClient.AgonesV1()
flt, err := client.Fleets(framework.Namespace).Create(ctx, flt, metav1.CreateOptions{})
require.NoError(t, err)
defer client.Fleets(framework.Namespace).Delete(ctx, flt.ObjectMeta.Name, metav1.DeleteOptions{}) // nolint:errcheck
framework.AssertFleetCondition(t, flt, e2e.FleetReadyCount(flt.Spec.Replicas))
flt, err = client.Fleets(framework.Namespace).Get(ctx, 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)
assert.Len(t, statusErr.Status().Details.Causes, 1)
assert.Equal(t, metav1.CauseTypeFieldValueNotSupported, statusErr.Status().Details.Causes[0].Type)
assert.Contains(t, statusErr.Status().Details.Causes[0].Message, `supported values: "RollingUpdate", "Recreate"`)
}
// 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(ctx, fltCopy, metav1.UpdateOptions{})
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(ctx, flt.ObjectMeta.Name, types.JSONPatchType, []byte(patch), metav1.PatchOptions{})
verifyErr(err)
}
func TestFleetScaleWithDualAllocations(t *testing.T) {
t.Parallel()
ctx := context.Background()
client := framework.AgonesClient.AgonesV1()
flt := defaultFleet(framework.Namespace)
flt.Spec.Replicas = 5
flt, err := client.Fleets(framework.Namespace).Create(ctx, flt, metav1.CreateOptions{})
require.NoError(t, err)
defer client.Fleets(framework.Namespace).Delete(ctx, flt.ObjectMeta.Name, metav1.DeleteOptions{}) // nolint:errcheck
log := e2e.TestLogger(t).WithField("fleet", flt.Name)
framework.AssertFleetCondition(t, flt, e2e.FleetReadyCount(flt.Spec.Replicas))
_ = framework.CreateAndApplyAllocation(t, flt)
framework.AssertFleetCondition(t, flt, func(_ *logrus.Entry, fleet *agonesv1.Fleet) bool {
return fleet.Status.AllocatedReplicas == 1
})
err = wait.PollUntilContextTimeout(context.Background(), time.Second, time.Minute, true, func(ctx context.Context) (done bool, err error) {
flt, err = client.Fleets(framework.Namespace).Get(ctx, flt.ObjectMeta.GetName(), metav1.GetOptions{})
if err != nil {
return false, err
}
fltCopy := flt.DeepCopy()
fltCopy.Spec.Template.ObjectMeta.Labels = map[string]string{"version": "new"}
_, err = client.Fleets(framework.Namespace).Update(ctx, fltCopy, metav1.UpdateOptions{})
return true, err
})
require.NoError(t, err)
selector := labels.SelectorFromSet(labels.Set{agonesv1.FleetNameLabel: flt.ObjectMeta.Name})
require.Eventually(t, func() bool {
gssList, err := framework.AgonesClient.AgonesV1().GameServerSets(framework.Namespace).List(ctx,
metav1.ListOptions{LabelSelector: selector.String()})
if err != nil {
log.WithError(err).Error("Should be able to list")
return false
}
// wait until there are two of them
if len(gssList.Items) < 2 {
return false
}
// sort by timestamp, so we have a consistent order.
sort.Slice(gssList.Items, func(i, j int) bool {
return gssList.Items[i].ObjectMeta.CreationTimestamp.Compare(gssList.Items[j].ObjectMeta.CreationTimestamp.Time) == -1
})
// First one will have 1 with one allocated, second one should have 9 ready.
if gssList.Items[0].Status.AllocatedReplicas != 1 || gssList.Items[1].Status.ReadyReplicas != 4 {
log.WithField("gss0", fmt.Sprintf("%+v", gssList.Items[0].Status)).WithField("gss1", fmt.Sprintf("%+v", gssList.Items[1].Status)).Info("Checking GameServerSet")
return false
}
return true
}, 5*time.Minute, time.Second)
// Allocate 2 game servers.
_ = framework.CreateAndApplyAllocation(t, flt)
_ = framework.CreateAndApplyAllocation(t, flt)
// Scale the fleet down to 2 replicas.
framework.ScaleFleet(t, log, flt, 2)
framework.AssertFleetCondition(t, flt, func(_ *logrus.Entry, fleet *agonesv1.Fleet) bool {
log.WithField("fleet", fmt.Sprintf("%+v", fleet.Status)).Info("Checking after 2 more allocations, and scaling to 2")
return fleet.Status.AllocatedReplicas == 3 && fleet.Status.ReadyReplicas == 0
})
require.NoError(t, err)
// Then scale the fleet back to 10 replicas.
framework.ScaleFleet(t, log, flt, 5)
require.NoError(t, err)
framework.AssertFleetCondition(t, flt, func(_ *logrus.Entry, fleet *agonesv1.Fleet) bool {
log.WithField("fleet", fmt.Sprintf("%+v", fleet.Status)).Info("Checking after scaling back to 5")
return fleet.Status.AllocatedReplicas == 3 && fleet.Status.ReadyReplicas == 2
})
}
func TestFleetScaleUpAllocateEditAndScaleDownToZero(t *testing.T) {
t.Parallel()
ctx := context.Background()
client := framework.AgonesClient.AgonesV1()
flt := defaultFleet(framework.Namespace)
flt.Spec.Replicas = 1
flt, err := client.Fleets(framework.Namespace).Create(ctx, flt, metav1.CreateOptions{})
require.NoError(t, err)
defer client.Fleets(framework.Namespace).Delete(ctx, flt.ObjectMeta.Name, metav1.DeleteOptions{}) // nolint:errcheck
assert.Equal(t, int32(1), flt.Spec.Replicas)
framework.AssertFleetCondition(t, flt, e2e.FleetReadyCount(flt.Spec.Replicas))
// Scale up to 5 replicas
const targetScale = 5
flt = scaleFleetPatch(ctx, t, flt, targetScale)
framework.AssertFleetCondition(t, flt, e2e.FleetReadyCount(targetScale))
// Allocate 1 replica
gsa := framework.CreateAndApplyAllocation(t, flt)
framework.AssertFleetCondition(t, flt, func(_ *logrus.Entry, fleet *agonesv1.Fleet) bool {
return fleet.Status.AllocatedReplicas == 1
})
flt, err = client.Fleets(framework.Namespace).Get(ctx, flt.ObjectMeta.GetName(), metav1.GetOptions{})
require.NoError(t, err)
// Edit Port to 6000
// Change Port to trigger creating a new GSSet
fltCopy := flt.DeepCopy()
fltCopy.Spec.Template.Spec.Ports = []agonesv1.GameServerPort{{
ContainerPort: 6000,
Name: "gameport",
PortPolicy: agonesv1.Dynamic,
Protocol: corev1.ProtocolUDP,
}}
flt, err = client.Fleets(framework.Namespace).Update(ctx, fltCopy, metav1.UpdateOptions{})
require.NoError(t, err)
assert.Equal(t, int32(6000), flt.Spec.Template.Spec.Ports[0].ContainerPort)
// Wait for one more GSSet to be created
err = wait.PollUntilContextTimeout(context.Background(), 2*time.Second, 2*time.Minute, true, func(ctx context.Context) (bool, error) {
selector := labels.SelectorFromSet(labels.Set{agonesv1.FleetNameLabel: flt.ObjectMeta.Name})
list, err := framework.AgonesClient.AgonesV1().GameServerSets(framework.Namespace).List(ctx,
metav1.ListOptions{LabelSelector: selector.String()})
if err != nil {
return false, err
}
ready := false
// 2 GSSet should be created
if len(list.Items) == 2 {
ready = true
}
return ready, nil
})
require.NoError(t, err)
// RollingUpdate has happened due to changing Port, so waiting the complete of the RollingUpdate
framework.AssertFleetCondition(t, flt, func(_ *logrus.Entry, fleet *agonesv1.Fleet) bool {
return fleet.Status.ReadyReplicas == 4
})
// Scale down to zero
const scaleDownTarget = 0
flt = scaleFleetPatch(ctx, t, flt, scaleDownTarget)
// Expect Replicas = 0, No GSS or GS
framework.AssertFleetCondition(t, flt, e2e.FleetReadyCount(0))
// Cleanup the allocated GameServer
gp := int64(1)
err = client.GameServers(framework.Namespace).Delete(ctx, gsa.Status.GameServerName, metav1.DeleteOptions{GracePeriodSeconds: &gp})
require.NoError(t, err)
framework.AssertFleetCondition(t, flt, e2e.FleetReadyCount(0))
framework.AssertFleetCondition(t, flt, func(_ *logrus.Entry, fleet *agonesv1.Fleet) bool {
return fleet.Status.AllocatedReplicas == 0
})
framework.AssertFleetCondition(t, flt, func(_ *logrus.Entry, fleet *agonesv1.Fleet) bool {
return fleet.Status.Replicas == 0
})
}
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()
ctx := context.Background()
client := framework.AgonesClient.AgonesV1()
flt := defaultFleet(framework.Namespace)
flt.Spec.Replicas = 1
flt, err := client.Fleets(framework.Namespace).Create(ctx, flt, metav1.CreateOptions{})
require.NoError(t, err)
defer client.Fleets(framework.Namespace).Delete(ctx, flt.ObjectMeta.Name, metav1.DeleteOptions{}) // 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(ctx, t, flt, targetScale)
assert.Equal(t, int32(targetScale), flt.Spec.Replicas)
} else {
flt = scaleFleetSubresource(ctx, t, flt, targetScale)
}
framework.AssertFleetCondition(t, flt, e2e.FleetReadyCount(targetScale))
gsa := framework.CreateAndApplyAllocation(t, flt)
framework.AssertFleetCondition(t, flt, func(_ *logrus.Entry, fleet *agonesv1.Fleet) bool {
return fleet.Status.AllocatedReplicas == 1
})
flt, err = client.Fleets(framework.Namespace).Get(ctx, flt.ObjectMeta.GetName(), metav1.GetOptions{})
require.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(ctx, fltCopy, metav1.UpdateOptions{})
require.NoError(t, err)
// Wait for one more GSSet to be created and ReadyReplicas created in new GSS
err = wait.PollUntilContextTimeout(context.Background(), 1*time.Second, time.Minute, true, func(ctx context.Context) (bool, error) {
selector := labels.SelectorFromSet(labels.Set{agonesv1.FleetNameLabel: flt.ObjectMeta.Name})
list, err := framework.AgonesClient.AgonesV1().GameServerSets(framework.Namespace).List(ctx,
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
})
require.NoError(t, err)
// scale down, with allocation
const scaleDownTarget = 1
if usePatch {
flt = scaleFleetPatch(ctx, t, flt, scaleDownTarget)
} else {
flt = scaleFleetSubresource(ctx, t, flt, scaleDownTarget)
}
framework.AssertFleetCondition(t, flt, e2e.FleetReadyCount(0))
// delete the allocated GameServer
gp := int64(1)
err = client.GameServers(framework.Namespace).Delete(ctx, gsa.Status.GameServerName, metav1.DeleteOptions{GracePeriodSeconds: &gp})
require.NoError(t, err)
framework.AssertFleetCondition(t, flt, e2e.FleetReadyCount(1))
framework.AssertFleetCondition(t, flt, func(_ *logrus.Entry, 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()
ctx := context.Background()
fixtures := []struct {
// Use scaleFleetPatch (true) or scaleFleetSubresource (false)
usePatch bool
maxSurge string
// If true, create and cycle GS Allocations when triggering a rolling update:
// - Repeatedly allocate and shutdown GameServers (keeping ~50% of the Fleet in an Allocated state).
// - Once 50% of the Fleet is Allocated, trigger the rolling update.
// - Keep allocating/shutting down GameServers, to allocate in both the old and new GSSets.
// - Verify the rolling update completes.
// This simulates updating a Fleet that is live/in-use, and reproduces an issue where allocated GameServers
// causes a rolling update to get stuck and keep the old GameServerSet up.
cycleAllocations bool
}{
{
usePatch: true,
maxSurge: "25%",
cycleAllocations: false,
},
{
usePatch: true,
maxSurge: "10%",
cycleAllocations: false,
},
{
usePatch: false,
maxSurge: "25%",
cycleAllocations: false,
},
{
usePatch: false,
maxSurge: "10%",
cycleAllocations: false,
},
{
usePatch: true,
maxSurge: "25%",
cycleAllocations: true,
},
}
for i := range fixtures {
fixture := fixtures[i]
t.Run(fmt.Sprintf("Use fleet Patch %t %s cycle %t", fixture.usePatch, fixture.maxSurge, fixture.cycleAllocations), func(t *testing.T) {
client := framework.AgonesClient.AgonesV1()
flt := defaultFleet(framework.Namespace)
flt.ApplyDefaults()
flt.Spec.Replicas = 1
rollingUpdatePercent := intstr.FromString(fixture.maxSurge)
flt.Spec.Strategy.RollingUpdate.MaxSurge = &rollingUpdatePercent
flt.Spec.Strategy.RollingUpdate.MaxUnavailable = &rollingUpdatePercent
log := e2e.TestLogger(t).WithField("fleet", flt.ObjectMeta.Name)
flt, err := client.Fleets(framework.Namespace).Create(ctx, flt, metav1.CreateOptions{})
require.NoError(t, err)
defer client.Fleets(framework.Namespace).Delete(ctx, flt.ObjectMeta.Name, metav1.DeleteOptions{}) // nolint:errcheck
assert.Equal(t, int32(1), flt.Spec.Replicas)
assert.Equal(t, fixture.maxSurge, flt.Spec.Strategy.RollingUpdate.MaxSurge.StrVal)
assert.Equal(t, fixture.maxSurge, flt.Spec.Strategy.RollingUpdate.MaxUnavailable.StrVal)
framework.AssertFleetCondition(t, flt, e2e.FleetReadyCount(flt.Spec.Replicas))
// scale up
const targetScale = 8
if fixture.usePatch {
flt = scaleFleetPatch(ctx, t, flt, targetScale)
assert.Equal(t, int32(targetScale), flt.Spec.Replicas)
} else {
flt = scaleFleetSubresource(ctx, t, flt, targetScale)
}
framework.AssertFleetCondition(t, flt, e2e.FleetReadyCount(targetScale))
flt, err = client.Fleets(framework.Namespace).Get(ctx, flt.ObjectMeta.GetName(), metav1.GetOptions{})
require.NoError(t, err)
cycleCtx, cancelCycle := context.WithCancel(ctx)
defer cancelCycle()
if fixture.cycleAllocations {
// Repeatedly cycle allocations to keep ~half of the GameServers Allocated. Repeatedly Allocate and
// delete such that both the old and new GSSet contain allocated GameServers.
const halfScale = targetScale / 2
const period = 3 * time.Second
go framework.CycleAllocations(cycleCtx, t, flt, period, period*halfScale)
// Wait for at least half of the fleet to have be cycled (either Allocated or shutting down)
// before updating the fleet.
err = framework.WaitForFleetCondition(t, flt, func(_ *logrus.Entry, fleet *agonesv1.Fleet) bool {
return fleet.Status.ReadyReplicas < halfScale
})
}
// Change ContainerPort to trigger creating a new GSSet. Retry in case of a conflict.
fltName := flt.GetName()
require.Eventually(t, func() bool {
flt, err = client.Fleets(framework.Namespace).Get(ctx, fltName, metav1.GetOptions{})
require.NoError(t, err)
fltCopy := flt.DeepCopy()
fltCopy.Spec.Template.Spec.Ports[0].ContainerPort++
flt, err = client.Fleets(framework.Namespace).Update(ctx, fltCopy, metav1.UpdateOptions{})
if err != nil {
log.WithError(err).Info("Failed to update Fleet")
}
return err == nil
}, time.Minute, time.Second)
selector := labels.SelectorFromSet(labels.Set{agonesv1.FleetNameLabel: flt.ObjectMeta.Name})
// New GSS was created
err = wait.PollUntilContextTimeout(context.Background(), 1*time.Second, 30*time.Second, true, func(ctx context.Context) (bool, error) {
gssList, err := framework.AgonesClient.AgonesV1().GameServerSets(framework.Namespace).List(ctx,
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.PollUntilContextTimeout(context.Background(), 1*time.Second, 5*time.Minute, true, func(ctx context.Context) (bool, error) {
list, err := framework.AgonesClient.AgonesV1().GameServers(framework.Namespace).List(ctx,
metav1.ListOptions{LabelSelector: selector.String()})
if err != nil {
return false, err
}
maxSurge, err := intstr.GetScaledValueFromIntOrPercent(flt.Spec.Strategy.RollingUpdate.MaxSurge, int(flt.Spec.Replicas), true)
require.NoError(t, err)
roundUp := false
maxUnavailable, err := intstr.GetScaledValueFromIntOrPercent(flt.Spec.Strategy.RollingUpdate.MaxUnavailable, int(flt.Spec.Replicas), roundUp)
if maxUnavailable == 0 {
maxUnavailable = 1
}
// This difference is inevitable, also could be seen with Deployments and ReplicaSets
shift := maxUnavailable
require.NoError(t, err)
// Ignore any GameServers that are shutting down (resulting from Allocation cycling).
shuttingDown := 0
for _, gs := range list.Items {
if gs.IsBeingDeleted() {
shuttingDown++
}
}
expectedTotal := targetScale + maxSurge + maxUnavailable + shift + shuttingDown
if len(list.Items) > expectedTotal {
err = fmt.Errorf("new replicas should be less than target + maxSurge + maxUnavailable + shift + shuttingDown. Replicas: %d, Expected: %d", len(list.Items), expectedTotal)
}
if err != nil {
return false, err
}
gssList, err := framework.AgonesClient.AgonesV1().GameServerSets(framework.Namespace).List(ctx,
metav1.ListOptions{LabelSelector: selector.String()})
if err != nil {
return false, err
}
return len(gssList.Items) == 1, nil
})
assert.NoError(t, err)
// Stop cycling Allocations.
// The AssertFleetConditions below will wait until the Allocation cycling has
// fully stopped (when all Allocated GameServers are shut down).
cancelCycle()
// scale down, with allocation
const scaleDownTarget = 1
if fixture.usePatch {
flt = scaleFleetPatch(ctx, t, flt, scaleDownTarget)
} else {
flt = scaleFleetSubresource(ctx, t, flt, scaleDownTarget)
}
framework.AssertFleetCondition(t, flt, e2e.FleetReadyCount(1))
framework.AssertFleetCondition(t, flt, func(_ *logrus.Entry, fleet *agonesv1.Fleet) bool {
return fleet.Status.AllocatedReplicas == 0
})
})
}
}
func TestUpdateFleetReplicaAndSpec(t *testing.T) {
t.Parallel()
client := framework.AgonesClient.AgonesV1()
ctx := context.Background()
flt := defaultFleet(framework.Namespace)
flt.ApplyDefaults()
flt, err := client.Fleets(framework.Namespace).Create(ctx, flt, metav1.CreateOptions{})
require.NoError(t, err)
logrus.WithField("fleet", flt).Info("Created Fleet")
selector := labels.SelectorFromSet(labels.Set{agonesv1.FleetNameLabel: flt.ObjectMeta.Name})
framework.AssertFleetCondition(t, flt, e2e.FleetReadyCount(flt.Spec.Replicas))
require.Eventuallyf(t, func() bool {
list, err := client.GameServerSets(framework.Namespace).List(ctx,
metav1.ListOptions{LabelSelector: selector.String()})
require.NoError(t, err)
return len(list.Items) == 1
}, time.Minute, time.Second, "Wrong number of GameServerSets")
// update both replicas and template at the same time
flt, err = client.Fleets(framework.Namespace).Get(ctx, flt.ObjectMeta.GetName(), metav1.GetOptions{})
require.NoError(t, err)
fltCopy := flt.DeepCopy()
fltCopy.Spec.Replicas = 0
fltCopy.Spec.Template.Spec.Ports[0].ContainerPort++
require.NotEqual(t, flt.Spec.Template.Spec.Ports[0].ContainerPort, fltCopy.Spec.Template.Spec.Ports[0].ContainerPort)
flt, err = client.Fleets(framework.Namespace).Update(ctx, fltCopy, metav1.UpdateOptions{})
require.NoError(t, err)
require.Empty(t, flt.Spec.Replicas)
framework.AssertFleetCondition(t, flt, e2e.FleetReadyCount(flt.Spec.Replicas))
require.Eventuallyf(t, func() bool {
list, err := client.GameServerSets(framework.Namespace).List(ctx,
metav1.ListOptions{LabelSelector: selector.String()})
require.NoError(t, err)
return len(list.Items) == 1 && list.Items[0].Spec.Replicas == 0
}, time.Minute, time.Second, "Wrong number of GameServerSets")
}
func TestScaleFleetUpAndDownWithGameServerAllocation(t *testing.T) {
t.Parallel()
ctx := context.Background()
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(ctx, flt, metav1.CreateOptions{})
require.NoError(t, err)
defer client.Fleets(framework.Namespace).Delete(ctx, flt.ObjectMeta.Name, metav1.DeleteOptions{}) // 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(ctx, t, flt, targetScale)
assert.Equal(t, int32(targetScale), flt.Spec.Replicas)
} else {
flt = scaleFleetSubresource(ctx, t, flt, targetScale)
}
framework.AssertFleetCondition(t, flt, e2e.FleetReadyCount(targetScale))
// get an allocation
gsa := &allocationv1.GameServerAllocation{ObjectMeta: metav1.ObjectMeta{GenerateName: "allocation-"},
Spec: allocationv1.GameServerAllocationSpec{
Selectors: []allocationv1.GameServerSelector{{LabelSelector: metav1.LabelSelector{MatchLabels: map[string]string{agonesv1.FleetNameLabel: flt.ObjectMeta.Name}}}},
}}
gsa, err = framework.AgonesClient.AllocationV1().GameServerAllocations(framework.Namespace).Create(ctx, gsa, metav1.CreateOptions{})
require.NoError(t, err)
assert.Equal(t, allocationv1.GameServerAllocationAllocated, gsa.Status.State)
framework.AssertFleetCondition(t, flt, func(_ *logrus.Entry, fleet *agonesv1.Fleet) bool {
return fleet.Status.AllocatedReplicas == 1
})
// scale down, with allocation
const scaleDownTarget = 1
if usePatch {
flt = scaleFleetPatch(ctx, t, flt, scaleDownTarget)
} else {
flt = scaleFleetSubresource(ctx, t, flt, scaleDownTarget)
}
framework.AssertFleetCondition(t, flt, e2e.FleetReadyCount(0))
// delete the allocated GameServer
gp := int64(1)
err = client.GameServers(framework.Namespace).Delete(ctx, gsa.Status.GameServerName, metav1.DeleteOptions{GracePeriodSeconds: &gp})
require.NoError(t, err)
framework.AssertFleetCondition(t, flt, e2e.FleetReadyCount(1))
framework.AssertFleetCondition(t, flt, func(_ *logrus.Entry, fleet *agonesv1.Fleet) bool {
return fleet.Status.AllocatedReplicas == 0
})
})
}
}
func TestFleetUpdates(t *testing.T) {
t.Parallel()
ctx := context.Background()
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()
log := e2e.TestLogger(t)
flt := v()
flt.Spec.Template.ObjectMeta.Annotations = map[string]string{key: red}
flt, err := client.Fleets(framework.Namespace).Create(ctx, flt, metav1.CreateOptions{})
require.NoError(t, err)
defer client.Fleets(framework.Namespace).Delete(ctx, flt.ObjectMeta.Name, metav1.DeleteOptions{}) // nolint:errcheck
// gate that we have the keys we expect.
err = framework.WaitForFleetGameServersCondition(flt, func(gs *agonesv1.GameServer) bool {
return gs.ObjectMeta.Annotations[key] == red
})
require.NoError(t, err)
// if the generation has been updated, it's time to try again.
err = wait.PollUntilContextTimeout(context.Background(), time.Second, time.Minute, true, func(ctx context.Context) (bool, error) {
flt, err = framework.AgonesClient.AgonesV1().Fleets(framework.Namespace).Get(ctx, flt.ObjectMeta.Name, metav1.GetOptions{})
if err != nil {
log.WithError(err).WithField("flt", flt.ObjectMeta.Name).Warn("Could not retrieve fleet, trying again")
return false, err
}
fltCopy := flt.DeepCopy()
fltCopy.Spec.Template.ObjectMeta.Annotations[key] = green
_, err = framework.AgonesClient.AgonesV1().Fleets(framework.Namespace).Update(ctx, fltCopy, metav1.UpdateOptions{})
if err != nil {
log.WithError(err).WithField("flt", flt.ObjectMeta.Name).Warn("Could not update fleet, trying again")
return false, nil
}
return true, nil
})
require.NoError(t, err)
// let's make sure we're fully Ready
framework.AssertFleetCondition(t, flt, func(_ *logrus.Entry, fleet *agonesv1.Fleet) bool {
return flt.Spec.Replicas == fleet.Status.ReadyReplicas
})
// ...and fully rolled out
err = framework.WaitForFleetGameServersCondition(flt, func(gs *agonesv1.GameServer) bool {
return gs.ObjectMeta.Annotations[key] == green
})
require.NoError(t, err)
})
}
}
func TestUpdateGameServerConfigurationInFleet(t *testing.T) {
t.Parallel()
ctx := context.Background()
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(ctx, flt, metav1.CreateOptions{})
require.NoError(t, err)
defer client.Fleets(framework.Namespace).Delete(ctx, flt.ObjectMeta.Name, metav1.DeleteOptions{}) // 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{
Selectors: []allocationv1.GameServerSelector{{LabelSelector: metav1.LabelSelector{MatchLabels: map[string]string{agonesv1.FleetNameLabel: flt.ObjectMeta.Name}}}},
}}
gsa, err = framework.AgonesClient.AllocationV1().GameServerAllocations(framework.Namespace).Create(ctx, gsa, metav1.CreateOptions{})
require.NoError(t, err)
assert.Equal(t, allocationv1.GameServerAllocationAllocated, gsa.Status.State)
framework.AssertFleetCondition(t, flt, func(_ *logrus.Entry, fleet *agonesv1.Fleet) bool {
return fleet.Status.AllocatedReplicas == 1
})
flt, err = framework.AgonesClient.AgonesV1().Fleets(framework.Namespace).Get(ctx, flt.Name, metav1.GetOptions{})
require.NoError(t, err)
// 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(ctx, fltCopy, metav1.UpdateOptions{})
require.NoError(t, err)
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)
})
require.NoError(t, err)
}
func TestReservedGameServerInFleet(t *testing.T) {
t.Parallel()
ctx := context.Background()
client := framework.AgonesClient.AgonesV1()
flt := defaultFleet(framework.Namespace)
flt.Spec.Replicas = 3
flt, err := client.Fleets(framework.Namespace).Create(ctx, flt, metav1.CreateOptions{})
if assert.NoError(t, err) {
defer client.Fleets(framework.Namespace).Delete(ctx, flt.ObjectMeta.Name, metav1.DeleteOptions{}) // 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(ctx, gsCopy, metav1.UpdateOptions{})
assert.NoError(t, err)
// make sure counts are correct
framework.AssertFleetCondition(t, flt, func(_ *logrus.Entry, fleet *agonesv1.Fleet) bool {
return fleet.Status.ReadyReplicas == 2 && fleet.Status.ReservedReplicas == 1
})
// scale down to 0
flt = scaleFleetSubresource(ctx, t, flt, 0)
framework.AssertFleetCondition(t, flt, e2e.FleetReadyCount(0))
// one should be left behind
framework.AssertFleetCondition(t, flt, func(log *logrus.Entry, fleet *agonesv1.Fleet) bool {
result := fleet.Status.ReservedReplicas == 1
log.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.PollUntilContextTimeout(context.Background(), 2*time.Second, 5*time.Minute, true, func(_ context.Context) (done bool, err error) {
list, err := framework.ListGameServersFromFleet(flt)
if err != nil {
return true, err
}
l := len(list)
e := logrus.WithField("len", l)
if l >= 1 {
e = e.WithField("state", list[0].Status.State)
}
e.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()
ctx := context.Background()
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(ctx, flt, metav1.CreateOptions{})
assert.NotNil(t, err)
statusErr, ok := err.(*k8serrors.StatusError)
assert.True(t, ok)
assert.Len(t, statusErr.Status().Details.Causes, 2)
assert.Contains(t, statusErr.Status().Details.Causes[1].Message, "Container must be empty or the name of a container in the pod template")
assert.Equal(t, metav1.CauseTypeFieldValueInvalid, statusErr.Status().Details.Causes[0].Type)
assert.Contains(t, statusErr.Status().Details.Causes[0].Message, "Could not find a container named testing")
flt.Spec.Template.Spec.Container = ""
_, err = client.Fleets(framework.Namespace).Create(ctx, flt, metav1.CreateOptions{})
assert.NotNil(t, err)
statusErr, ok = err.(*k8serrors.StatusError)
assert.True(t, ok)
if assert.Len(t, statusErr.Status().Details.Causes, 2) {
assert.Equal(t, metav1.CauseTypeFieldValueInvalid, statusErr.Status().Details.Causes[1].Type)
assert.Contains(t, statusErr.Status().Details.Causes[1].Message, "Could not find a container named ")
}
assert.Equal(t, metav1.CauseTypeFieldValueRequired, statusErr.Status().Details.Causes[0].Type)
assert.Contains(t, statusErr.Status().Details.Causes[0].Message, agonesv1.ErrContainerRequired)
// use valid name for a container, one of two defined above
flt.Spec.Template.Spec.Container = containerName
_, err = client.Fleets(framework.Namespace).Create(ctx, flt, metav1.CreateOptions{})
require.NoError(t, err)
defer client.Fleets(framework.Namespace).Delete(ctx, flt.ObjectMeta.Name, metav1.DeleteOptions{}) // 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(ctx, fltPort, metav1.CreateOptions{})
assert.NotNil(t, err)
statusErr, ok = err.(*k8serrors.StatusError)
assert.True(t, ok)
assert.Len(t, statusErr.Status().Details.Causes, 1)
assert.Contains(t, statusErr.Status().Details.Causes[0].Message, agonesv1.ErrHostPort)
fltPort.Spec.Template.Spec.Ports[0].HostPort = 0 // validation fails above because the HostPort is specified, make it good.
_, err = client.Fleets(framework.Namespace).Create(ctx, fltPort, metav1.CreateOptions{})
require.NoError(t, err)
defer client.Fleets(framework.Namespace).Delete(ctx, fltPort.ObjectMeta.Name, metav1.DeleteOptions{}) // 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()
ctx := context.Background()
client := framework.AgonesClient.AgonesV1()
flt := defaultFleet(framework.Namespace)
nameLen := validation.LabelValueMaxLength + 1
flt.Name = strings.Repeat("f", nameLen)
_, err := client.Fleets(framework.Namespace).Create(ctx, flt, metav1.CreateOptions{})
require.NotNil(t, err)
statusErr := err.(*k8serrors.StatusError)
assert.True(t, len(statusErr.Status().Details.Causes) > 0)
assert.Equal(t, metav1.CauseType("FieldValueTooLong"), statusErr.Status().Details.Causes[0].Type)
goodFlt := defaultFleet(framework.Namespace)
goodFlt.Name = flt.Name[0 : nameLen-1]
goodFlt, err = client.Fleets(framework.Namespace).Create(ctx, goodFlt, metav1.CreateOptions{})
require.NoError(t, err)
defer client.Fleets(framework.Namespace).Delete(ctx, goodFlt.ObjectMeta.Name, metav1.DeleteOptions{}) // nolint:errcheck
}
func assertSuccessOrUpdateConflict(t *testing.T, err error) {
if !k8serrors.IsConflict(err) {
// update conflicts are sometimes ok, we simply lost the race.
require.NoError(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()
ctx := context.Background()
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(ctx, flt, metav1.CreateOptions{})
require.NoError(t, err)
defer client.Fleets(framework.Namespace).Delete(ctx, flt.ObjectMeta.Name, metav1.DeleteOptions{}) // nolint:errcheck
assert.Equal(t, size, flt.Spec.Replicas)
framework.AssertFleetCondition(t, flt, e2e.FleetReadyCount(flt.Spec.Replicas))
var allocs []string