Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 8 additions & 6 deletions agent/cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -282,12 +282,14 @@ func main() {
// process's CPU/memory from /proc and uses the operator-supplied limits
// as the denominator; otherwise it falls back to its own cgroup.
go heartbeat.Run(ctx, heartbeat.Config{
ServerName: serverName,
Template: templateName,
Game: gameName,
Version: Version,
RCON: rconClient,
Interval: 20 * time.Second,
ServerName: serverName,
PodUID: os.Getenv("GAMEPLANE_POD_UID"),
Template: templateName,
Game: gameName,
Version: Version,
RCON: rconClient,
RCONProtocol: rconProtocol,
Interval: 20 * time.Second,
PlayerList: func() *caps.PlayerList {
if playerActions != nil {
return playerActions.List
Expand Down
53 changes: 44 additions & 9 deletions agent/internal/heartbeat/heartbeat.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import (
"os"
"regexp"
"strconv"
"strings"
"time"

metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
Expand Down Expand Up @@ -53,12 +54,14 @@ type UsageReader interface {
// Config holds the configuration for the heartbeat process.
type Config struct {
ServerName string
PodUID string
Namespace string
Template string
Game string
Version string
Interval time.Duration
RCON Rcon
RCONProtocol string
Usage UsageReader
PlayerList *caps.PlayerList
PlayerListRE *regexp.Regexp
Expand Down Expand Up @@ -135,8 +138,10 @@ func Run(ctx context.Context, cfg Config) {
}

func sendOnce(ctx context.Context, dyn dynamic.Interface, cfg Config) error {
observedAt := metav1.Now().UTC().Format(time.RFC3339)
agent := map[string]any{
"lastHeartbeat": metav1.Now().UTC().Format(time.RFC3339),
"lastHeartbeat": observedAt,
"playerQuery": nil,
"version": cfg.Version,
// gameVersion: the agent has no source for the game's actual
// running version. cfg.Game is the template's game identifier
Expand Down Expand Up @@ -164,8 +169,11 @@ 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(ctx, cfg); err == nil {
if online, maxN, qualified, err := queryPlayerCounts(ctx, cfg); err == nil {
agent["playersOnline"] = online
if cfg.PodUID != "" && qualified {
agent["playerQuery"] = map[string]string{"podUID": cfg.PodUID, "observedAt": observedAt}
}
// Status patch: playersMax is only emitted when maxN > 0 (a real
// finite limit). Unknown (maxN=0) and unlimited (maxN=-1) both patch
// to null, since -1 is an internal metric-only sentinel and the
Expand Down Expand Up @@ -247,27 +255,34 @@ 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(ctx context.Context, cfg Config) (online, maxPlayers int, err error) {
func queryPlayerCounts(ctx context.Context, cfg Config) (online, maxPlayers int, qualified bool, err error) {
if cfg.PlayerQuery != nil {
return queryPlayerCountsA2S(ctx, cfg)
online, maxPlayers, err = queryPlayerCountsA2S(ctx, cfg)
return online, maxPlayers, err == nil, err
}
cmd := "list"
if cfg.PlayerList != nil && cfg.PlayerList.Command != "" {
cmd = cfg.PlayerList.Command
}
raw, err := cfg.RCON.Exec(cmd)
if err != nil {
return 0, 0, err
return 0, 0, false, err
}
// Preserve legacy dashboard counts even for loose parses. A number in
// a loading message or zero matches in an error reply cannot qualify
// startup. An empty JSON list is the normal empty Rust/Palworld reply.
qualified = cfg.PlayerList != nil && cfg.PlayerList.Command != "" &&
(cfg.PlayerList.EntryRegex == "" || cfg.PlayerListRE != nil)

// If a custom regex is configured, count matches for online and set maxPlayers to -1.
if cfg.PlayerListRE != nil {
online = players.CountWithRegex(raw, cfg.PlayerListRE)
return online, -1, nil
return online, -1, qualified && (online > 0 || emptyPlayerList(raw, cfg.RCONProtocol, cmd)), nil
}

// Default behavior: use ParseCounts for Minecraft, loose first-number parse for online.
if _, m, ok := players.ParseCounts(raw); ok {
_, m, knownCounts := players.ParseCounts(raw)
if knownCounts {
maxPlayers = m
}
// Very loose parse for online — we only care about the first number.
Expand All @@ -280,9 +295,29 @@ func queryPlayerCounts(ctx context.Context, cfg Config) (online, maxPlayers int,
n = n*10 + int(raw[i]-'0')
i++
}
return n, maxPlayers, nil
return n, maxPlayers, qualified && (knownCounts || playerCountReply.MatchString(strings.TrimSpace(raw))), nil
}
return 0, maxPlayers, false, fmt.Errorf("no player count in %q", raw)
}

var playerCountReply = regexp.MustCompile(`(?i)^(?:there are )?[0-9]+(?: players?(?: online| connected)?)?[.:]?$`)

func emptyPlayerList(raw, protocol, command string) bool {
trimmed := strings.TrimSpace(raw)
if protocol == "battleye" && command == "players" {
// BattlEye lists a row per connected player followed by its total.
// Only a complete table with the native empty footer confirms zero.
return strings.Contains(trimmed, "[#] [IP Address]:[Port] [Ping] [GUID] [Name]") && strings.HasSuffix(trimmed, "\n(0 players in total)")
}
var entries []json.RawMessage
if strings.HasPrefix(trimmed, "[") {
return json.Unmarshal([]byte(trimmed), &entries) == nil && len(entries) == 0
}
if strings.HasPrefix(trimmed, "{") {
var list struct{ Players []json.RawMessage }
return json.Unmarshal([]byte(trimmed), &list) == nil && list.Players != nil && len(list.Players) == 0
}
return 0, maxPlayers, fmt.Errorf("no player count in %q", raw)
return false
}

// a2sTimeout bounds one player-count query, well inside the heartbeat
Expand Down
67 changes: 62 additions & 5 deletions agent/internal/heartbeat/heartbeat_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"net"
"os"
"path/filepath"
"regexp"
"strings"
"testing"

Expand Down Expand Up @@ -56,6 +57,7 @@ func TestSendOnce(t *testing.T) {

cfg := Config{
ServerName: "srv",
PodUID: "pod-uid",
Namespace: "ns",
Version: "v1",
Game: "minecraft-java",
Expand All @@ -73,6 +75,9 @@ func TestSendOnce(t *testing.T) {
if agent["playersOnline"].(float64) != 4 {
t.Fatalf("playersOnline=%v", agent["playersOnline"])
}
if query, ok := agent["playerQuery"]; !ok || query != nil {
t.Fatalf("an undeclared fallback command must clear the startup observation: %v", query)
}
if agent["version"].(string) != "v1" {
t.Fatalf("agent payload=%+v", agent)
}
Expand Down Expand Up @@ -252,6 +257,9 @@ func TestSendOnce_RconFailureEmitsNullPlayers(t *testing.T) {
if v != nil {
t.Fatalf("want null playersOnline on rcon failure, got %v", v)
}
if query, ok := agent["playerQuery"]; !ok || query != nil {
t.Fatalf("a failed query must clear the startup observation: %v", query)
}
}

func TestSendOnce_PatchErrorPropagates(t *testing.T) {
Expand Down Expand Up @@ -289,6 +297,7 @@ func TestSendOnce_CustomListCommandWithRegex(t *testing.T) {

cfg := Config{
ServerName: "srv",
PodUID: "query-pod",
Namespace: "ns",
RCON: fakeRcon{out: "[alice]\n[bob]\n[charlie]\n"},
PlayerList: &caps.PlayerList{
Expand All @@ -309,6 +318,10 @@ func TestSendOnce_CustomListCommandWithRegex(t *testing.T) {
if agent["playersOnline"].(float64) != 3 {
t.Fatalf("playersOnline got %v, want 3", agent["playersOnline"])
}
query, ok := agent["playerQuery"].(map[string]any)
if !ok || query["podUID"] != cfg.PodUID || query["observedAt"] != agent["lastHeartbeat"] {
t.Fatalf("declared query did not carry its Pod and sample time: %v", query)
}
if agent["playersMax"] != nil {
t.Fatalf("playersMax got %v, want null", agent["playersMax"])
}
Expand All @@ -334,7 +347,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(t.Context(), cfg)
n, maxN, _, err := queryPlayerCounts(t.Context(), cfg)
if (err == nil) != tc.ok {
t.Fatalf("err=%v ok=%v", err, tc.ok)
}
Expand All @@ -355,7 +368,7 @@ func TestQueryPlayerCounts_CustomCommand(t *testing.T) {
Command: "mylist",
},
}
n, maxN, err := queryPlayerCounts(t.Context(), cfg)
n, maxN, _, err := queryPlayerCounts(t.Context(), cfg)
if err != nil {
t.Fatalf("queryPlayerCounts: %v", err)
}
Expand All @@ -380,7 +393,7 @@ func TestQueryPlayerCounts_WithRegex(t *testing.T) {
},
PlayerListRE: re,
}
n, maxN, err := queryPlayerCounts(t.Context(), cfg)
n, maxN, _, err := queryPlayerCounts(t.Context(), cfg)
if err != nil {
t.Fatalf("queryPlayerCounts: %v", err)
}
Expand All @@ -392,6 +405,47 @@ func TestQueryPlayerCounts_WithRegex(t *testing.T) {
}
}

func TestNativeStartupObservationRequiresRecognizableList(t *testing.T) {
re, err := players.CompileEntryRegex(`"DisplayName":"(?P<name>[^"]+)"`)
if err != nil {
t.Fatal(err)
}
for _, tc := range []struct {
reply string
want bool
}{
{`[]`, true}, {`{"players":[]}`, true}, {`[{"DisplayName":"Ada"}]`, true},
{"", false}, {"Loading world 25%", false}, {`{"error":"busy"}`, false}, {`[{}]`, false},
} {
cfg := Config{RCON: fakeRcon{out: tc.reply}, PlayerList: &caps.PlayerList{Command: "playerlist", EntryRegex: re.String()}, PlayerListRE: re}
_, _, qualified, err := queryPlayerCounts(t.Context(), cfg)
if err != nil || qualified != tc.want {
t.Errorf("native query for %q: qualified %t, err %v; want %t", tc.reply, qualified, err, tc.want)
}
}
_, _, qualified, err := queryPlayerCounts(t.Context(), Config{RCON: fakeRcon{out: "Loading world 25%"}, PlayerList: &caps.PlayerList{Command: "list"}})
if err != nil || qualified {
t.Fatalf("a loose numeric parse of a loading message qualified startup: %t, %v", qualified, err)
}
}

func TestBattlEyeEmptyPlayersQualifiesPrewarm(t *testing.T) {
const header = "Players on server:\r\n[#] [IP Address]:[Port] [Ping] [GUID] [Name]\r\n--------------------------------------------------\r\n"
cfg := Config{RCONProtocol: "battleye", RCON: fakeRcon{out: header + "(0 players in total)\r\n"}, PlayerList: &caps.PlayerList{Command: "players", EntryRegex: `^\d+\s+\S+:\d+`}, PlayerListRE: regexp.MustCompile(`(?m)^\d+\s+\S+:\d+`)}
n, _, qualified, err := queryPlayerCounts(t.Context(), cfg)
if err != nil || n != 0 || !qualified {
t.Fatalf("empty BattlEye players table: count %d, qualified %t, err %v", n, qualified, err)
}
for _, malformed := range []string{"(0 players in total)", header, header + "(1 players in total)"} {
if emptyPlayerList(malformed, "battleye", "players") {
t.Errorf("incomplete or nonempty players table qualified: %q", malformed)
}
}
if emptyPlayerList(header+"(0 players in total)", "websocket", "players") || emptyPlayerList(header+"(0 players in total)", "battleye", "bans") {
t.Error("accepted BattlEye player output for a different protocol or command")
}
}

// 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 {
Expand Down Expand Up @@ -422,13 +476,16 @@ func TestQueryPlayerCounts_A2S(t *testing.T) {
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)
n, maxN, qualified, 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 !qualified {
t.Fatal("valid native UDP reply did not qualify startup")
}
if maxN != 10 {
t.Fatalf("max got %d, want 10", maxN)
}
Expand All @@ -448,7 +505,7 @@ func TestQueryPlayerCounts_A2SErrors(t *testing.T) {
"unknown protocol": {Protocol: "gamespy", Port: closedPort},
} {
t.Run(name, func(t *testing.T) {
if _, _, err := queryPlayerCounts(t.Context(), Config{PlayerQuery: q}); err == nil {
if _, _, qualified, err := queryPlayerCounts(t.Context(), Config{PlayerQuery: q}); err == nil || qualified {
t.Fatal("want an error")
}
})
Expand Down
1 change: 1 addition & 0 deletions agent/specs.md
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@ Per-package roles:
- **`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/<name>/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.
- A successful module-declared `players.query` or `players.list` also records `status.agent.playerQuery` with the reporting Pod UID and the time the query began. The operator uses this observation to qualify a cold start for games without a readiness probe. RCON qualification accepts a recognized count, a match for the module's player-entry expression, an empty JSON player list, or a BattlEye `players` table reporting zero players. A failed or unrecognized reply, an undeclared fallback command, or a missing Pod UID clears the observation. Games whose empty lists use another format can supply `spec.probes.readiness`. The fleet qualification drill records the first successful real-client join separately.
- **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.
Expand Down
3 changes: 3 additions & 0 deletions changelog/unreleased/1163-cold-wake-capacity.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Breaking: limited cold starts require a game readiness signal

If you use a positive `operator.wakeStartLimit`, configure a game readiness probe or a declared A2S/RCON player query for each sleeping game, and update pinned agents that report those queries. The game now keeps its slot while its world loads. A game that cannot schedule can give its slot to another wake and retry later. The default limit of zero continues to allow unlimited wakes. [Wake configuration and qualification](../../docs/wake-qualification.md) · [PR #1163](https://github.com/GameplanePanel/Gameplane/pull/1163)
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
annotations:
gameplane.local/crd-bundle-sha256: ef3e35f3a47f3d8c43724210829b1ff2f73a0fabc0d1dab1234c4bd91973a5b6
gameplane.local/crd-bundle-sha256: 47831c2609a602e0ab54885f646234f5996e4ff98c88f3ead59090f0b7eb0315
controller-gen.kubebuilder.io/version: v0.22.0
name: backupexports.gameplane.local
spec:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
annotations:
gameplane.local/crd-bundle-sha256: ef3e35f3a47f3d8c43724210829b1ff2f73a0fabc0d1dab1234c4bd91973a5b6
gameplane.local/crd-bundle-sha256: 47831c2609a602e0ab54885f646234f5996e4ff98c88f3ead59090f0b7eb0315
controller-gen.kubebuilder.io/version: v0.22.0
name: backups.gameplane.local
spec:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
annotations:
gameplane.local/crd-bundle-sha256: ef3e35f3a47f3d8c43724210829b1ff2f73a0fabc0d1dab1234c4bd91973a5b6
gameplane.local/crd-bundle-sha256: 47831c2609a602e0ab54885f646234f5996e4ff98c88f3ead59090f0b7eb0315
controller-gen.kubebuilder.io/version: v0.22.0
name: backupschedules.gameplane.local
spec:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
annotations:
gameplane.local/crd-bundle-sha256: ef3e35f3a47f3d8c43724210829b1ff2f73a0fabc0d1dab1234c4bd91973a5b6
gameplane.local/crd-bundle-sha256: 47831c2609a602e0ab54885f646234f5996e4ff98c88f3ead59090f0b7eb0315
controller-gen.kubebuilder.io/version: v0.22.0
name: clusters.gameplane.local
spec:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
annotations:
gameplane.local/crd-bundle-sha256: ef3e35f3a47f3d8c43724210829b1ff2f73a0fabc0d1dab1234c4bd91973a5b6
gameplane.local/crd-bundle-sha256: 47831c2609a602e0ab54885f646234f5996e4ff98c88f3ead59090f0b7eb0315
controller-gen.kubebuilder.io/version: v0.22.0
name: gameservers.gameplane.local
spec:
Expand Down Expand Up @@ -2622,6 +2622,25 @@ spec:
when unlimited / unknown.
format: int64
type: integer
playerQuery:
description: |-
PlayerQuery identifies the latest successful module-declared A2S or
RCON player-list query. An unsuccessful query clears the observation.
properties:
observedAt:
description: |-
ObservedAt is when the query began, so a slow reply cannot qualify a
game container that restarted while the request was in flight.
format: date-time
type: string
podUID:
description: PodUID identifies the reporting game Pod across
ordinal-zero replacements.
type: string
required:
- observedAt
- podUID
type: object
playersMax:
description: PlayersMax is the configured max player count, if
known.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
annotations:
gameplane.local/crd-bundle-sha256: ef3e35f3a47f3d8c43724210829b1ff2f73a0fabc0d1dab1234c4bd91973a5b6
gameplane.local/crd-bundle-sha256: 47831c2609a602e0ab54885f646234f5996e4ff98c88f3ead59090f0b7eb0315
controller-gen.kubebuilder.io/version: v0.22.0
name: gametemplates.gameplane.local
spec:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
annotations:
gameplane.local/crd-bundle-sha256: ef3e35f3a47f3d8c43724210829b1ff2f73a0fabc0d1dab1234c4bd91973a5b6
gameplane.local/crd-bundle-sha256: 47831c2609a602e0ab54885f646234f5996e4ff98c88f3ead59090f0b7eb0315
controller-gen.kubebuilder.io/version: v0.22.0
name: modules.gameplane.local
spec:
Expand Down
Loading
Loading