Support Agones

This commit is contained in:
Daniel Oliveira
2021-01-20 19:09:21 +01:00
parent c38e020c9f
commit d8229a88df

View File

@ -1,8 +1,10 @@
package server
import (
sdk "agones.dev/agones/sdks/go"
"context"
"fmt"
quakenet "github.com/criticalstack/quake-kube/internal/quake/net"
"log"
"net/url"
"time"
@ -15,8 +17,6 @@ import (
quakeserver "github.com/criticalstack/quake-kube/internal/quake/server"
httputil "github.com/criticalstack/quake-kube/internal/util/net/http"
"github.com/criticalstack/quake-kube/public"
sdk "agones.dev/agones/sdks/go"
)
var opts struct {
@ -57,34 +57,9 @@ func NewCommand() *cobra.Command {
}
if opts.WithAgones {
log.Println("starting Agones SDK client")
s, err := sdk.NewSDK()
if err != nil {
return errors.Wrap(err, "Agones SDK could not be initialized")
if err := startAgones(ctx, opts.ServerAddr); err != nil {
log.Printf("[Agones] Error: %v", err)
}
if err := s.Ready(); err != nil {
log.Println("failed to make the server Ready")
}
go func() {
tick := time.Tick(2 * time.Second)
maxAttempts := 0
for {
if err := s.Health(); err != nil {
if maxAttempts > 5 {
log.Fatalf("Could not send health ping: %v", err)
}
maxAttempts++
}
select {
case <-ctx.Done():
log.Print("Stopped health pings")
return
case <-tick:
}
}
}()
}
go func() {
@ -126,3 +101,66 @@ func NewCommand() *cobra.Command {
cmd.Flags().BoolVar(&opts.WithAgones, "with-agones", false, "use Agones SDK integration")
return cmd
}
func startAgones(ctx context.Context, addr string) error {
log.Println("[Agones] starting Agones SDK client")
s, err := sdk.NewSDK()
if err != nil {
return err
}
if err := s.Ready(); err != nil {
log.Println("[Agones] failed to make the server Ready")
}
go func() {
tick := time.Tick(2 * time.Second)
maxAttempts := 0
for {
if err := s.Health(); err != nil {
if maxAttempts > 5 {
log.Fatalf("[Agones] could not send health ping: %v", err)
}
maxAttempts++
} else {
maxAttempts = 0
}
select {
case <-ctx.Done():
log.Print("[Agones] stopped health pings")
return
case <-tick:
}
}
}()
go func() {
tick := time.Tick(5 * time.Second)
for {
if status, err := quakenet.GetStatus(addr); err == nil {
if err != nil {
log.Printf("[Agones] failed to get status from server: %s", err.Error())
continue
}
for _, p := range status.Players {
log.Printf("[Agones] player: %s", p.Name)
if _, err := s.Alpha().PlayerConnect(p.Name); err != nil {
log.Printf("[Agones] failed to register player: %s", err.Error())
}
}
log.Println("[Agones] status checked")
}
select {
case <-ctx.Done():
log.Print("[Agones] stopped status checks")
return
case <-tick:
}
}
}()
return nil
}