diff --git a/agent/cmd/main.go b/agent/cmd/main.go index 7e1611101..41df703c3 100644 --- a/agent/cmd/main.go +++ b/agent/cmd/main.go @@ -284,8 +284,15 @@ func main() { } return nil }(), - Usage: usageReader, - Metrics: m, + PlayerQuery: func() *caps.PlayerQuery { + if playerActions != nil { + return playerActions.Query + } + return nil + }(), + QueryHost: rconHost, + Usage: usageReader, + Metrics: m, }) go func() { diff --git a/agent/internal/a2s/a2s.go b/agent/internal/a2s/a2s.go new file mode 100644 index 000000000..2c5741dbe --- /dev/null +++ b/agent/internal/a2s/a2s.go @@ -0,0 +1,139 @@ +// Package a2s reads a game server's player counts with Valve's A2S_INFO +// query, which most Steam dedicated servers answer on their query port. +// +// Protocol reference: https://developer.valvesoftware.com/wiki/Server_queries +// +// Wire format (UDP, one datagram each way): +// +// request: FF FF FF FF | 'T'(0x54) | "Source Engine Query\x00" [| 4-byte challenge] +// reply: FF FF FF FF | 'I'(0x49) | protocol byte | name\x00 | map\x00 | +// folder\x00 | game\x00 | app ID (2 bytes, little-endian) | +// players byte | max players byte | bots byte | ... +// +// A server may answer the first request with a challenge instead, +// FF FF FF FF | 'A'(0x41) | 4-byte challenge, and then expects the request +// again with the challenge appended. Only the single-packet reply is +// supported: A2S_INFO replies fit in one datagram in practice, and a +// split reply (FE FF FF FF) is reported as an error. +package a2s + +import ( + "bytes" + "context" + "errors" + "fmt" + "net" + "time" +) + +const ( + headerInfo = 0x49 + headerChallenge = 0x41 + // Replies are at most one datagram; 1400 bytes is the protocol's + // maximum single-packet size, with headroom. + maxPacket = 4096 + // A server answers at most this many challenges before we give up, + // so a server that keeps issuing new ones can't hold the query open. + maxChallenges = 2 +) + +var ( + singlePacket = []byte{0xFF, 0xFF, 0xFF, 0xFF} + infoRequest = append(append([]byte{}, singlePacket...), append([]byte{'T'}, "Source Engine Query\x00"...)...) +) + +// Info is the part of an A2S_INFO reply that the agent reports. +type Info struct { + // Players is the number of players online, bots included. + Players int + // MaxPlayers is the server's player limit. + MaxPlayers int + // Bots is the number of those players that are bots. + Bots int +} + +// Humans is the number of online players who aren't bots. +func (i Info) Humans() int { + if i.Bots >= i.Players { + return 0 + } + return i.Players - i.Bots +} + +// QueryInfo sends A2S_INFO to addr (host:port) and parses the reply. The +// timeout bounds the whole exchange, challenge round trips included; ctx +// bounds the dial. +func QueryInfo(ctx context.Context, addr string, timeout time.Duration) (Info, error) { + dialer := net.Dialer{Timeout: timeout} + conn, err := dialer.DialContext(ctx, "udp", addr) + if err != nil { + return Info{}, fmt.Errorf("a2s dial %s: %w", addr, err) + } + defer func() { _ = conn.Close() }() + if err := conn.SetDeadline(time.Now().Add(timeout)); err != nil { + return Info{}, fmt.Errorf("a2s deadline: %w", err) + } + + req := infoRequest + buf := make([]byte, maxPacket) + for range maxChallenges + 1 { + if _, err := conn.Write(req); err != nil { + return Info{}, fmt.Errorf("a2s write: %w", err) + } + n, err := conn.Read(buf) + if err != nil { + return Info{}, fmt.Errorf("a2s read: %w", err) + } + challenge, info, err := parseReply(buf[:n]) + if err != nil { + return Info{}, err + } + if challenge == nil { + return info, nil + } + req = append(append([]byte{}, infoRequest...), challenge...) + } + return Info{}, errors.New("a2s: server kept answering with a challenge") +} + +// parseReply returns either the challenge to resend the request with, or +// the parsed info. +func parseReply(b []byte) (challenge []byte, info Info, err error) { + if len(b) < 5 || !bytes.Equal(b[:4], singlePacket) { + return nil, Info{}, errors.New("a2s: not a single-packet reply") + } + switch b[4] { + case headerChallenge: + if len(b) < 9 { + return nil, Info{}, errors.New("a2s: short challenge") + } + return append([]byte{}, b[5:9]...), Info{}, nil + case headerInfo: + info, err := parseInfo(b[5:]) + return nil, info, err + default: + return nil, Info{}, fmt.Errorf("a2s: unexpected reply header 0x%02x", b[4]) + } +} + +// parseInfo parses an A2S_INFO payload, after its 0x49 header. +func parseInfo(b []byte) (Info, error) { + // Protocol version byte. + if len(b) < 1 { + return Info{}, errors.New("a2s: short info reply") + } + b = b[1:] + // Name, map, folder and game. + for range 4 { + i := bytes.IndexByte(b, 0) + if i < 0 { + return Info{}, errors.New("a2s: truncated string in info reply") + } + b = b[i+1:] + } + // App ID (2 bytes), then players, max players and bots. + if len(b) < 5 { + return Info{}, errors.New("a2s: short info reply") + } + return Info{Players: int(b[2]), MaxPlayers: int(b[3]), Bots: int(b[4])}, nil +} diff --git a/agent/internal/a2s/a2s_test.go b/agent/internal/a2s/a2s_test.go new file mode 100644 index 000000000..571cfeb7f --- /dev/null +++ b/agent/internal/a2s/a2s_test.go @@ -0,0 +1,131 @@ +package a2s + +import ( + "bytes" + "net" + "strings" + "testing" + "time" +) + +// infoReply builds an A2S_INFO reply with the given counts. +func infoReply(players, maxPlayers, bots byte) []byte { + b := append([]byte{}, singlePacket...) + b = append(b, headerInfo, 17) + b = append(b, "My Server\x00Dedicated\x00valheim\x00Valheim\x00"...) + b = append(b, 0x00, 0x00) // app ID + return append(b, players, maxPlayers, bots, 'd', 'l', 0, 1) +} + +// serve answers each request on a loopback UDP socket with reply(request). +func serve(t *testing.T, reply func(req []byte) []byte) string { + t.Helper() + pc, err := (&net.ListenConfig{}).ListenPacket(t.Context(), "udp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = pc.Close() }) + go func() { + buf := make([]byte, maxPacket) + for { + n, addr, err := pc.ReadFrom(buf) + if err != nil { + return + } + if r := reply(append([]byte{}, buf[:n]...)); r != nil { + _, _ = pc.WriteTo(r, addr) + } + } + }() + return pc.LocalAddr().String() +} + +func TestQueryInfo(t *testing.T) { + addr := serve(t, func(req []byte) []byte { + if !bytes.Equal(req, infoRequest) { + t.Errorf("request = %q, want %q", req, infoRequest) + } + return infoReply(3, 10, 1) + }) + info, err := QueryInfo(t.Context(), addr, time.Second) + if err != nil { + t.Fatal(err) + } + if info != (Info{Players: 3, MaxPlayers: 10, Bots: 1}) { + t.Errorf("info = %+v", info) + } + if info.Humans() != 2 { + t.Errorf("Humans() = %d, want 2", info.Humans()) + } +} + +func TestQueryInfoChallenge(t *testing.T) { + challenge := []byte{0xDE, 0xAD, 0xBE, 0xEF} + addr := serve(t, func(req []byte) []byte { + if bytes.HasSuffix(req, challenge) { + return infoReply(0, 10, 0) + } + return append(append(append([]byte{}, singlePacket...), headerChallenge), challenge...) + }) + info, err := QueryInfo(t.Context(), addr, time.Second) + if err != nil { + t.Fatal(err) + } + if info.Players != 0 || info.MaxPlayers != 10 { + t.Errorf("info = %+v", info) + } +} + +func TestQueryInfoEndlessChallenge(t *testing.T) { + addr := serve(t, func([]byte) []byte { + return append(append([]byte{}, singlePacket...), headerChallenge, 1, 2, 3, 4) + }) + if _, err := QueryInfo(t.Context(), addr, time.Second); err == nil || !strings.Contains(err.Error(), "challenge") { + t.Errorf("err = %v, want a challenge error", err) + } +} + +func TestQueryInfoTimeout(t *testing.T) { + addr := serve(t, func([]byte) []byte { return nil }) + if _, err := QueryInfo(t.Context(), addr, 100*time.Millisecond); err == nil { + t.Error("want a timeout error") + } +} + +func TestQueryInfoBadAddress(t *testing.T) { + if _, err := QueryInfo(t.Context(), "no-port", time.Second); err == nil || !strings.Contains(err.Error(), "dial") { + t.Errorf("err = %v, want a dial error", err) + } +} + +func TestQueryInfoMalformedReply(t *testing.T) { + addr := serve(t, func([]byte) []byte { return []byte{0xFF, 0xFF, 0xFF, 0xFF, 0x6D} }) + if _, err := QueryInfo(t.Context(), addr, time.Second); err == nil || !strings.Contains(err.Error(), "header") { + t.Errorf("err = %v, want an unexpected-header error", err) + } +} + +func TestParseReplyErrors(t *testing.T) { + cases := map[string][]byte{ + "empty": nil, + "split packet": {0xFE, 0xFF, 0xFF, 0xFF, headerInfo}, + "unknown header": {0xFF, 0xFF, 0xFF, 0xFF, 0x6D}, + "short challenge": {0xFF, 0xFF, 0xFF, 0xFF, headerChallenge, 1}, + "no protocol": {0xFF, 0xFF, 0xFF, 0xFF, headerInfo}, + "truncated string": append([]byte{0xFF, 0xFF, 0xFF, 0xFF, headerInfo, 17}, "name"...), + "no counts": append([]byte{0xFF, 0xFF, 0xFF, 0xFF, headerInfo, 17}, "a\x00b\x00c\x00d\x00\x00"...), + } + for name, b := range cases { + t.Run(name, func(t *testing.T) { + if _, _, err := parseReply(b); err == nil { + t.Error("want an error") + } + }) + } +} + +func TestHumansNeverNegative(t *testing.T) { + if got := (Info{Players: 1, Bots: 2}).Humans(); got != 0 { + t.Errorf("Humans() = %d, want 0", got) + } +} diff --git a/agent/internal/caps/caps.go b/agent/internal/caps/caps.go index cf89d253f..d05239753 100644 --- a/agent/internal/caps/caps.go +++ b/agent/internal/caps/caps.go @@ -109,6 +109,18 @@ type PlayerActions struct { BanList *BanList `json:"banList,omitempty"` Whitelist *Whitelist `json:"whitelist,omitempty"` List *PlayerList `json:"list,omitempty"` + // Query reads the online player count over a server query protocol + // instead of the console. The heartbeat prefers it when set. + Query *PlayerQuery `json:"query,omitempty"` +} + +// PlayerQuery mirrors spec.capabilities.players.query: a server query +// protocol, answered inside the pod, that reports the player count. +type PlayerQuery struct { + // Protocol is the query protocol; "a2s" (Valve's A2S_INFO) is the only one. + Protocol string `json:"protocol"` + // Port is the UDP port that answers the query. + Port int `json:"port"` } // BanList reads and parses the game's ban list. diff --git a/agent/internal/heartbeat/heartbeat.go b/agent/internal/heartbeat/heartbeat.go index 3de616703..55cd30071 100644 --- a/agent/internal/heartbeat/heartbeat.go +++ b/agent/internal/heartbeat/heartbeat.go @@ -19,8 +19,10 @@ import ( "encoding/json" "fmt" "log/slog" + "net" "os" "regexp" + "strconv" "time" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -29,6 +31,7 @@ import ( "k8s.io/client-go/dynamic" "k8s.io/client-go/rest" + "github.com/GameplanePanel/gameplane/agent/internal/a2s" "github.com/GameplanePanel/gameplane/agent/internal/caps" "github.com/GameplanePanel/gameplane/agent/internal/metrics" "github.com/GameplanePanel/gameplane/agent/internal/players" @@ -59,7 +62,12 @@ type Config struct { Usage UsageReader PlayerList *caps.PlayerList PlayerListRE *regexp.Regexp - Metrics *metrics.Metrics + // PlayerQuery, when set, replaces the console player list as the + // source of player counts. QueryHost is where it is sent (loopback in + // the pod); empty means 127.0.0.1. + PlayerQuery *caps.PlayerQuery + QueryHost string + Metrics *metrics.Metrics } var gvr = schema.GroupVersionResource{ @@ -156,7 +164,7 @@ func sendOnce(ctx context.Context, dyn dynamic.Interface, cfg Config) error { // with null clears any prior value. playersMax stays null when the game // reports an online count but no maximum, so the dashboard shows "—" // rather than a bogus cap of 0. - if online, maxN, err := queryPlayerCounts(cfg); err == nil { + if online, maxN, err := queryPlayerCounts(ctx, cfg); err == nil { agent["playersOnline"] = online // Status patch: playersMax is only emitted when maxN > 0 (a real // finite limit). Unknown (maxN=0) and unlimited (maxN=-1) both patch @@ -239,7 +247,10 @@ func nullable(v int64, known bool) any { // When EntryRegex is configured, the online count is the number of regex // matches. err is non-nil only when RCON fails or no online count can be // parsed at all. -func queryPlayerCounts(cfg Config) (online, maxPlayers int, err error) { +func queryPlayerCounts(ctx context.Context, cfg Config) (online, maxPlayers int, err error) { + if cfg.PlayerQuery != nil { + return queryPlayerCountsA2S(ctx, cfg) + } cmd := "list" if cfg.PlayerList != nil && cfg.PlayerList.Command != "" { cmd = cfg.PlayerList.Command @@ -274,6 +285,28 @@ func queryPlayerCounts(cfg Config) (online, maxPlayers int, err error) { return 0, maxPlayers, fmt.Errorf("no player count in %q", raw) } +// a2sTimeout bounds one player-count query, well inside the heartbeat +// interval. +const a2sTimeout = 2 * time.Second + +// queryPlayerCountsA2S reads the player count over the declared query +// protocol. Bots don't count as players, so a server with only bots on it +// reports 0 and can sleep. A server limit of 0 is reported as unknown. +func queryPlayerCountsA2S(ctx context.Context, cfg Config) (online, maxPlayers int, err error) { + if cfg.PlayerQuery.Protocol != "a2s" { + return 0, 0, fmt.Errorf("unsupported player query protocol %q", cfg.PlayerQuery.Protocol) + } + host := cfg.QueryHost + if host == "" { + host = "127.0.0.1" + } + info, err := a2s.QueryInfo(ctx, net.JoinHostPort(host, strconv.Itoa(cfg.PlayerQuery.Port)), a2sTimeout) + if err != nil { + return 0, 0, fmt.Errorf("player query: %w", err) + } + return info.Humans(), info.MaxPlayers, nil +} + // readNamespace reads the SA-projected namespace file written into // every pod. func readNamespace() string { diff --git a/agent/internal/heartbeat/heartbeat_test.go b/agent/internal/heartbeat/heartbeat_test.go index 531075f07..df212aaa0 100644 --- a/agent/internal/heartbeat/heartbeat_test.go +++ b/agent/internal/heartbeat/heartbeat_test.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "errors" + "net" "os" "path/filepath" "strings" @@ -333,7 +334,7 @@ func TestQueryPlayerCounts(t *testing.T) { for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { cfg := Config{RCON: fakeRcon{out: tc.out, err: tc.err}} - n, maxN, err := queryPlayerCounts(cfg) + n, maxN, err := queryPlayerCounts(t.Context(), cfg) if (err == nil) != tc.ok { t.Fatalf("err=%v ok=%v", err, tc.ok) } @@ -354,7 +355,7 @@ func TestQueryPlayerCounts_CustomCommand(t *testing.T) { Command: "mylist", }, } - n, maxN, err := queryPlayerCounts(cfg) + n, maxN, err := queryPlayerCounts(t.Context(), cfg) if err != nil { t.Fatalf("queryPlayerCounts: %v", err) } @@ -379,7 +380,7 @@ func TestQueryPlayerCounts_WithRegex(t *testing.T) { }, PlayerListRE: re, } - n, maxN, err := queryPlayerCounts(cfg) + n, maxN, err := queryPlayerCounts(t.Context(), cfg) if err != nil { t.Fatalf("queryPlayerCounts: %v", err) } @@ -391,6 +392,69 @@ func TestQueryPlayerCounts_WithRegex(t *testing.T) { } } +// a2sServer answers A2S_INFO on a loopback UDP port with the given counts, +// and returns that port. +func a2sServer(t *testing.T, playersN, maxN, bots byte) int { + t.Helper() + pc, err := (&net.ListenConfig{}).ListenPacket(t.Context(), "udp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = pc.Close() }) + reply := append([]byte{0xFF, 0xFF, 0xFF, 0xFF, 0x49, 17}, "Server\x00Map\x00valheim\x00Valheim\x00\x00\x00"...) + reply = append(reply, playersN, maxN, bots) + go func() { + buf := make([]byte, 1500) + for { + _, addr, err := pc.ReadFrom(buf) + if err != nil { + return + } + _, _ = pc.WriteTo(reply, addr) + } + }() + return pc.LocalAddr().(*net.UDPAddr).Port +} + +func TestQueryPlayerCounts_A2S(t *testing.T) { + cfg := Config{ + // The query replaces the console: a console answer must be ignored. + RCON: fakeRcon{out: "There are 9 of a max of 99 players online:"}, + PlayerQuery: &caps.PlayerQuery{Protocol: "a2s", Port: a2sServer(t, 3, 10, 1)}, + } + n, maxN, err := queryPlayerCounts(t.Context(), cfg) + if err != nil { + t.Fatalf("queryPlayerCounts: %v", err) + } + if n != 2 { + t.Fatalf("online got %d, want 2 (bots don't count)", n) + } + if maxN != 10 { + t.Fatalf("max got %d, want 10", maxN) + } +} + +func TestQueryPlayerCounts_A2SErrors(t *testing.T) { + // Nothing listens on a closed socket's port, so the query fails rather + // than reporting 0: an unreachable server is unknown, not empty. + pc, err := (&net.ListenConfig{}).ListenPacket(t.Context(), "udp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + closedPort := pc.LocalAddr().(*net.UDPAddr).Port + _ = pc.Close() + for name, q := range map[string]*caps.PlayerQuery{ + "unreachable": {Protocol: "a2s", Port: closedPort}, + "unknown protocol": {Protocol: "gamespy", Port: closedPort}, + } { + t.Run(name, func(t *testing.T) { + if _, _, err := queryPlayerCounts(t.Context(), Config{PlayerQuery: q}); err == nil { + t.Fatal("want an error") + } + }) + } +} + func TestReadNamespace(t *testing.T) { // In a normal CI/test env this file is absent; readNamespace must // return "" rather than panicking. diff --git a/agent/specs.md b/agent/specs.md index 733efb84e..e5de61231 100644 --- a/agent/specs.md +++ b/agent/specs.md @@ -62,6 +62,7 @@ agent/ ├── cmd/main.go # Entry point: flag parsing, auth setup, chi router, heartbeat goroutine ├── cmd/metrics.go # Separate plain-HTTP /metrics listener (--metrics-addr), off the mTLS control mux ├── internal/ +│ ├── a2s/ # Valve A2S_INFO client for player counts (capabilities.players.query) │ ├── actions/ # Module-declared operator actions (templated RCON) │ ├── auth/ # Request authenticator (mTLS + bearer token) │ ├── caps/ # Mirrors GameTemplate.spec.capabilities schema (JSON unmarshaling) @@ -99,10 +100,14 @@ Per-package roles: connection. Established connections keep their existing TLS state. Regular PEM files are also supported; replace the set consistently to avoid temporary handshake failures during updates. +- **`a2s`**: `QueryInfo(ctx, addr, timeout)` sends Valve's A2S_INFO request over UDP and parses the single-packet reply (`FF FF FF FF 'I'`, protocol byte, four NUL-terminated strings, app ID, then the players, max players and bots bytes). A challenge reply (`FF FF FF FF 'A'` + 4 bytes) is answered by resending the request with the challenge appended, at most twice; a server still challenging after that is an error. The timeout bounds the whole exchange. Split replies (`FE FF FF FF`), any other header, truncated strings and short replies are errors; nothing after the bots byte is read. `Info.Humans()` is players minus bots, never below 0. - **`caps`**: Unmarshals JSON capabilities blob from `GAMEPLANE_CAPABILITIES` env; exposes `Spec` with `Players`, `Quiesce`, `Lifecycle`, `Actions`, `Status`, `Mods`. - **`console`**: Accepts `{ kind: "cmd", body: "" }` JSON over WebSocket, runs it via RCON, replies with `{ kind: "out"|"err", body: "" }`. On an RCON failure the `err` body is the generic `upstream unavailable`; the detailed error is logged with every occurrence of the submitted command replaced by ``, since RCON clients embed the command in their errors and it may carry a secret. - **`files`**: Walks the filesystem under `--data-root`, validates paths lexically, then performs every operation relative to a directory descriptor on the root with `openat(O_NOFOLLOW)` per component (no `..`, no symlink at any component), handles multipart uploads. - **`heartbeat`**: Runs a background goroutine that every 20 seconds patches `gameservers//status` with `status.agent.lastHeartbeat`, `status.agent.playersOnline`, `status.agent.playersMax`, `status.agent.gameVersion`, and resource usage via the pod's ServiceAccount. `gameVersion` is currently always patched `null` ("unknown") — the agent has no source for the game's actual running version; it must never be filled in with the game/template identifier (e.g. `minecraft-java`), which is a different value. + - **Player-count source precedence:** when the capabilities declare `players.query`, the heartbeat's count comes only from that query (`queryPlayerCountsA2S`), sent to `--rcon-host` (loopback) on the declared port with a 2-second timeout; the console `players.list` command is not consulted for the count, even when RCON is configured, and is never a fallback. Without `players.query`, the count comes from the console list, as before. `players.query` affects only the heartbeat: the `/players` route, the Players tab list and moderation still use the console. + - **Bots:** an A2S count is `players − bots` (clamped at 0), so a server with only bots on it reports 0 and can sleep. `playersMax` is the reply's max players; 0 is patched as unknown (null). + - **Failure:** an unsupported protocol, a dial, write or read error, a timeout, a malformed or split reply, or a server that keeps challenging makes the query fail for that heartbeat, and `playersOnline` and `playersMax` are patched null ("unknown"), clearing any earlier count. Unknown is never reported as 0, so a failing query keeps the server awake (see the operator's idle rule); the next heartbeat queries again. - **`lifecycle`**: HTTP handler for the operator's `/lifecycle/stop` call; runs module-declared stop commands over RCON before the game process terminates. - **`logs`**: Tails a game log file (path from `--game-log-path`) over WebSocket; supports streaming from end (default, "live") or start ("backlog"). Absolute paths must be inside `--data-root`; relative paths resolve beneath it. Downloads and all tail opens, rotation probes, and reopens use regular-file descriptors confined to the trusted data root. Symlinks in any component below the root and nonregular files are rejected; FIFO rejection does not block. Downloads serve the opened descriptor even if the path changes. Ordinary rename rotation and missing-file retries remain supported. Filesystem failures use generic client errors. - **`mods`**: Tracks installed mods in a per-volume manifest (`.gameplane-mods.json`); downloads from registry with strict egress validation via `netguard.IsPublic`. diff --git a/changelog/unreleased/991-a2s-player-count.md b/changelog/unreleased/991-a2s-player-count.md new file mode 100644 index 000000000..1b2c27393 --- /dev/null +++ b/changelog/unreleased/991-a2s-player-count.md @@ -0,0 +1,7 @@ +# Player counts from the Steam server query + +A module can read its player count over Valve's A2S query instead of the +console, with `capabilities.players.query` (`protocol: a2s` and the UDP query +port). Games without a console that lists players, such as Valheim, which has +no RCON, can then show a player count and sleep when empty. +[PR #991](https://github.com/GameplanePanel/Gameplane/pull/991) diff --git a/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_backups.yaml b/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_backups.yaml index bc3f3ac1d..3ffc19740 100644 --- a/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_backups.yaml +++ b/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_backups.yaml @@ -3,7 +3,7 @@ apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: annotations: - gameplane.local/crd-bundle-sha256: 2baa2e6e380e574531191108c18a893841f7b89399fc8216fd13bc22d1a6caf8 + gameplane.local/crd-bundle-sha256: f6d823caf1184485fc5a5cec8ff73668bbf02fbd250b06f24c9139766558b017 controller-gen.kubebuilder.io/version: v0.22.0 name: backups.gameplane.local spec: diff --git a/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_backupschedules.yaml b/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_backupschedules.yaml index f33859e4a..baa2cd0ea 100644 --- a/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_backupschedules.yaml +++ b/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_backupschedules.yaml @@ -3,7 +3,7 @@ apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: annotations: - gameplane.local/crd-bundle-sha256: 2baa2e6e380e574531191108c18a893841f7b89399fc8216fd13bc22d1a6caf8 + gameplane.local/crd-bundle-sha256: f6d823caf1184485fc5a5cec8ff73668bbf02fbd250b06f24c9139766558b017 controller-gen.kubebuilder.io/version: v0.22.0 name: backupschedules.gameplane.local spec: diff --git a/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_clusters.yaml b/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_clusters.yaml index d0365960b..bf894b0e4 100644 --- a/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_clusters.yaml +++ b/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_clusters.yaml @@ -3,7 +3,7 @@ apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: annotations: - gameplane.local/crd-bundle-sha256: 2baa2e6e380e574531191108c18a893841f7b89399fc8216fd13bc22d1a6caf8 + gameplane.local/crd-bundle-sha256: f6d823caf1184485fc5a5cec8ff73668bbf02fbd250b06f24c9139766558b017 controller-gen.kubebuilder.io/version: v0.22.0 name: clusters.gameplane.local spec: diff --git a/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_gameservers.yaml b/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_gameservers.yaml index caa94093b..842028872 100644 --- a/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_gameservers.yaml +++ b/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_gameservers.yaml @@ -3,7 +3,7 @@ apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: annotations: - gameplane.local/crd-bundle-sha256: 2baa2e6e380e574531191108c18a893841f7b89399fc8216fd13bc22d1a6caf8 + gameplane.local/crd-bundle-sha256: f6d823caf1184485fc5a5cec8ff73668bbf02fbd250b06f24c9139766558b017 controller-gen.kubebuilder.io/version: v0.22.0 name: gameservers.gameplane.local spec: diff --git a/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_gametemplates.yaml b/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_gametemplates.yaml index eeedfd49d..e5f5cd9ea 100644 --- a/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_gametemplates.yaml +++ b/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_gametemplates.yaml @@ -3,7 +3,7 @@ apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: annotations: - gameplane.local/crd-bundle-sha256: 2baa2e6e380e574531191108c18a893841f7b89399fc8216fd13bc22d1a6caf8 + gameplane.local/crd-bundle-sha256: f6d823caf1184485fc5a5cec8ff73668bbf02fbd250b06f24c9139766558b017 controller-gen.kubebuilder.io/version: v0.22.0 name: gametemplates.gameplane.local spec: @@ -871,6 +871,34 @@ spec: required: - command type: object + query: + description: |- + Query reads the online player count from a server query protocol + instead of the console, for games with no console that lists players + (Valheim has no RCON at all). When set, the heartbeat's player count, + which idle sleep relies on, comes from this query. The Players tab's + list and moderation still use the console. + properties: + port: + description: |- + Port is the UDP port, inside the pod, that answers the query: for + Valheim, 2457 (the game port plus one). + format: int32 + maximum: 65535 + minimum: 1 + type: integer + protocol: + description: |- + Protocol is the query protocol. "a2s" is Valve's Steam server query + (A2S_INFO over UDP), which most Steam dedicated servers answer on + their query port. + enum: + - a2s + type: string + required: + - port + - protocol + type: object unban: description: Unban lifts a ban, e.g. "pardon {{.Player}}". type: string diff --git a/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_modules.yaml b/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_modules.yaml index eba6cab84..aee445da9 100644 --- a/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_modules.yaml +++ b/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_modules.yaml @@ -3,7 +3,7 @@ apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: annotations: - gameplane.local/crd-bundle-sha256: 2baa2e6e380e574531191108c18a893841f7b89399fc8216fd13bc22d1a6caf8 + gameplane.local/crd-bundle-sha256: f6d823caf1184485fc5a5cec8ff73668bbf02fbd250b06f24c9139766558b017 controller-gen.kubebuilder.io/version: v0.22.0 name: modules.gameplane.local spec: diff --git a/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_modulesources.yaml b/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_modulesources.yaml index 3dbc18243..9339dd748 100644 --- a/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_modulesources.yaml +++ b/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_modulesources.yaml @@ -3,7 +3,7 @@ apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: annotations: - gameplane.local/crd-bundle-sha256: 2baa2e6e380e574531191108c18a893841f7b89399fc8216fd13bc22d1a6caf8 + gameplane.local/crd-bundle-sha256: f6d823caf1184485fc5a5cec8ff73668bbf02fbd250b06f24c9139766558b017 controller-gen.kubebuilder.io/version: v0.22.0 name: modulesources.gameplane.local spec: diff --git a/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_networkcaptures.yaml b/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_networkcaptures.yaml index 32f1924e7..586891bc2 100644 --- a/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_networkcaptures.yaml +++ b/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_networkcaptures.yaml @@ -3,7 +3,7 @@ apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: annotations: - gameplane.local/crd-bundle-sha256: 2baa2e6e380e574531191108c18a893841f7b89399fc8216fd13bc22d1a6caf8 + gameplane.local/crd-bundle-sha256: f6d823caf1184485fc5a5cec8ff73668bbf02fbd250b06f24c9139766558b017 controller-gen.kubebuilder.io/version: v0.22.0 name: networkcaptures.gameplane.local spec: diff --git a/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_restores.yaml b/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_restores.yaml index 811681208..782c4e556 100644 --- a/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_restores.yaml +++ b/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_restores.yaml @@ -3,7 +3,7 @@ apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: annotations: - gameplane.local/crd-bundle-sha256: 2baa2e6e380e574531191108c18a893841f7b89399fc8216fd13bc22d1a6caf8 + gameplane.local/crd-bundle-sha256: f6d823caf1184485fc5a5cec8ff73668bbf02fbd250b06f24c9139766558b017 controller-gen.kubebuilder.io/version: v0.22.0 name: restores.gameplane.local spec: diff --git a/charts/gameplane/crd-manifests/gameplane.local_backups.yaml b/charts/gameplane/crd-manifests/gameplane.local_backups.yaml index bc3f3ac1d..3ffc19740 100644 --- a/charts/gameplane/crd-manifests/gameplane.local_backups.yaml +++ b/charts/gameplane/crd-manifests/gameplane.local_backups.yaml @@ -3,7 +3,7 @@ apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: annotations: - gameplane.local/crd-bundle-sha256: 2baa2e6e380e574531191108c18a893841f7b89399fc8216fd13bc22d1a6caf8 + gameplane.local/crd-bundle-sha256: f6d823caf1184485fc5a5cec8ff73668bbf02fbd250b06f24c9139766558b017 controller-gen.kubebuilder.io/version: v0.22.0 name: backups.gameplane.local spec: diff --git a/charts/gameplane/crd-manifests/gameplane.local_backupschedules.yaml b/charts/gameplane/crd-manifests/gameplane.local_backupschedules.yaml index f33859e4a..baa2cd0ea 100644 --- a/charts/gameplane/crd-manifests/gameplane.local_backupschedules.yaml +++ b/charts/gameplane/crd-manifests/gameplane.local_backupschedules.yaml @@ -3,7 +3,7 @@ apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: annotations: - gameplane.local/crd-bundle-sha256: 2baa2e6e380e574531191108c18a893841f7b89399fc8216fd13bc22d1a6caf8 + gameplane.local/crd-bundle-sha256: f6d823caf1184485fc5a5cec8ff73668bbf02fbd250b06f24c9139766558b017 controller-gen.kubebuilder.io/version: v0.22.0 name: backupschedules.gameplane.local spec: diff --git a/charts/gameplane/crd-manifests/gameplane.local_clusters.yaml b/charts/gameplane/crd-manifests/gameplane.local_clusters.yaml index d0365960b..bf894b0e4 100644 --- a/charts/gameplane/crd-manifests/gameplane.local_clusters.yaml +++ b/charts/gameplane/crd-manifests/gameplane.local_clusters.yaml @@ -3,7 +3,7 @@ apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: annotations: - gameplane.local/crd-bundle-sha256: 2baa2e6e380e574531191108c18a893841f7b89399fc8216fd13bc22d1a6caf8 + gameplane.local/crd-bundle-sha256: f6d823caf1184485fc5a5cec8ff73668bbf02fbd250b06f24c9139766558b017 controller-gen.kubebuilder.io/version: v0.22.0 name: clusters.gameplane.local spec: diff --git a/charts/gameplane/crd-manifests/gameplane.local_gameservers.yaml b/charts/gameplane/crd-manifests/gameplane.local_gameservers.yaml index caa94093b..842028872 100644 --- a/charts/gameplane/crd-manifests/gameplane.local_gameservers.yaml +++ b/charts/gameplane/crd-manifests/gameplane.local_gameservers.yaml @@ -3,7 +3,7 @@ apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: annotations: - gameplane.local/crd-bundle-sha256: 2baa2e6e380e574531191108c18a893841f7b89399fc8216fd13bc22d1a6caf8 + gameplane.local/crd-bundle-sha256: f6d823caf1184485fc5a5cec8ff73668bbf02fbd250b06f24c9139766558b017 controller-gen.kubebuilder.io/version: v0.22.0 name: gameservers.gameplane.local spec: diff --git a/charts/gameplane/crd-manifests/gameplane.local_gametemplates.yaml b/charts/gameplane/crd-manifests/gameplane.local_gametemplates.yaml index eeedfd49d..e5f5cd9ea 100644 --- a/charts/gameplane/crd-manifests/gameplane.local_gametemplates.yaml +++ b/charts/gameplane/crd-manifests/gameplane.local_gametemplates.yaml @@ -3,7 +3,7 @@ apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: annotations: - gameplane.local/crd-bundle-sha256: 2baa2e6e380e574531191108c18a893841f7b89399fc8216fd13bc22d1a6caf8 + gameplane.local/crd-bundle-sha256: f6d823caf1184485fc5a5cec8ff73668bbf02fbd250b06f24c9139766558b017 controller-gen.kubebuilder.io/version: v0.22.0 name: gametemplates.gameplane.local spec: @@ -871,6 +871,34 @@ spec: required: - command type: object + query: + description: |- + Query reads the online player count from a server query protocol + instead of the console, for games with no console that lists players + (Valheim has no RCON at all). When set, the heartbeat's player count, + which idle sleep relies on, comes from this query. The Players tab's + list and moderation still use the console. + properties: + port: + description: |- + Port is the UDP port, inside the pod, that answers the query: for + Valheim, 2457 (the game port plus one). + format: int32 + maximum: 65535 + minimum: 1 + type: integer + protocol: + description: |- + Protocol is the query protocol. "a2s" is Valve's Steam server query + (A2S_INFO over UDP), which most Steam dedicated servers answer on + their query port. + enum: + - a2s + type: string + required: + - port + - protocol + type: object unban: description: Unban lifts a ban, e.g. "pardon {{.Player}}". type: string diff --git a/charts/gameplane/crd-manifests/gameplane.local_modules.yaml b/charts/gameplane/crd-manifests/gameplane.local_modules.yaml index eba6cab84..aee445da9 100644 --- a/charts/gameplane/crd-manifests/gameplane.local_modules.yaml +++ b/charts/gameplane/crd-manifests/gameplane.local_modules.yaml @@ -3,7 +3,7 @@ apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: annotations: - gameplane.local/crd-bundle-sha256: 2baa2e6e380e574531191108c18a893841f7b89399fc8216fd13bc22d1a6caf8 + gameplane.local/crd-bundle-sha256: f6d823caf1184485fc5a5cec8ff73668bbf02fbd250b06f24c9139766558b017 controller-gen.kubebuilder.io/version: v0.22.0 name: modules.gameplane.local spec: diff --git a/charts/gameplane/crd-manifests/gameplane.local_modulesources.yaml b/charts/gameplane/crd-manifests/gameplane.local_modulesources.yaml index 3dbc18243..9339dd748 100644 --- a/charts/gameplane/crd-manifests/gameplane.local_modulesources.yaml +++ b/charts/gameplane/crd-manifests/gameplane.local_modulesources.yaml @@ -3,7 +3,7 @@ apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: annotations: - gameplane.local/crd-bundle-sha256: 2baa2e6e380e574531191108c18a893841f7b89399fc8216fd13bc22d1a6caf8 + gameplane.local/crd-bundle-sha256: f6d823caf1184485fc5a5cec8ff73668bbf02fbd250b06f24c9139766558b017 controller-gen.kubebuilder.io/version: v0.22.0 name: modulesources.gameplane.local spec: diff --git a/charts/gameplane/crd-manifests/gameplane.local_networkcaptures.yaml b/charts/gameplane/crd-manifests/gameplane.local_networkcaptures.yaml index 32f1924e7..586891bc2 100644 --- a/charts/gameplane/crd-manifests/gameplane.local_networkcaptures.yaml +++ b/charts/gameplane/crd-manifests/gameplane.local_networkcaptures.yaml @@ -3,7 +3,7 @@ apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: annotations: - gameplane.local/crd-bundle-sha256: 2baa2e6e380e574531191108c18a893841f7b89399fc8216fd13bc22d1a6caf8 + gameplane.local/crd-bundle-sha256: f6d823caf1184485fc5a5cec8ff73668bbf02fbd250b06f24c9139766558b017 controller-gen.kubebuilder.io/version: v0.22.0 name: networkcaptures.gameplane.local spec: diff --git a/charts/gameplane/crd-manifests/gameplane.local_restores.yaml b/charts/gameplane/crd-manifests/gameplane.local_restores.yaml index 811681208..782c4e556 100644 --- a/charts/gameplane/crd-manifests/gameplane.local_restores.yaml +++ b/charts/gameplane/crd-manifests/gameplane.local_restores.yaml @@ -3,7 +3,7 @@ apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: annotations: - gameplane.local/crd-bundle-sha256: 2baa2e6e380e574531191108c18a893841f7b89399fc8216fd13bc22d1a6caf8 + gameplane.local/crd-bundle-sha256: f6d823caf1184485fc5a5cec8ff73668bbf02fbd250b06f24c9139766558b017 controller-gen.kubebuilder.io/version: v0.22.0 name: restores.gameplane.local spec: diff --git a/docs/module-authoring.md b/docs/module-authoring.md index 3f10dcc6c..c33921e68 100644 --- a/docs/module-authoring.md +++ b/docs/module-authoring.md @@ -1281,6 +1281,42 @@ capabilities: From `modules/palworld/template.yaml` (note: Palworld uses the REST admin API `protocol: palworld`, not RCON, so the players list is fetched via the REST endpoint, not a console command). +- `query` reads the online player count from a server query protocol + instead of the console, for games whose console can't list players, or + that have none. `protocol: a2s` is Valve's Steam server query (A2S_INFO), + which most Steam dedicated servers answer; `port` is the UDP query port, + which must be declared in `spec.ports`. The agent sends the query inside + the pod, so the port needn't be advertised. The count drives the + dashboard's player count and [idle sleep](architecture.md#sleep-an-idle-server): + a server with no player count never sleeps. Bots aren't counted. The + Players tab's list and moderation still use the console. + + From `modules/valheim/template.yaml` (Valheim has no RCON; it answers + A2S on the game port plus one): + + ```yaml + capabilities: + players: + query: + protocol: a2s + port: 2457 + ``` + + When `query` is set, it is the only source of the count: the console's + `list` isn't used for it, even as a fallback. The agent needs a reply + in Valve's single-packet A2S_INFO format: the `FF FF FF FF` header, `I` + (0x49), the protocol byte, the server name, map, folder and game as + NUL-terminated strings, the two-byte app ID, then one byte each for + players, max players and bots. Anything after the bots byte is ignored. + A server that first answers with a challenge (`FF FF FF FF`, `A`, four + bytes) is asked again with the challenge, up to twice. Split replies + (`FE FF FF FF`, sent when a reply doesn't fit one UDP packet) aren't + supported; A2S_INFO replies fit in one packet for the games that use + this, but a server whose reply is split reports no count. So does one + that doesn't answer within two seconds, or answers in another format: + its count is unknown, not 0, and it doesn't sleep. Check a new module + by watching `status.agent.playersOnline` while a player joins and + leaves. - The operator uses the verified agent endpoint for live backups. For `minecraft-java`, declare the sequence above. The agent checks the English vanilla response to each command, including the already-on and already-off diff --git a/gp-module/internal/validator/rules.go b/gp-module/internal/validator/rules.go index 8f970077b..b30e012b0 100644 --- a/gp-module/internal/validator/rules.go +++ b/gp-module/internal/validator/rules.go @@ -258,6 +258,41 @@ func validatePorts(node *yaml.Node) []Finding { return findings } +// validatePlayerQuery checks that capabilities.players.query points at one +// of the template's declared UDP ports. The CRD bounds the port's range but +// can't see spec.ports, so a query aimed at the TCP game port, or a port the +// game doesn't use, would otherwise only show up as a server that never +// reports a player count, and so never sleeps. +func validatePlayerQuery(node *yaml.Node) []Finding { + query := common.FindNode(node, "spec.capabilities.players.query") + if query == nil || query.Kind != yaml.MappingNode { + return nil + } + portField := common.FindNode(query, "port") + if portField == nil { + return nil + } + if portsNode := common.FindNode(node, "spec.ports"); portsNode != nil && portsNode.Kind == yaml.SequenceNode { + for _, pNode := range portsNode.Content { + protoField := common.FindNode(pNode, "protocol") + containerPort := common.FindNode(pNode, "containerPort") + if protoField != nil && protoField.Value == "UDP" && containerPort != nil && containerPort.Value == portField.Value { + return nil + } + } + } + return []Finding{{ + Level: SeverityError, + RuleID: RuleTemplateSchemaViolation, + File: "template.yaml", + Line: portField.Line, + Column: portField.Column, + Field: "spec.capabilities.players.query.port", + Message: fmt.Sprintf("player query port %s is not a declared UDP port", portField.Value), + Remediation: "Set port to the game's UDP query port, and declare it in spec.ports with protocol: UDP.", + }} +} + func validateConfigSchemaRules(node *yaml.Node) []Finding { var findings []Finding cfgNode := common.FindNode(node, "spec.configSchema") diff --git a/gp-module/internal/validator/validator.go b/gp-module/internal/validator/validator.go index 6cb8451aa..9859a8c4e 100644 --- a/gp-module/internal/validator/validator.go +++ b/gp-module/internal/validator/validator.go @@ -168,6 +168,7 @@ func ValidateFiles(dirName string, files map[string][]byte, opts ValidateOptions findings = append(findings, validateImageDigest(node, string(tmplBytes))...) findings = append(findings, validatePorts(node)...) findings = append(findings, validateConfigSchemaRules(node)...) + findings = append(findings, validatePlayerQuery(node)...) } } diff --git a/gp-module/internal/validator/validator_test.go b/gp-module/internal/validator/validator_test.go index a1f8e5847..f5091c788 100644 --- a/gp-module/internal/validator/validator_test.go +++ b/gp-module/internal/validator/validator_test.go @@ -964,3 +964,64 @@ spec: t.Errorf("got %d envName findings, want %d: %v", len(msgs), len(want), msgs) } } + +func TestValidate_PlayerQueryPort(t *testing.T) { + t.Parallel() + template := func(queryPort string) []byte { + return []byte(`apiVersion: gameplane.io/v1alpha1 +kind: GameTemplate +metadata: + name: test-mod +spec: + image: "example.com/img@sha256:ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" + ports: + - name: game + containerPort: 2456 + protocol: UDP + - name: query + containerPort: 2457 + protocol: UDP + - name: status + containerPort: 80 + protocol: TCP + capabilities: + players: + query: + protocol: a2s + port: ` + queryPort + "\n") + } + cases := map[string]bool{ + "2457": false, // a declared UDP port + "80": true, // declared, but TCP + "9999": true, // not declared + } + for port, wantFinding := range cases { + t.Run(port, func(t *testing.T) { + t.Parallel() + files := map[string][]byte{ + "module.yaml": []byte(`apiVersion: gameplane.local/module/v1 +name: test-mod +displayName: Test Mod +version: 1.0.0 +game: test +summary: Test +`), + "template.yaml": template(port), + "README.md": []byte("# Test\n"), + } + report, err := ValidateFiles("test-mod", files, ValidateOptions{}) + if err != nil { + t.Fatal(err) + } + got := false + for _, f := range report.Findings { + if f.Field == "spec.capabilities.players.query.port" { + got = true + } + } + if got != wantFinding { + t.Errorf("port %s: query finding = %v, want %v (findings: %+v)", port, got, wantFinding, report.Findings) + } + }) + } +} diff --git a/gp-module/specs.md b/gp-module/specs.md index 25282568b..82766fed5 100644 --- a/gp-module/specs.md +++ b/gp-module/specs.md @@ -81,6 +81,8 @@ gp-module/ └── .testcoverage.yml # 80% coverage threshold gate ``` +- Check that `capabilities.players.query.port` is one of the template's declared UDP ports (`validatePlayerQuery`); the CRD bounds the port's range but can't see `spec.ports`, so a query aimed at a TCP port or an undeclared one is an `ERROR` (rule `template-schema-violation`) rather than a server that silently never reports a count. + ## Key Invariants 1. **Strictly Offline First.** Scaffolding, validation, and preview operations NEVER make outbound network calls or require a running Kubernetes cluster. diff --git a/operator/api/v1alpha1/gametemplate_types.go b/operator/api/v1alpha1/gametemplate_types.go index 9cd5be700..ceb38e7c2 100644 --- a/operator/api/v1alpha1/gametemplate_types.go +++ b/operator/api/v1alpha1/gametemplate_types.go @@ -810,6 +810,29 @@ type PlayerActionsSpec struct { // List configures how the online player list is read. // +optional List *PlayerListSpec `json:"list,omitempty"` + + // Query reads the online player count from a server query protocol + // instead of the console, for games with no console that lists players + // (Valheim has no RCON at all). When set, the heartbeat's player count, + // which idle sleep relies on, comes from this query. The Players tab's + // list and moderation still use the console. + // +optional + Query *PlayerQuerySpec `json:"query,omitempty"` +} + +// PlayerQuerySpec reads the player count over a game server query protocol. +type PlayerQuerySpec struct { + // Protocol is the query protocol. "a2s" is Valve's Steam server query + // (A2S_INFO over UDP), which most Steam dedicated servers answer on + // their query port. + // +kubebuilder:validation:Enum=a2s + Protocol string `json:"protocol"` + + // Port is the UDP port, inside the pod, that answers the query: for + // Valheim, 2457 (the game port plus one). + // +kubebuilder:validation:Minimum=1 + // +kubebuilder:validation:Maximum=65535 + Port int32 `json:"port"` } // WhitelistSpec declares how to manage the game's whitelist (allow list). diff --git a/operator/api/v1alpha1/zz_generated.deepcopy.go b/operator/api/v1alpha1/zz_generated.deepcopy.go index 317f659a2..40978d948 100644 --- a/operator/api/v1alpha1/zz_generated.deepcopy.go +++ b/operator/api/v1alpha1/zz_generated.deepcopy.go @@ -2319,6 +2319,11 @@ func (in *PlayerActionsSpec) DeepCopyInto(out *PlayerActionsSpec) { *out = new(PlayerListSpec) **out = **in } + if in.Query != nil { + in, out := &in.Query, &out.Query + *out = new(PlayerQuerySpec) + **out = **in + } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PlayerActionsSpec. @@ -2346,6 +2351,21 @@ func (in *PlayerListSpec) DeepCopy() *PlayerListSpec { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *PlayerQuerySpec) DeepCopyInto(out *PlayerQuerySpec) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PlayerQuerySpec. +func (in *PlayerQuerySpec) DeepCopy() *PlayerQuerySpec { + if in == nil { + return nil + } + out := new(PlayerQuerySpec) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *PlayitTunnelSpec) DeepCopyInto(out *PlayitTunnelSpec) { *out = *in diff --git a/operator/config/crd/gameplane.local_gametemplates.yaml b/operator/config/crd/gameplane.local_gametemplates.yaml index 3436e4105..ab6673ed7 100644 --- a/operator/config/crd/gameplane.local_gametemplates.yaml +++ b/operator/config/crd/gameplane.local_gametemplates.yaml @@ -870,6 +870,34 @@ spec: required: - command type: object + query: + description: |- + Query reads the online player count from a server query protocol + instead of the console, for games with no console that lists players + (Valheim has no RCON at all). When set, the heartbeat's player count, + which idle sleep relies on, comes from this query. The Players tab's + list and moderation still use the console. + properties: + port: + description: |- + Port is the UDP port, inside the pod, that answers the query: for + Valheim, 2457 (the game port plus one). + format: int32 + maximum: 65535 + minimum: 1 + type: integer + protocol: + description: |- + Protocol is the query protocol. "a2s" is Valve's Steam server query + (A2S_INFO over UDP), which most Steam dedicated servers answer on + their query port. + enum: + - a2s + type: string + required: + - port + - protocol + type: object unban: description: Unban lifts a ban, e.g. "pardon {{.Player}}". type: string diff --git a/operator/specs.md b/operator/specs.md index ba248551a..0da5aa7f8 100644 --- a/operator/specs.md +++ b/operator/specs.md @@ -411,7 +411,8 @@ Primary reconcilers register with the manager in `cmd/main.go` and handle CRD li - Empty flag value is a strict no-op — preserves pre-feature behavior (all three sources nil → cluster default). - Error handling: `checkPVCProvisioningFailure` detects missing StorageClass and surfaces it as Ready condition False, reason `PVCProvisioningFailed`, with message naming the class — leaves GameServer in phase Pending (not Failed, so it is recoverable once an admin creates the StorageClass). - Requires `storage.k8s.io/storageclasses` get/list permission (on each reconcile to verify existence). - - Pod spec assembly: inject agent sidecar (image + pull policy + env), mount agent certs + logs volume. + - Pod spec assembly: inject agent sidecar (image + pull policy + env), mount agent certs + logs volume. The template's capabilities, `players.query` included, reach the agent unchanged in the `GAMEPLANE_CAPABILITIES` JSON env (`resolveCapabilities`); a change rolls the StatefulSet like any other template change. + - **Player counts and idle sleep:** the operator reads only `status.agent.playersOnline`, whatever the agent's source (console list or `players.query`). A count of 0 starts the idle clock; an absent count (a failed or missing query) clears it and keeps the server awake, so a query that stops answering can never sleep a server. E2E: `TestGameServer_A2SPlayerCountDrivesIdle` (template configuration → injection → heartbeat → idle eligibility, with a nonzero count, a real zero and a failed query). - Config & credentials: render game startup config (template vars, port mappings, mod credentials). - RCON integration: create agent RBAC, mTLS certs; expose RCON port if template declares it. - Graceful stop: if template has Lifecycle.Stop sequence, orchestrate via agent before scaling down. diff --git a/test/e2e/a2s_player_count_e2e_test.go b/test/e2e/a2s_player_count_e2e_test.go new file mode 100644 index 000000000..6f5b86921 --- /dev/null +++ b/test/e2e/a2s_player_count_e2e_test.go @@ -0,0 +1,161 @@ +//go:build e2e + +package e2e + +import ( + "context" + "fmt" + "testing" + "time" + + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/types" +) + +// a2sFixture answers Valve's A2S_INFO on UDP 27015, challenge round trip +// included, the way Steam dedicated servers such as Valheim do. /tmp/a2s +// holds " "; while /tmp/a2s-silent exists it doesn't answer, +// so the agent's query times out. +const a2sFixture = `import pathlib,socket,struct +state=pathlib.Path('/tmp/a2s') +silent=pathlib.Path('/tmp/a2s-silent') +state.write_text('3 1') +request=b'\xff\xff\xff\xffTSource Engine Query\x00' +challenge=b'\x01\x02\x03\x04' +s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) +s.bind(('0.0.0.0',27015)) +while True: + data,peer=s.recvfrom(1400) + if silent.exists() or not data.startswith(request): continue + if data[len(request):]!=challenge: + s.sendto(b'\xff\xff\xff\xffA'+challenge,peer); continue + players,bots=(int(v) for v in state.read_text().split()) + s.sendto(b'\xff\xff\xff\xffI\x11e2e\x00map\x00e2e\x00e2e\x00'+struct.pack('