diff --git a/agent/cmd/main.go b/agent/cmd/main.go index 6d354f46a..ff8ee2546 100644 --- a/agent/cmd/main.go +++ b/agent/cmd/main.go @@ -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 diff --git a/agent/internal/heartbeat/heartbeat.go b/agent/internal/heartbeat/heartbeat.go index 55cd30071..b8e2b8864 100644 --- a/agent/internal/heartbeat/heartbeat.go +++ b/agent/internal/heartbeat/heartbeat.go @@ -23,6 +23,7 @@ import ( "os" "regexp" "strconv" + "strings" "time" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -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 @@ -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 @@ -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 @@ -247,9 +255,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(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 != "" { @@ -257,17 +266,23 @@ func queryPlayerCounts(ctx context.Context, cfg Config) (online, maxPlayers int, } 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. @@ -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 diff --git a/agent/internal/heartbeat/heartbeat_test.go b/agent/internal/heartbeat/heartbeat_test.go index df212aaa0..2a42ba8a7 100644 --- a/agent/internal/heartbeat/heartbeat_test.go +++ b/agent/internal/heartbeat/heartbeat_test.go @@ -7,6 +7,7 @@ import ( "net" "os" "path/filepath" + "regexp" "strings" "testing" @@ -56,6 +57,7 @@ func TestSendOnce(t *testing.T) { cfg := Config{ ServerName: "srv", + PodUID: "pod-uid", Namespace: "ns", Version: "v1", Game: "minecraft-java", @@ -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) } @@ -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) { @@ -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{ @@ -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"]) } @@ -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) } @@ -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) } @@ -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) } @@ -392,6 +405,47 @@ func TestQueryPlayerCounts_WithRegex(t *testing.T) { } } +func TestNativeStartupObservationRequiresRecognizableList(t *testing.T) { + re, err := players.CompileEntryRegex(`"DisplayName":"(?P[^"]+)"`) + 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 { @@ -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) } @@ -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") } }) diff --git a/agent/specs.md b/agent/specs.md index def747999..8581b5856 100644 --- a/agent/specs.md +++ b/agent/specs.md @@ -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//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. diff --git a/changelog/unreleased/1163-cold-wake-capacity.md b/changelog/unreleased/1163-cold-wake-capacity.md new file mode 100644 index 000000000..0b66f9854 --- /dev/null +++ b/changelog/unreleased/1163-cold-wake-capacity.md @@ -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) diff --git a/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_backupexports.yaml b/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_backupexports.yaml index 6f271a5be..155414abc 100644 --- a/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_backupexports.yaml +++ b/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_backupexports.yaml @@ -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: 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 61f36fdba..a07b0bf81 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: ef3e35f3a47f3d8c43724210829b1ff2f73a0fabc0d1dab1234c4bd91973a5b6 + gameplane.local/crd-bundle-sha256: 47831c2609a602e0ab54885f646234f5996e4ff98c88f3ead59090f0b7eb0315 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 7235b25e3..458782392 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: ef3e35f3a47f3d8c43724210829b1ff2f73a0fabc0d1dab1234c4bd91973a5b6 + gameplane.local/crd-bundle-sha256: 47831c2609a602e0ab54885f646234f5996e4ff98c88f3ead59090f0b7eb0315 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 413ea59f3..f728222a3 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: ef3e35f3a47f3d8c43724210829b1ff2f73a0fabc0d1dab1234c4bd91973a5b6 + gameplane.local/crd-bundle-sha256: 47831c2609a602e0ab54885f646234f5996e4ff98c88f3ead59090f0b7eb0315 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 6e3caa2a8..4db85efae 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: ef3e35f3a47f3d8c43724210829b1ff2f73a0fabc0d1dab1234c4bd91973a5b6 + gameplane.local/crd-bundle-sha256: 47831c2609a602e0ab54885f646234f5996e4ff98c88f3ead59090f0b7eb0315 controller-gen.kubebuilder.io/version: v0.22.0 name: gameservers.gameplane.local spec: @@ -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. 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 a789b3a6d..28590a3be 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: ef3e35f3a47f3d8c43724210829b1ff2f73a0fabc0d1dab1234c4bd91973a5b6 + gameplane.local/crd-bundle-sha256: 47831c2609a602e0ab54885f646234f5996e4ff98c88f3ead59090f0b7eb0315 controller-gen.kubebuilder.io/version: v0.22.0 name: gametemplates.gameplane.local spec: 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 adad20b92..8d181728a 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: ef3e35f3a47f3d8c43724210829b1ff2f73a0fabc0d1dab1234c4bd91973a5b6 + gameplane.local/crd-bundle-sha256: 47831c2609a602e0ab54885f646234f5996e4ff98c88f3ead59090f0b7eb0315 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 dac40825c..e86536e7c 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: ef3e35f3a47f3d8c43724210829b1ff2f73a0fabc0d1dab1234c4bd91973a5b6 + gameplane.local/crd-bundle-sha256: 47831c2609a602e0ab54885f646234f5996e4ff98c88f3ead59090f0b7eb0315 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 275e1f9a2..b3ec8f6b2 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: ef3e35f3a47f3d8c43724210829b1ff2f73a0fabc0d1dab1234c4bd91973a5b6 + gameplane.local/crd-bundle-sha256: 47831c2609a602e0ab54885f646234f5996e4ff98c88f3ead59090f0b7eb0315 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 79d79de63..19e7b4cf5 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: ef3e35f3a47f3d8c43724210829b1ff2f73a0fabc0d1dab1234c4bd91973a5b6 + gameplane.local/crd-bundle-sha256: 47831c2609a602e0ab54885f646234f5996e4ff98c88f3ead59090f0b7eb0315 controller-gen.kubebuilder.io/version: v0.22.0 name: restores.gameplane.local spec: diff --git a/charts/gameplane/crd-manifests/gameplane.local_backupexports.yaml b/charts/gameplane/crd-manifests/gameplane.local_backupexports.yaml index 6f271a5be..155414abc 100644 --- a/charts/gameplane/crd-manifests/gameplane.local_backupexports.yaml +++ b/charts/gameplane/crd-manifests/gameplane.local_backupexports.yaml @@ -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: diff --git a/charts/gameplane/crd-manifests/gameplane.local_backups.yaml b/charts/gameplane/crd-manifests/gameplane.local_backups.yaml index 61f36fdba..a07b0bf81 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: ef3e35f3a47f3d8c43724210829b1ff2f73a0fabc0d1dab1234c4bd91973a5b6 + gameplane.local/crd-bundle-sha256: 47831c2609a602e0ab54885f646234f5996e4ff98c88f3ead59090f0b7eb0315 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 7235b25e3..458782392 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: ef3e35f3a47f3d8c43724210829b1ff2f73a0fabc0d1dab1234c4bd91973a5b6 + gameplane.local/crd-bundle-sha256: 47831c2609a602e0ab54885f646234f5996e4ff98c88f3ead59090f0b7eb0315 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 413ea59f3..f728222a3 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: ef3e35f3a47f3d8c43724210829b1ff2f73a0fabc0d1dab1234c4bd91973a5b6 + gameplane.local/crd-bundle-sha256: 47831c2609a602e0ab54885f646234f5996e4ff98c88f3ead59090f0b7eb0315 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 6e3caa2a8..4db85efae 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: ef3e35f3a47f3d8c43724210829b1ff2f73a0fabc0d1dab1234c4bd91973a5b6 + gameplane.local/crd-bundle-sha256: 47831c2609a602e0ab54885f646234f5996e4ff98c88f3ead59090f0b7eb0315 controller-gen.kubebuilder.io/version: v0.22.0 name: gameservers.gameplane.local spec: @@ -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. diff --git a/charts/gameplane/crd-manifests/gameplane.local_gametemplates.yaml b/charts/gameplane/crd-manifests/gameplane.local_gametemplates.yaml index a789b3a6d..28590a3be 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: ef3e35f3a47f3d8c43724210829b1ff2f73a0fabc0d1dab1234c4bd91973a5b6 + gameplane.local/crd-bundle-sha256: 47831c2609a602e0ab54885f646234f5996e4ff98c88f3ead59090f0b7eb0315 controller-gen.kubebuilder.io/version: v0.22.0 name: gametemplates.gameplane.local spec: diff --git a/charts/gameplane/crd-manifests/gameplane.local_modules.yaml b/charts/gameplane/crd-manifests/gameplane.local_modules.yaml index adad20b92..8d181728a 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: ef3e35f3a47f3d8c43724210829b1ff2f73a0fabc0d1dab1234c4bd91973a5b6 + gameplane.local/crd-bundle-sha256: 47831c2609a602e0ab54885f646234f5996e4ff98c88f3ead59090f0b7eb0315 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 dac40825c..e86536e7c 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: ef3e35f3a47f3d8c43724210829b1ff2f73a0fabc0d1dab1234c4bd91973a5b6 + gameplane.local/crd-bundle-sha256: 47831c2609a602e0ab54885f646234f5996e4ff98c88f3ead59090f0b7eb0315 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 275e1f9a2..b3ec8f6b2 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: ef3e35f3a47f3d8c43724210829b1ff2f73a0fabc0d1dab1234c4bd91973a5b6 + gameplane.local/crd-bundle-sha256: 47831c2609a602e0ab54885f646234f5996e4ff98c88f3ead59090f0b7eb0315 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 79d79de63..19e7b4cf5 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: ef3e35f3a47f3d8c43724210829b1ff2f73a0fabc0d1dab1234c4bd91973a5b6 + gameplane.local/crd-bundle-sha256: 47831c2609a602e0ab54885f646234f5996e4ff98c88f3ead59090f0b7eb0315 controller-gen.kubebuilder.io/version: v0.22.0 name: restores.gameplane.local spec: diff --git a/charts/gameplane/templates/operator.yaml b/charts/gameplane/templates/operator.yaml index 7dd6d77ee..f84abec88 100644 --- a/charts/gameplane/templates/operator.yaml +++ b/charts/gameplane/templates/operator.yaml @@ -189,8 +189,8 @@ rules: - apiGroups: [""] resources: [pods/ephemeralcontainers] verbs: [get, patch, update] - # File-only pod for a stopped server (spec 040, gameserver_files.go): the - # operator creates and removes -files in this managed namespace only. + # The operator creates and removes file-only Pods for stopped servers. + # It can also withdraw an unbound game Pod during cold-start admission. - apiGroups: [""] resources: [pods] verbs: [create, delete] diff --git a/charts/gameplane/values.yaml b/charts/gameplane/values.yaml index 9002821f3..44638798a 100644 --- a/charts/gameplane/values.yaml +++ b/charts/gameplane/values.yaml @@ -118,7 +118,8 @@ operator: # Disabling it with one replica selects Recreate to prevent overlapping writers. leaderElect: true # Size for the smallest available startup CPU, memory and I/O headroom - # following a worker loss. Zero preserves unlimited native idle wake. + # following a worker loss. With a positive limit, each waking game needs + # a game readiness probe or a declared A2S/RCON player query. Zero is unlimited. wakeStartLimit: 0 resources: requests: { cpu: 100m, memory: 64Mi } diff --git a/docs/module-authoring.md b/docs/module-authoring.md index 94fd0fa1e..3dbe77aa4 100644 --- a/docs/module-authoring.md +++ b/docs/module-authoring.md @@ -1878,9 +1878,13 @@ probes: failureThreshold: 10 ``` -Many game images don't expose HTTP. The `itzg/minecraft-server` image -ships a `mc-health` exec probe; Source images usually expose nothing -useful, so readiness falls back to TCP on the game port. +Choose a probe that succeeds when the game has loaded its world. For example, +the `itzg/minecraft-server` image ships the `mc-health` command for an exec +probe. For a UDP game, a declared A2S player query or an RCON player-list +command can supply the startup signal when the game has no readiness probe. +A server can also set `spec.probes.readiness` for its particular image. +Fleets with a positive `operator.wakeStartLimit` use this evidence to decide +when another sleeping game can start. [Cold-wake qualification](wake-qualification.md) ### Storage layout diff --git a/docs/wake-qualification.md b/docs/wake-qualification.md index 5a0bdc597..57afc1cd7 100644 --- a/docs/wake-qualification.md +++ b/docs/wake-qualification.md @@ -10,15 +10,25 @@ explicitly selected by `--restart-operator`. ## Join objectives and evidence The isolated `TestColdWakeFleet_ConcurrentJoins` CI leg boots two independent -Minecraft Java 1.21.4 worlds and a Teeworlds 0.7.5 server. Each round releases -four TCP and two UDP clients, restarts the operator and checks every join. -One Minecraft world and the UDP server exchange Service/Hostport exposure -between rounds. The other Minecraft world keeps its NodePort. With the fleet -limit set to one, the drill records Kubernetes StatefulSet snapshots every -500 ms, checks that each of the three games started, and fails if any snapshot -contains two starting games. The artifact includes the observed transitions. -The Minecraft client must receive Login Success. The unmodified Teeworlds -client must enter its online state after receiving two world snapshots. +Minecraft Java 1.21.4 worlds and a Teeworlds 0.7.5 server. Each round runs +four TCP and two UDP clients with a fleet limit of one. The other clients +start and the operator restarts after the lead game receives its slot. +One Minecraft world and the UDP server exchange Service and Hostport +exposure between rounds. The other Minecraft world keeps its NodePort. + +In the first round, the lead Minecraft Pod reports Ready before its game +can answer. Its game container exits once with code 42, restarts and waits +35 seconds before loading the saved world. A competing wake must remain queued +while that process loads. The drill samples desired replicas across the fleet, +queries Minecraft directly with RCON and checks that its Service still routes +to the sentinel during loading. In the second round, the lead game's required +worker label is absent. The drill waits for a scheduler reason on the GameServer, +the unbound Pod to disappear, and a different game to begin loading before it +restores the label. Snapshots must stay within the configured limit throughout. + +An external Minecraft client must receive Login Success. The unmodified +Teeworlds client must enter its online state after receiving two world snapshots. +Its game readiness probe makes a separate UDP join over loopback on each boot. The job uploads per-attempt measurements and the kind node's CPU, memory, disk I/O and pressure counters. These worlds and the five-minute CI objective describe the regression fixture. Entitled games and production @@ -86,19 +96,26 @@ python3 wake_burst.py --context staging --plan sleepers.json --client ./join-onc --restart-operator gameplane-system/gameplane-operator > burst.json ``` -The driver releases all clients together. Every retry uses the same published +By default the driver releases all clients together. Every retry uses the same published address. After a new wake token appears while clients are still trying, it restarts the operator once and waits for rollout. The report records observed wake intent and phase separately from the first successful game join. It checks the original GameServer UID, a matching new request/acknowledgement, cleared sleep and lifecycle ownership, and a single game Pod UID without game container restarts. The Pod watch replays from the pre-burst list's resource -version. Expired watch history invalidates the lifecycle proof. +version. Expired watch history invalidates the lifecycle proof. In the isolated +drill, one round requires the lead game's single planned process exit. The +other requires the deleted, unbound Pod to have reported Unschedulable before +the replacement boot. All other targets retain the single-Pod, zero-restart check. 4. Archive `burst.json`, game builds, world/save sizes, node topology, image-cache state and storage class. The report gives successes and retries alongside nearest-rank p95/p99 among **successful** clients per target and - game/path/protocol cohort. Time starts at burst release. Compare failed and + game/path/protocol cohort. Time starts at `releasedAt`. Each target reports + `summary.firstSuccessfulJoinMs` from the real clients and + `recovery.firstPodReadyAt` from the kubelet's first Ready condition on the + surviving Pod. `recovery.firstPodReadyMs` expresses that condition on the + burst timeline using the node clock's timestamp precision. Compare failed and over-objective clients with the full denominator. Repeat on fresh sleepers and retain individual samples; a four-client p99 is just the slowest join. 5. Match the game node names and UTC run interval to CPU/memory usage and @@ -131,8 +148,12 @@ The operator records each reservation in the `gameplane-wake-starts` ConfigMap in its own namespace before it clears the GameServer sleep marker. The GameServer UID and sleep episode let a replacement operator resume the same reservation. A queued game retains its unacknowledged wake token and -waker. Its `status.idle.reason` reports the capacity wait. When the game -StatefulSet first has a Ready replica the next waiter can use the slot. +waker. Its `status.idle.reason` reports the capacity wait. To qualify a +game for limited wake, configure a game-container readiness probe that +succeeds after world loading, or declare an A2S query or an RCON +player-list command that the running game answers. Servers without a signal +stay queued and report the missing configuration. A game using native +queries needs an updated agent that identifies the Pod that made the query. The reservation moves through these states; the diagram omits the wait and retry loops: @@ -144,17 +165,26 @@ stateDiagram-v2 Queued --> Admitted: a slot is freed Requested --> Admitted: slot available Admitted --> Starting: sleep marker cleared, token acked - Starting --> Released: first Ready replica + Starting --> Released: game readiness probe or native query succeeds + Starting --> Parked: unschedulable attempt withdrawn and drained + Parked --> Queued: retry placement Released --> [*] ``` -Readiness ends startup accounting. Only the game client's completed join -measures the player objective. - -An indefinitely Pending or unready cold start continues to consume capacity. -Inspect the named GameServer, its StatefulSet and scheduler events. Repair -the fault, or stop the game and wait for its replicas to reach zero. Manual -stops and operation-owned games retain the existing lifecycle precedence. +The operator checks the current game container. A readiness probe must have +passed. For a game using a native query, the agent must report a fresh +successful query for this Pod after the current container started. A +prewarmed world can therefore release its slot before any players arrive. +The burst records Kubernetes readiness and the first successful client join +separately. + +A scheduled game keeps its reservation while its world loads, however long +that takes. When a waiting game needs capacity, an unbound Pod that the +scheduler reports as unschedulable can be withdrawn. The slot becomes +available after the StatefulSet has scaled to zero and the old Pod is gone. +The parked game must be admitted again before a recovered worker can run it. +Inspect `status.idle.reason` and the Pod's scheduler events for the cause. +Manual stops and operation-owned games retain their lifecycle precedence. Explicit starts, fresh games and backup/restore are outside this limit; include them in the headroom calculation. Avoid editing the reservation ConfigMap while games are waking. diff --git a/operator/api/v1alpha1/gameserver_types.go b/operator/api/v1alpha1/gameserver_types.go index d127233cb..fa1efb63e 100644 --- a/operator/api/v1alpha1/gameserver_types.go +++ b/operator/api/v1alpha1/gameserver_types.go @@ -1040,6 +1040,11 @@ type AgentStatus struct { // +optional LastHeartbeat *metav1.Time `json:"lastHeartbeat,omitempty"` + // PlayerQuery identifies the latest successful module-declared A2S or + // RCON player-list query. An unsuccessful query clears the observation. + // +optional + PlayerQuery *PlayerQueryObservation `json:"playerQuery,omitempty"` + // PlayersOnline is the count reported by the game protocol (RCON / // server query). Null (absent) means "unknown" — the game exposes no // player source, or the query failed. Consumers must not treat unknown @@ -1092,6 +1097,15 @@ type AgentStatus struct { DiskTotalBytes *int64 `json:"diskTotalBytes,omitempty"` } +// PlayerQueryObservation ties a native query to the Pod that answered it. +type PlayerQueryObservation struct { + // PodUID identifies the reporting game Pod across ordinal-zero replacements. + PodUID string `json:"podUID"` + // ObservedAt is when the query began, so a slow reply cannot qualify a + // game container that restarted while the request was in flight. + ObservedAt metav1.Time `json:"observedAt"` +} + // +kubebuilder:object:root=true // +kubebuilder:resource:shortName=gs // +kubebuilder:printcolumn:name="Template",type=string,JSONPath=`.spec.templateRef.name` diff --git a/operator/api/v1alpha1/zz_generated.deepcopy.go b/operator/api/v1alpha1/zz_generated.deepcopy.go index f4f7ac9ae..395ecf299 100644 --- a/operator/api/v1alpha1/zz_generated.deepcopy.go +++ b/operator/api/v1alpha1/zz_generated.deepcopy.go @@ -99,6 +99,11 @@ func (in *AgentStatus) DeepCopyInto(out *AgentStatus) { in, out := &in.LastHeartbeat, &out.LastHeartbeat *out = (*in).DeepCopy() } + if in.PlayerQuery != nil { + in, out := &in.PlayerQuery, &out.PlayerQuery + *out = new(PlayerQueryObservation) + (*in).DeepCopyInto(*out) + } if in.PlayersOnline != nil { in, out := &in.PlayersOnline, &out.PlayersOnline *out = new(int32) @@ -2686,6 +2691,22 @@ 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 *PlayerQueryObservation) DeepCopyInto(out *PlayerQueryObservation) { + *out = *in + in.ObservedAt.DeepCopyInto(&out.ObservedAt) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PlayerQueryObservation. +func (in *PlayerQueryObservation) DeepCopy() *PlayerQueryObservation { + if in == nil { + return nil + } + out := new(PlayerQueryObservation) + in.DeepCopyInto(out) + 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 diff --git a/operator/config/crd/gameplane.local_gameservers.yaml b/operator/config/crd/gameplane.local_gameservers.yaml index 225f65a4e..78cb96c06 100644 --- a/operator/config/crd/gameplane.local_gameservers.yaml +++ b/operator/config/crd/gameplane.local_gameservers.yaml @@ -2621,6 +2621,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. diff --git a/operator/internal/controller/gameserver_controller.go b/operator/internal/controller/gameserver_controller.go index ae3f148e3..ae2d285cb 100644 --- a/operator/internal/controller/gameserver_controller.go +++ b/operator/internal/controller/gameserver_controller.go @@ -1696,6 +1696,9 @@ func (r *GameServerReconciler) desiredReplicas( if gs.Annotations[restoreGuardAnnotation] != "" { return r.softStop(ctx, gs, tmpl) } + if live.Annotations[wakeStartParkedAnnotation] != "" { + return 0, 5 * time.Second, nil + } // A pending restart (stamped by the API) drives a transient scale-down → // scale-up entirely operator-side, so the request can't be lost to a // coalesced reconcile the way a client-issued suspend/resume pair can. @@ -1961,6 +1964,25 @@ func (r *GameServerReconciler) reconcileStatefulSet( if owner := metav1.GetControllerOf(ss); owner != nil && owner.UID != live.UID { return fmt.Errorf("StatefulSet belongs to a different GameServer identity") } + if gs.Annotations[wakeStartParkedAnnotation] != live.Annotations[wakeStartParkedAnnotation] || gs.Annotations[wakeStartEpisodeAnnotation] != live.Annotations[wakeStartEpisodeAnnotation] { + return fmt.Errorf("wake reservation changed before StatefulSet mutation") + } + if live.Annotations[wakeStartParkedAnnotation] != "" && live.Annotations[lifecycleOperationAnnotation] == "" { + // Stamp the actual workload before releasing its wake slot. A scale-up + // which read the old GameServer now conflicts on StatefulSet update. + if ss.Annotations == nil { + ss.Annotations = map[string]string{} + } + ss.Annotations[wakeStartParkedAnnotation] = live.Annotations[wakeStartEpisodeAnnotation] + actualReplicas, replicas = 0, 0 + if ss.ResourceVersion != "" { + return r.parkWakeWorkload(ctx, &live, ss) + } + } else { + if err := clearWakeParkFence(ss); err != nil { + return err + } + } if live.Spec.Networking.Expose == "Hostport" && live.Annotations[hostportNodeAnnotation] != "" { node, err := r.hostportEndpointNode(ctx, &live) if err != nil { diff --git a/operator/internal/controller/gameserver_idle.go b/operator/internal/controller/gameserver_idle.go index 84d15170e..5541ba686 100644 --- a/operator/internal/controller/gameserver_idle.go +++ b/operator/internal/controller/gameserver_idle.go @@ -105,6 +105,8 @@ type idleOutcome struct { // sleep/wake are the transitions to write as annotations this pass. sleep bool wake bool + // reservedEpisode identifies the cold wake admitted this pass. + reservedEpisode string // status is the read model to fold into the single status patch that // reconcileStatus issues; nil when spec.idle is not configured. status *gameplanev1alpha1.IdleStatus @@ -358,12 +360,35 @@ func (r *GameServerReconciler) reconcileIdle( in.lastWakeTime = &t } } + parked := gs.Annotations[wakeStartParkedAnnotation] + limited := r.WakeStartLimit > 0 && in.spec != nil && in.spec.Enabled && !in.suspended + if parked != "" && !limited { + // Disabling the cap or idle policy, or a manual stop, supersedes the + // parked request. Let the ordinary power/idle transition clear its fence. + in.wakePending = true + } + if parked != "" && limited { + if parked == wakeParkDraining { + err := r.finishWakeParking(ctx, gs, in.now) + return idleAsleep, wakeQueueStatus(gs, "parked: waiting for the unschedulable start to drain"), 5 * time.Second, nil, err + } + retryAt, err := time.Parse(time.RFC3339Nano, parked) + if err != nil { + return idleAsleep, nil, 0, nil, fmt.Errorf("parse parked wake retry: %w", err) + } + if in.now.Before(retryAt) { + return idleAsleep, wakeQueueStatus(gs, "parked: unschedulable start will retry fleet admission"), retryAt.Sub(in.now), nil, nil + } + // A parked wake was already acknowledged. Retry its original intent + // even if its prewarm window has passed or the request token is unchanged. + in.wakePending = true + } out := idleDecide(in) if in.preparing && !serviceWake && !out.wake { out = idleOutcome{state: idleAwake, wake: true, status: &gameplanev1alpha1.IdleStatus{Reason: "wake-on-connect handoff cancelled"}, err: out.err} } - if out.wake && in.asleepSince != nil && !in.preparing && !in.suspended && in.spec != nil && in.spec.Enabled && r.WakeStartLimit > 0 { + if out.wake && in.asleepSince != nil && !in.preparing && limited { // A server that saves a root override while the cluster disallows one // takes no wake slot and is not admitted (spec 030, OD-9 item 4). Its // SecurityAllowed condition explains the hold. @@ -375,20 +400,77 @@ func (r *GameServerReconciler) reconcileIdle( } return idleAsleep, rootHeld, 0, out.err, nil } + configured, err := gameStartupSignalConfigured(ctx, r.APIReader, gs) + if err != nil { + return idleAsleep, nil, 0, nil, err + } + if !configured { + return idleAsleep, wakeQueueStatus(gs, wakeStartupSignalMissing), 5 * time.Second, out.err, nil + } + blocked, err := r.wakeHostportBlocked(ctx, gs) + if err != nil { + return idleAsleep, nil, 0, nil, err + } + if blocked != "" { + return idleAsleep, wakeQueueStatus(gs, blocked), 5 * time.Second, out.err, nil + } admitted, err := r.reserveWakeStart(ctx, gs) if err != nil { return idleAsleep, nil, 0, nil, err } if !admitted { - queued := &gameplanev1alpha1.IdleStatus{Asleep: true, AsleepSince: &metav1.Time{Time: *in.asleepSince}, - Reason: "queued for fleet cold-start capacity"} - if gs.Status.Idle != nil { - queued.LastWakeTime = gs.Status.Idle.LastWakeTime.DeepCopy() - } - return idleAsleep, queued, 5 * time.Second, out.err, nil + return idleAsleep, wakeQueueStatus(gs, "queued for fleet cold-start capacity"), 5 * time.Second, out.err, nil } + out.reservedEpisode = gs.Annotations[IdleAsleepSinceAnnotation] out.status.Reason = "cold start admitted; waiting for game readiness" } + episode := gs.Annotations[wakeStartEpisodeAnnotation] + if limited && in.asleepSince == nil && episode != "" && gs.Annotations[wakeStartQualifiedAnnotation] != episode { + since, err := time.Parse(time.RFC3339, episode) + if err != nil { + return idleAwake, nil, 0, nil, err + } + ready, err := qualifiedGameStartup(ctx, r.APIReader, gs, since) + if err != nil { + return idleAwake, nil, 0, nil, err + } + if ready { + if err := r.releaseWakeSlot(ctx, gs); err != nil { + return idleAwake, nil, 0, nil, err + } + base := gs.DeepCopy() + gs.Annotations[wakeStartQualifiedAnnotation] = episode + if err := r.Patch(ctx, gs, client.MergeFromWithOptions(base, client.MergeFromWithOptimisticLock{})); err != nil { + return idleAwake, nil, 0, nil, err + } + } else { + var ss appsv1.StatefulSet + err := r.APIReader.Get(ctx, client.ObjectKeyFromObject(gs), &ss) + if err != nil && !apierrors.IsNotFound(err) { + return idleAwake, nil, 0, nil, err + } + reason := "cold start admitted; waiting for game readiness" + if err == nil && metav1.IsControlledBy(&ss, gs) { + blocked, err := r.blockedWakeStart(ctx, gs, &ss) + if err != nil { + return idleAwake, nil, 0, nil, err + } + if blocked != "" { + reason = "cold start blocked: " + blocked + } + } + out.state, out.sleep, out.requeue = idleAwake, false, 5*time.Second + out.status.Asleep, out.status.AsleepSince, out.status.EmptySince = false, nil, nil + out.status.Reason = reason + } + } + if !limited && episode != "" && !out.sleep && !out.wake { + base := gs.DeepCopy() + clearWakeStartAnnotations(gs) + if err := r.Patch(ctx, gs, client.MergeFromWithOptions(base, client.MergeFromWithOptimisticLock{})); err != nil { + return idleAwake, nil, 0, nil, err + } + } if out.state == idleAsleep && (in.preparing || (out.sleep && serviceWake)) { out.state = idlePreparing } @@ -400,6 +482,28 @@ func (r *GameServerReconciler) reconcileIdle( return out.state, out.status, out.requeue, out.err, nil } +func wakeQueueStatus(gs *gameplanev1alpha1.GameServer, reason string) *gameplanev1alpha1.IdleStatus { + if blocked := gs.Annotations[wakeStartBlockedReasonAnnotation]; gs.Annotations[wakeStartParkedAnnotation] != "" && blocked != "" { + reason += " (" + blocked + ")" + } + s := &gameplanev1alpha1.IdleStatus{Asleep: true, Reason: reason} + if since := parseAnnotationTime(gs, IdleAsleepSinceAnnotation); since != nil { + s.AsleepSince = &metav1.Time{Time: *since} + } + if gs.Status.Idle != nil { + s.LastWakeTime = gs.Status.Idle.LastWakeTime.DeepCopy() + } + return s +} + +func clearWakeStartAnnotations(gs *gameplanev1alpha1.GameServer) { + delete(gs.Annotations, wakeStartEpisodeAnnotation) + delete(gs.Annotations, wakeStartParkedAnnotation) + delete(gs.Annotations, wakeStartParkedForAnnotation) + delete(gs.Annotations, wakeStartBlockedReasonAnnotation) + delete(gs.Annotations, wakeStartQualifiedAnnotation) +} + // applyIdleTransition writes the sleep marker or clears it (acking any wake // request in the same patch, so a token can never be honored without being // acked and re-run forever). @@ -411,11 +515,24 @@ func (r *GameServerReconciler) applyIdleTransition( gs.Annotations = map[string]string{} } switch { - case out.state == idlePreparing: - gs.Annotations[idleSentinelPreparingAnnotation] = now.Format(time.RFC3339) case out.sleep: - gs.Annotations[IdleAsleepSinceAnnotation] = now.Format(time.RFC3339) + clearWakeStartAnnotations(gs) + layout := time.RFC3339 + if r.WakeStartLimit > 0 { + layout = time.RFC3339Nano + } + marker := IdleAsleepSinceAnnotation + if out.state == idlePreparing { + marker = idleSentinelPreparingAnnotation + } + gs.Annotations[marker] = now.Format(layout) case out.wake: + if gs.Annotations[IdleAsleepSinceAnnotation] != "" { + clearWakeStartAnnotations(gs) + if out.reservedEpisode != "" { + gs.Annotations[wakeStartEpisodeAnnotation] = out.reservedEpisode + } + } delete(gs.Annotations, IdleAsleepSinceAnnotation) delete(gs.Annotations, idleSentinelPreparingAnnotation) // Drop the soft-stop grace clock too: a wake that lands mid-drain must diff --git a/operator/internal/controller/gameserver_sentinel.go b/operator/internal/controller/gameserver_sentinel.go index 618b6c26b..9a05ce6f0 100644 --- a/operator/internal/controller/gameserver_sentinel.go +++ b/operator/internal/controller/gameserver_sentinel.go @@ -126,7 +126,8 @@ type sentinelPlan struct { // // - ClusterIP / NodePort / LoadBalancer: the sentinel doesn't compete // with the game pod for anything, so it is kept alive — and the -// Service kept routed to it — until the game pod itself reports Ready. +// Service kept routed to it — until the game Pod is ready to serve. +// Limited wakes also require the configured game-level startup signal. // A player connection the sentinel is holding open can then be handed // straight through instead of being dropped mid-wake. Once the public // endpoints point to the ready game the Deployment is deleted. The pod's long @@ -207,11 +208,11 @@ func (r *GameServerReconciler) planSentinel( if err != nil || waker == nil { return sentinelPlan{}, err } - gamePods, _, err := r.serviceRoutePods(ctx, gs, tmpl, "gameplane-game") + gameReady, err := r.gameReadyForWake(ctx, gs, tmpl) if err != nil { return sentinelPlan{}, err } - if len(gamePods) > 0 { + if gameReady { routed, err := r.gameRouteReady(ctx, gs, tmpl) return sentinelPlan{wantSentinel: !routed}, err } @@ -220,6 +221,27 @@ func (r *GameServerReconciler) planSentinel( return r.keepServiceRoute(ctx, gs) } +// The Service must have an owned, ready game Pod with the advertised ports. +// Limited wakes also require the current game process to pass its startup check. +func (r *GameServerReconciler) gameReadyForWake(ctx context.Context, gs *gameplanev1alpha1.GameServer, tmpl *gameplanev1alpha1.GameTemplate) (bool, error) { + pods, _, err := r.serviceRoutePods(ctx, gs, tmpl, "gameplane-game") + if err != nil || len(pods) == 0 { + return false, err + } + episode := gs.Annotations[wakeStartEpisodeAnnotation] + if r.WakeStartLimit <= 0 || (episode == "" && !templateStartupSignalConfigured(gs, tmpl)) { + return true, nil + } + var since time.Time + if episode != "" { + since, err = time.Parse(time.RFC3339, episode) + if err != nil { + return false, fmt.Errorf("invalid wake-start episode: %w", err) + } + } + return qualifiedGameStartup(ctx, r.hostportReader(), gs, since) +} + func (r *GameServerReconciler) keepServiceRoute(ctx context.Context, gs *gameplanev1alpha1.GameServer) (sentinelPlan, error) { var svc corev1.Service if err := r.hostportReader().Get(ctx, client.ObjectKeyFromObject(gs), &svc); err != nil { diff --git a/operator/internal/controller/gameserver_sentinel_test.go b/operator/internal/controller/gameserver_sentinel_test.go index 370f94c7d..6445cd8f8 100644 --- a/operator/internal/controller/gameserver_sentinel_test.go +++ b/operator/internal/controller/gameserver_sentinel_test.go @@ -7,6 +7,7 @@ import ( appsv1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" + discoveryv1 "k8s.io/api/discovery/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client/fake" @@ -15,6 +16,56 @@ import ( gameplanev1alpha1 "github.com/GameplanePanel/gameplane/operator/api/v1alpha1" ) +func TestServiceWakeKeepsSentinelWhileLimitedGameLoads(t *testing.T) { + f := newServiceRouteFixture() + gs, tmpl := f.gs, f.tmpl + gs.Spec.Idle = &gameplanev1alpha1.IdleSpec{Enabled: true, WakeOnConnect: true} + gs.Annotations = map[string]string{wakeStartEpisodeAnnotation: time.Now().Add(-time.Minute).UTC().Format(time.RFC3339)} + tmpl.Spec.Capabilities = &gameplanev1alpha1.CapabilitiesSpec{Players: &gameplanev1alpha1.PlayerActionsSpec{ + Query: &gameplanev1alpha1.PlayerQuerySpec{Protocol: "a2s", Port: 19132}, + }} + ss := wipeStoppedSet(gs) + *ss.Spec.Replicas = 1 + ss.Status.Replicas, ss.Status.ReadyReplicas = 1, 1 + pod := f.pod.DeepCopy() + pod.Name, pod.UID = gs.Name+"-0", "current-game" + pod.Status.PodIPs = []corev1.PodIP{{IP: "10.0.0.8"}, {IP: "fd00::8"}} + pod.Labels = serviceRouteSelector(gs, "gameplane-game") + pod.OwnerReferences = []metav1.OwnerReference{*metav1.NewControllerRef(ss, appsv1.SchemeGroupVersion.WithKind("StatefulSet"))} + game := corev1.Container{Name: gameContainerName} + for _, port := range tmpl.Spec.Ports { + game.Ports = append(game.Ports, corev1.ContainerPort{Name: port.Name, ContainerPort: port.ContainerPort, Protocol: port.Protocol}) + } + pod.Spec.Containers = []corev1.Container{game} + pod.Status.ContainerStatuses = []corev1.ContainerStatus{{Name: gameContainerName, Ready: true, ContainerID: "containerd://game", + State: corev1.ContainerState{Running: &corev1.ContainerStateRunning{StartedAt: metav1.NewTime(time.Now().Add(-10 * time.Second))}}}} + + checkPlan := func(limit int, wantSentinel, routeToSentinel bool) { + t.Helper() + r := f.reconciler(t, ss, pod) + r.WakeStartLimit = limit + plan, err := r.planSentinel(t.Context(), gs, tmpl, idleAwake) + if err != nil || plan.wantSentinel != wantSentinel || plan.routeToSentinel != routeToSentinel { + t.Fatalf("limit=%d, wantSentinel=%t, routeToSentinel=%t: plan=%+v, err=%v", limit, wantSentinel, routeToSentinel, plan, err) + } + } + checkPlan(1, true, true) + checkPlan(0, true, false) + + sample := metav1.Now() + gs.Status.Agent = &gameplanev1alpha1.AgentStatus{PlayersOnline: idlePtr(int32(0)), LastHeartbeat: &sample, + PlayerQuery: &gameplanev1alpha1.PlayerQueryObservation{PodUID: string(pod.UID), ObservedAt: sample}} + checkPlan(1, true, false) + f.service.Spec.Selector = pod.Labels + checkPlan(1, true, false) + for index, slice := range []*discoveryv1.EndpointSlice{f.v4, f.v6} { + ref := slice.Endpoints[0].TargetRef + ref.Name, ref.UID = pod.Name, pod.UID + slice.Endpoints[0].Addresses = []string{pod.Status.PodIPs[index].IP} + } + checkPlan(1, false, false) +} + func TestSentinelDeploymentOwnership(t *testing.T) { for _, owner := range []string{"current", "previous", "unowned"} { t.Run(owner, func(t *testing.T) { diff --git a/operator/internal/controller/gameserver_wake_admission.go b/operator/internal/controller/gameserver_wake_admission.go index c54f37690..f9989d82e 100644 --- a/operator/internal/controller/gameserver_wake_admission.go +++ b/operator/internal/controller/gameserver_wake_admission.go @@ -3,6 +3,8 @@ package controller import ( "context" "fmt" + "maps" + "slices" "strings" "time" @@ -15,7 +17,16 @@ import ( gameplanev1alpha1 "github.com/GameplanePanel/gameplane/operator/api/v1alpha1" ) -const wakeStartsName = "gameplane-wake-starts" +const ( + wakeStartsName = "gameplane-wake-starts" + wakeStartEpisodeAnnotation = "gameplane.local/wake-start-episode" + wakeStartParkedAnnotation = "gameplane.local/wake-start-parked" + wakeStartParkedForAnnotation = "gameplane.local/wake-start-parked-for" + wakeStartBlockedReasonAnnotation = "gameplane.local/wake-start-blocked-reason" + wakeStartQualifiedAnnotation = "gameplane.local/wake-start-qualified" + wakeParkDraining = "draining" + wakeParkRetry = 30 * time.Second +) // reserveWakeStart atomically reserves this sleep episode before its wake token // is acknowledged. Both writes survive operator restart. Losing a ConfigMap or @@ -46,23 +57,32 @@ func (r *GameServerReconciler) reserveWakeStart(ctx context.Context, gs *gamepla if !starts.DeletionTimestamp.IsZero() { return false, nil } - ref := metav1.GetControllerOf(&starts) - if ref == nil || ref.APIVersion != appsv1.SchemeGroupVersion.String() || ref.Kind != "Deployment" || ref.Name != "gameplane-operator" { - return false, fmt.Errorf("refusing foreign wake reservation ConfigMap %s", key) + if err := r.validateWakeLedgerOwner(ctx, &starts); err != nil { + return false, err } uid := string(gs.UID) episode := gs.Namespace + "/" + gs.Name + "@" + gs.Annotations[IdleAsleepSinceAnnotation] + // Read the request after the ledger. A stale pre-park admission can neither + // consume a just-released slot nor clear a later episode's workload fence. + var current gameplanev1alpha1.GameServer + if err := r.APIReader.Get(ctx, client.ObjectKeyFromObject(gs), ¤t); err != nil { + return false, err + } + if current.UID != gs.UID || current.ResourceVersion != gs.ResourceVersion || current.Annotations[wakeStartParkedAnnotation] == wakeParkDraining { + return false, nil + } if starts.Data[uid] == episode { return true, nil } if starts.Data == nil { starts.Data = map[string]string{} } - // Ignore objects that have completed, stopped, slept again or been - // replaced. A Pending/slow start retains its reservation regardless of age. + // Search every occupied slot for completions before requesting a withdrawal. + // Concurrent contenders choose the same candidate and race on its version. + withdrawal := wakeWithdrawal{waiter: uid} if len(starts.Data) >= r.WakeStartLimit { - for owner, saved := range starts.Data { - inUse, err := r.wakeStartInUse(ctx, owner, saved) + for _, owner := range slices.Sorted(maps.Keys(starts.Data)) { + inUse, err := r.wakeStartInUse(ctx, owner, starts.Data[owner], &withdrawal) if err != nil { return false, err } @@ -72,6 +92,20 @@ func (r *GameServerReconciler) reserveWakeStart(ctx context.Context, gs *gamepla } } if len(starts.Data) >= r.WakeStartLimit { + if !withdrawal.inProgress && withdrawal.candidate != nil { + gs := withdrawal.candidate + base := gs.DeepCopy() + if gs.Annotations == nil { + gs.Annotations = map[string]string{} + } + gs.Annotations[wakeStartEpisodeAnnotation] = withdrawal.since + gs.Annotations[IdleAsleepSinceAnnotation] = withdrawal.since + gs.Annotations[wakeStartParkedAnnotation] = wakeParkDraining + gs.Annotations[wakeStartParkedForAnnotation] = uid + gs.Annotations[wakeStartBlockedReasonAnnotation] = withdrawal.reason + delete(gs.Annotations, wakeStartQualifiedAnnotation) + return false, r.Patch(ctx, gs, client.MergeFromWithOptions(base, client.MergeFromWithOptimisticLock{})) + } return false, nil } starts.Data[uid] = episode @@ -81,7 +115,15 @@ func (r *GameServerReconciler) reserveWakeStart(ctx context.Context, gs *gamepla return true, nil } -func (r *GameServerReconciler) wakeStartInUse(ctx context.Context, uid, episode string) (bool, error) { +type wakeWithdrawal struct { + waiter string + candidate *gameplanev1alpha1.GameServer + reason string + since string + inProgress bool +} + +func (r *GameServerReconciler) wakeStartInUse(ctx context.Context, uid, episode string, withdrawal *wakeWithdrawal) (bool, error) { target, since, ok := strings.Cut(episode, "@") namespace, name, named := strings.Cut(target, "/") if !ok || !named || namespace == "" || name == "" || since == "" { @@ -95,7 +137,20 @@ func (r *GameServerReconciler) wakeStartInUse(ctx context.Context, uid, episode if string(owner.UID) != uid { return false, nil } - if asleep := owner.Annotations[IdleAsleepSinceAnnotation]; asleep != "" { + stopping := owner.Spec.Suspend || !owner.DeletionTimestamp.IsZero() + if parked := owner.Annotations[wakeStartParkedAnnotation]; parked != "" && owner.Annotations[wakeStartEpisodeAnnotation] == since && !stopping { + if parked == wakeParkDraining { + drained, err := r.parkedWakeDrained(ctx, &owner) + if !drained && owner.Annotations[wakeStartParkedForAnnotation] == withdrawal.waiter { + withdrawal.inProgress = true + } + return !drained, err + } + // A retry timestamp is written only after removing the old reservation. + // A slot present now belongs to the next admit/ack transaction. + return true, nil + } + if asleep := owner.Annotations[IdleAsleepSinceAnnotation]; asleep != "" && (!stopping || owner.Annotations[wakeStartEpisodeAnnotation] != since) { // Between the reservation and the wake patch, the episode itself owns // the slot. A concurrent takeover of the lifecycle changes the GS // resourceVersion, fencing any outstanding wake patch. @@ -118,7 +173,10 @@ func (r *GameServerReconciler) wakeStartInUse(ctx context.Context, uid, episode var ss appsv1.StatefulSet if err := r.APIReader.Get(ctx, key, &ss); err != nil { if apierrors.IsNotFound(err) { - return !owner.Spec.Suspend && owner.DeletionTimestamp.IsZero() && owner.Status.Phase != gameplanev1alpha1.GameServerPhaseFailed, nil + if stopping { + return true, nil + } // Wait for an observed stopped workload or removal of the owner. + return owner.Annotations[wakeStartEpisodeAnnotation] != "" || owner.Status.Phase != gameplanev1alpha1.GameServerPhaseFailed, nil } return false, err } @@ -128,8 +186,163 @@ func (r *GameServerReconciler) wakeStartInUse(ctx context.Context, uid, episode if ss.Status.ObservedGeneration < ss.Generation { return true, nil } - if owner.Spec.Suspend || !owner.DeletionTimestamp.IsZero() { - return ss.Status.Replicas > 0, nil + if stopping { + if ss.Spec.Replicas == nil || *ss.Spec.Replicas != 0 || ss.Status.Replicas != 0 { + return true, nil + } + return r.wakePodExists(ctx, &owner) + } + _, held, err := lifecycleOwner(&owner) + if err != nil { + return true, err + } + if !held && withdrawal.candidate == nil && owner.Spec.Idle != nil && owner.Spec.Idle.Enabled && !pendingWipe(&owner) && !tokenPending(&owner, RestartRequestedAnnotation, RestartCompletedAnnotation) { + blocked, err := r.blockedWakeStart(ctx, &owner, &ss) + if err != nil { + return true, err + } + if blocked != "" { + withdrawal.candidate, withdrawal.since, withdrawal.reason = &owner, since, blocked + return true, nil + } + } + if owner.Annotations[wakeStartEpisodeAnnotation] == "" { + // An already-acknowledged wake on upgrade may have no qualifying + // signal. Finish just that legacy episode under its previous contract. + configured, err := gameStartupSignalConfigured(ctx, r.APIReader, &owner) + if err != nil { + return true, err + } + if !configured { + return ss.Spec.Replicas == nil || *ss.Spec.Replicas == 0 || ss.Status.ReadyReplicas == 0, nil + } + } + started, err := time.Parse(time.RFC3339, since) + if err != nil { + return true, err + } + ready, err := qualifiedGameStartup(ctx, r.APIReader, &owner, started) + return !ready, err +} + +// Only the scheduler can declare an unbound game Pod unplaceable. A slow +// startup, missing heartbeat or image pull on an assigned node keeps its slot. +func (r *GameServerReconciler) blockedWakeStart(ctx context.Context, gs *gameplanev1alpha1.GameServer, ss *appsv1.StatefulSet) (string, error) { + var pod corev1.Pod + err := r.APIReader.Get(ctx, client.ObjectKey{Namespace: gs.Namespace, Name: gs.Name + "-0"}, &pod) + if apierrors.IsNotFound(err) { + return r.wakeHostportBlocked(ctx, gs) + } + if err != nil { + return "", err + } + if !metav1.IsControlledBy(&pod, ss) || !pod.DeletionTimestamp.IsZero() || pod.Spec.NodeName != "" || pod.Status.Phase != corev1.PodPending { + return "", nil + } + for _, c := range pod.Status.Conditions { + if c.Type == corev1.PodScheduled && c.Status == corev1.ConditionFalse && c.Reason == corev1.PodReasonUnschedulable { + return c.Reason + ": " + c.Message, nil + } + } + return "", nil +} + +func (r *GameServerReconciler) wakeHostportBlocked(ctx context.Context, gs *gameplanev1alpha1.GameServer) (string, error) { + if gs.Spec.Networking.Expose != "Hostport" || gs.Annotations[hostportNodeAnnotation] == "" { + return "", nil + } + node, err := r.hostportEndpointNode(ctx, gs) + if err != nil { + return "", err + } + if node == nil || !hostportNodeReady(node) || node.Spec.Unschedulable { + return "recorded Hostport endpoint node is unavailable", nil + } + return "", nil +} + +// A positive replica write that predates parking must conflict on the stamped +// StatefulSet resourceVersion. An absent workload cannot fence a stale Create. +func (r *GameServerReconciler) parkedWakeDrained(ctx context.Context, gs *gameplanev1alpha1.GameServer) (bool, error) { + var ss appsv1.StatefulSet + key := client.ObjectKeyFromObject(gs) + if err := r.APIReader.Get(ctx, key, &ss); err != nil { + return false, client.IgnoreNotFound(err) + } + if !metav1.IsControlledBy(&ss, gs) || !ss.DeletionTimestamp.IsZero() || ss.Annotations[wakeStartParkedAnnotation] != gs.Annotations[wakeStartEpisodeAnnotation] || + ss.Spec.Replicas == nil || *ss.Spec.Replicas != 0 || ss.Status.ObservedGeneration < ss.Generation || ss.Status.Replicas != 0 { + return false, nil + } + // GameServer StatefulSets have exactly one ordinal. Include even a + // terminating or same-name replacement Pod in the drain barrier. + exists, err := r.wakePodExists(ctx, gs) + return !exists, err +} + +func (r *GameServerReconciler) wakePodExists(ctx context.Context, gs *gameplanev1alpha1.GameServer) (bool, error) { + var pod corev1.Pod + err := r.APIReader.Get(ctx, client.ObjectKey{Namespace: gs.Namespace, Name: gs.Name + "-0"}, &pod) + return err == nil, client.IgnoreNotFound(err) +} + +func (r *GameServerReconciler) validateWakeLedgerOwner(ctx context.Context, starts *corev1.ConfigMap) error { + ref := metav1.GetControllerOf(starts) + if ref == nil || ref.UID == "" || ref.APIVersion != appsv1.SchemeGroupVersion.String() || ref.Kind != "Deployment" || ref.Name != "gameplane-operator" { + return fmt.Errorf("refusing foreign wake reservation ConfigMap %s/%s", starts.Namespace, starts.Name) + } + var operator appsv1.Deployment + if err := r.APIReader.Get(ctx, client.ObjectKey{Namespace: starts.Namespace, Name: ref.Name}, &operator); err != nil { + return err + } + if operator.UID != ref.UID || !operator.DeletionTimestamp.IsZero() { + return fmt.Errorf("wake reservation owner Deployment was replaced or is deleting") + } + return nil +} + +func (r *GameServerReconciler) finishWakeParking(ctx context.Context, gs *gameplanev1alpha1.GameServer, now time.Time) error { + drained, err := r.parkedWakeDrained(ctx, gs) + if err != nil || !drained { + return err + } + if err := r.releaseWakeSlot(ctx, gs); err != nil { + return err + } + base := gs.DeepCopy() + gs.Annotations[wakeStartParkedAnnotation] = now.Add(wakeParkRetry).Format(time.RFC3339Nano) + return r.Patch(ctx, gs, client.MergeFromWithOptions(base, client.MergeFromWithOptimisticLock{})) +} + +func (r *GameServerReconciler) releaseWakeSlot(ctx context.Context, gs *gameplanev1alpha1.GameServer) error { + var ledger corev1.ConfigMap + err := r.APIReader.Get(ctx, client.ObjectKey{Namespace: r.WakeStartNamespace, Name: wakeStartsName}, &ledger) + if err != nil && !apierrors.IsNotFound(err) { + return err + } + if err == nil { + if !ledger.DeletionTimestamp.IsZero() { + return fmt.Errorf("wake reservation ConfigMap is deleting") + } + if err := r.validateWakeLedgerOwner(ctx, &ledger); err != nil { + return err + } + } + uid := string(gs.UID) + episode := gs.Namespace + "/" + gs.Name + "@" + gs.Annotations[wakeStartEpisodeAnnotation] + if ledger.Data[uid] == episode { + // Confirm the same park after reading the ledger. A delayed reconciler + // must not delete the new slot acquired after the retry interval. + var live gameplanev1alpha1.GameServer + if err := r.APIReader.Get(ctx, client.ObjectKeyFromObject(gs), &live); err != nil { + return err + } + if live.ResourceVersion != gs.ResourceVersion { + return fmt.Errorf("GameServer changed before wake slot release") + } + delete(ledger.Data, uid) + if err := r.Update(ctx, &ledger); err != nil { + return err + } } - return ss.Spec.Replicas == nil || *ss.Spec.Replicas == 0 || ss.Status.ReadyReplicas == 0, nil + return nil } diff --git a/operator/internal/controller/gameserver_wake_admission_test.go b/operator/internal/controller/gameserver_wake_admission_test.go index b2db32481..0d60d6130 100644 --- a/operator/internal/controller/gameserver_wake_admission_test.go +++ b/operator/internal/controller/gameserver_wake_admission_test.go @@ -7,7 +7,9 @@ import ( appsv1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/utils/ptr" "sigs.k8s.io/controller-runtime/pkg/client" gameplanev1alpha1 "github.com/GameplanePanel/gameplane/operator/api/v1alpha1" @@ -23,6 +25,7 @@ func TestColdWakeCapacitySurvivesOperatorRestart(t *testing.T) { t.Fatal(err) } first.Spec.Idle = &gameplanev1alpha1.IdleSpec{Enabled: true, WakeOnConnect: true} + first.Spec.Probes = &gameplanev1alpha1.GameProbesSpec{Readiness: &corev1.Probe{ProbeHandler: corev1.ProbeHandler{Exec: &corev1.ExecAction{Command: []string{"check-world"}}}}} first.Annotations = map[string]string{IdleAsleepSinceAnnotation: time.Now().Add(-time.Hour).UTC().Format(time.RFC3339), IdleWakeRequestedAnnotation: "first-wake"} if err := r.Update(ctx, first); err != nil { t.Fatal(err) @@ -50,12 +53,15 @@ func TestColdWakeCapacitySurvivesOperatorRestart(t *testing.T) { t.Fatalf("first start still has no StatefulSet: admitted=%t err=%v", ok, err) } one := int32(1) - ss := &appsv1.StatefulSet{ObjectMeta: metav1.ObjectMeta{Name: first.Name, Namespace: first.Namespace, OwnerReferences: []metav1.OwnerReference{ + ss := &appsv1.StatefulSet{ObjectMeta: metav1.ObjectMeta{Name: first.Name, Namespace: first.Namespace, UID: "ss-uid", OwnerReferences: []metav1.OwnerReference{ *metav1.NewControllerRef(first, gameplanev1alpha1.GroupVersion.WithKind("GameServer")), }}, Spec: appsv1.StatefulSetSpec{Replicas: &one}} if err := r.Create(ctx, ss); err != nil { t.Fatal(err) } + if state, idle, retry, _, err := restarted.reconcileIdle(ctx, first, true); err != nil || state != idleAwake || idle.Asleep || !strings.Contains(idle.Reason, "waiting for game readiness") || retry <= 0 { + t.Fatalf("owner did not hold its startup while the game Pod was missing: %+v %v", idle, err) + } if ok, err := restarted.reserveWakeStart(ctx, second); err != nil || ok { t.Fatalf("first pod still starting: admitted=%t err=%v", ok, err) } @@ -63,6 +69,22 @@ func TestColdWakeCapacitySurvivesOperatorRestart(t *testing.T) { if err := r.Status().Update(ctx, ss); err != nil { t.Fatal(err) } + if ok, err := restarted.reserveWakeStart(ctx, second); err != nil || ok { + t.Fatalf("StatefulSet readiness alone released the startup: admitted=%t err=%v", ok, err) + } + pod := &corev1.Pod{ObjectMeta: metav1.ObjectMeta{Namespace: first.Namespace, Name: first.Name + "-0", UID: "game-pod", OwnerReferences: []metav1.OwnerReference{*metav1.NewControllerRef(ss, appsv1.SchemeGroupVersion.WithKind("StatefulSet"))}}, + Spec: corev1.PodSpec{Containers: []corev1.Container{{Name: gameContainerName, ReadinessProbe: first.Spec.Probes.Readiness}}}, + Status: corev1.PodStatus{Phase: corev1.PodRunning, Conditions: []corev1.PodCondition{{Type: corev1.PodReady, Status: corev1.ConditionTrue}}, ContainerStatuses: []corev1.ContainerStatus{{Name: gameContainerName, ContainerID: "containerd://world", Ready: true, State: corev1.ContainerState{Running: &corev1.ContainerStateRunning{StartedAt: metav1.NewTime(time.Now().Add(-time.Minute))}}}}}} + if err := r.Create(ctx, pod); err != nil { + t.Fatal(err) + } + if _, _, _, _, err := restarted.reconcileIdle(ctx, first, true); err != nil || first.Annotations[wakeStartQualifiedAnnotation] != first.Annotations[wakeStartEpisodeAnnotation] { + t.Fatalf("owner did not persist game readiness: %+v %v", first.Annotations, err) + } + var released corev1.ConfigMap + if err := r.Get(ctx, client.ObjectKey{Namespace: "panel", Name: wakeStartsName}, &released); err != nil || len(released.Data) != 0 { + t.Fatalf("qualifying an owner did not free its reservation: %v %v", released.Data, err) + } state, _, _, _, err = restarted.reconcileIdle(ctx, second, true) if err != nil || state != idleAwake || second.Annotations[IdleWakeCompletedAnnotation] != "second-wake" { t.Fatalf("queued wake was not admitted after readiness: state=%d err=%v annotations=%v", state, err, second.Annotations) @@ -76,3 +98,276 @@ func TestColdWakeCapacitySurvivesOperatorRestart(t *testing.T) { t.Fatalf("wake reservations must be collected without blocking Deployment deletion: %+v", owner) } } + +func TestWakeParkingRacesBindingAndFencesReplacement(t *testing.T) { + for _, bindingWins := range []bool{true, false} { + r, first, tmpl := revisionFixture(t) + ctx := t.Context() + r.WakeStartLimit, r.WakeStartNamespace = 1, "panel" + since := time.Now().Add(-time.Hour).UTC().Format(time.RFC3339) + first.Spec.Idle = &gameplanev1alpha1.IdleSpec{Enabled: true, WakeOnConnect: true} + first.Annotations[wakeStartEpisodeAnnotation] = since + if err := r.Update(ctx, first); err != nil { + t.Fatal(err) + } + second := first.DeepCopy() + second.ObjectMeta = metav1.ObjectMeta{Namespace: first.Namespace, Name: "queued", UID: "queued", Annotations: map[string]string{IdleAsleepSinceAnnotation: since, IdleWakeRequestedAnnotation: "request"}} + dep := &appsv1.Deployment{ObjectMeta: metav1.ObjectMeta{Name: "gameplane-operator", Namespace: "panel", UID: "deployment"}} + ledger := &corev1.ConfigMap{ObjectMeta: metav1.ObjectMeta{Name: wakeStartsName, Namespace: "panel", OwnerReferences: []metav1.OwnerReference{*metav1.NewControllerRef(dep, appsv1.SchemeGroupVersion.WithKind("Deployment"))}}, Data: map[string]string{string(first.UID): first.Namespace + "/" + first.Name + "@" + since}} + ss := &appsv1.StatefulSet{ObjectMeta: metav1.ObjectMeta{Name: first.Name, Namespace: first.Namespace, UID: "statefulset", OwnerReferences: []metav1.OwnerReference{*metav1.NewControllerRef(first, gameplanev1alpha1.GroupVersion.WithKind("GameServer"))}}, Spec: appsv1.StatefulSetSpec{Replicas: ptr.To(int32(1)), UpdateStrategy: appsv1.StatefulSetUpdateStrategy{Type: appsv1.RollingUpdateStatefulSetStrategyType}}} + pod := &corev1.Pod{ObjectMeta: metav1.ObjectMeta{Namespace: first.Namespace, Name: first.Name + "-0", UID: "unscheduled", OwnerReferences: []metav1.OwnerReference{*metav1.NewControllerRef(ss, appsv1.SchemeGroupVersion.WithKind("StatefulSet"))}}, Status: corev1.PodStatus{Phase: corev1.PodPending, Conditions: []corev1.PodCondition{{Type: corev1.PodScheduled, Status: corev1.ConditionFalse, Reason: corev1.PodReasonUnschedulable, Message: "no eligible worker"}}}} + for _, obj := range []client.Object{second, dep, ledger, ss, pod} { + if err := r.Create(ctx, obj); err != nil { + t.Fatal(err) + } + } + if _, idle, _, _, err := r.reconcileIdle(ctx, first, true); err != nil || !strings.Contains(idle.Reason, "no eligible worker") || idle.Asleep { + t.Fatalf("owner did not report why its admitted wake was blocked: %+v %v", idle, err) + } + if got, err := r.reserveWakeStart(ctx, second); got || err != nil { + t.Fatalf("capacity before park: %v %v", got, err) + } + if err := r.Get(ctx, client.ObjectKeyFromObject(first), first); err != nil { + t.Fatal(err) + } + if first.Annotations[wakeStartParkedAnnotation] != wakeParkDraining { + t.Fatalf("no durable park: %v", first.Annotations) + } + // Recreate the reconciler; stale positive replica decisions still use + // the live park, before and after the replacement scheduling gate. + r = &GameServerReconciler{Client: r.Client, APIReader: r.APIReader, Scheme: r.Scheme, WakeStartLimit: 1, WakeStartNamespace: "panel"} + advance := func() { + t.Helper() + if err := r.reconcileStatefulSet(ctx, first, tmpl, nil, &materializedConfig{}, 1); err != nil { + t.Fatal(err) + } + if err := r.Get(ctx, client.ObjectKeyFromObject(ss), ss); err != nil { + t.Fatal(err) + } + } + advance() + if *ss.Spec.Replicas != 1 || ss.Spec.UpdateStrategy.Type != appsv1.OnDeleteStatefulSetStrategyType || len(ss.Spec.Template.Spec.SchedulingGates) != 1 { + t.Fatalf("did not fence replacement: %+v", ss.Spec) + } + if bindingWins { + pod.Spec.NodeName = "recovered-worker" + if err := r.Update(ctx, pod); err != nil { + t.Fatal(err) + } + } + advance() + if bindingWins { + if err := r.Get(ctx, client.ObjectKeyFromObject(first), first); err != nil { + t.Fatal(err) + } + if first.Annotations[wakeStartParkedAnnotation] != "" || *ss.Spec.Replicas != 1 { + t.Fatal("withdrew an already-bound game") + } + if err := r.Get(ctx, client.ObjectKeyFromObject(pod), pod); err != nil || pod.Spec.NodeName != "recovered-worker" { + t.Fatalf("bound pod lost: %v", err) + } + if got, err := r.reserveWakeStart(ctx, second); got || err != nil { + t.Fatalf("released bound startup: %v %v", got, err) + } + continue + } + if err := r.Get(ctx, client.ObjectKeyFromObject(pod), pod); !apierrors.IsNotFound(err) { + t.Fatalf("original pending pod survived: %v", err) + } + replacement := pod.DeepCopy() + replacement.UID = "gated-replacement" + replacement.ResourceVersion = "" + replacement.Spec.SchedulingGates = ss.Spec.Template.Spec.SchedulingGates + if err := r.Create(ctx, replacement); err != nil { + t.Fatal(err) + } + advance() + if *ss.Spec.Replicas != 0 || ss.Annotations[wakeStartParkedAnnotation] != since { + t.Fatal("stale positive replica decision escaped its fence") + } + if got, err := r.reserveWakeStart(ctx, second); got || err != nil { + t.Fatalf("released before the replacement drained: %v %v", got, err) + } + if err := r.Delete(ctx, replacement); err != nil { + t.Fatal(err) + } + if got, err := r.reserveWakeStart(ctx, second); !got || err != nil { + t.Fatalf("placeable contender did not take drained slot: %v %v", got, err) + } + state, idle, retry, _, err := r.reconcileIdle(ctx, first, true) + if err != nil || state != idleAsleep || !strings.Contains(idle.Reason, "parked") || !strings.Contains(idle.Reason, "no eligible worker") || retry <= 0 { + t.Fatalf("parked request lost after release: %+v %v", idle, err) + } + if until, err := time.Parse(time.RFC3339Nano, first.Annotations[wakeStartParkedAnnotation]); err != nil || !until.After(time.Now()) { + t.Fatalf("parked request immediately resumed: %v %v", until, err) + } + if state, idle, retry, _, err := r.reconcileIdle(ctx, first, true); err != nil || state != idleAsleep || retry <= 0 || !strings.Contains(idle.Reason, "will retry") { + t.Fatalf("parked owner did not respect its retry time: %+v %v", idle, err) + } + if err := r.Delete(ctx, second); err != nil { + t.Fatal(err) + } + first.Spec.Probes = &gameplanev1alpha1.GameProbesSpec{Readiness: &corev1.Probe{ProbeHandler: corev1.ProbeHandler{TCPSocket: &corev1.TCPSocketAction{}}}} + first.Annotations[wakeStartParkedAnnotation] = time.Now().Add(-time.Second).UTC().Format(time.RFC3339Nano) + if err := r.Update(ctx, first); err != nil { + t.Fatal(err) + } + if state, idle, _, _, err := r.reconcileIdle(ctx, first, true); err != nil || state != idleAwake || first.Annotations[wakeStartParkedAnnotation] != "" || first.Annotations[wakeStartEpisodeAnnotation] != since { + t.Fatalf("parked owner lost its original wake after the other owner left: %+v %v", idle, err) + } + advance() + if *ss.Spec.Replicas != 1 || ss.Spec.UpdateStrategy.Type != appsv1.RollingUpdateStatefulSetStrategyType || len(ss.Spec.Template.Spec.SchedulingGates) != 0 || ss.Annotations[wakeParkStrategyAnnotation] != "" { + t.Fatalf("resumed game inherited the parking fence: %+v", ss.Spec) + } + } +} + +func TestWakeWithoutStartupSignalKeepsRequestAndUsesNoSlot(t *testing.T) { + r, gs, _ := revisionFixture(t) + r.WakeStartLimit, r.WakeStartNamespace = 1, "panel" + gs.Spec.Idle = &gameplanev1alpha1.IdleSpec{Enabled: true} + gs.Annotations[IdleAsleepSinceAnnotation] = time.Now().Add(-time.Hour).UTC().Format(time.RFC3339) + gs.Annotations[IdleWakeRequestedAnnotation] = "wake" + if err := r.Update(t.Context(), gs); err != nil { + t.Fatal(err) + } + state, idle, _, _, err := r.reconcileIdle(t.Context(), gs, false) + if err != nil || state != idleAsleep || idle.Reason != wakeStartupSignalMissing || gs.Annotations[IdleWakeCompletedAnnotation] != "" { + t.Fatalf("unqualified wake admitted: %+v %v", idle, err) + } + if err := r.Get(t.Context(), client.ObjectKey{Namespace: "panel", Name: wakeStartsName}, &corev1.ConfigMap{}); !apierrors.IsNotFound(err) { + t.Fatalf("unqualified wake created a reservation: %v", err) + } +} + +func TestParkedWakeHonorsPowerAndLimitChanges(t *testing.T) { + for _, change := range []string{"suspend", "disable idle", "unlimited"} { + t.Run(change, func(t *testing.T) { + r, gs, _ := revisionFixture(t) + r.WakeStartLimit = 1 + since := time.Now().Add(-time.Hour).UTC().Format(time.RFC3339) + gs.Annotations[wakeStartEpisodeAnnotation] = since + gs.Annotations[IdleAsleepSinceAnnotation] = since + gs.Annotations[wakeStartParkedAnnotation] = wakeParkDraining + gs.Spec.Idle = &gameplanev1alpha1.IdleSpec{Enabled: true} + switch change { + case "suspend": + gs.Spec.Suspend = true + case "disable idle": + gs.Spec.Idle.Enabled = false + case "unlimited": + r.WakeStartLimit = 0 + } + if err := r.Update(t.Context(), gs); err != nil { + t.Fatal(err) + } + state, _, _, _, err := r.reconcileIdle(t.Context(), gs, false) + if err != nil || state != idleAwake || gs.Annotations[wakeStartParkedAnnotation] != "" || gs.Annotations[IdleAsleepSinceAnnotation] != "" || gs.Spec.Suspend != (change == "suspend") { + t.Fatalf("power change lost or park retained: %+v %v", gs, err) + } + }) + } +} + +func TestStoppedWakeHoldsCapacityThroughPodDrain(t *testing.T) { + r, gs, _ := revisionFixture(t) + ctx := t.Context() + since := time.Now().UTC().Format(time.RFC3339Nano) + episode := gs.Namespace + "/" + gs.Name + "@" + since + gs.Spec.Suspend = true + gs.Annotations[wakeStartEpisodeAnnotation] = since + if err := r.Update(ctx, gs); err != nil { + t.Fatal(err) + } + assertInUse := func(want bool) { + t.Helper() + got, err := r.wakeStartInUse(ctx, string(gs.UID), episode, &wakeWithdrawal{}) + if err != nil || got != want { + t.Fatalf("slot in use = %v, %v; want %v", got, err, want) + } + } + assertInUse(true) // no workload yet to fence the start + ss := &appsv1.StatefulSet{ObjectMeta: metav1.ObjectMeta{Name: gs.Name, Namespace: gs.Namespace, UID: "workload", + OwnerReferences: []metav1.OwnerReference{*metav1.NewControllerRef(gs, gameplanev1alpha1.GroupVersion.WithKind("GameServer"))}}, + Spec: appsv1.StatefulSetSpec{Replicas: ptr.To(int32(1))}} + if err := r.Create(ctx, ss); err != nil { + t.Fatal(err) + } + assertInUse(true) + pod := &corev1.Pod{ObjectMeta: metav1.ObjectMeta{Name: gs.Name + "-0", Namespace: gs.Namespace}} + if err := r.Create(ctx, pod); err != nil { + t.Fatal(err) + } + *ss.Spec.Replicas = 0 + if err := r.Update(ctx, ss); err != nil { + t.Fatal(err) + } + assertInUse(true) + if err := r.Delete(ctx, pod); err != nil { + t.Fatal(err) + } + assertInUse(false) +} + +func TestLegacyWakeUsesExistingReadyContractWithoutGameSignal(t *testing.T) { + r, gs, _ := revisionFixture(t) + ctx := t.Context() + gs.Spec.Idle = &gameplanev1alpha1.IdleSpec{Enabled: true} + if err := r.Update(ctx, gs); err != nil { + t.Fatal(err) + } + since := time.Now().UTC().Format(time.RFC3339Nano) + episode := gs.Namespace + "/" + gs.Name + "@" + since + ss := &appsv1.StatefulSet{ObjectMeta: metav1.ObjectMeta{Name: gs.Name, Namespace: gs.Namespace, UID: "workload", + OwnerReferences: []metav1.OwnerReference{*metav1.NewControllerRef(gs, gameplanev1alpha1.GroupVersion.WithKind("GameServer"))}}, + Spec: appsv1.StatefulSetSpec{Replicas: ptr.To(int32(1))}} + if err := r.Create(ctx, ss); err != nil { + t.Fatal(err) + } + if used, err := r.wakeStartInUse(ctx, string(gs.UID), episode, &wakeWithdrawal{}); err != nil || !used { + t.Fatalf("legacy startup freed its slot early: %t, %v", used, err) + } + ss.Status.ReadyReplicas = 1 + if err := r.Status().Update(ctx, ss); err != nil { + t.Fatal(err) + } + if used, err := r.wakeStartInUse(ctx, string(gs.UID), episode, &wakeWithdrawal{}); err != nil || used { + t.Fatalf("legacy startup stranded the slot after readiness: %t, %v", used, err) + } +} + +func TestHostportWakeWaitsForRecordedWorkerWithoutReserving(t *testing.T) { + r, gs, _ := revisionFixture(t) + ctx := t.Context() + r.WakeStartLimit, r.WakeStartNamespace = 1, "panel" + gs.Spec.Idle = &gameplanev1alpha1.IdleSpec{Enabled: true, WakeOnConnect: true} + gs.Spec.Networking.Expose = "Hostport" + gs.Spec.Probes = &gameplanev1alpha1.GameProbesSpec{Readiness: &corev1.Probe{}} + gs.Annotations[IdleAsleepSinceAnnotation] = time.Now().UTC().Format(time.RFC3339Nano) + gs.Annotations[IdleWakeRequestedAnnotation] = "wake" + gs.Annotations[hostportNodeAnnotation], gs.Annotations[hostportNodeUIDAnnotation] = "worker", "node" + if err := r.Update(ctx, gs); err != nil { + t.Fatal(err) + } + check := func() { + t.Helper() + state, idle, retry, _, err := r.reconcileIdle(ctx, gs, false) + if err != nil || state != idleAsleep || !strings.Contains(idle.Reason, "Hostport endpoint node") || retry <= 0 || gs.Annotations[IdleWakeCompletedAnnotation] != "" { + t.Fatalf("Hostport wake advanced without its worker: %+v %v", idle, err) + } + } + check() + node := &corev1.Node{ObjectMeta: metav1.ObjectMeta{Name: "worker", UID: "node"}, + Spec: corev1.NodeSpec{Unschedulable: true}, Status: corev1.NodeStatus{Conditions: []corev1.NodeCondition{{Type: corev1.NodeReady, Status: corev1.ConditionTrue}}}} + if err := r.Create(ctx, node); err != nil { + t.Fatal(err) + } + check() + node.Spec.Unschedulable = false + if err := r.Update(ctx, node); err != nil { + t.Fatal(err) + } + if reason, err := r.wakeHostportBlocked(ctx, gs); err != nil || reason != "" { + t.Fatalf("recorded worker recovered but wake remains blocked: %q %v", reason, err) + } +} diff --git a/operator/internal/controller/gameserver_wake_parking.go b/operator/internal/controller/gameserver_wake_parking.go new file mode 100644 index 000000000..d9556297e --- /dev/null +++ b/operator/internal/controller/gameserver_wake_parking.go @@ -0,0 +1,92 @@ +package controller + +import ( + "context" + "encoding/json" + "fmt" + "slices" + + appsv1 "k8s.io/api/apps/v1" + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/utils/ptr" + "sigs.k8s.io/controller-runtime/pkg/client" + + gameplanev1alpha1 "github.com/GameplanePanel/gameplane/operator/api/v1alpha1" +) + +const wakeParkStrategyAnnotation = "gameplane.local/wake-start-original-strategy" +const wakeParkSchedulingGate = "gameplane.local/wake-start-withdrawing" + +func wakeSchedulingGate(gate corev1.PodSchedulingGate) bool { + return gate.Name == wakeParkSchedulingGate +} + +// The parking decision and Pod binding are writes to different objects. Keep +// the slot while protecting replacements, then race the scheduler on the same +// Pod resourceVersion. A Pod that wins binding keeps running under its slot. +func (r *GameServerReconciler) parkWakeWorkload(ctx context.Context, gs *gameplanev1alpha1.GameServer, ss *appsv1.StatefulSet) error { + if ss.Spec.Replicas != nil && *ss.Spec.Replicas == 0 { + return nil + } + if ss.Annotations[wakeParkStrategyAnnotation] == "" { + strategy, err := json.Marshal(ss.Spec.UpdateStrategy) + if err != nil { + return err + } + ss.Annotations[wakeParkStrategyAnnotation] = string(strategy) + } + if ss.Spec.UpdateStrategy.Type != appsv1.OnDeleteStatefulSetStrategyType || !slices.ContainsFunc(ss.Spec.Template.Spec.SchedulingGates, wakeSchedulingGate) { + ss.Spec.UpdateStrategy = appsv1.StatefulSetUpdateStrategy{Type: appsv1.OnDeleteStatefulSetStrategyType} + if !slices.ContainsFunc(ss.Spec.Template.Spec.SchedulingGates, wakeSchedulingGate) { + ss.Spec.Template.Spec.SchedulingGates = append(ss.Spec.Template.Spec.SchedulingGates, corev1.PodSchedulingGate{Name: wakeParkSchedulingGate}) + } + return nil + } + if ss.Status.ObservedGeneration < ss.Generation { + return nil + } + var pod corev1.Pod + err := r.APIReader.Get(ctx, client.ObjectKey{Namespace: gs.Namespace, Name: gs.Name + "-0"}, &pod) + if apierrors.IsNotFound(err) { + ss.Spec.Replicas = ptr.To(int32(0)) + return nil + } + if err != nil { + return err + } + if !metav1.IsControlledBy(&pod, ss) || pod.UID == "" { + return fmt.Errorf("cannot withdraw wake: Pod %s/%s has an unexpected owner", pod.Namespace, pod.Name) + } + if !pod.DeletionTimestamp.IsZero() { + return nil + } + if pod.Spec.NodeName != "" || (pod.Status.Phase != corev1.PodPending && pod.Status.Phase != "") { + base := gs.DeepCopy() + delete(gs.Annotations, wakeStartParkedAnnotation) + delete(gs.Annotations, wakeStartParkedForAnnotation) + delete(gs.Annotations, wakeStartBlockedReasonAnnotation) + delete(gs.Annotations, IdleAsleepSinceAnnotation) + return r.Patch(ctx, gs, client.MergeFromWithOptions(base, client.MergeFromWithOptimisticLock{})) + } + if slices.ContainsFunc(pod.Spec.SchedulingGates, wakeSchedulingGate) { + ss.Spec.Replicas = ptr.To(int32(0)) + return nil + } + return client.IgnoreNotFound(r.Delete(ctx, &pod, client.Preconditions{UID: &pod.UID, ResourceVersion: &pod.ResourceVersion})) +} + +func clearWakeParkFence(ss *appsv1.StatefulSet) error { + if raw := ss.Annotations[wakeParkStrategyAnnotation]; raw != "" { + var strategy appsv1.StatefulSetUpdateStrategy + if err := json.Unmarshal([]byte(raw), &strategy); err != nil { + return fmt.Errorf("decode parked StatefulSet update strategy: %w", err) + } + ss.Spec.UpdateStrategy = strategy + ss.Spec.Template.Spec.SchedulingGates = slices.DeleteFunc(ss.Spec.Template.Spec.SchedulingGates, wakeSchedulingGate) + delete(ss.Annotations, wakeParkStrategyAnnotation) + } + delete(ss.Annotations, wakeStartParkedAnnotation) + return nil +} diff --git a/operator/internal/controller/gameserver_wake_readiness.go b/operator/internal/controller/gameserver_wake_readiness.go new file mode 100644 index 000000000..1fa5c9cbd --- /dev/null +++ b/operator/internal/controller/gameserver_wake_readiness.go @@ -0,0 +1,113 @@ +package controller + +import ( + "context" + "slices" + "time" + + appsv1 "k8s.io/api/apps/v1" + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "sigs.k8s.io/controller-runtime/pkg/client" + + gameplanev1alpha1 "github.com/GameplanePanel/gameplane/operator/api/v1alpha1" +) + +const wakeStartupSignalMissing = "configure a game readiness probe, an A2S players.query, or an RCON players.list command to qualify startup" + +func templateStartupSignalConfigured(gs *gameplanev1alpha1.GameServer, tmpl *gameplanev1alpha1.GameTemplate) bool { + if effectiveGameProbes(gs, tmpl).Readiness != nil { + return true + } + caps := tmpl.Spec.Capabilities + if caps == nil || caps.Players == nil { + return false + } + if query := caps.Players.Query; query != nil { + return query.Protocol == "a2s" && query.Port > 0 && query.Port <= 65535 + } + // The CLI transport writes to stdin and cannot read a game reply. + return templateHasRCON(tmpl) && rconProtocol(tmpl) != "cli" && caps.Players.List != nil && caps.Players.List.Command != "" +} + +func gameStartupSignalConfigured(ctx context.Context, reader client.Reader, gs *gameplanev1alpha1.GameServer) (bool, error) { + tmpl, err := effectiveGameTemplate(ctx, reader, gs) + if err != nil { + return false, err + } + return templateStartupSignalConfigured(gs, tmpl), nil +} + +// qualifiedGameStartup checks the live game process. A wake that cancels +// sleep during the grace period can keep the same serving process. +func qualifiedGameStartup(ctx context.Context, reader client.Reader, gs *gameplanev1alpha1.GameServer, since time.Time) (bool, error) { + var ss appsv1.StatefulSet + if err := reader.Get(ctx, client.ObjectKeyFromObject(gs), &ss); err != nil { + return false, client.IgnoreNotFound(err) + } + if gs.UID == "" || ss.UID == "" || !metav1.IsControlledBy(&ss, gs) || !ss.DeletionTimestamp.IsZero() || + ss.Spec.Replicas == nil || *ss.Spec.Replicas == 0 || ss.Status.ObservedGeneration < ss.Generation { + return false, nil + } + var pod corev1.Pod + if err := reader.Get(ctx, client.ObjectKey{Namespace: gs.Namespace, Name: gs.Name + "-0"}, &pod); err != nil { + return false, client.IgnoreNotFound(err) + } + if pod.UID == "" || !metav1.IsControlledBy(&pod, &ss) || !pod.DeletionTimestamp.IsZero() || pod.Status.Phase != corev1.PodRunning || !podReady(&pod) { + return false, nil + } + // The caller may have an informer snapshot from before the agent cleared + // a failed native query, or before a new stop or sleep began. + var live gameplanev1alpha1.GameServer + if err := reader.Get(ctx, client.ObjectKeyFromObject(gs), &live); err != nil { + return false, client.IgnoreNotFound(err) + } + if live.UID != gs.UID || !live.DeletionTimestamp.IsZero() || live.Spec.Suspend || + live.Annotations[IdleAsleepSinceAnnotation] != "" || live.Annotations[idleSentinelPreparingAnnotation] != "" || + live.Annotations[stopRequestedAtAnnotation] != "" || live.Annotations[wakeStartParkedAnnotation] != "" || live.Annotations[wakeStartEpisodeAnnotation] != gs.Annotations[wakeStartEpisodeAnnotation] { + return false, nil + } + return gameProcessQualified(&pod, live.Status.Agent, since, time.Now()), nil +} + +func gameProcessQualified(pod *corev1.Pod, agent *gameplanev1alpha1.AgentStatus, since, now time.Time) bool { + i := slices.IndexFunc(pod.Status.ContainerStatuses, func(s corev1.ContainerStatus) bool { return s.Name == gameContainerName }) + if i < 0 { + return false + } + game := &pod.Status.ContainerStatuses[i] + if !game.Ready || game.ContainerID == "" || game.State.Running == nil || game.State.Running.StartedAt.IsZero() { + return false + } + started := game.State.Running.StartedAt.Time + // kubelet reports StartedAt to whole seconds. An episode can be stamped + // earlier in that same second with nanosecond precision. + if started.After(now) || since.After(now) { + return false + } + for _, container := range pod.Spec.Containers { + if container.Name != gameContainerName { + continue + } + // For games with an explicit readiness probe this process's Ready + // status is the module's chosen gate, even if RCON answered earlier. + if container.ReadinessProbe != nil { + if !started.Before(since.Truncate(time.Second)) { + return true + } + // On a cancelled sleep, the same container may keep passing its + // probe throughout. Require a Ready transition for this process. + return slices.ContainsFunc(pod.Status.Conditions, func(c corev1.PodCondition) bool { + return c.Type == corev1.PodReady && c.Status == corev1.ConditionTrue && !c.LastTransitionTime.Time.Before(started) && !c.LastTransitionTime.After(now) + }) + } + if agent == nil || agent.PlayerQuery == nil || agent.LastHeartbeat == nil || agent.PlayersOnline == nil || agent.PlayerQuery.PodUID != string(pod.UID) { + return false + } + observed := agent.PlayerQuery.ObservedAt.Time + // Kubelet times have second precision. Waiting for a later second + // excludes a reply from before a same-Pod game-container restart. + return observed.Equal(agent.LastHeartbeat.Time) && observed.After(started) && !observed.Before(since) && !observed.After(now) && now.Sub(observed) < heartbeatFreshness + } + return false +} diff --git a/operator/internal/controller/gameserver_wake_readiness_test.go b/operator/internal/controller/gameserver_wake_readiness_test.go new file mode 100644 index 000000000..57766963f --- /dev/null +++ b/operator/internal/controller/gameserver_wake_readiness_test.go @@ -0,0 +1,164 @@ +package controller + +import ( + "testing" + "time" + + appsv1 "k8s.io/api/apps/v1" + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/utils/ptr" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + + gameplanev1alpha1 "github.com/GameplanePanel/gameplane/operator/api/v1alpha1" +) + +func TestWakeStartupRequiresCurrentGameEvidence(t *testing.T) { + now := time.Now().UTC().Truncate(time.Second) + started := metav1.NewTime(now.Add(-10 * time.Second)) + sample := metav1.NewTime(now.Add(-2 * time.Second)) + gs := &gameplanev1alpha1.GameServer{ObjectMeta: metav1.ObjectMeta{Name: "game", Namespace: "games", UID: "gs"}} + ss := &appsv1.StatefulSet{ObjectMeta: metav1.ObjectMeta{Name: gs.Name, Namespace: gs.Namespace, UID: "ss", + OwnerReferences: []metav1.OwnerReference{*metav1.NewControllerRef(gs, gameplanev1alpha1.GroupVersion.WithKind("GameServer"))}}, + Spec: appsv1.StatefulSetSpec{Replicas: ptr.To(int32(1))}} + pod := &corev1.Pod{ObjectMeta: metav1.ObjectMeta{Name: gs.Name + "-0", Namespace: gs.Namespace, UID: "pod", + OwnerReferences: []metav1.OwnerReference{*metav1.NewControllerRef(ss, appsv1.SchemeGroupVersion.WithKind("StatefulSet"))}}, + Spec: corev1.PodSpec{Containers: []corev1.Container{{Name: gameContainerName}}}, + Status: corev1.PodStatus{Phase: corev1.PodRunning, Conditions: []corev1.PodCondition{{Type: corev1.PodReady, Status: corev1.ConditionTrue}}, + ContainerStatuses: []corev1.ContainerStatus{{Name: gameContainerName, Ready: true, ContainerID: "containerd://game", + State: corev1.ContainerState{Running: &corev1.ContainerStateRunning{StartedAt: started}}}}}} + agent := &gameplanev1alpha1.AgentStatus{LastHeartbeat: &sample, PlayersOnline: ptr.To(int32(0)), + PlayerQuery: &gameplanev1alpha1.PlayerQueryObservation{PodUID: string(pod.UID), ObservedAt: sample}} + since := now.Add(-15 * time.Second) + for _, tc := range []struct { + name string + change func(*corev1.Pod, *gameplanev1alpha1.AgentStatus) + want bool + }{ + {"native empty game", nil, true}, + {"missing game status", func(p *corev1.Pod, _ *gameplanev1alpha1.AgentStatus) { + p.Status.ContainerStatuses = nil + }, false}, + {"missing game container", func(p *corev1.Pod, _ *gameplanev1alpha1.AgentStatus) { + p.Spec.Containers[0].Name = "agent" + }, false}, + {"container clock ahead of controller", func(p *corev1.Pod, _ *gameplanev1alpha1.AgentStatus) { + p.Status.ContainerStatuses[0].State.Running.StartedAt = metav1.NewTime(now.Add(time.Hour)) + }, false}, + {"Kubernetes ready without query", func(_ *corev1.Pod, a *gameplanev1alpha1.AgentStatus) { a.PlayerQuery = nil }, false}, + {"old pod", func(_ *corev1.Pod, a *gameplanev1alpha1.AgentStatus) { a.PlayerQuery.PodUID = "previous" }, false}, + {"old process", func(p *corev1.Pod, _ *gameplanev1alpha1.AgentStatus) { + p.Status.ContainerStatuses[0].State.Running.StartedAt = sample + }, false}, + {"fresh query after cancelled sleep", func(p *corev1.Pod, _ *gameplanev1alpha1.AgentStatus) { + p.Status.ContainerStatuses[0].State.Running.StartedAt = metav1.NewTime(since.Add(-time.Minute)) + }, true}, + {"query before cancelled sleep", func(p *corev1.Pod, a *gameplanev1alpha1.AgentStatus) { + p.Status.ContainerStatuses[0].State.Running.StartedAt = metav1.NewTime(since.Add(-time.Minute)) + a.PlayerQuery.ObservedAt = metav1.NewTime(since.Add(-time.Second)) + a.LastHeartbeat = &a.PlayerQuery.ObservedAt + }, false}, + {"same episode second", func(p *corev1.Pod, _ *gameplanev1alpha1.AgentStatus) { + p.Status.ContainerStatuses[0].State.Running.StartedAt = metav1.NewTime(since) + }, true}, + {"stale sample", func(p *corev1.Pod, a *gameplanev1alpha1.AgentStatus) { + p.Status.ContainerStatuses[0].State.Running.StartedAt = metav1.NewTime(now.Add(-3 * time.Minute)) + a.PlayerQuery.ObservedAt = metav1.NewTime(now.Add(-2 * time.Minute)) + a.LastHeartbeat = &a.PlayerQuery.ObservedAt + }, false}, + {"later heartbeat without provenance", func(_ *corev1.Pod, a *gameplanev1alpha1.AgentStatus) { a.LastHeartbeat = &started }, false}, + {"new StatefulSet", func(p *corev1.Pod, _ *gameplanev1alpha1.AgentStatus) { p.OwnerReferences[0].UID = "previous" }, false}, + {"explicit probe", func(p *corev1.Pod, a *gameplanev1alpha1.AgentStatus) { + p.Spec.Containers[0].ReadinessProbe = &corev1.Probe{} + a.PlayerQuery = nil + }, true}, + {"continuous probe after cancelled sleep", func(p *corev1.Pod, a *gameplanev1alpha1.AgentStatus) { + p.Spec.Containers[0].ReadinessProbe = &corev1.Probe{} + p.Status.ContainerStatuses[0].State.Running.StartedAt = metav1.NewTime(since.Add(-time.Minute)) + p.Status.Conditions[0].LastTransitionTime = metav1.NewTime(since.Add(-time.Second)) + a.PlayerQuery = nil + }, true}, + {"ready condition from older process", func(p *corev1.Pod, _ *gameplanev1alpha1.AgentStatus) { + p.Spec.Containers[0].ReadinessProbe = &corev1.Probe{} + p.Status.ContainerStatuses[0].State.Running.StartedAt = metav1.NewTime(since.Add(-time.Minute)) + p.Status.Conditions[0].LastTransitionTime = metav1.NewTime(since.Add(-2 * time.Minute)) + }, false}, + {"native query before explicit probe passes", func(p *corev1.Pod, _ *gameplanev1alpha1.AgentStatus) { + p.Spec.Containers[0].ReadinessProbe = &corev1.Probe{} + p.Status.ContainerStatuses[0].Ready = false + }, false}, + } { + t.Run(tc.name, func(t *testing.T) { + p, server := pod.DeepCopy(), gs.DeepCopy() + server.Status.Agent = agent.DeepCopy() + if tc.change != nil { + tc.change(p, server.Status.Agent) + } + reader := fake.NewClientBuilder().WithScheme(wipeScheme(t)).WithObjects(ss, p, server).Build() + // Every caller has an earlier successful query in its cache. Only + // the native observation still visible in the live API can qualify. + cached := gs.DeepCopy() + cached.Status.Agent = agent.DeepCopy() + got, err := qualifiedGameStartup(t.Context(), reader, cached, since.Add(300*time.Millisecond)) + if err != nil || got != tc.want { + t.Fatalf("qualifiedGameStartup = %v, %v; want %v", got, err, tc.want) + } + }) + } +} + +func TestWakeReadinessFencesCachedEpisodeAfterNewSleep(t *testing.T) { + r, server, _ := revisionFixture(t) + ctx := t.Context() + cached := server.DeepCopy() + server.Annotations[IdleAsleepSinceAnnotation] = time.Now().UTC().Format(time.RFC3339Nano) + if err := r.Update(ctx, server); err != nil { + t.Fatal(err) + } + ss := &appsv1.StatefulSet{ObjectMeta: metav1.ObjectMeta{Name: server.Name, Namespace: server.Namespace, UID: "ss", + OwnerReferences: []metav1.OwnerReference{*metav1.NewControllerRef(server, gameplanev1alpha1.GroupVersion.WithKind("GameServer"))}}, + Spec: appsv1.StatefulSetSpec{Replicas: ptr.To(int32(1))}} + if err := r.Create(ctx, ss); err != nil { + t.Fatal(err) + } + pod := &corev1.Pod{ObjectMeta: metav1.ObjectMeta{Name: server.Name + "-0", Namespace: server.Namespace, UID: "still-serving", + OwnerReferences: []metav1.OwnerReference{*metav1.NewControllerRef(ss, appsv1.SchemeGroupVersion.WithKind("StatefulSet"))}}, + Spec: corev1.PodSpec{Containers: []corev1.Container{{Name: gameContainerName, ReadinessProbe: &corev1.Probe{}}}}, + Status: corev1.PodStatus{Phase: corev1.PodRunning, Conditions: []corev1.PodCondition{{Type: corev1.PodReady, Status: corev1.ConditionTrue}}, + ContainerStatuses: []corev1.ContainerStatus{{Name: gameContainerName, Ready: true, ContainerID: "previous", State: corev1.ContainerState{ + Running: &corev1.ContainerStateRunning{StartedAt: metav1.NewTime(time.Now().Add(-time.Minute))}}}}}} + if err := r.Create(ctx, pod); err != nil { + t.Fatal(err) + } + if ready, err := qualifiedGameStartup(ctx, r.APIReader, cached, time.Now().Add(-time.Hour)); err != nil || ready { + t.Fatalf("stale wake qualified during the next sleep: %t, %v", ready, err) + } +} + +func TestTemplateStartupSignalRequiresProbeOrQueryableProtocol(t *testing.T) { + gs := &gameplanev1alpha1.GameServer{} + tmpl := &gameplanev1alpha1.GameTemplate{} + tmpl.Spec.RCON = &gameplanev1alpha1.RCONSpec{Protocol: "websocket"} + players := &gameplanev1alpha1.PlayerActionsSpec{} + tmpl.Spec.Capabilities = &gameplanev1alpha1.CapabilitiesSpec{Players: players} + if templateStartupSignalConfigured(gs, tmpl) { + t.Fatal("RCON without a declared list cannot qualify") + } + players.List = &gameplanev1alpha1.PlayerListSpec{Command: "playerlist"} + if !templateStartupSignalConfigured(gs, tmpl) { + t.Fatal("declared RCON player list cannot qualify") + } + tmpl.Spec.RCON.Protocol = "cli" + if templateStartupSignalConfigured(gs, tmpl) { + t.Fatal("stdin-only CLI cannot confirm a game reply") + } + players.Query = &gameplanev1alpha1.PlayerQuerySpec{Protocol: "a2s", Port: 2457} + if !templateStartupSignalConfigured(gs, tmpl) { + t.Fatal("native UDP game query cannot qualify") + } + players.Query = nil + gs.Spec.Probes = &gameplanev1alpha1.GameProbesSpec{Readiness: &corev1.Probe{}} + if !templateStartupSignalConfigured(gs, tmpl) { + t.Fatal("per-server readiness override cannot qualify") + } +} diff --git a/operator/specs.md b/operator/specs.md index 492ddb00e..7ec15b85f 100644 --- a/operator/specs.md +++ b/operator/specs.md @@ -234,6 +234,22 @@ separate five-second maximum fits inside that budget. Concurrent callers share the in-flight PATCH result. UDP reads enqueue coalesced requests to one bounded worker, and established TCP sessions use the longer session/drain context. +## Fleet cold-start admission + +`--wake-start-limit` applies to native idle wakes and scheduled prewarming. +A positive limit reserves capacity in `gameplane-wake-starts` before the +operator acknowledges the wake request. A game-container readiness probe or +a successful declared A2S/RCON player query qualifies the current process. +The query evidence includes its source Pod UID and observation time, which +must be later than the game container's start. Service-backed wakes use the +same evidence to return traffic to the game. Zero keeps unlimited wake. + +A waiting request can displace an unschedulable attempt. The operator fences +the parked workload at zero, observes that its Pod has gone, and requires a +new reservation for the retry. A slow world on an assigned worker keeps its +slot. The reservation and the parking state survive operator restarts. See +the [cold-wake qualification drill](../docs/wake-qualification.md). + ## Template revision admission - Admission and the final pin update reject removing or retyping a populated diff --git a/test/e2e/cold_wake_fleet_e2e_test.go b/test/e2e/cold_wake_fleet_e2e_test.go index ff548b0bd..97e830f88 100644 --- a/test/e2e/cold_wake_fleet_e2e_test.go +++ b/test/e2e/cold_wake_fleet_e2e_test.go @@ -10,6 +10,7 @@ import ( "os" "os/exec" "path/filepath" + "regexp" "slices" "strings" "testing" @@ -17,6 +18,7 @@ import ( 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" ) @@ -63,15 +65,33 @@ func TestColdWakeFleet_ConcurrentJoins(t *testing.T) { k("-n", "gameplane-system", "rollout", "status", "deployment/gameplane-operator", "--timeout=3m") mc := minecraftBotSpec() mc.Template, mc.Expose, mc.WakeProtocol = "fleet-minecraft", "NodePort", "minecraft" + secondMC := mc + secondMC.Template = "fleet-minecraft-second" + // Only the cold boots delay loading the real saved world. The first + // exits once before opening its listeners and restarts in the same Pod. + mc.Probes = nil + mc.Players = map[string]any{"list": map[string]any{"command": "list"}} + mc.Command = []any{"/bin/sh", "-ec", `if [ -e /data/.wake-cold ]; then + if [ ! -e /data/.wake-restarted ]; then touch /data/.wake-restarted; sleep 8; exit 42; fi + sleep 35 + fi + exec /image/scripts/start`} tw := gameBotSpec{Template: "fleet-teeworlds", Game: "teeworlds", DisplayName: "Teeworlds 0.7.5", Image: "gameplane-test/wake-teeworlds:ci", Expose: "Hostport", WakeProtocol: "generic", ProbePort: 8303, Ports: []gamePort{{Name: "game", Port: 8303, Protocol: "UDP"}}, MountPath: "/world", StorageSize: "64Mi", ReadyTimeout: 3 * time.Minute, - Resources: gameResources{ReqCPU: "50m", ReqMem: "32Mi", LimCPU: "1", LimMem: "128Mi"}, - Probes: map[string]any{"readiness": map[string]any{"exec": map[string]any{"command": []any{"sh", "-ec", "grep -qs ':206F ' /proc/net/udp /proc/net/udp6"}}, "periodSeconds": int64(2)}}} + Resources: gameResources{ReqCPU: "50m", ReqMem: "128Mi", LimCPU: "1", LimMem: "512Mi"}, + Probes: map[string]any{"readiness": map[string]any{ + "exec": map[string]any{"command": []any{"sh", "-ec", "test -f /tmp/world-ready || { python3 /opt/teeworlds-join.py --inside -game teeworlds -addr 127.0.0.1:8303 -user readycheck -deadline 12000ms && touch /tmp/world-ready; }"}}, + "periodSeconds": int64(5), "timeoutSeconds": int64(15), + }}} mcName, ns := createGameBotServer(t, envInstance, mc) + envInstance.Eventually(t, mc.ReadyTimeout, func() (bool, string) { + ready, err := checkFleetWorld(ctx, ns, mcName, false) + return ready && err == nil, "waiting for Minecraft to answer its first player query" + }) + worldRevision := waitForFleetWorldQuery(t, ns, mcName, "") + k("-n", ns, "exec", mcName+"-0", "-c", "game", "--", "touch", "/data/.wake-cold") parkFleetGame(ctx, t, ns, mcName) - secondMC := mc - secondMC.Template = "fleet-minecraft-second" secondName, _ := createGameBotServer(t, envInstance, secondMC) parkFleetGame(ctx, t, ns, secondName) twName, _ := createGameBotServer(t, envInstance, tw) @@ -149,9 +169,32 @@ func TestColdWakeFleet_ConcurrentJoins(t *testing.T) { if err := os.WriteFile(plan, data, 0o600); err != nil { t.Fatal(err) } - cmd := exec.CommandContext(ctx, "python3", "wake_burst.py", "--plan", plan, "--client", client, "--context", "kind-"+cluster, - "--restart-operator", "gameplane-system/gameplane-operator", "--kind-node", node.Name) - finishStarts := observeFleetStarts(ctx, ns, []string{mcName, secondName, twName}, 1) + lead := mcName + args := []string{"wake_burst.py", "--plan", plan, "--client", client, "--context", "kind-" + cluster, + "--restart-operator", "gameplane-system/gameplane-operator", "--kind-node", node.Name} + blocked := "" + if round == 2 { + lead, blocked = secondName, secondName + // Only this sleeping game needs the missing worker label. The + // operator, its waker, and the other two games remain placeable. + if _, exists := node.Labels[fleetWorkerLabel]; exists { + t.Fatal("fixture worker label already in use") + } + k("-n", ns, "patch", "gameserver", blocked, "--type=merge", "-p", fmt.Sprintf(`{"spec":{"nodeSelector":{%q:"available"}}}`, fleetWorkerLabel)) + t.Cleanup(func() { + cleanup, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + if _, err := envInstance.Kubectl(cleanup, "label", "node", node.Name, fleetWorkerLabel+"-"); err != nil { + t.Errorf("restore fixture worker label: %v", err) + } + }) + args = append(args, "--expect-withdrawal") + } else { + args = append(args, "--expect-lead-exit-code", "42") + } + args = append(args, "--lead-target", ns+"/"+lead) + cmd := exec.CommandContext(ctx, "python3", args...) + finishStarts := observeFleetStarts(ctx, ns, []string{mcName, secondName, twName}, mcName, blocked, node.Name, 1) out, runErr := cmd.CombinedOutput() starts, err := finishStarts() if writeErr := os.WriteFile(filepath.Join(reportDir, fmt.Sprintf("round-%d-admission.json", round)), starts, 0o600); writeErr != nil { @@ -166,6 +209,7 @@ func TestColdWakeFleet_ConcurrentJoins(t *testing.T) { if runErr != nil { t.Fatalf("cold join burst: %v\n%s", runErr, out) } + waitForFleetWorldQuery(t, ns, mcName, worldRevision) if round == 1 { parkFleetGame(ctx, t, ns, secondName) mc.Expose, tw.Expose = "Hostport", "NodePort" @@ -195,19 +239,85 @@ func TestColdWakeFleet_ConcurrentJoins(t *testing.T) { } } -// Each list is a single Kubernetes snapshot across all target StatefulSets. -// Record active startups from desired replicas and readiness independently of -// the operator's reservation ledger, including during the operator restart. -func observeFleetStarts(ctx context.Context, ns string, targets []string, limit int) func() ([]byte, error) { +const fleetWorkerLabel = "e2e.gameplane.local/cold-wake-worker" + +var vanillaPlayerList = regexp.MustCompile(`There are [0-9]+ of a max of [0-9]+ players online`) + +// Verify what the deployed agent actually queried, including after the server +// generation changes from NodePort to Hostport between rounds. +func waitForFleetWorldQuery(t *testing.T, ns, name, expectedRevision string) string { + t.Helper() + var revision string + envInstance.Eventually(t, time.Minute, func() (bool, string) { + gs, err := envInstance.Dyn.Resource(gameServerGVR).Namespace(ns).Get(t.Context(), name, metav1.GetOptions{}) + if err != nil { + return false, err.Error() + } + revision = gs.GetAnnotations()["gameplane.local/effective-template-revision"] + if revision == "" || (expectedRevision != "" && revision != expectedRevision) { + return false, fmt.Sprintf("effective world template revision %q, expected %q", revision, expectedRevision) + } + pod, err := envInstance.K8s.CoreV1().Pods(ns).Get(t.Context(), name+"-0", metav1.GetOptions{}) + if err != nil { + return false, err.Error() + } + for _, c := range pod.Spec.Containers { + if c.Name == "game" && c.ReadinessProbe != nil { + return false, "slow-world fixture unexpectedly has a kubelet game readiness probe" + } + } + uid, _, _ := unstructured.NestedString(gs.Object, "status", "agent", "playerQuery", "podUID") + raw, _, _ := unstructured.NestedString(gs.Object, "status", "agent", "playerQuery", "observedAt") + observed, err := time.Parse(time.RFC3339Nano, raw) + for _, c := range pod.Status.ContainerStatuses { + if c.Name == "game" && c.State.Running != nil && err == nil && + uid == string(pod.UID) && observed.After(c.State.Running.StartedAt.Time) { + return true, "" + } + } + return false, "no native player query from the current Minecraft process" + }) + return revision +} + +func checkFleetWorld(ctx context.Context, ns, slow string, serviceBacked bool) (bool, error) { + // Read the selector first: a game that answers RCON during this sample + // may legitimately take over the Service on the same reconcile. + var selector string + if serviceBacked { + svc, err := envInstance.K8s.CoreV1().Services(ns).Get(ctx, slow, metav1.GetOptions{}) + if err != nil { + return false, err + } + selector = svc.Spec.Selector["app.kubernetes.io/name"] + } + probeCtx, cancel := context.WithTimeout(ctx, 3*time.Second) + defer cancel() + reply, err := envInstance.Kubectl(probeCtx, "-n", ns, "exec", slow+"-0", "-c", "game", "--", "rcon-cli", "list") + ready := err == nil && vanillaPlayerList.MatchString(reply) + if !ready && serviceBacked && selector != "gameplane-waker" { + return false, fmt.Errorf("public Service routed away from the waker while %s was loading", slow) + } + return ready, nil +} + +// Use one snapshot of all desired replica counts and the games' own startup +// signals. Neither the cap nor the recovery assertion reads the reservation ledger. +func observeFleetStarts(ctx context.Context, ns string, targets []string, slow, blocked, node string, limit int) func() ([]byte, error) { stop := make(chan struct{}) done := make(chan struct{}) type sample struct { - ElapsedMS int64 `json:"elapsedMs"` - Starting []string `json:"starting"` + ElapsedMS int64 `json:"elapsedMs"` + Starting []string `json:"starting"` + ReadyWhileLoading bool `json:"podReadyBeforeGame"` + WorkerRecovered bool `json:"workerRecovered"` + BlockedReason string `json:"blockedReason,omitempty"` } var samples []sample seen := make(map[string]bool) var sampleErr error + var loaded, sawReadyLoading, sawCompetingWake, sawRestartedLoading, workerRecovered bool + var blockedReason string go func() { defer close(done) began := time.Now() @@ -220,15 +330,86 @@ func observeFleetStarts(ctx context.Context, ns string, targets []string, limit return } starting := []string{} + readyLoading, blockedAtZero := false, false for _, set := range sets.Items { - if slices.Contains(targets, set.Name) && set.Spec.Replicas != nil && *set.Spec.Replicas > 0 && set.Status.ReadyReplicas == 0 { + if !slices.Contains(targets, set.Name) || set.Spec.Replicas == nil { + continue + } + if *set.Spec.Replicas == 0 { + blockedAtZero = blockedAtZero || set.Name == blocked + continue + } + if set.Name == slow && set.Status.ReadyReplicas > 0 && !loaded { + loaded, err = checkFleetWorld(ctx, ns, slow, blocked == "") + if err != nil { + sampleErr = err + return + } + readyLoading = !loaded + sawReadyLoading = sawReadyLoading || readyLoading + } + if set.Status.ReadyReplicas == 0 || (set.Name == slow && !loaded) { starting = append(starting, set.Name) seen[set.Name] = true } } + if readyLoading && blocked == "" { + if !sawRestartedLoading { + pod, err := envInstance.K8s.CoreV1().Pods(ns).Get(ctx, slow+"-0", metav1.GetOptions{}) + if err != nil { + sampleErr = err + return + } + for _, c := range pod.Status.ContainerStatuses { + if c.Name == "game" && c.RestartCount == 1 && c.State.Running != nil { + sawRestartedLoading = true + } + } + } + for _, name := range targets { + if name == slow || sawCompetingWake || !sawRestartedLoading { + continue + } + game, err := envInstance.Dyn.Resource(gameServerGVR).Namespace(ns).Get(ctx, name, metav1.GetOptions{}) + if err != nil { + sampleErr = err + return + } + ann := game.GetAnnotations() + sawCompetingWake = ann["gameplane.local/idle-wake-requested"] != ann["gameplane.local/idle-wake-completed"] + } + } + if blocked != "" && !workerRecovered { + game, err := envInstance.Dyn.Resource(gameServerGVR).Namespace(ns).Get(ctx, blocked, metav1.GetOptions{}) + if err != nil { + sampleErr = err + return + } + reason, _, _ := unstructured.NestedString(game.Object, "status", "idle", "reason") + if strings.Contains(strings.ToLower(reason), "unschedulable") { + blockedReason = reason + } + if blockedAtZero && len(starting) > 0 && blockedReason != "" { + _, err := envInstance.K8s.CoreV1().Pods(ns).Get(ctx, blocked+"-0", metav1.GetOptions{}) + if err != nil && !apierrors.IsNotFound(err) { + sampleErr = err + return + } + if apierrors.IsNotFound(err) { + if _, err := envInstance.Kubectl(ctx, "label", "node", node, fleetWorkerLabel+"=available"); err != nil { + sampleErr = fmt.Errorf("restore eligible worker during competing startup: %w", err) + return + } + workerRecovered = true + } + } + } slices.Sort(starting) - if len(samples) == 0 || !slices.Equal(samples[len(samples)-1].Starting, starting) { - samples = append(samples, sample{time.Since(began).Milliseconds(), starting}) + next := sample{time.Since(began).Milliseconds(), starting, readyLoading, workerRecovered, blockedReason} + if len(samples) == 0 || !slices.Equal(samples[len(samples)-1].Starting, starting) || + samples[len(samples)-1].ReadyWhileLoading != readyLoading || samples[len(samples)-1].WorkerRecovered != workerRecovered || + samples[len(samples)-1].BlockedReason != blockedReason { + samples = append(samples, next) } if len(starting) > limit { sampleErr = fmt.Errorf("observed %d simultaneous starts above limit %d: %v", len(starting), limit, starting) @@ -250,6 +431,15 @@ func observeFleetStarts(ctx context.Context, ns string, targets []string, limit if sampleErr == nil && len(seen) != len(targets) { sampleErr = fmt.Errorf("observed %d of %d distinct startups", len(seen), len(targets)) } + if sampleErr == nil && (!sawReadyLoading || !loaded) { + sampleErr = fmt.Errorf("missed %s startup: Pod Ready during load=%t, in-game player list answered=%t", slow, sawReadyLoading, loaded) + } + if sampleErr == nil && blocked == "" && !sawCompetingWake { + sampleErr = fmt.Errorf("no competing wake token during %s restarted world load", slow) + } + if sampleErr == nil && blocked != "" && !workerRecovered { + sampleErr = fmt.Errorf("%s did not drain and allow another game to start before worker recovery (reason %q)", blocked, blockedReason) + } data, err := json.MarshalIndent(samples, "", " ") if err != nil { return nil, err diff --git a/test/e2e/gamebot_helpers_e2e_test.go b/test/e2e/gamebot_helpers_e2e_test.go index 349dcf9fe..5edff28cb 100644 --- a/test/e2e/gamebot_helpers_e2e_test.go +++ b/test/e2e/gamebot_helpers_e2e_test.go @@ -159,6 +159,8 @@ type gameBotSpec struct { ExpectDepth joindepth.JoinDepth ProbeArgs []string Probes map[string]any // spec.probes; nil means the operator sets no probe + Command []any // optional replacement game image entrypoint + Players map[string]any // optional declared player queries RCON map[string]any // spec.rcon ConsoleMode string // spec.consoleMode Actions []any // spec.capabilities.actions; nil means no actions @@ -331,6 +333,9 @@ func createGameBotServer(t *testing.T, env *Env, s gameBotSpec) (gsName, namespa if s.Probes != nil { spec["probes"] = s.Probes } + if s.Command != nil { + spec["command"] = s.Command + } if s.RCON != nil { spec["rcon"] = s.RCON } @@ -338,6 +343,9 @@ func createGameBotServer(t *testing.T, env *Env, s gameBotSpec) (gsName, namespa spec["consoleMode"] = s.ConsoleMode } capabilities := map[string]any{} + if s.Players != nil { + capabilities["players"] = s.Players + } if s.Actions != nil { capabilities["actions"] = s.Actions } diff --git a/test/e2e/lint-gate-verify.sh b/test/e2e/lint-gate-verify.sh index ac5445bec..9009ea38f 100755 --- a/test/e2e/lint-gate-verify.sh +++ b/test/e2e/lint-gate-verify.sh @@ -378,14 +378,14 @@ check_r001_matrix_completeness() { # Check for missing modules. while IFS= read -r mod; do - if ! printf '%s\n' "$matrix_mods" | grep -qx "$mod"; then + if ! grep -Fxq -- "$mod" <<<"$matrix_mods"; then fail "R-001: Module '$mod' listed in go.work but missing from lint job matrix" fi done <<<"$go_mods" # Check for extra modules. while IFS= read -r mod; do - if ! printf '%s\n' "$go_mods" | grep -qx "$mod"; then + if ! grep -Fxq -- "$mod" <<<"$go_mods"; then fail "R-001: Module '$mod' in lint job matrix but not in go.work" fi done <<<"$matrix_mods" diff --git a/test/e2e/test_wake_burst.py b/test/e2e/test_wake_burst.py index 65c7ad01a..b4e24a1b2 100644 --- a/test/e2e/test_wake_burst.py +++ b/test/e2e/test_wake_burst.py @@ -1,4 +1,5 @@ import json +from copy import deepcopy import unittest from unittest.mock import Mock @@ -24,6 +25,8 @@ def test_partial_and_timeout_are_retained_in_denominator(self): got = summary(results, 1) self.assertEqual((got["joined"], got["clients"], got["withinObjective"], got["retries"]), (2, 3, 1, 3)) self.assertEqual(got["p99JoinedMs"], 2000) + self.assertEqual(got["firstSuccessfulJoinMs"], 100) + self.assertIsNone(summary(results[2:], 1)["firstSuccessfulJoinMs"]) self.assertIsNone(summary(results[2:], 1)["p95JoinedMs"]) def test_unsupported_udp_requires_real_adapter(self): @@ -45,22 +48,63 @@ def test_recovery_rejects_duplicate_boot_restart_owner_and_missed_wake(self): pod = {"metadata": {"uid": "p1", "ownerReferences": [{"controller": True, "uid": "sts"}]}, "spec": {"nodeName": "worker"}, "status": {"containerStatuses": [{"name": "game", "restartCount": 0}]}} def event(): - return json.dumps({"type": "ADDED", "object": pod}) - cluster.text = Mock(return_value=event()) - self.assertTrue(cluster.recovery(target("one"), base)["passed"]) + return {"type": "ADDED", "object": deepcopy(pod)} + self.assertTrue(cluster.recovery(target("one"), base, [event()])["passed"]) for field, value in [(SLEEP, "timestamp"), (ACK, "old"), (OWNER, "backup")]: annotations = state["metadata"]["annotations"] original = annotations.copy() annotations[field] = value - self.assertFalse(cluster.recovery(target("one"), base)["passed"]) + self.assertFalse(cluster.recovery(target("one"), base, [event()])["passed"]) state["metadata"]["annotations"] = original first = event() pod["metadata"]["uid"] = "p2" - cluster.text.return_value = first + "\n" + event() - self.assertFalse(cluster.recovery(target("one"), base)["passed"]) + self.assertFalse(cluster.recovery(target("one"), base, [first, event()])["passed"]) pod["status"]["containerStatuses"][0]["restartCount"] = 1 - cluster.text.return_value = event() - self.assertFalse(cluster.recovery(target("one"), base)["passed"]) - cluster.text.return_value = json.dumps({"type": "ERROR", "object": {"code": 410}}) + pod["status"]["containerStatuses"][0]["lastState"] = {"terminated": {"exitCode": 42}} + self.assertFalse(cluster.recovery(target("one"), base, [event()])["passed"]) + self.assertTrue(cluster.recovery(target("one"), base, [event()], expected_exit=42)["passed"]) + self.assertFalse(cluster.recovery(target("one"), base, [event()], expected_exit=1)["passed"]) + pod["status"]["containerStatuses"][0]["restartCount"] = 2 + self.assertFalse(cluster.recovery(target("one"), base, [event()], expected_exit=42)["passed"]) with self.assertRaises(ValueError): - cluster.recovery(target("one"), base) + cluster.recovery(target("one"), base, [{"type": "ERROR", "object": {"code": 410}}]) + + def test_watch_preserves_and_advances_the_server_list_version(self): + cluster = Cluster("test") + cluster.text = Mock(side_effect=[ + json.dumps({"metadata": {"resourceVersion": "100"}, "items": []}), "", + json.dumps({"metadata": {"resourceVersion": "120"}, "items": []}), + json.dumps({"type": "DELETED", "object": {"metadata": {"resourceVersion": "118"}}}), + ]) + finished = Mock() + finished.is_set.side_effect = [False, True] + events = cluster.watch_pods(target("one"), {"podRV": "90"}, finished) + self.assertEqual(events[0]["type"], "DELETED") + self.assertIn("resourceVersion=90", cluster.text.call_args_list[1].args[-1]) + self.assertIn("resourceVersion=100", cluster.text.call_args_list[3].args[-1]) + cluster.text = Mock(return_value=json.dumps({"metadata": {"resourceVersion": ""}, "items": []})) + with self.assertRaises(ValueError): + cluster.pod_list(target("one")) + + def test_required_withdrawal_and_pod_readiness_are_separate_from_client_evidence(self): + cluster = Cluster("test") + cluster.get = Mock(return_value={"metadata": {"uid": "gs", "annotations": {REQUEST: "new", ACK: "new"}}, "spec": {}}) + base = {"gameUID": "gs", "statefulSetUID": "sts", "previousWake": None, "podRV": "1"} + def event(kind, uid, node, conditions): + return {"type": kind, "object": { + "metadata": {"uid": uid, "ownerReferences": [{"uid": "sts", "controller": True}]}, + "spec": {"nodeName": node}, "status": {"conditions": conditions}}} + waiting = [{"type": "PodScheduled", "status": "False", "reason": "Unschedulable"}] + ready_at = "2026-01-01T12:00:05Z" + ready = event("MODIFIED", "replacement", "worker", [{"type": "Ready", "status": "True", "lastTransitionTime": ready_at}]) + old = event("DELETED", "blocked", "", waiting) + result = cluster.recovery(target("one"), base, [old, ready], expect_withdrawal=True) + self.assertTrue(result["passed"]) + self.assertEqual((result["firstPodReadyAt"], result["withdrawnPodUIDs"]), (ready_at, ["blocked"])) + self.assertFalse(cluster.recovery(target("one"), base, [old, ready])["passed"]) + bound = event("ADDED", "blocked", "worker", []) + self.assertFalse(cluster.recovery(target("one"), base, [bound, old, ready], expect_withdrawal=True)["passed"]) + gated = event("DELETED", "gated", "", []) + gated["object"]["spec"]["schedulingGates"] = [{"name": "gameplane.local/wake-start-withdrawing"}] + self.assertTrue(cluster.recovery(target("one"), base, [old, gated, ready], expect_withdrawal=True)["passed"]) + self.assertFalse(cluster.recovery(target("one"), base, [gated, ready], expect_withdrawal=True)["passed"]) diff --git a/test/e2e/wake_burst.py b/test/e2e/wake_burst.py index 66f2e2c7f..86dd3c762 100644 --- a/test/e2e/wake_burst.py +++ b/test/e2e/wake_burst.py @@ -3,6 +3,7 @@ import argparse import concurrent.futures +import contextlib import datetime import json import math @@ -68,7 +69,8 @@ def verdict(exit_code, output): def measure_client(t, user, client, start, release): - release.wait() + if not release.wait(timeout=t["deadlineSeconds"]): + return {"joined": False, "elapsedMs": t["deadlineSeconds"] * 1000, "attempts": []} began = start[0] deadline = began + t["deadlineSeconds"] attempts = [] @@ -103,6 +105,7 @@ def percentile(p): return {"clients": len(results), "joined": len(elapsed), "withinObjective": sum(ms <= objective * 1000 for ms in elapsed), "retries": sum(max(0, len(r["attempts"]) - 1) for r in results), + "firstSuccessfulJoinMs": elapsed[0] if elapsed else None, "p95JoinedMs": percentile(.95), "p99JoinedMs": percentile(.99)} @@ -123,6 +126,34 @@ def text(self, *args, timeout=20): def get(self, t, kind, name): return json.loads(self.text("get", kind, name, "-n", t["namespace"], "-o", "json")) + def pods_url(self, target, **query): + query["fieldSelector"] = "metadata.name=" + target["name"] + "-0" + return f"/api/v1/namespaces/{target['namespace']}/pods?{urlencode(query)}" + + def pod_list(self, target): + # kubectl get -o json can synthesize a List with an empty resourceVersion. + pods = json.loads(self.text("get", "--raw", self.pods_url(target))) + if not pods["metadata"].get("resourceVersion"): + raise ValueError("Pod list has no resourceVersion for the wake watch") + return pods + + def watch_pods(self, target, base, finished): + cursor, events = base["podRV"], [] + while True: + final = finished.is_set() + # Even when no game Pod exists for a long time, advance the watch + # past this list after replay, before the old cursor expires. + boundary = self.pod_list(target)["metadata"]["resourceVersion"] + raw = self.text("get", "--raw", self.pods_url(target, watch="true", + timeoutSeconds=1 if final else 8, resourceVersion=cursor)) + batch = [json.loads(line) for line in raw.splitlines()] + if any(e["type"] not in ("ADDED", "MODIFIED", "DELETED", "BOOKMARK") for e in batch): + raise ValueError("incomplete Kubernetes Pod watch") + events.extend(batch) + if final: + return events + cursor = batch[-1]["object"]["metadata"]["resourceVersion"] if batch else boundary + def baseline(self, t): gs = self.get(t, "gameserver", t["name"]) annotations = gs["metadata"].get("annotations", {}) @@ -145,8 +176,7 @@ def baseline(self, t): if not any(ref.get("controller") and ref["uid"] == gs["metadata"]["uid"] for ref in child["metadata"].get("ownerReferences", [])): raise ValueError(f"{t['name']} workload belongs to a different GameServer") - pods = json.loads(self.text("get", "pods", "-n", t["namespace"], "--field-selector", - "metadata.name=" + t["name"] + "-0", "-o", "json")) + pods = self.pod_list(t) if (sts["spec"].get("replicas") != 0 or pods["items"] or waker.get("status", {}).get("readyReplicas", 0) != 1): raise ValueError(f"{t['name']} requires zero game Pods and one ready sentinel") @@ -156,22 +186,19 @@ def baseline(self, t): def observation(self, target, base): gs = self.get(target, "gameserver", target["name"]) - token = gs["metadata"].get("annotations", {}).get(REQUEST) + annotations = gs["metadata"].get("annotations", {}) + token = annotations.get(REQUEST) return {"wakeRequested": bool(token and token != base["previousWake"]), + "wakeAcknowledged": bool(token and token != base["previousWake"] and token == annotations.get(ACK)), "phase": gs.get("status", {}).get("phase"), - "asleep": bool(gs["metadata"].get("annotations", {}).get(SLEEP))} + "idleReason": (gs.get("status", {}).get("idle") or {}).get("reason"), + "asleep": bool(annotations.get(SLEEP))} - def recovery(self, target, base): + def recovery(self, target, base, events, expect_withdrawal=False, expected_exit=None): gs = self.get(target, "gameserver", target["name"]) ann = gs["metadata"].get("annotations", {}) - # Replay the API watch from the pre-burst list. Polling the final Pod - # alone would hide a short-lived duplicate. Compaction invalidates proof. - query = urlencode({"watch": "true", "timeoutSeconds": 1, "resourceVersion": base["podRV"], - "fieldSelector": "metadata.name=" + target["name"] + "-0"}) - raw = self.text("get", "--raw", f"/api/v1/namespaces/{target['namespace']}/pods?{query}") pods = {} - for line in raw.splitlines(): - event = json.loads(line) + for event in events: typ, pod = event["type"], event["object"] if typ == "BOOKMARK": continue @@ -181,20 +208,39 @@ def recovery(self, target, base): for ref in pod["metadata"].get("ownerReferences", [])): raise ValueError("game Pod owner changed") uid = pod["metadata"]["uid"] - restarts = max((c["restartCount"] for c in pod.get("status", {}).get("containerStatuses", []) - if c["name"] == "game"), default=0) - pods[uid] = {"node": pod["spec"].get("nodeName"), "restarts": max(restarts, pods.get(uid, {}).get("restarts", 0)), - "deleted": typ == "DELETED" or bool(pod["metadata"].get("deletionTimestamp"))} + container = next((c for c in pod.get("status", {}).get("containerStatuses", []) if c["name"] == "game"), {}) + seen = pods.setdefault(uid, {"node": None, "restarts": 0, "previousExitCode": None, + "unschedulable": False, "parkingGate": False, "firstReadyAt": None}) + seen["parkingGate"] |= any(gate["name"] == "gameplane.local/wake-start-withdrawing" + for gate in pod["spec"].get("schedulingGates", [])) + seen["node"] = seen["node"] or pod["spec"].get("nodeName") + seen["restarts"] = max(container.get("restartCount", 0), seen["restarts"]) + if exited := container.get("lastState", {}).get("terminated"): + seen["previousExitCode"] = exited["exitCode"] + seen["deleted"] = typ == "DELETED" + seen["terminating"] = bool(pod["metadata"].get("deletionTimestamp")) + for cond in pod.get("status", {}).get("conditions", []): + if cond["type"] == "PodScheduled" and cond["status"] == "False" and cond.get("reason") == "Unschedulable": + seen["unschedulable"] = True + if cond["type"] == "Ready" and cond["status"] == "True" and not seen["firstReadyAt"]: + seen["firstReadyAt"] = cond["lastTransitionTime"] + withdrawn = {uid for uid, p in pods.items() if p["deleted"] and (p["unschedulable"] or p["parkingGate"]) and + not p["node"] and not p["firstReadyAt"] and not p["restarts"]} + retained = [p for uid, p in pods.items() if uid not in withdrawn] good = (gs["metadata"]["uid"] == base["gameUID"] and not gs["spec"].get("suspend") and not ann.get(OWNER) and not ann.get(SLEEP) and ann.get(REQUEST) and ann[REQUEST] != base["previousWake"] and ann[REQUEST] == ann.get(ACK) - and len(pods) == 1 and all(not p["restarts"] and not p["deleted"] for p in pods.values())) + and bool(withdrawn) == expect_withdrawal + and sum(pods[uid]["unschedulable"] for uid in withdrawn) == int(expect_withdrawal) and len(retained) == 1 + and all(p["restarts"] == int(expected_exit is not None) and p["previousExitCode"] == expected_exit + and not p["deleted"] and not p["terminating"] for p in retained)) if node := base.get("hostportNode"): good = (good and ann.get(NODE) == node["name"] and ann.get(NODE_UID) == node["uid"] and self.get(target, "node", node["name"])["metadata"]["uid"] == node["uid"] - and all(p["node"] == node["name"] for p in pods.values())) + and all(p["node"] == node["name"] for p in retained)) return {"acknowledged": ann.get(ACK), "requested": ann.get(REQUEST), "owner": bool(ann.get(OWNER)), - "phase": gs.get("status", {}).get("phase"), "pods": pods, "passed": bool(good)} + "phase": gs.get("status", {}).get("phase"), "pods": pods, "withdrawnPodUIDs": sorted(withdrawn), + "firstPodReadyAt": retained[0]["firstReadyAt"] if len(retained) == 1 else None, "passed": bool(good)} def sample(self): at = datetime.datetime.now(datetime.timezone.utc).isoformat() @@ -226,6 +272,13 @@ def run(args, targets): raise ValueError(f"missing executable: {exe}") cluster = Cluster(args.context, args.kind_node) bases = [cluster.baseline(t) for t in targets] + names = {f"{t['namespace']}/{t['name']}" for t in targets} + if args.lead_target and args.lead_target not in names: + raise ValueError("lead target must be in the plan") + if (args.expect_withdrawal or args.expect_lead_exit_code is not None) and not args.lead_target: + raise ValueError("expected withdrawal or process restart requires a lead target") + if args.expect_lead_exit_code is not None and not 1 <= args.expect_lead_exit_code <= 255: + raise ValueError("expected game exit code must be between 1 and 255") restart = args.restart_operator.split("/") if args.restart_operator else None if restart and (len(restart) != 2 or not all(DNS_LABEL.fullmatch(s) for s in restart)): raise ValueError("operator must be namespace/deployment") @@ -233,13 +286,19 @@ def run(args, targets): "operatorRestart": "pending" if restart else "not requested", "nodeMetrics": [cluster.sample()], "targets": [], "errors": []} history = [[] for t in targets] - release, start = threading.Event(), [] + release, followers, start = threading.Event(), threading.Event(), [] clients = sum(t["clients"] for t in targets) prefix = "gp" + secrets.token_hex(4) - with concurrent.futures.ThreadPoolExecutor(max_workers=clients) as pool: - groups = [[pool.submit(measure_client, t, f"{prefix}{i:02x}{j:02x}", args.client, start, release) + finished = threading.Event() + with concurrent.futures.ThreadPoolExecutor(max_workers=len(targets)) as watchers, contextlib.ExitStack() as cleanup, \ + concurrent.futures.ThreadPoolExecutor(max_workers=clients) as pool: + cleanup.callback(finished.set) + watches = [watchers.submit(cluster.watch_pods, t, b, finished) for t, b in zip(targets, bases)] + groups = [[pool.submit(measure_client, t, f"{prefix}{i:02x}{j:02x}", args.client, start, + release if not args.lead_target or f"{t['namespace']}/{t['name']}" == args.lead_target else followers) for j in range(t["clients"])] for i, t in enumerate(targets)] futures = [f for group in groups for f in group] + report["releasedAt"] = datetime.datetime.now(datetime.timezone.utc).isoformat() start.append(time.monotonic()) release.set() while not all(f.done() for f in futures): @@ -250,9 +309,14 @@ def run(args, targets): if not timeline or timeline[-1]["state"] != state: timeline.append({"observedMs": round((time.monotonic() - start[0]) * 1000), "state": state}) waking |= state["wakeRequested"] + if not followers.is_set() and args.lead_target == f"{t['namespace']}/{t['name']}" and state["wakeAcknowledged"]: + if cluster.get(t, "statefulset", t["name"])["spec"].get("replicas") == 1: + followers.set() + report["followersReleasedMs"] = round((time.monotonic() - start[0]) * 1000) except (ValueError, subprocess.SubprocessError) as err: report["errors"].append(f"{t['name']} observation: {err}") - if restart and report["operatorRestart"] == "pending" and waking and not all(f.done() for f in futures): + if (restart and report["operatorRestart"] == "pending" and waking and + (not args.lead_target or followers.is_set()) and not all(f.done() for f in futures)): try: cluster.text("rollout", "restart", "deployment/" + restart[1], "-n", restart[0]) report["operatorRestart"] = {"deployment": args.restart_operator, @@ -268,18 +332,28 @@ def run(args, targets): "-n", restart[0], "--timeout=120s", timeout=130) except subprocess.SubprocessError as err: report["errors"].append(f"operator recovery: {err}") + finished.set() cohorts = {} - for target, base, group, timeline in zip(targets, bases, groups, history): + for target, base, group, timeline, watch in zip(targets, bases, groups, history, watches): results = [f.result() for f in group] key = (target["game"], target["path"], target["protocol"], target["objectiveSeconds"]) cohorts.setdefault(key, []).extend(results) try: - recovery = cluster.recovery(target, base) + lead = args.lead_target == f"{target['namespace']}/{target['name']}" + recovery = cluster.recovery(target, base, watch.result(), expect_withdrawal=lead and args.expect_withdrawal, + expected_exit=args.expect_lead_exit_code if lead else None) + ready_at = recovery["firstPodReadyAt"] + if ready_at: + ready = datetime.datetime.fromisoformat(ready_at.replace("Z", "+00:00")) + released = datetime.datetime.fromisoformat(report["releasedAt"]) + recovery["firstPodReadyMs"] = round((ready - released).total_seconds() * 1000) except (subprocess.SubprocessError, ValueError, KeyError) as err: recovery = {"passed": False, "error": str(err)} report["targets"].append({"target": {k: v for k, v in target.items() if k != "adapter"}, "baseline": base, "summary": summary(results, target["objectiveSeconds"]), "clients": results, "observations": timeline, "recovery": recovery}) + if not recovery.get("firstPodReadyAt"): + report["errors"].append(f"{target['name']} has no recorded Pod Ready transition") report["cohorts"] = [{"game": g, "path": path, "protocol": proto, "objectiveSeconds": limit, **summary(results, limit)} for (g, path, proto, limit), results in cohorts.items()] report["joinAndRecoveryPassed"] = (not report["errors"] and all(t["summary"]["withinObjective"] == t["summary"]["clients"] and @@ -293,6 +367,12 @@ def main(): parser.add_argument("--context", required=True) parser.add_argument("--plan", required=True) parser.add_argument("--client", default="join-once") + parser.add_argument("--lead-target", metavar="NAMESPACE/GAME", + help="release the other clients after this game's first acknowledged scale-up") + parser.add_argument("--expect-withdrawal", action="store_true", + help="require a deleted unscheduled attempt for the lead target") + parser.add_argument("--expect-lead-exit-code", type=int, metavar="CODE", + help="require precisely one intentional game-container restart with this exit code on the lead target") parser.add_argument("--kind-node", help="collect CPU, memory and I/O counters and PSI from this disposable kind node") parser.add_argument("--restart-operator", metavar="NAMESPACE/DEPLOYMENT", help="restart this operator after a wake arrives while clients are still joining") diff --git a/web/src/types.ts b/web/src/types.ts index 9a22b0636..6e47f280e 100644 --- a/web/src/types.ts +++ b/web/src/types.ts @@ -688,6 +688,7 @@ export interface GameServer { endpoints?: GameServerEndpoint[]; agent?: { lastHeartbeat?: string; + playerQuery?: { podUID: string; observedAt: string }; // null/absent means "unknown" (agent couldn't query the game, or // the heartbeat is stale and the API blanked it). playersOnline?: number | null;