Last active
November 29, 2023 05:54
-
-
Save castaneai/1a1ee0c102377923d47c1a243043694a to your computer and use it in GitHub Desktop.
Agones high density GameServer example with label locking method.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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