Skip to content

Instantly share code, notes, and snippets.

@castaneai
Last active November 29, 2023 05:54
Show Gist options
  • Save castaneai/1a1ee0c102377923d47c1a243043694a to your computer and use it in GitHub Desktop.
Save castaneai/1a1ee0c102377923d47c1a243043694a to your computer and use it in GitHub Desktop.
Agones high density GameServer example with label locking method.
package main
import (
"context"
"log"
"os"
"os/signal"
"syscall"
"time"
sdkpb "agones.dev/agones/pkg/sdk"
sdk "agones.dev/agones/sdks/go"
)
func main() {
ctx, shutdown := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer shutdown()
agones, err := sdk.NewSDK()
if err != nil {
log.Fatalf("failed to connect to Agones SDK: %+v", err)
}
if err := agones.Ready(); err != nil {
log.Fatalf("failed to send Ready to Agones SDK: %+v", err)
}
if err := agones.SetLabel("available", "true"); err != nil {
log.Fatalf("failed to set label available to true: %+v", err)
}
go func() {
ticker := time.NewTicker(2 * time.Second)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
_ = agones.Health()
}
}
}()
allocatedCh := make(chan struct{})
var lastAllocated string
if err := agones.WatchGameServer(func(gs *sdkpb.GameServer) {
v, ok := gs.ObjectMeta.Annotations["agones.dev/last-allocated"]
if !ok {
return
}
if v != lastAllocated {
lastAllocated = v
allocatedCh <- struct{}{}
}
}); err != nil {
log.Fatalf("failed to watch gameserver: %+v", err)
}
for {
select {
case <-ctx.Done():
log.Printf("shutdown...")
_ = agones.Shutdown()
return
case <-allocatedCh:
setAllocatable(agones)
}
}
}
func setAllocatable(agones *sdk.SDK) {
if err := agones.SetLabel("available", "true"); err != nil {
log.Printf("failed to set available label to true: %+v", err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment