-
Notifications
You must be signed in to change notification settings - Fork 820
/
sdkserver.go
1501 lines (1302 loc) · 50.2 KB
/
sdkserver.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 sdkserver
import (
"context"
"fmt"
"io"
"net/http"
"slices"
"strings"
"sync"
"time"
"github.com/mennanov/fmutils"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
corev1 "k8s.io/api/core/v1"
apiequality "k8s.io/apimachinery/pkg/api/equality"
k8serrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/kubernetes/scheme"
k8sv1 "k8s.io/client-go/kubernetes/typed/core/v1"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/tools/record"
"k8s.io/utils/clock"
"agones.dev/agones/pkg/apis/agones"
agonesv1 "agones.dev/agones/pkg/apis/agones/v1"
"agones.dev/agones/pkg/client/clientset/versioned"
typedv1 "agones.dev/agones/pkg/client/clientset/versioned/typed/agones/v1"
"agones.dev/agones/pkg/client/informers/externalversions"
listersv1 "agones.dev/agones/pkg/client/listers/agones/v1"
"agones.dev/agones/pkg/gameserverallocations"
"agones.dev/agones/pkg/sdk"
"agones.dev/agones/pkg/sdk/alpha"
"agones.dev/agones/pkg/sdk/beta"
"agones.dev/agones/pkg/util/apiserver"
"agones.dev/agones/pkg/util/logfields"
"agones.dev/agones/pkg/util/runtime"
"agones.dev/agones/pkg/util/workerqueue"
)
// Operation is a synchronisation action
type Operation string
const (
updateState Operation = "updateState"
updateLabel Operation = "updateLabel"
updateAnnotation Operation = "updateAnnotation"
updatePlayerCapacity Operation = "updatePlayerCapacity"
updateConnectedPlayers Operation = "updateConnectedPlayers"
updateCounters Operation = "updateCounters"
updateLists Operation = "updateLists"
updatePeriod time.Duration = time.Second
)
var (
_ sdk.SDKServer = &SDKServer{}
_ alpha.SDKServer = &SDKServer{}
_ beta.SDKServer = &SDKServer{}
)
type counterUpdateRequest struct {
// Capacity of the Counter as set by capacitySet.
capacitySet *int64
// Count of the Counter as set by countSet.
countSet *int64
// Tracks the sum of CountIncrement, CountDecrement, and/or CountSet requests from the client SDK.
diff int64
// Counter as retreived from the GameServer
counter agonesv1.CounterStatus
}
type listUpdateRequest struct {
// Capacity of the List as set by capacitySet.
capacitySet *int64
// String keys are the Values to remove from the List
valuesToDelete map[string]bool
// Values to add to the List
valuesToAppend []string
}
// SDKServer is a gRPC server, that is meant to be a sidecar
// for a GameServer that will update the game server status on SDK requests
//
//nolint:govet // ignore fieldalignment, singleton
type SDKServer struct {
logger *logrus.Entry
gameServerName string
namespace string
informerFactory externalversions.SharedInformerFactory
gameServerGetter typedv1.GameServersGetter
gameServerLister listersv1.GameServerLister
gameServerSynced cache.InformerSynced
connected bool
server *http.Server
clock clock.Clock
health agonesv1.Health
healthTimeout time.Duration
healthMutex sync.RWMutex
healthLastUpdated time.Time
healthFailureCount int32
healthChecksRunning sync.Once
workerqueue *workerqueue.WorkerQueue
streamMutex sync.RWMutex
connectedStreams []sdk.SDK_WatchGameServerServer
ctx context.Context
recorder record.EventRecorder
gsLabels map[string]string
gsAnnotations map[string]string
gsState agonesv1.GameServerState
gsStateChannel chan agonesv1.GameServerState
gsUpdateMutex sync.RWMutex
gsWaitForSync sync.WaitGroup
reserveTimer *time.Timer
gsReserveDuration *time.Duration
gsPlayerCapacity int64
gsConnectedPlayers []string
gsCounterUpdates map[string]counterUpdateRequest
gsListUpdates map[string]listUpdateRequest
gsCopy *agonesv1.GameServer
}
// NewSDKServer creates a SDKServer that sets up an
// InClusterConfig for Kubernetes
func NewSDKServer(gameServerName, namespace string, kubeClient kubernetes.Interface,
agonesClient versioned.Interface, logLevel logrus.Level, healthPort int) (*SDKServer, error) {
mux := http.NewServeMux()
resync := 30 * time.Second
if runtime.FeatureEnabled(runtime.FeatureDisableResyncOnSDKServer) {
resync = 0
}
// limit the informer to only working with the gameserver that the sdk is attached to
tweakListOptions := func(opts *metav1.ListOptions) {
s1 := fields.OneTermEqualSelector("metadata.name", gameServerName)
opts.FieldSelector = s1.String()
}
factory := externalversions.NewSharedInformerFactoryWithOptions(agonesClient, resync, externalversions.WithNamespace(namespace), externalversions.WithTweakListOptions(tweakListOptions))
gameServers := factory.Agones().V1().GameServers()
s := &SDKServer{
gameServerName: gameServerName,
namespace: namespace,
gameServerGetter: agonesClient.AgonesV1(),
gameServerLister: gameServers.Lister(),
gameServerSynced: gameServers.Informer().HasSynced,
server: &http.Server{
Addr: fmt.Sprintf(":%d", healthPort),
Handler: mux,
},
clock: clock.RealClock{},
healthMutex: sync.RWMutex{},
healthFailureCount: 0,
streamMutex: sync.RWMutex{},
gsLabels: map[string]string{},
gsAnnotations: map[string]string{},
gsUpdateMutex: sync.RWMutex{},
gsWaitForSync: sync.WaitGroup{},
gsConnectedPlayers: []string{},
gsStateChannel: make(chan agonesv1.GameServerState, 2),
}
if runtime.FeatureEnabled(runtime.FeatureCountsAndLists) {
// Once FeatureCountsAndLists is in GA, move this into SDKServer creation above.
s.gsCounterUpdates = map[string]counterUpdateRequest{}
s.gsListUpdates = map[string]listUpdateRequest{}
}
s.informerFactory = factory
s.logger = runtime.NewLoggerWithType(s).WithField("gsKey", namespace+"/"+gameServerName)
s.logger.Logger.SetLevel(logLevel)
_, _ = gameServers.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
UpdateFunc: func(_, newObj interface{}) {
gs := newObj.(*agonesv1.GameServer)
s.sendGameServerUpdate(gs)
},
})
eventBroadcaster := record.NewBroadcaster()
eventBroadcaster.StartLogging(s.logger.Debugf)
eventBroadcaster.StartRecordingToSink(&k8sv1.EventSinkImpl{Interface: kubeClient.CoreV1().Events("")})
s.recorder = eventBroadcaster.NewRecorder(scheme.Scheme, corev1.EventSource{Component: "gameserver-sidecar"})
mux.HandleFunc("/healthz", func(w http.ResponseWriter, _ *http.Request) {
_, err := w.Write([]byte("ok"))
if err != nil {
s.logger.WithError(err).Error("could not send ok response on healthz")
w.WriteHeader(http.StatusInternalServerError)
}
})
mux.HandleFunc("/gshealthz", func(w http.ResponseWriter, _ *http.Request) {
s.ensureHealthChecksRunning()
if s.healthy() {
_, err := w.Write([]byte("ok"))
if err != nil {
s.logger.WithError(err).Error("could not send ok response on gshealthz")
w.WriteHeader(http.StatusInternalServerError)
}
} else {
w.WriteHeader(http.StatusInternalServerError)
}
})
// we haven't synced yet
s.gsWaitForSync.Add(1)
s.workerqueue = workerqueue.NewWorkerQueue(
s.syncGameServer,
s.logger,
logfields.GameServerKey,
strings.Join([]string{agones.GroupName, s.namespace, s.gameServerName}, "."))
s.logger.Info("Created GameServer sidecar")
return s, nil
}
// Run processes the rate limited queue.
// Will block until stop is closed
func (s *SDKServer) Run(ctx context.Context) error {
s.informerFactory.Start(ctx.Done())
if !cache.WaitForCacheSync(ctx.Done(), s.gameServerSynced) {
return errors.New("failed to wait for caches to sync")
}
// need this for streaming gRPC commands
s.ctx = ctx
// we have the gameserver details now
s.gsWaitForSync.Done()
gs, err := s.gameServer()
if err != nil {
return err
}
s.health = gs.Spec.Health
s.logger.WithField("health", s.health).Debug("Setting health configuration")
s.healthTimeout = time.Duration(gs.Spec.Health.PeriodSeconds) * time.Second
s.touchHealthLastUpdated()
if gs.Status.State == agonesv1.GameServerStateReserved && gs.Status.ReservedUntil != nil {
s.gsUpdateMutex.Lock()
s.resetReserveAfter(context.Background(), time.Until(gs.Status.ReservedUntil.Time))
s.gsUpdateMutex.Unlock()
}
// populate player tracking values
if runtime.FeatureEnabled(runtime.FeaturePlayerTracking) {
s.gsUpdateMutex.Lock()
if gs.Status.Players != nil {
s.gsPlayerCapacity = gs.Status.Players.Capacity
s.gsConnectedPlayers = gs.Status.Players.IDs
}
s.gsUpdateMutex.Unlock()
}
// then start the http endpoints
s.logger.Debug("Starting SDKServer http health check...")
go func() {
if err := s.server.ListenAndServe(); err != nil {
if err == http.ErrServerClosed {
s.logger.WithError(err).Error("Health check: http server closed")
} else {
err = errors.Wrap(err, "Could not listen on :8080")
runtime.HandleError(s.logger.WithError(err), err)
}
}
}()
defer s.server.Close() // nolint: errcheck
s.workerqueue.Run(ctx, 1)
return nil
}
// WaitForConnection attempts a GameServer GET every 3s until the client responds.
// This is a workaround for the informer hanging indefinitely on first LIST due
// to a flaky network to the Kubernetes service endpoint.
func (s *SDKServer) WaitForConnection(ctx context.Context) error {
// In normal operaiton, waitForConnection is called exactly once in Run().
// In unit tests, waitForConnection() can be called before Run() to ensure
// that connected is true when Run() is called, otherwise the List() below
// may race with a test that changes a mock. (Despite the fact that we drop
// the data on the ground, the Go race detector will pereceive a data race.)
if s.connected {
return nil
}
try := 0
return wait.PollUntilContextCancel(ctx, 4*time.Second, true, func(ctx context.Context) (bool, error) {
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
defer cancel()
// Specifically use gameServerGetter since it's the raw client (gameServerLister is the informer).
// We use List here to avoid needing permission to Get().
_, err := s.gameServerGetter.GameServers(s.namespace).List(ctx, metav1.ListOptions{
FieldSelector: fields.OneTermEqualSelector("metadata.name", s.gameServerName).String(),
})
if err != nil {
s.logger.WithField("try", try).WithError(err).Info("Connection to Kubernetes service failed")
try++
return false, nil
}
s.logger.WithField("try", try).Info("Connection to Kubernetes service established")
s.connected = true
return true, nil
})
}
// syncGameServer synchronises the GameServer with the requested operations.
// The format of the key is {operation}. To prevent old operation data from
// overwriting the new one, the operation data is persisted in SDKServer.
func (s *SDKServer) syncGameServer(ctx context.Context, key string) error {
switch Operation(key) {
case updateState:
return s.updateState(ctx)
case updateLabel:
return s.updateLabels(ctx)
case updateAnnotation:
return s.updateAnnotations(ctx)
case updatePlayerCapacity:
return s.updatePlayerCapacity(ctx)
case updateConnectedPlayers:
return s.updateConnectedPlayers(ctx)
case updateCounters:
return s.updateCounter(ctx)
case updateLists:
return s.updateList(ctx)
}
return errors.Errorf("could not sync game server key: %s", key)
}
// updateState sets the GameServer Status's state to the one persisted in SDKServer,
// i.e. SDKServer.gsState.
func (s *SDKServer) updateState(ctx context.Context) error {
s.gsUpdateMutex.RLock()
s.logger.WithField("state", s.gsState).Debug("Updating state")
if len(s.gsState) == 0 {
s.gsUpdateMutex.RUnlock()
return errors.Errorf("could not update GameServer %s/%s to empty state", s.namespace, s.gameServerName)
}
s.gsUpdateMutex.RUnlock()
gs, err := s.gameServer()
if err != nil {
return err
}
// If we are currently in shutdown/being deleted, there is no escaping.
if gs.IsBeingDeleted() {
s.logger.Debug("GameServerState being shutdown. Skipping update.")
// Explicitly update gsStateChannel if current state is Shutdown since sendGameServerUpdate will not triggered.
if s.gsState == agonesv1.GameServerStateShutdown && gs.Status.State != agonesv1.GameServerStateShutdown {
go func() {
s.gsStateChannel <- agonesv1.GameServerStateShutdown
}()
}
return nil
}
// If the state is currently unhealthy, you can't go back to Ready.
if gs.Status.State == agonesv1.GameServerStateUnhealthy {
s.logger.Debug("GameServerState already unhealthy. Skipping update.")
return nil
}
s.gsUpdateMutex.RLock()
gsCopy := gs.DeepCopy()
gsCopy.Status.State = s.gsState
// If we are setting the Reserved status, check for the duration, and set that too.
if gsCopy.Status.State == agonesv1.GameServerStateReserved && s.gsReserveDuration != nil {
n := metav1.NewTime(time.Now().Add(*s.gsReserveDuration))
gsCopy.Status.ReservedUntil = &n
} else {
gsCopy.Status.ReservedUntil = nil
}
s.gsUpdateMutex.RUnlock()
// If we are setting the Allocated status, set the last-allocated annotation as well.
if gsCopy.Status.State == agonesv1.GameServerStateAllocated {
ts, err := s.clock.Now().MarshalText()
if err != nil {
return err
}
if gsCopy.ObjectMeta.Annotations == nil {
gsCopy.ObjectMeta.Annotations = map[string]string{}
}
gsCopy.ObjectMeta.Annotations[gameserverallocations.LastAllocatedAnnotationKey] = string(ts)
}
gs, err = s.patchGameServer(ctx, gs, gsCopy)
if err != nil {
return errors.Wrapf(err, "could not update GameServer %s/%s to state %s", s.namespace, s.gameServerName, gsCopy.Status.State)
}
message := "SDK state change"
level := corev1.EventTypeNormal
// post state specific work here
switch gs.Status.State {
case agonesv1.GameServerStateUnhealthy:
level = corev1.EventTypeWarning
message = "Health check failure"
case agonesv1.GameServerStateReserved:
s.gsUpdateMutex.Lock()
if s.gsReserveDuration != nil {
message += fmt.Sprintf(", for %s", s.gsReserveDuration)
s.resetReserveAfter(context.Background(), *s.gsReserveDuration)
}
s.gsUpdateMutex.Unlock()
}
s.recorder.Event(gs, level, string(gs.Status.State), message)
return nil
}
// Gets the GameServer from the cache, or from the local SDKServer if that version is more recent.
func (s *SDKServer) gameServer() (*agonesv1.GameServer, error) {
// this ensure that if we get requests for the gameserver before the cache has been synced,
// they will block here until it's ready
s.gsWaitForSync.Wait()
gs, err := s.gameServerLister.GameServers(s.namespace).Get(s.gameServerName)
if err != nil {
return gs, errors.Wrapf(err, "could not retrieve GameServer %s/%s", s.namespace, s.gameServerName)
}
s.gsUpdateMutex.RLock()
defer s.gsUpdateMutex.RUnlock()
if s.gsCopy != nil && gs.ObjectMeta.Generation < s.gsCopy.Generation {
return s.gsCopy, nil
}
return gs, nil
}
// patchGameServer is a helper function to create and apply a patch update, so the changes in
// gsCopy are applied to the original gs.
func (s *SDKServer) patchGameServer(ctx context.Context, gs, gsCopy *agonesv1.GameServer) (*agonesv1.GameServer, error) {
patch, err := gs.Patch(gsCopy)
if err != nil {
return nil, err
}
gs, err = s.gameServerGetter.GameServers(s.namespace).Patch(ctx, gs.GetObjectMeta().GetName(), types.JSONPatchType, patch, metav1.PatchOptions{})
// if the test operation fails, no reason to error log
if err != nil && k8serrors.IsInvalid(err) {
err = workerqueue.NewTraceError(err)
}
return gs, errors.Wrapf(err, "error attempting to patch gameserver: %s/%s", gsCopy.ObjectMeta.Namespace, gsCopy.ObjectMeta.Name)
}
// updateLabels updates the labels on this GameServer to the ones persisted in SDKServer,
// i.e. SDKServer.gsLabels, with the prefix of "agones.dev/sdk-"
func (s *SDKServer) updateLabels(ctx context.Context) error {
s.logger.WithField("labels", s.gsLabels).Debug("Updating label")
gs, err := s.gameServer()
if err != nil {
return err
}
gsCopy := gs.DeepCopy()
s.gsUpdateMutex.RLock()
if len(s.gsLabels) > 0 && gsCopy.ObjectMeta.Labels == nil {
gsCopy.ObjectMeta.Labels = map[string]string{}
}
for k, v := range s.gsLabels {
gsCopy.ObjectMeta.Labels[metadataPrefix+k] = v
}
s.gsUpdateMutex.RUnlock()
_, err = s.patchGameServer(ctx, gs, gsCopy)
return err
}
// updateAnnotations updates the Annotations on this GameServer to the ones persisted in SDKServer,
// i.e. SDKServer.gsAnnotations, with the prefix of "agones.dev/sdk-"
func (s *SDKServer) updateAnnotations(ctx context.Context) error {
s.logger.WithField("annotations", s.gsAnnotations).Debug("Updating annotation")
gs, err := s.gameServer()
if err != nil {
return err
}
gsCopy := gs.DeepCopy()
s.gsUpdateMutex.RLock()
if len(s.gsAnnotations) > 0 && gsCopy.ObjectMeta.Annotations == nil {
gsCopy.ObjectMeta.Annotations = map[string]string{}
}
for k, v := range s.gsAnnotations {
gsCopy.ObjectMeta.Annotations[metadataPrefix+k] = v
}
s.gsUpdateMutex.RUnlock()
_, err = s.patchGameServer(ctx, gs, gsCopy)
return err
}
// enqueueState enqueue a State change request into the
// workerqueue
func (s *SDKServer) enqueueState(state agonesv1.GameServerState) {
s.gsUpdateMutex.Lock()
// Update cached state, but prevent transitions out of `Unhealthy` by the SDK.
if s.gsState != agonesv1.GameServerStateUnhealthy {
s.gsState = state
}
s.gsUpdateMutex.Unlock()
s.workerqueue.Enqueue(cache.ExplicitKey(string(updateState)))
}
// Ready enters the RequestReady state change for this GameServer into
// the workqueue so it can be updated
func (s *SDKServer) Ready(_ context.Context, e *sdk.Empty) (*sdk.Empty, error) {
s.logger.Debug("Received Ready request, adding to queue")
s.stopReserveTimer()
s.enqueueState(agonesv1.GameServerStateRequestReady)
return e, nil
}
// Allocate enters an Allocate state change into the workqueue, so it can be updated
func (s *SDKServer) Allocate(_ context.Context, e *sdk.Empty) (*sdk.Empty, error) {
s.stopReserveTimer()
s.enqueueState(agonesv1.GameServerStateAllocated)
return e, nil
}
// Shutdown enters the Shutdown state change for this GameServer into
// the workqueue so it can be updated. If gracefulTermination feature is enabled,
// Shutdown will block on GameServer being shutdown.
func (s *SDKServer) Shutdown(_ context.Context, e *sdk.Empty) (*sdk.Empty, error) {
s.logger.Debug("Received Shutdown request, adding to queue")
s.stopReserveTimer()
s.enqueueState(agonesv1.GameServerStateShutdown)
return e, nil
}
// Health receives each health ping, and tracks the last time the health
// check was received, to track if a GameServer is healthy
func (s *SDKServer) Health(stream sdk.SDK_HealthServer) error {
for {
_, err := stream.Recv()
if err == io.EOF {
s.logger.Debug("Health stream closed.")
return stream.SendAndClose(&sdk.Empty{})
}
if err != nil {
return errors.Wrap(err, "Error with Health check")
}
s.logger.Debug("Health Ping Received")
s.touchHealthLastUpdated()
}
}
// SetLabel adds the Key/Value to be used to set the label with the metadataPrefix to the `GameServer`
// metdata
func (s *SDKServer) SetLabel(_ context.Context, kv *sdk.KeyValue) (*sdk.Empty, error) {
s.logger.WithField("values", kv).Debug("Adding SetLabel to queue")
s.gsUpdateMutex.Lock()
s.gsLabels[kv.Key] = kv.Value
s.gsUpdateMutex.Unlock()
s.workerqueue.Enqueue(cache.ExplicitKey(string(updateLabel)))
return &sdk.Empty{}, nil
}
// SetAnnotation adds the Key/Value to be used to set the annotations with the metadataPrefix to the `GameServer`
// metdata
func (s *SDKServer) SetAnnotation(_ context.Context, kv *sdk.KeyValue) (*sdk.Empty, error) {
s.logger.WithField("values", kv).Debug("Adding SetAnnotation to queue")
s.gsUpdateMutex.Lock()
s.gsAnnotations[kv.Key] = kv.Value
s.gsUpdateMutex.Unlock()
s.workerqueue.Enqueue(cache.ExplicitKey(string(updateAnnotation)))
return &sdk.Empty{}, nil
}
// GetGameServer returns the current GameServer configuration and state from the backing GameServer CRD
func (s *SDKServer) GetGameServer(context.Context, *sdk.Empty) (*sdk.GameServer, error) {
s.logger.Debug("Received GetGameServer request")
gs, err := s.gameServer()
if err != nil {
return nil, err
}
return convert(gs), nil
}
// WatchGameServer sends events through the stream when changes occur to the
// backing GameServer configuration / status
func (s *SDKServer) WatchGameServer(_ *sdk.Empty, stream sdk.SDK_WatchGameServerServer) error {
s.logger.Debug("Received WatchGameServer request, adding stream to connectedStreams")
gs, err := s.GetGameServer(context.Background(), &sdk.Empty{})
if err != nil {
return err
}
if err := stream.Send(gs); err != nil {
return err
}
s.streamMutex.Lock()
s.connectedStreams = append(s.connectedStreams, stream)
s.streamMutex.Unlock()
// don't exit until we shutdown, because that will close the stream
<-s.ctx.Done()
return nil
}
// Reserve moves this GameServer to the Reserved state for the Duration specified
func (s *SDKServer) Reserve(_ context.Context, d *sdk.Duration) (*sdk.Empty, error) {
s.stopReserveTimer()
e := &sdk.Empty{}
// 0 is forever.
if d.Seconds > 0 {
duration := time.Duration(d.Seconds) * time.Second
s.gsUpdateMutex.Lock()
s.gsReserveDuration = &duration
s.gsUpdateMutex.Unlock()
}
s.logger.Debug("Received Reserve request, adding to queue")
s.enqueueState(agonesv1.GameServerStateReserved)
return e, nil
}
// resetReserveAfter will move the GameServer back to being ready after the specified duration.
// This function should be wrapped in a s.gsUpdateMutex lock when being called.
func (s *SDKServer) resetReserveAfter(ctx context.Context, duration time.Duration) {
if s.reserveTimer != nil {
s.reserveTimer.Stop()
}
s.reserveTimer = time.AfterFunc(duration, func() {
if _, err := s.Ready(ctx, &sdk.Empty{}); err != nil {
s.logger.WithError(errors.WithStack(err)).Error("error returning to Ready after reserved")
}
})
}
// stopReserveTimer stops the reserve timer. This is a no-op and safe to call if the timer is nil
func (s *SDKServer) stopReserveTimer() {
s.gsUpdateMutex.Lock()
defer s.gsUpdateMutex.Unlock()
if s.reserveTimer != nil {
s.reserveTimer.Stop()
}
s.gsReserveDuration = nil
}
// PlayerConnect should be called when a player connects.
// [Stage:Alpha]
// [FeatureFlag:PlayerTracking]
func (s *SDKServer) PlayerConnect(_ context.Context, id *alpha.PlayerID) (*alpha.Bool, error) {
if !runtime.FeatureEnabled(runtime.FeaturePlayerTracking) {
return &alpha.Bool{Bool: false}, errors.Errorf("%s not enabled", runtime.FeaturePlayerTracking)
}
s.logger.WithField("playerID", id.PlayerID).Debug("Player Connected")
s.gsUpdateMutex.Lock()
defer s.gsUpdateMutex.Unlock()
// the player is already connected, return false.
for _, playerID := range s.gsConnectedPlayers {
if playerID == id.PlayerID {
return &alpha.Bool{Bool: false}, nil
}
}
if int64(len(s.gsConnectedPlayers)) >= s.gsPlayerCapacity {
return &alpha.Bool{Bool: false}, errors.New("players are already at capacity")
}
// let's retain the original order, as it should be a smaller patch on data change
s.gsConnectedPlayers = append(s.gsConnectedPlayers, id.PlayerID)
s.workerqueue.EnqueueAfter(cache.ExplicitKey(string(updateConnectedPlayers)), updatePeriod)
return &alpha.Bool{Bool: true}, nil
}
// PlayerDisconnect should be called when a player disconnects.
// [Stage:Alpha]
// [FeatureFlag:PlayerTracking]
func (s *SDKServer) PlayerDisconnect(_ context.Context, id *alpha.PlayerID) (*alpha.Bool, error) {
if !runtime.FeatureEnabled(runtime.FeaturePlayerTracking) {
return &alpha.Bool{Bool: false}, errors.Errorf("%s not enabled", runtime.FeaturePlayerTracking)
}
s.logger.WithField("playerID", id.PlayerID).Debug("Player Disconnected")
s.gsUpdateMutex.Lock()
defer s.gsUpdateMutex.Unlock()
found := -1
for i, playerID := range s.gsConnectedPlayers {
if playerID == id.PlayerID {
found = i
break
}
}
if found == -1 {
return &alpha.Bool{Bool: false}, nil
}
// let's retain the original order, as it should be a smaller patch on data change
s.gsConnectedPlayers = append(s.gsConnectedPlayers[:found], s.gsConnectedPlayers[found+1:]...)
s.workerqueue.EnqueueAfter(cache.ExplicitKey(string(updateConnectedPlayers)), updatePeriod)
return &alpha.Bool{Bool: true}, nil
}
// IsPlayerConnected returns if the playerID is currently connected to the GameServer.
// This is always accurate, even if the value hasn’t been updated to the GameServer status yet.
// [Stage:Alpha]
// [FeatureFlag:PlayerTracking]
func (s *SDKServer) IsPlayerConnected(_ context.Context, id *alpha.PlayerID) (*alpha.Bool, error) {
if !runtime.FeatureEnabled(runtime.FeaturePlayerTracking) {
return &alpha.Bool{Bool: false}, errors.Errorf("%s not enabled", runtime.FeaturePlayerTracking)
}
s.gsUpdateMutex.RLock()
defer s.gsUpdateMutex.RUnlock()
result := &alpha.Bool{Bool: false}
for _, playerID := range s.gsConnectedPlayers {
if playerID == id.PlayerID {
result.Bool = true
break
}
}
return result, nil
}
// GetConnectedPlayers returns the list of the currently connected player ids.
// This is always accurate, even if the value hasn’t been updated to the GameServer status yet.
// [Stage:Alpha]
// [FeatureFlag:PlayerTracking]
func (s *SDKServer) GetConnectedPlayers(_ context.Context, _ *alpha.Empty) (*alpha.PlayerIDList, error) {
if !runtime.FeatureEnabled(runtime.FeaturePlayerTracking) {
return nil, errors.Errorf("%s not enabled", runtime.FeaturePlayerTracking)
}
s.gsUpdateMutex.RLock()
defer s.gsUpdateMutex.RUnlock()
return &alpha.PlayerIDList{List: s.gsConnectedPlayers}, nil
}
// GetPlayerCount returns the current player count.
// [Stage:Alpha]
// [FeatureFlag:PlayerTracking]
func (s *SDKServer) GetPlayerCount(_ context.Context, _ *alpha.Empty) (*alpha.Count, error) {
if !runtime.FeatureEnabled(runtime.FeaturePlayerTracking) {
return nil, errors.Errorf("%s not enabled", runtime.FeaturePlayerTracking)
}
s.gsUpdateMutex.RLock()
defer s.gsUpdateMutex.RUnlock()
return &alpha.Count{Count: int64(len(s.gsConnectedPlayers))}, nil
}
// SetPlayerCapacity to change the game server's player capacity.
// [Stage:Alpha]
// [FeatureFlag:PlayerTracking]
func (s *SDKServer) SetPlayerCapacity(_ context.Context, count *alpha.Count) (*alpha.Empty, error) {
if !runtime.FeatureEnabled(runtime.FeaturePlayerTracking) {
return nil, errors.Errorf("%s not enabled", runtime.FeaturePlayerTracking)
}
s.gsUpdateMutex.Lock()
s.gsPlayerCapacity = count.Count
s.gsUpdateMutex.Unlock()
s.workerqueue.Enqueue(cache.ExplicitKey(string(updatePlayerCapacity)))
return &alpha.Empty{}, nil
}
// GetPlayerCapacity returns the current player capacity, as set by SDK.SetPlayerCapacity()
// [Stage:Alpha]
// [FeatureFlag:PlayerTracking]
func (s *SDKServer) GetPlayerCapacity(_ context.Context, _ *alpha.Empty) (*alpha.Count, error) {
if !runtime.FeatureEnabled(runtime.FeaturePlayerTracking) {
return nil, errors.Errorf("%s not enabled", runtime.FeaturePlayerTracking)
}
s.gsUpdateMutex.RLock()
defer s.gsUpdateMutex.RUnlock()
return &alpha.Count{Count: s.gsPlayerCapacity}, nil
}
// GetCounter returns a Counter. Returns error if the counter does not exist.
// [Stage:Beta]
// [FeatureFlag:CountsAndLists]
func (s *SDKServer) GetCounter(_ context.Context, in *beta.GetCounterRequest) (*beta.Counter, error) {
if !runtime.FeatureEnabled(runtime.FeatureCountsAndLists) {
return nil, errors.Errorf("%s not enabled", runtime.FeatureCountsAndLists)
}
s.logger.WithField("name", in.Name).Debug("Getting Counter")
gs, err := s.gameServer()
if err != nil {
return nil, err
}
s.gsUpdateMutex.RLock()
defer s.gsUpdateMutex.RUnlock()
counter, ok := gs.Status.Counters[in.Name]
if !ok {
return nil, errors.Errorf("counter not found: %s", in.Name)
}
s.logger.WithField("Get Counter", counter).Debugf("Got Counter %s", in.Name)
protoCounter := &beta.Counter{Name: in.Name, Count: counter.Count, Capacity: counter.Capacity}
// If there are batched changes that have not yet been applied, apply them to the Counter.
// This does NOT validate batched the changes.
if counterUpdate, ok := s.gsCounterUpdates[in.Name]; ok {
if counterUpdate.capacitySet != nil {
protoCounter.Capacity = *counterUpdate.capacitySet
}
if counterUpdate.countSet != nil {
protoCounter.Count = *counterUpdate.countSet
}
protoCounter.Count += counterUpdate.diff
if protoCounter.Count < 0 {
protoCounter.Count = 0
s.logger.Debug("truncating Count in Get Counter request to 0")
}
if protoCounter.Count > protoCounter.Capacity {
protoCounter.Count = protoCounter.Capacity
s.logger.Debug("truncating Count in Get Counter request to Capacity")
}
s.logger.WithField("Get Counter", counter).Debugf("Applied Batched Counter Updates %v", counterUpdate)
}
return protoCounter, nil
}
// UpdateCounter collapses all UpdateCounterRequests for a given Counter into a single request.
// UpdateCounterRequest must be one and only one of Capacity, Count, or CountDiff.
// Returns error if the Counter does not exist (name cannot be updated).
// Returns error if the Count is out of range [0,Capacity].
// [Stage:Beta]
// [FeatureFlag:CountsAndLists]
func (s *SDKServer) UpdateCounter(_ context.Context, in *beta.UpdateCounterRequest) (*beta.Counter, error) {
if !runtime.FeatureEnabled(runtime.FeatureCountsAndLists) {
return nil, errors.Errorf("%s not enabled", runtime.FeatureCountsAndLists)
}
if in.CounterUpdateRequest == nil {
return nil, errors.Errorf("invalid argument. CounterUpdateRequest: %v cannot be nil", in.CounterUpdateRequest)
}
if in.CounterUpdateRequest.CountDiff == 0 && in.CounterUpdateRequest.Count == nil && in.CounterUpdateRequest.Capacity == nil {
return nil, errors.Errorf("invalid argument. Malformed CounterUpdateRequest: %v", in.CounterUpdateRequest)
}
s.logger.WithField("name", in.CounterUpdateRequest.Name).Debug("Update Counter Request")
gs, err := s.gameServer()
if err != nil {
return nil, err
}
s.gsUpdateMutex.Lock()
defer s.gsUpdateMutex.Unlock()
// Check if we already have a batch request started for this Counter. If not, add new request to
// the gsCounterUpdates map.
name := in.CounterUpdateRequest.Name
batchCounter := s.gsCounterUpdates[name]
counter, ok := gs.Status.Counters[name]
// We didn't find the Counter named key in the gameserver.
if !ok {
return nil, errors.Errorf("counter not found: %s", name)
}
batchCounter.counter = *counter.DeepCopy()
// Updated based on if client call is CapacitySet
if in.CounterUpdateRequest.Capacity != nil {
if in.CounterUpdateRequest.Capacity.GetValue() < 0 {
return nil, errors.Errorf("out of range. Capacity must be greater than or equal to 0. Found Capacity: %d", in.CounterUpdateRequest.Capacity.GetValue())
}
capacitySet := in.CounterUpdateRequest.Capacity.GetValue()
batchCounter.capacitySet = &capacitySet
}
// Update based on if Client call is CountSet
if in.CounterUpdateRequest.Count != nil {
// Verify that 0 <= Count >= Capacity
countSet := in.CounterUpdateRequest.Count.GetValue()
capacity := batchCounter.counter.Capacity
if batchCounter.capacitySet != nil {
capacity = *batchCounter.capacitySet
}
if countSet < 0 || countSet > capacity {
return nil, errors.Errorf("out of range. Count must be within range [0,Capacity]. Found Count: %d, Capacity: %d", countSet, capacity)
}
batchCounter.countSet = &countSet
// Clear any previous CountIncrement or CountDecrement requests, and add the CountSet as the first item.
batchCounter.diff = 0
}
// Update based on if Client call is CountIncrement or CountDecrement
if in.CounterUpdateRequest.CountDiff != 0 {
count := batchCounter.counter.Count
if batchCounter.countSet != nil {
count = *batchCounter.countSet
}
count += batchCounter.diff + in.CounterUpdateRequest.CountDiff
// Verify that 0 <= Count >= Capacity
capacity := batchCounter.counter.Capacity
if batchCounter.capacitySet != nil {
capacity = *batchCounter.capacitySet
}
if count < 0 || count > capacity {
return nil, errors.Errorf("out of range. Count must be within range [0,Capacity]. Found Count: %d, Capacity: %d", count, capacity)
}
batchCounter.diff += in.CounterUpdateRequest.CountDiff
}
s.gsCounterUpdates[name] = batchCounter
// Queue up the Update for later batch processing by updateCounters.
s.workerqueue.Enqueue(cache.ExplicitKey(updateCounters))
return &beta.Counter{}, nil
}
// updateCounter updates the Counters in the GameServer's Status with the batched update requests.
func (s *SDKServer) updateCounter(ctx context.Context) error {
gs, err := s.gameServer()
if err != nil {
return err
}
gsCopy := gs.DeepCopy()
s.logger.WithField("batchCounterUpdates", s.gsCounterUpdates).Debug("Batch updating Counter(s)")
s.gsUpdateMutex.Lock()
defer s.gsUpdateMutex.Unlock()
names := []string{}
for name, ctrReq := range s.gsCounterUpdates {
counter, ok := gsCopy.Status.Counters[name]
if !ok {
continue
}
// Changes may have been made to the Counter since we validated the incoming changes in
// UpdateCounter, and we need to verify if the batched changes can be fully applied, partially
// applied, or cannot be applied.
if ctrReq.capacitySet != nil {
counter.Capacity = *ctrReq.capacitySet
}
if ctrReq.countSet != nil {
counter.Count = *ctrReq.countSet
}
newCnt := counter.Count + ctrReq.diff
if newCnt < 0 {
newCnt = 0
s.logger.Debug("truncating Count in Update Counter request to 0")
}
if newCnt > counter.Capacity {
newCnt = counter.Capacity
s.logger.Debug("truncating Count in Update Counter request to Capacity")
}
counter.Count = newCnt
gsCopy.Status.Counters[name] = counter
names = append(names, name)
}
gs, err = s.patchGameServer(ctx, gs, gsCopy)
if err != nil {
return err
}
// Record an event per update Counter