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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -1746,6 +1746,9 @@ jobs:
- name: unit test (probe protocols)
working-directory: test/e2e
run: go test ./...
- name: verify cold-start join evidence and lifecycle accounting
working-directory: test/e2e
run: python3 -m unittest test_wake_burst

# The api's PostgreSQL backend (--db-driver=postgres) is compiled only
# with -tags postgres, so the `go` matrix and `lint` never build it. This
Expand Down Expand Up @@ -2408,6 +2411,8 @@ jobs:
- name: bring up cluster + helm install
run: ./deploy/kind/e2e.sh up "$CLUSTER" e2e
- name: run go e2e (game bot)
env:
GAMEPLANE_E2E_WAKE_REPORTS: ${{ runner.temp }}/wake-burst-reports
# Blocking. The bot runs as a Job inside the cluster and dials the game
# Service directly, removing the `kubectl port-forward` hop this job's
# flakiness was once blamed on. (That blame turned out to be wrong: the
Expand All @@ -2416,11 +2421,23 @@ jobs:
# network path a real client uses.)
run: |
RUN_REGEX="^${BOT_TEST}$"
if [[ "$BOT_TEST" == TestColdWakeFleet_ConcurrentJoins ]]; then
docker build -t gameplane-test/wake-teeworlds:ci test/e2e/testdata/wake-burst
kind load docker-image --name "$CLUSTER" gameplane-test/wake-teeworlds:ci
fi
cd test/e2e && \
GAMEPLANE_E2E_REUSE_CLUSTER=1 \
GAMEPLANE_E2E_CLUSTER="$CLUSTER" \
GAMEPLANE_E2E_GAME_BOT=1 \
go test -tags=e2e -timeout 30m -v -run "$RUN_REGEX" ./...
- name: upload cold-join and node-pressure measurements
if: always() && matrix.test == 'TestColdWakeFleet_ConcurrentJoins'
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: wake-joins-and-pressure-${{ github.run_attempt }}
path: ${{ runner.temp }}/wake-burst-reports/*.json
if-no-files-found: warn
retention-days: 7
- name: dump cluster state on failure (e2e-game-bot)
if: failure()
uses: ./.github/actions/dump-cluster-state
Expand Down
5 changes: 5 additions & 0 deletions changelog/unreleased/904-wake-admission.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Concurrent game server wakes

The operator durably reserves fleet wake slots, observes explicit stops and recovers
in-flight starts after a restart. TCP and UDP clients can retry during a cold start without
launching a second copy of the game. [PR #904](https://github.com/GameplanePanel/Gameplane/pull/904)
3 changes: 3 additions & 0 deletions charts/gameplane/templates/operator.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -386,6 +386,9 @@ spec:
- --agent-client-key=/etc/gameplane/agent-client/tls.key
- --agent-ca-secret-name={{ .Values.api.agentMTLS.caSecretRef.name }}
- --game-namespaces={{ join "," $gameNamespaces }}
{{- with .Values.operator.wakeStartLimit }}
- {{ printf "--wake-start-limit=%v" . | quote }}
{{- end }}
- --control-plane-namespace={{ include "gameplane.operatorClusterCredentialsNamespace" . }}
{{- if not $rbac.remoteClusters }}
- --remote-clusters=false
Expand Down
3 changes: 3 additions & 0 deletions charts/gameplane/values.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,9 @@ operator:
# Required with multiple replicas and recommended during rolling upgrades.
# 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.
wakeStartLimit: 0
resources:
requests: { cpu: 100m, memory: 64Mi }
limits: { cpu: 500m, memory: 256Mi }
Expand Down
3 changes: 3 additions & 0 deletions docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,9 @@ manage Gameplane with `kubectl apply` — the operator is authoritative.

### Sleep an idle server

For real-game retry budgets, concurrent cold joins and operator-restart
evidence, see [qualifying simultaneous cold joins](wake-qualification.md).

Opt-in per server via `spec.idle`. Every reconcile the operator decides, from
the object alone, whether idle time is accruing:

Expand Down
145 changes: 145 additions & 0 deletions docs/wake-qualification.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
# Qualifying simultaneous cold joins

Run the burst on dedicated staging sleepers with the same images, worlds,
storage, resource requests, worker placement and exposure used by the intended
tier. Obtain approval for the operator restart on that cluster. The driver sends
real player traffic and leaves each awakened server running. It observes
GameServers and Pods. Its only administration command is the operator rollout
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.
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
tier objectives need separate measurements.

These are example qualification objectives for a retry-tolerant tier. Record
the intended per-game objective in the plan before each run. The numbers are
trial inputs. No fleet capacity or game startup percentile has been established.

| Game | Completion evidence | Example objective | Observation deadline |
| --- | --- | --- | --- |
| Offline-mode Minecraft Java | Server sends Login Success (0x02) to the named player | Every client joined within 90 s | 180 s |
| Unpassworded Terraria | Nonempty WorldData (7) after player slot assignment | Every client joined within 60 s | 120 s |
| Entitled UDP game or authenticated client | Version-matched real client records a server-originated in-game artifact | Set from the tier's player retry window | Set independently to retain slow failures |

The standard client reuses the [game protocol fixtures](../test/e2e/internal/specs.md).
Its one-attempt interface also works for a restored-world canary:

```sh
cd test/e2e
go build -o join-once ./cmd/join-once
./join-once -game minecraft-java -addr mc.staging.svc:25565 -user gpcanary -deadline 25s
```

Success requires exit zero and exactly one `VERDICT<TAB>PASS<TAB>JOINED<TAB>evidence`
line. Query replies, encryption/password challenges, an accepted socket and
the sentinel's wake acknowledgement all fall short of this criterion. Each
licensed or authenticated client adapter must implement the same flags, launch
one join attempt, identify the server's post-join artifact in its verdict,
and close the client by its deadline. Keep provider tokens out of arguments,
the plan and verdicts. A missing adapter leaves that path unqualified. The
[game coverage table](game-coverage.md) records existing protocol limitations.

## Run a burst

1. Prepare at least two unsuspended, idle-asleep servers with wake-on-connect
armed, no pending wake or lifecycle owner, zero game replicas, and one ready
sentinel each. Use distinct servers and published endpoints. Exclude other
player traffic and scheduled prewarming during the trial. Run from one
client host or Pod that can reach each published address and the Kubernetes
API. Use the game Service endpoint for a Service trial and the advertised
node and port for a Hostport handoff. A port-forward to a game Pod bypasses
the sentinel. Test UDP with a real client that emits enough real game
datagrams to trigger its configured wake threshold.
2. Save a JSON array like the one below. Replace addresses and names with the
actual sleepers. Add rows with `"path": "Hostport"` for the handoff drill.
For UDP add `"protocol": "udp"` and `"adapter": "/opt/game-clients/join-once"`
for an entitled, version-matched client. Exercise multiple sleepers of each
expensive game on the approved worker pool.

```json
[
{"namespace":"staging","name":"mc-a","game":"minecraft-java","addr":"mc-a.staging.svc:25565","path":"Service","protocol":"tcp","clients":4,"objectiveSeconds":90,"deadlineSeconds":180,"attemptSeconds":25,"retrySeconds":3},
{"namespace":"staging","name":"terra-b","game":"terraria","addr":"terra-b.staging.svc:7777","path":"Service","protocol":"tcp","clients":4,"objectiveSeconds":60,"deadlineSeconds":120,"attemptSeconds":25,"retrySeconds":3}
]
```

3. Run from `test/e2e`. Python 3 and `kubectl` are required. The explicit
cluster context needs reads of GameServers, StatefulSets, Deployments,
game Pod lists/watches, Nodes and node resource metrics. The restart drill
additionally needs patch/watch on the named operator Deployment.

```sh
python3 wake_burst.py --context staging --plan sleepers.json --client ./join-once \
--restart-operator gameplane-system/gameplane-operator > burst.json
```

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.

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
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
node pressure in the report. Attach per-node disk throughput, I/O latency
or pressure from the storage monitoring system for the same window.
Metrics-server sampling periods can exceed a short boot. Missing readings
are explicit. `joinAndRecoveryPassed` covers client objectives and the
lifecycle checks; pressure, entitlement, and tier qualification require
the accompanying evidence.

Run separate direct and relay trials with identical clients and worlds. Use
the relay packet-load baseline from #879 when available. Keep explicit
`spec.suspend` and lifecycle-owned backup/restore servers outside the burst.
For a tier whose first connection cannot tolerate the observed cold join,
configure the existing `spec.idle.wakeWindows` ahead of its playing hours
and verify the warm result with the same single-attempt client.

## Bounding simultaneous cold starts

Set `operator.wakeStartLimit` to a fleet-wide ceiling from 1 through 128.
Zero keeps the existing unlimited behavior. Measure the largest supported
game's startup CPU, resident memory and storage throughput, then repeat
with your maximum backup concurrency and one worker unavailable. Divide
each resource's remaining headroom by that game's measured peak demand.
Take the smallest whole number across all three resources and test it in
the burst. If no complete start fits, provision capacity or keep that
tier warm. On heterogeneous pools use the most constrained eligible pool.

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.
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.
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.
8 changes: 8 additions & 0 deletions operator/cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,7 @@ func main() {
moduleConfigMapNamespace string
moduleLocalRoot string
controlPlaneNamespace string
wakeStartLimit int
remoteClusters bool
gameNamespaces string
addressManager string
Expand Down Expand Up @@ -275,6 +276,7 @@ func main() {
}
flag.StringVar(&controlPlaneNamespace, "control-plane-namespace", controlPlaneNamespaceDefault,
"Namespace where registered cluster kubeconfig Secrets are stored.")
flag.IntVar(&wakeStartLimit, "wake-start-limit", 0, "Maximum concurrent idle cold starts across the fleet; zero disables admission.")
flag.BoolVar(&remoteClusters, "remote-clusters", true, "watch registered clusters and their kubeconfig credentials")
addressManagerDefault := os.Getenv("GAMEPLANE_ADDRESS_MANAGER")
if addressManagerDefault == "" {
Expand Down Expand Up @@ -313,6 +315,10 @@ func main() {
opts := zap.Options{Development: true}
opts.BindFlags(flag.CommandLine)
flag.Parse()
if wakeStartLimit < 0 || wakeStartLimit > 128 {
fmt.Fprintln(os.Stderr, "--wake-start-limit must be between 0 and 128")
os.Exit(1)
}
if agentTokenExpirationSeconds < 600 || agentTokenExpirationSeconds > 3600 {
fmt.Fprintln(os.Stderr, "agent-token-expiration-seconds must be between 600 and 3600")
os.Exit(1)
Expand Down Expand Up @@ -528,6 +534,8 @@ func main() {
AgentLogLevel: agentLogLevel,
AgentCASecretName: agentCASecretName,
AgentCASecretNamespace: agentCASecretNamespace,
WakeStartLimit: wakeStartLimit,
WakeStartNamespace: controlPlaneNamespaceDefault,
AgentClient: agentClient,
OperationQuiescer: agentClient,
PodAttacher: &controller.StopAttachClient{
Expand Down
5 changes: 4 additions & 1 deletion operator/internal/controller/gameserver_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,10 @@ const lifecycleConflictRetry = time.Second
type GameServerReconciler struct {
client.Client
APIReader client.Reader
Scheme *runtime.Scheme
// WakeStartLimit caps simultaneous idle cold starts across managed namespaces.
WakeStartLimit int
WakeStartNamespace string
Scheme *runtime.Scheme

// AgentImage is the container image used for the sidecar agent
// injected into every game pod. Set from an operator flag so the
Expand Down
15 changes: 15 additions & 0 deletions operator/internal/controller/gameserver_idle.go
Original file line number Diff line number Diff line change
Expand Up @@ -329,6 +329,21 @@ func (r *GameServerReconciler) reconcileIdle(
}

out := idleDecide(in)
if out.wake && in.asleepSince != nil && !in.suspended && in.spec != nil && in.spec.Enabled && r.WakeStartLimit > 0 {
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
}
out.status.Reason = "cold start admitted; waiting for game readiness"
}
if out.sleep || out.wake {
if err := r.applyIdleTransition(ctx, gs, out, in.now); err != nil {
return idleAwake, nil, 0, nil, err
Expand Down
Loading
Loading