From 64c9e65c5c7a81720d66170c1e8d5927df3c56ca Mon Sep 17 00:00:00 2001 From: Baylem Date: Sat, 14 Nov 2026 13:25:04 -0500 Subject: [PATCH 1/7] fix(images): verify SteamCMD executables before publishing amd64 base Signed-off-by: Baylem --- .github/workflows/images.yaml | 41 +++++++++++------- hack/check_steamcmd_platform.py | 73 +++++++++++++++++++++++++++++++++ hack/test_steamcmd_platform.py | 42 +++++++++++++++++++ 3 files changed, 141 insertions(+), 15 deletions(-) create mode 100644 hack/check_steamcmd_platform.py create mode 100644 hack/test_steamcmd_platform.py diff --git a/.github/workflows/images.yaml b/.github/workflows/images.yaml index aceff56f1..1fad5c61c 100644 --- a/.github/workflows/images.yaml +++ b/.github/workflows/images.yaml @@ -5,12 +5,14 @@ on: pull_request: paths: - containers/** + - hack/*steamcmd_platform*.py - .github/workflows/images.yaml push: branches: - master paths: - containers/** + - hack/*steamcmd_platform*.py - .github/workflows/images.yaml permissions: @@ -40,7 +42,7 @@ jobs: - base: steamcmd outputs: # Pass the steamcmd base digest to downstream game jobs via ${{ needs.common-base.outputs.steamcmd-digest }} - # On PRs, digest is empty and game job uses the local tag instead. + # Only publishing runs make this digest available in the registry. steamcmd-digest: ${{ steps.build.outputs.digest }} steamcmd-tags: ${{ steps.meta.outputs.tags }} steps: @@ -56,8 +58,9 @@ jobs: echo "::error::COSIGN_PRIVATE_KEY is required for image publishing" exit 1 fi - - uses: docker/setup-qemu-action@99012661954931238ded8c8b007157a8430204e1 # v4.4.0 - uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 + - name: test SteamCMD platform checks + run: python3 -m unittest discover -s hack -p test_steamcmd_platform.py # Login only when pushing to registry; skip on PRs to avoid unnecessary token operations. # Fork PRs have read-only GITHUB_TOKEN anyway, so login would fail confusingly. - if: github.event_name != 'pull_request' @@ -83,17 +86,29 @@ jobs: uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 with: context: containers/common/${{ matrix.base }} - # Common base images support both architectures (Ubuntu 26.04 LTS-based). - platforms: linux/amd64,linux/arm64 - # On PRs: validate multi-platform coverage without loading/pushing (buildx still fully builds). - # On master: push by digest only. The tags are attached after the - # digest is signed and verified, so a tag only ever names a signed image. - push: false - load: false - outputs: ${{ github.event_name != 'pull_request' && format('type=image,name={0},push-by-digest=true,name-canonical=true,push=true', steps.image.outputs.name) || '' }} + # The pinned foundation has amd64 userspace and the i386 SteamCMD binary. + platforms: linux/amd64 + provenance: mode=max + outputs: type=oci,dest=/tmp/steamcmd-oci,tar=false labels: ${{ steps.meta.outputs.labels }} build-args: | VERSION=dev + - name: verify SteamCMD platform and executable headers + env: + DIGEST: ${{ steps.build.outputs.digest }} + run: python3 hack/check_steamcmd_platform.py /tmp/steamcmd-oci "$DIGEST" + - if: github.event_name != 'pull_request' + name: install oras + uses: oras-project/setup-oras@5e2f2482b30b0cb3e14e67f89a80c88c659a7c63 # v2.0.3 + - if: github.event_name != 'pull_request' + name: publish the checked OCI index by digest + env: + DIGEST: ${{ steps.build.outputs.digest }} + IMAGE: ${{ steps.image.outputs.name }} + run: | + # An untagged destination copies the entire graph, including provenance. + oras cp --from-oci-layout "/tmp/steamcmd-oci@${DIGEST}" "$IMAGE" + test "$(oras resolve "${IMAGE}@${DIGEST}")" = "$DIGEST" - if: github.event_name != 'pull_request' name: install cosign uses: sigstore/cosign-installer@756fe2d284c7292c4e9b62c8a28f1e5629c59532 # v4.1.3 @@ -139,9 +154,6 @@ jobs: # Attach the tags only now that the digest carries a verified signature. # `oras tag` points each tag at the existing manifest without rewriting # it; the loop confirms every tag resolves to the signed digest. - - if: github.event_name != 'pull_request' - name: install oras - uses: oras-project/setup-oras@5e2f2482b30b0cb3e14e67f89a80c88c659a7c63 # v2.0.3 - if: github.event_name != 'pull_request' name: attach tags to the signed digest env: @@ -230,7 +242,6 @@ jobs: echo "::error::COSIGN_PRIVATE_KEY is required for image publishing" exit 1 fi - - uses: docker/setup-qemu-action@99012661954931238ded8c8b007157a8430204e1 # v4.4.0 - uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 # Login only when pushing to registry; skip on PRs to avoid unnecessary token operations. # Fork PRs have read-only GITHUB_TOKEN anyway, so login would fail confusingly. @@ -272,7 +283,7 @@ jobs: DIGEST: ${{ needs.common-base.outputs.steamcmd-digest }} EVENT: ${{ github.event_name }} run: | - if [ -z "$DIGEST" ]; then + if [ "$EVENT" = 'pull_request' ]; then # PR: use the named context (resolved via oci-layout:// URI passed to buildx). base_image="gameplane-steamcmd-base:pr" # Named context tells buildx where to find the base image built in this job. diff --git a/hack/check_steamcmd_platform.py b/hack/check_steamcmd_platform.py new file mode 100644 index 000000000..e20295822 --- /dev/null +++ b/hack/check_steamcmd_platform.py @@ -0,0 +1,73 @@ +"""Check the platform and ELF files in the BuildKit OCI layout before publishing.""" + +import hashlib +import json +from pathlib import Path +import subprocess +import sys +import tempfile + + +def image_platform(index): + platforms = [] + for descriptor in index["manifests"]: + platform = descriptor["platform"] + os_arch = (platform["os"], platform["architecture"]) + if (os_arch == ("unknown", "unknown") and + descriptor.get("annotations", {}).get("vnd.docker.reference.type") == "attestation-manifest"): + continue + platforms.append("/".join(os_arch)) + if len(platforms) != 1: + raise ValueError(f"expected one SteamCMD runtime platform, found {platforms}") + return platforms[0] + + +def check_executables(platform, directory): + # The 64-bit Ubuntu userspace runs Valve's 32-bit i386 binary on amd64. + # Inspect the files on the host; nothing from the image is executed. + machines = {"linux/amd64": 62, "linux/arm64": 183} + for name in ("bash", "dpkg", "steamcmd"): + with (directory / name).open("rb") as binary: + header = binary.read(20) + if len(header) != 20 or header[:4] != b"\x7fELF" or header[5] != 1: + raise ValueError(f"{name}: missing little-endian ELF header") + machine = int.from_bytes(header[18:20], "little") + expected = (1, 3) if name == "steamcmd" else (2, machines[platform]) + if (header[4], machine) != expected: + raise ValueError(f"{name}: {platform} has ELF class/machine {(header[4], machine)}, expected {expected}") + if platform != "linux/amd64": + raise ValueError(f"unsupported SteamCMD platform {platform}") + + +def check_layout(layout, digest): + source = f"oci:{layout}" + index = subprocess.check_output(["skopeo", "inspect", "--raw", source]) + if "sha256:" + hashlib.sha256(index).hexdigest() != digest: + raise ValueError("OCI index does not match the digest selected for publication") + platform = image_platform(json.loads(index)) + if platform not in {"linux/arm64", "linux/amd64"}: + raise ValueError(f"unsupported SteamCMD platform {platform}") + # Select the sole runtime child from the same index. Docker's image ID is + # the config digest, so the stopped container uses those filesystem layers. + image = "gameplane-steamcmd:platform-check" + subprocess.run(["skopeo", "--override-os", "linux", "--override-arch", platform.split("/")[1], + "copy", source, f"docker-daemon:{image}"], check=True) + config = json.loads(subprocess.check_output(["docker", "image", "inspect", image]))[0] + if f"{config['Os']}/{config['Architecture']}" != platform: + raise ValueError("OCI child configuration disagrees with the index platform") + container = subprocess.check_output(["docker", "create", "--platform", platform, "--network", "none", + "--entrypoint", "/bin/false", config["Id"]], text=True).strip() + try: + with tempfile.TemporaryDirectory() as temp: + directory = Path(temp) + for path in ("/bin/bash", "/usr/bin/dpkg", "/usr/lib/games/steam/steamcmd"): + subprocess.run(["docker", "cp", "-L", f"{container}:{path}", str(directory / Path(path).name)], + check=True) + check_executables(platform, directory) + finally: + subprocess.run(["docker", "rm", "-v", container], check=True) + print(f"Verified {digest}: {platform}, amd64 Bash and dpkg, i386 SteamCMD") + + +if __name__ == "__main__": + check_layout(*sys.argv[1:]) diff --git a/hack/test_steamcmd_platform.py b/hack/test_steamcmd_platform.py new file mode 100644 index 000000000..f54e493fe --- /dev/null +++ b/hack/test_steamcmd_platform.py @@ -0,0 +1,42 @@ +import tempfile +import unittest +from pathlib import Path + +from check_steamcmd_platform import check_executables, image_platform + + +class SteamCMDPlatformTest(unittest.TestCase): + def setUp(self): + temp = tempfile.TemporaryDirectory() + self.addCleanup(temp.cleanup) + self.directory = Path(temp.name) + for name, elf_class, machine in (("bash", 2, 62), ("dpkg", 2, 62), ("steamcmd", 1, 3)): + header = bytearray(20) + header[:6] = b"\x7fELF" + bytes([elf_class, 1]) + header[18:20] = machine.to_bytes(2, "little") + (self.directory / name).write_bytes(header) + + def test_amd64_with_i386_steamcmd(self): + check_executables("linux/amd64", self.directory) + + def test_arm64_label_with_x86_files(self): + # The original index and config both said arm64. Inspecting Bash catches + # the bad rootfs even when the two pieces of metadata agree. + platform = image_platform({"manifests": [{"platform": {"os": "linux", "architecture": "arm64"}}]}) + with self.assertRaisesRegex(ValueError, "bash: linux/arm64 has ELF"): + check_executables(platform, self.directory) + + def test_wrong_steamcmd_binary(self): + (self.directory / "steamcmd").write_bytes((self.directory / "bash").read_bytes()) + with self.assertRaisesRegex(ValueError, "steamcmd: linux/amd64 has ELF"): + check_executables("linux/amd64", self.directory) + + def test_extra_platform_is_rejected_with_attestations_present(self): + amd64 = {"platform": {"os": "linux", "architecture": "amd64"}} + attestation = {"platform": {"os": "unknown", "architecture": "unknown"}, + "annotations": {"vnd.docker.reference.type": "attestation-manifest"}} + descriptors = [amd64, attestation] + self.assertEqual(image_platform({"manifests": descriptors}), "linux/amd64") + descriptors.append({"platform": {"os": "linux", "architecture": "arm64"}}) + with self.assertRaisesRegex(ValueError, "one SteamCMD runtime platform"): + image_platform({"manifests": descriptors}) From 6245d0c05103eca04b0db9292331130dfeef9ce4 Mon Sep 17 00:00:00 2001 From: Baylem Date: Sat, 14 Nov 2026 13:28:23 -0500 Subject: [PATCH 2/7] fix(operator): enforce template architecture during game and volume placement Pin the five amd64-only catalog templates and retain recovery access to already-bound volumes. Document the native startup and image publication evidence still tracked in issue #921. Signed-off-by: Baylem --- .../unreleased/921-steamcmd-architecture.md | 3 + .../crds/gameplane.local_backups.yaml | 2 +- .../crds/gameplane.local_backupschedules.yaml | 2 +- .../crds/gameplane.local_clusters.yaml | 2 +- .../crds/gameplane.local_gameservers.yaml | 2 +- .../crds/gameplane.local_gametemplates.yaml | 10 ++- .../crds/gameplane.local_modules.yaml | 2 +- .../crds/gameplane.local_modulesources.yaml | 2 +- .../crds/gameplane.local_networkcaptures.yaml | 2 +- .../crds/gameplane.local_restores.yaml | 2 +- .../gameplane.local_backups.yaml | 2 +- .../gameplane.local_backupschedules.yaml | 2 +- .../gameplane.local_clusters.yaml | 2 +- .../gameplane.local_gameservers.yaml | 2 +- .../gameplane.local_gametemplates.yaml | 10 ++- .../gameplane.local_modules.yaml | 2 +- .../gameplane.local_modulesources.yaml | 2 +- .../gameplane.local_networkcaptures.yaml | 2 +- .../gameplane.local_restores.yaml | 2 +- containers/README.md | 12 +-- docs/module-authoring.md | 13 +++- modules | 2 +- operator/api/v1alpha1/gametemplate_types.go | 8 ++ operator/cmd/main.go | 2 + .../crd/gameplane.local_gametemplates.yaml | 8 ++ .../controller/backup_budgets_test.go | 20 +++++ .../internal/controller/backup_controller.go | 3 +- operator/internal/controller/backup_worker.go | 6 ++ .../controller/game_workload_policy.go | 76 ++++++++++++++++--- .../controller/game_workload_policy_test.go | 61 +++++++++++++-- .../controller/gameserver_controller.go | 12 +-- .../controller/gameserver_sentinel.go | 2 +- .../gameserver_sentinel_envtest_test.go | 5 +- .../gameserver_template_revision.go | 18 +++-- .../internal/controller/gameserver_wipe.go | 3 + .../controller/gameserver_wipe_test.go | 13 +++- .../controller/lifecycle_operation.go | 4 + .../internal/controller/restore_controller.go | 6 +- .../controller/restore_lifecycle_test.go | 37 +++++++++ 39 files changed, 303 insertions(+), 63 deletions(-) create mode 100644 changelog/unreleased/921-steamcmd-architecture.md diff --git a/changelog/unreleased/921-steamcmd-architecture.md b/changelog/unreleased/921-steamcmd-architecture.md new file mode 100644 index 000000000..29e5cfad9 --- /dev/null +++ b/changelog/unreleased/921-steamcmd-architecture.md @@ -0,0 +1,3 @@ +# SteamCMD image and worker architecture + +The SteamCMD base build targets `linux/amd64`. Game templates can require a worker architecture with `spec.requiredNodeArchitecture`. On mixed clusters, set the `kubernetes.io/arch: amd64` node selector on affected GameServers that still use older templates. [Affected games and upgrade steps](../../containers/README.md#platform-support) 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 cd0b3b518..85cc3a3c2 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: 3cfb12539ba83c3386c61b485a8069d635b9ed9121a4f316ed3a7232c145360a + gameplane.local/crd-bundle-sha256: 7eb90b2b8ead95f3060e33c210d41167f4aa52d4fb6766967638a0d3b457659e 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 0966c318f..77ea82c97 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: 3cfb12539ba83c3386c61b485a8069d635b9ed9121a4f316ed3a7232c145360a + gameplane.local/crd-bundle-sha256: 7eb90b2b8ead95f3060e33c210d41167f4aa52d4fb6766967638a0d3b457659e 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 7f05b0d14..14329ffe5 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: 3cfb12539ba83c3386c61b485a8069d635b9ed9121a4f316ed3a7232c145360a + gameplane.local/crd-bundle-sha256: 7eb90b2b8ead95f3060e33c210d41167f4aa52d4fb6766967638a0d3b457659e 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 449739c30..26fe294bd 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: 3cfb12539ba83c3386c61b485a8069d635b9ed9121a4f316ed3a7232c145360a + gameplane.local/crd-bundle-sha256: 7eb90b2b8ead95f3060e33c210d41167f4aa52d4fb6766967638a0d3b457659e controller-gen.kubebuilder.io/version: v0.22.0 name: gameservers.gameplane.local spec: diff --git a/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_gametemplates.yaml b/charts/gameplane/charts/gameplane-crds/crds/gameplane.local_gametemplates.yaml index d4235ae39..aa4421650 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: 3cfb12539ba83c3386c61b485a8069d635b9ed9121a4f316ed3a7232c145360a + gameplane.local/crd-bundle-sha256: 7eb90b2b8ead95f3060e33c210d41167f4aa52d4fb6766967638a0d3b457659e controller-gen.kubebuilder.io/version: v0.22.0 name: gametemplates.gameplane.local spec: @@ -2109,6 +2109,14 @@ spec: rule: '!has(self.authentication) || self.authentication || (!has(self.passwordSecretRef) && (!has(self.passwordEnv) || size(self.passwordEnv) == 0) && (!has(self.passwordFile) || size(self.passwordFile) == 0))' + requiredNodeArchitecture: + description: |- + RequiredNodeArchitecture is the kubernetes.io/arch label required by + the game executable (for example, amd64). Omit for portable templates. + The requirement also applies to version selections and image overrides. + maxLength: 63 + pattern: ^[a-z0-9]+$ + type: string resources: description: Resources are the default compute resources for the game container. 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 92101f6c5..71d4f5b60 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: 3cfb12539ba83c3386c61b485a8069d635b9ed9121a4f316ed3a7232c145360a + gameplane.local/crd-bundle-sha256: 7eb90b2b8ead95f3060e33c210d41167f4aa52d4fb6766967638a0d3b457659e 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 6a4fb0a5c..5caa50b55 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: 3cfb12539ba83c3386c61b485a8069d635b9ed9121a4f316ed3a7232c145360a + gameplane.local/crd-bundle-sha256: 7eb90b2b8ead95f3060e33c210d41167f4aa52d4fb6766967638a0d3b457659e 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 7b22bd7ae..81fb34664 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: 3cfb12539ba83c3386c61b485a8069d635b9ed9121a4f316ed3a7232c145360a + gameplane.local/crd-bundle-sha256: 7eb90b2b8ead95f3060e33c210d41167f4aa52d4fb6766967638a0d3b457659e 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 0a472481c..450bcbbe1 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: 3cfb12539ba83c3386c61b485a8069d635b9ed9121a4f316ed3a7232c145360a + gameplane.local/crd-bundle-sha256: 7eb90b2b8ead95f3060e33c210d41167f4aa52d4fb6766967638a0d3b457659e controller-gen.kubebuilder.io/version: v0.22.0 name: restores.gameplane.local spec: diff --git a/charts/gameplane/crd-manifests/gameplane.local_backups.yaml b/charts/gameplane/crd-manifests/gameplane.local_backups.yaml index cd0b3b518..85cc3a3c2 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: 3cfb12539ba83c3386c61b485a8069d635b9ed9121a4f316ed3a7232c145360a + gameplane.local/crd-bundle-sha256: 7eb90b2b8ead95f3060e33c210d41167f4aa52d4fb6766967638a0d3b457659e 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 0966c318f..77ea82c97 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: 3cfb12539ba83c3386c61b485a8069d635b9ed9121a4f316ed3a7232c145360a + gameplane.local/crd-bundle-sha256: 7eb90b2b8ead95f3060e33c210d41167f4aa52d4fb6766967638a0d3b457659e 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 7f05b0d14..14329ffe5 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: 3cfb12539ba83c3386c61b485a8069d635b9ed9121a4f316ed3a7232c145360a + gameplane.local/crd-bundle-sha256: 7eb90b2b8ead95f3060e33c210d41167f4aa52d4fb6766967638a0d3b457659e 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 449739c30..26fe294bd 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: 3cfb12539ba83c3386c61b485a8069d635b9ed9121a4f316ed3a7232c145360a + gameplane.local/crd-bundle-sha256: 7eb90b2b8ead95f3060e33c210d41167f4aa52d4fb6766967638a0d3b457659e controller-gen.kubebuilder.io/version: v0.22.0 name: gameservers.gameplane.local spec: diff --git a/charts/gameplane/crd-manifests/gameplane.local_gametemplates.yaml b/charts/gameplane/crd-manifests/gameplane.local_gametemplates.yaml index d4235ae39..aa4421650 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: 3cfb12539ba83c3386c61b485a8069d635b9ed9121a4f316ed3a7232c145360a + gameplane.local/crd-bundle-sha256: 7eb90b2b8ead95f3060e33c210d41167f4aa52d4fb6766967638a0d3b457659e controller-gen.kubebuilder.io/version: v0.22.0 name: gametemplates.gameplane.local spec: @@ -2109,6 +2109,14 @@ spec: rule: '!has(self.authentication) || self.authentication || (!has(self.passwordSecretRef) && (!has(self.passwordEnv) || size(self.passwordEnv) == 0) && (!has(self.passwordFile) || size(self.passwordFile) == 0))' + requiredNodeArchitecture: + description: |- + RequiredNodeArchitecture is the kubernetes.io/arch label required by + the game executable (for example, amd64). Omit for portable templates. + The requirement also applies to version selections and image overrides. + maxLength: 63 + pattern: ^[a-z0-9]+$ + type: string resources: description: Resources are the default compute resources for the game container. diff --git a/charts/gameplane/crd-manifests/gameplane.local_modules.yaml b/charts/gameplane/crd-manifests/gameplane.local_modules.yaml index 92101f6c5..71d4f5b60 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: 3cfb12539ba83c3386c61b485a8069d635b9ed9121a4f316ed3a7232c145360a + gameplane.local/crd-bundle-sha256: 7eb90b2b8ead95f3060e33c210d41167f4aa52d4fb6766967638a0d3b457659e 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 6a4fb0a5c..5caa50b55 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: 3cfb12539ba83c3386c61b485a8069d635b9ed9121a4f316ed3a7232c145360a + gameplane.local/crd-bundle-sha256: 7eb90b2b8ead95f3060e33c210d41167f4aa52d4fb6766967638a0d3b457659e 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 7b22bd7ae..81fb34664 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: 3cfb12539ba83c3386c61b485a8069d635b9ed9121a4f316ed3a7232c145360a + gameplane.local/crd-bundle-sha256: 7eb90b2b8ead95f3060e33c210d41167f4aa52d4fb6766967638a0d3b457659e 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 0a472481c..450bcbbe1 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: 3cfb12539ba83c3386c61b485a8069d635b9ed9121a4f316ed3a7232c145360a + gameplane.local/crd-bundle-sha256: 7eb90b2b8ead95f3060e33c210d41167f4aa52d4fb6766967638a0d3b457659e controller-gen.kubebuilder.io/version: v0.22.0 name: restores.gameplane.local spec: diff --git a/containers/README.md b/containers/README.md index b56e143f2..d0f9db787 100644 --- a/containers/README.md +++ b/containers/README.md @@ -226,11 +226,13 @@ docker run -it \ ## Platform support -- **Common bases** — built for `linux/amd64,linux/arm64` (Ubuntu 26.04 LTS, portable). -- **Game images** — built for `linux/amd64` only by default. - - Game server binaries (especially Unity-based, like Nuclear Option) are x86_64-only. - - ARM64 support requires a native ARM64 binary from the game publisher, which most do not officially provide. - - To add ARM64 support: obtain the ARM64 binary, update the Dockerfile and workflow matrix to build `linux/amd64,linux/arm64`. +The SteamCMD base requires `linux/amd64`. Bash and dpkg are x86-64 executables, and SteamCMD is a 32-bit Intel executable. Workers must support both x86 ABIs. The published game images in this workflow also target `linux/amd64`. + +Squad, The Isle, Mount & Blade II Bannerlord and Nuclear Option inherit this base. ARK Survival Evolved moved to `hermsi/ark-server`; its catalog pin also requires amd64. On mixed clusters these games need an eligible amd64 worker with access to their volume. The official templates declare `spec.requiredNodeArchitecture: amd64`. For older templates and operators, set `spec.nodeSelector["kubernetes.io/arch"]` to `amd64` on each affected GameServer before starting it. + +Publishing a corrected base changes future builds. Previously published indices and digest-pinned game images retain their original contents. In particular, the old common-base index `sha256:7cc7c2a9f45a6f0f69654517666de75db944e08ff110028a2586eaca77287801` advertises an ARM64 child containing Intel executables. Rebuild downstream images from the corrected signed base, record their signed digests, and update the module pins and any local overrides. Install the compatible operator and CRDs before adopting the updated module bundles. + +For release qualification, start each game from its published digest and official template on a real amd64 worker with a fresh volume. Record the worker architecture, kernel, active `binfmt_misc` handlers, module version, image digest, and a successful game query or connection after first install. Include ARK's pinned vendor digest in the placement check. On a cluster with only ARM64 workers eligible, verify that Kubernetes leaves the game Pending. Attach the results to [issue #921](https://github.com/GameplanePanel/Gameplane/issues/921). An ARM64 release would also need a supported runtime for the installer and game, a successful start on that worker, and performance evidence for any emulation it requires. ## Image signing diff --git a/docs/module-authoring.md b/docs/module-authoring.md index 63d764054..0d66fc5bd 100644 --- a/docs/module-authoring.md +++ b/docs/module-authoring.md @@ -684,9 +684,16 @@ make module-pin # rewrites every modules/*/template.yaml in place It resolves each tag through the registry's standard bearer-token flow (any OCI registry, not just Docker Hub), preserves the templates' comments, and leaves any ref it cannot resolve untouched rather than guessing. The digest it -writes is the **tag manifest's** digest — for a multi-arch image that is the -index digest covering every published platform, so a pinned module still runs -on both amd64 and arm64. +writes is the **tag manifest's** digest. For a multi-arch image, this is the +index digest covering the platforms the publisher advertises. + +If every supported game version requires one worker architecture, set +`spec.requiredNodeArchitecture` on the GameTemplate. For example, use `amd64` +for a game that needs the Gameplane SteamCMD base. Verify the actual installer +and server on that architecture. Kubernetes intersects the resulting +`kubernetes.io/arch` requirement with the server's placement and the operator's +worker policy. Set the module's `gameplaneMinVersion` to a release that enforces +the field so older operators reject the bundle. Because pinning stops upstream releases from arriving on their own, the `GameplanePanel/module` repo runs `refresh-pins.yml` monthly to re-resolve every diff --git a/modules b/modules index a660997ca..4590865ed 160000 --- a/modules +++ b/modules @@ -1 +1 @@ -Subproject commit a660997ca02987d3ff3ea0f2c635d2e29f074cdb +Subproject commit 4590865ed27bd845d241aa47caa61bdea396b221 diff --git a/operator/api/v1alpha1/gametemplate_types.go b/operator/api/v1alpha1/gametemplate_types.go index 14d14e9d6..a3d94e6bf 100644 --- a/operator/api/v1alpha1/gametemplate_types.go +++ b/operator/api/v1alpha1/gametemplate_types.go @@ -66,6 +66,14 @@ type GameTemplateSpec struct { // +kubebuilder:validation:MinLength=1 Image string `json:"image"` + // RequiredNodeArchitecture is the kubernetes.io/arch label required by + // the game executable (for example, amd64). Omit for portable templates. + // The requirement also applies to version selections and image overrides. + // +kubebuilder:validation:Pattern=`^[a-z0-9]+$` + // +kubebuilder:validation:MaxLength=63 + // +optional + RequiredNodeArchitecture string `json:"requiredNodeArchitecture,omitempty"` + // Versions is an optional catalog of selectable game versions surfaced // in the Create Server wizard. Each entry maps a user choice to a // concrete image (and optional per-version env / mod loader). When empty diff --git a/operator/cmd/main.go b/operator/cmd/main.go index 94a0488c8..3be6f4deb 100644 --- a/operator/cmd/main.go +++ b/operator/cmd/main.go @@ -575,6 +575,7 @@ func main() { AgentClient: agentClient, ResticImage: resticImage, BackupResources: backupResources, + GameWorkloadPolicy: gameWorkloadPolicy, JobBackoffLimit: &backupJobBackoff32, JobActiveDeadlineSeconds: backupJobActiveDeadlineSeconds, EventRecorder: mgr.GetEventRecorder("backup-controller"), @@ -600,6 +601,7 @@ func main() { OperationQuiescer: agentClient, ResticImage: resticImage, BackupResources: backupResources, + GameWorkloadPolicy: gameWorkloadPolicy, JobBackoffLimit: &backupJobBackoff32, JobActiveDeadlineSeconds: backupJobActiveDeadlineSeconds, }).SetupWithManager(mgr); err != nil { diff --git a/operator/config/crd/gameplane.local_gametemplates.yaml b/operator/config/crd/gameplane.local_gametemplates.yaml index 4e38b0049..e9b026d95 100644 --- a/operator/config/crd/gameplane.local_gametemplates.yaml +++ b/operator/config/crd/gameplane.local_gametemplates.yaml @@ -2108,6 +2108,14 @@ spec: rule: '!has(self.authentication) || self.authentication || (!has(self.passwordSecretRef) && (!has(self.passwordEnv) || size(self.passwordEnv) == 0) && (!has(self.passwordFile) || size(self.passwordFile) == 0))' + requiredNodeArchitecture: + description: |- + RequiredNodeArchitecture is the kubernetes.io/arch label required by + the game executable (for example, amd64). Omit for portable templates. + The requirement also applies to version selections and image overrides. + maxLength: 63 + pattern: ^[a-z0-9]+$ + type: string resources: description: Resources are the default compute resources for the game container. diff --git a/operator/internal/controller/backup_budgets_test.go b/operator/internal/controller/backup_budgets_test.go index de02cecc6..14930e620 100644 --- a/operator/internal/controller/backup_budgets_test.go +++ b/operator/internal/controller/backup_budgets_test.go @@ -307,6 +307,26 @@ func TestBackupRawSourceWaitsForInitialScheduling(t *testing.T) { } } +func TestStoppedBackupFirstConsumerUsesGameArchitecture(t *testing.T) { + r, _ := stoppedBackupFixture(t, true) + tmpl := &gameplanev1alpha1.GameTemplate{ObjectMeta: metav1.ObjectMeta{Name: "template"}, + Spec: gameplanev1alpha1.GameTemplateSpec{RequiredNodeArchitecture: "amd64"}} + pvc := &corev1.PersistentVolumeClaim{ObjectMeta: metav1.ObjectMeta{Name: "server-data", Namespace: "ns"}} + for _, obj := range []client.Object{tmpl, pvc} { + if err := r.Create(t.Context(), obj); err != nil { + t.Fatal(err) + } + } + budgetPass(t, r, "first") + var job batchv1.Job + if err := r.Get(t.Context(), client.ObjectKey{Namespace: "ns", Name: "first"}, &job); err != nil { + t.Fatal(err) + } + if job.Spec.Template.Spec.NodeSelector[corev1.LabelArchStable] != "amd64" { + t.Fatalf("backup can bind an incompatible local volume: %v", job.Spec.Template.Spec.NodeSelector) + } +} + func TestBackupPreparedWorkerFailurePreservesJobMessage(t *testing.T) { r, _ := guardFixtureWorkers(t, false, guardBackup("failed-worker")) budgetPass(t, r, "failed-worker") diff --git a/operator/internal/controller/backup_controller.go b/operator/internal/controller/backup_controller.go index 86c9efdf2..97a5df0c1 100644 --- a/operator/internal/controller/backup_controller.go +++ b/operator/internal/controller/backup_controller.go @@ -123,7 +123,8 @@ type BackupReconciler struct { ResticImage string // BackupResources replaces resources for backup/init and repository cleanup // workers. Nil uses defaults; an explicit empty object clears them. - BackupResources *corev1.ResourceRequirements + BackupResources *corev1.ResourceRequirements + GameWorkloadPolicy *GameWorkloadPolicy // JobBackoffLimit / JobActiveDeadlineSeconds bound the restic backup Job. // Set from operator flags; nil / zero fall back to // DefaultBackupJobBackoffLimit / DefaultBackupJobActiveDeadlineSeconds. diff --git a/operator/internal/controller/backup_worker.go b/operator/internal/controller/backup_worker.go index 9ed35bc37..30bac3d2d 100644 --- a/operator/internal/controller/backup_worker.go +++ b/operator/internal/controller/backup_worker.go @@ -305,6 +305,12 @@ func (r *BackupReconciler) reconcilePreparedRestic(ctx context.Context, b *gamep job = batchv1.Job{ObjectMeta: metav1.ObjectMeta{Name: b.Name, Namespace: b.Namespace, Annotations: map[string]string{backupWorkerProtocolAnnotation: "v1"}}, Spec: batchv1.JobSpec{BackoffLimit: &backoff, ActiveDeadlineSeconds: &deadline, Template: corev1.PodTemplateSpec{ObjectMeta: metav1.ObjectMeta{Labels: map[string]string{backupRestoreJobLabel: backupRestoreJobValue, backupUIDLabel: string(b.UID)}}, Spec: r.buildPreparedBackupPodSpec(b, tmpl, source, bound.UID, preparation)}}} job.Spec.Template.Spec.RestartPolicy = corev1.RestartPolicyNever + if source.NodeName == "" { + // A scheduled game Pod has already bound its mounted claims. + if err := r.GameWorkloadPolicy.placeFirstVolumeConsumer(ctx, r.backupAPIReader(), bound, tmpl, &job.Spec.Template.Spec); err != nil { + return ctrl.Result{}, err + } + } if err := controllerutil.SetControllerReference(b, &job, r.Scheme); err != nil { return ctrl.Result{}, err } diff --git a/operator/internal/controller/game_workload_policy.go b/operator/internal/controller/game_workload_policy.go index 57cd09275..b750bc24d 100644 --- a/operator/internal/controller/game_workload_policy.go +++ b/operator/internal/controller/game_workload_policy.go @@ -119,6 +119,9 @@ func ParseGameWorkloadPolicy(raw string) (*GameWorkloadPolicy, error) { // validate checks the merged game resources and placement before the controller can create or change a workload. func (p *GameWorkloadPolicy) validate(gs *gameplanev1alpha1.GameServer, tmpl *gameplanev1alpha1.GameTemplate) error { + if err := p.validatePlacement(gs, tmpl); err != nil { + return err + } res := effectiveResources(gs, tmpl) for name, request := range res.Requests { if limit, ok := res.Limits[name]; ok && request.Cmp(limit) > 0 { @@ -128,6 +131,29 @@ func (p *GameWorkloadPolicy) validate(gs *gameplanev1alpha1.GameServer, tmpl *ga if p == nil { return nil } + cpu := res.Requests.Cpu() + if cpu.Cmp(p.MinCPURequest) < 0 || cpu.Cmp(p.MaxCPURequest) > 0 { + return fmt.Errorf("effective resources.requests.cpu must be between %s and %s", p.MinCPURequest.String(), p.MaxCPURequest.String()) + } + request, limit := res.Requests.Memory(), res.Limits.Memory() + if request.Cmp(p.MinMemoryRequest) < 0 || limit.IsZero() || limit.Cmp(p.MaxMemoryLimit) > 0 { + return fmt.Errorf("effective resources.requests.memory must be at least %s, and resources.limits.memory must cover the request and stay within %s", p.MinMemoryRequest.String(), p.MaxMemoryLimit.String()) + } + return nil +} + +func (p *GameWorkloadPolicy) validatePlacement(gs *gameplanev1alpha1.GameServer, tmpl *gameplanev1alpha1.GameTemplate) error { + if arch := tmpl.Spec.RequiredNodeArchitecture; arch != "" { + if value, found := gs.Spec.NodeSelector[corev1.LabelArchStable]; found && value != arch { + return fmt.Errorf("spec.nodeSelector sets %s=%q but the game template requires %q", corev1.LabelArchStable, value, arch) + } + if p != nil && p.PoolLabel == corev1.LabelArchStable && p.PoolValue != arch { + return fmt.Errorf("game worker pool sets %s=%q but the game template requires %q", corev1.LabelArchStable, p.PoolValue, arch) + } + } + if p == nil { + return nil + } if value, found := gs.Spec.NodeSelector[p.PoolLabel]; found && value != p.PoolValue { return fmt.Errorf("spec.nodeSelector conflicts with the required game worker pool %s=%s", p.PoolLabel, p.PoolValue) } @@ -137,23 +163,49 @@ func (p *GameWorkloadPolicy) validate(gs *gameplanev1alpha1.GameServer, tmpl *ga return fmt.Errorf("spec.tolerations may only tolerate %s=%s:NoSchedule", p.PoolLabel, p.PoolValue) } } - cpu := res.Requests.Cpu() - if cpu.Cmp(p.MinCPURequest) < 0 || cpu.Cmp(p.MaxCPURequest) > 0 { - return fmt.Errorf("effective resources.requests.cpu must be between %s and %s", p.MinCPURequest.String(), p.MaxCPURequest.String()) - } - request, limit := res.Requests.Memory(), res.Limits.Memory() - if request.Cmp(p.MinMemoryRequest) < 0 || limit.IsZero() || limit.Cmp(p.MaxMemoryLimit) > 0 { - return fmt.Errorf("effective resources.requests.memory must be at least %s, and resources.limits.memory must cover the request and stay within %s", p.MinMemoryRequest.String(), p.MaxMemoryLimit.String()) - } return nil } -// placement combines the server's node selectors with the administrator's dedicated worker-pool taint and label. -func (p *GameWorkloadPolicy) placement(gs *gameplanev1alpha1.GameServer) (map[string]string, []corev1.Toleration) { +// placement combines the template's executable architecture and the server's +// selectors with the administrator's dedicated worker-pool taint and label. +func (p *GameWorkloadPolicy) placement(gs *gameplanev1alpha1.GameServer, tmpl *gameplanev1alpha1.GameTemplate) (map[string]string, []corev1.Toleration) { + selector := gs.Spec.NodeSelector + if arch := tmpl.Spec.RequiredNodeArchitecture; arch != "" { + selector = make(map[string]string, len(gs.Spec.NodeSelector)+1) + maps.Copy(selector, gs.Spec.NodeSelector) + selector[corev1.LabelArchStable] = arch + } if p == nil { - return gs.Spec.NodeSelector, gs.Spec.Tolerations + return selector, gs.Spec.Tolerations + } + return workerPlacement(p.PoolLabel, p.PoolValue, selector) +} + +// A worker can be the first consumer of a suspended game's local storage. +// Already-bound claims retain their volume topology so legacy data can be recovered. +func (p *GameWorkloadPolicy) placeFirstVolumeConsumer(ctx context.Context, reader client.Reader, gs *gameplanev1alpha1.GameServer, tmpl *gameplanev1alpha1.GameTemplate, pod *corev1.PodSpec) error { + if tmpl.Spec.RequiredNodeArchitecture == "" { + return nil } - return workerPlacement(p.PoolLabel, p.PoolValue, gs.Spec.NodeSelector) + for _, volume := range pod.Volumes { + if volume.PersistentVolumeClaim == nil { + continue + } + var pvc corev1.PersistentVolumeClaim + key := client.ObjectKey{Namespace: gs.Namespace, Name: volume.PersistentVolumeClaim.ClaimName} + if err := reader.Get(ctx, key, &pvc); err != nil { + return fmt.Errorf("read game volume %s before scheduling worker: %w", key, err) + } + if pvc.Spec.VolumeName == "" { + if err := p.validatePlacement(gs, tmpl); err != nil { + return err + } + pod.NodeSelector, pod.Tolerations = p.placement(gs, tmpl) + pod.Affinity = hostportAffinity(gs) + break + } + } + return nil } func validWorkerPool(key, value string) bool { diff --git a/operator/internal/controller/game_workload_policy_test.go b/operator/internal/controller/game_workload_policy_test.go index 8f82a5abb..314d2e33a 100644 --- a/operator/internal/controller/game_workload_policy_test.go +++ b/operator/internal/controller/game_workload_policy_test.go @@ -71,13 +71,13 @@ func TestGamePartialResourceOverrideAndPlacement(t *testing.T) { if tmpl.Spec.Resources.Requests.Cpu().String() != "250m" || gs.Spec.Resources.Limits != nil { t.Fatal("merge mutated its inputs") } - selector, tolerations := p.placement(gs) + selector, tolerations := p.placement(gs, tmpl) if selector["rack"] != "west" || selector[p.PoolLabel] != p.PoolValue || len(gs.Spec.NodeSelector) != 1 || len(tolerations) != 1 || tolerations[0].Operator != corev1.TolerationOpEqual { t.Fatalf("worker placement: %v %v", selector, tolerations) } var disabled *GameWorkloadPolicy - sel, tol := disabled.placement(gs) + sel, tol := disabled.placement(gs, tmpl) if len(sel) != 1 || sel["rack"] != "west" || len(tol) != 1 || tol[0] != gs.Spec.Tolerations[0] { t.Fatalf("legacy placement changed: %v %v", sel, tol) } @@ -119,6 +119,8 @@ func TestGameWorkloadPolicyRendersMergedResourcesAndWorkerPlacement(t *testing.T p, _, tmpl := gamePolicyFixture(t) r.GameWorkloadPolicy = p effective.Spec.Resources = tmpl.Spec.Resources + effective.Spec.RequiredNodeArchitecture = "amd64" + gs.Spec.NodeSelector = map[string]string{"rack": "west"} gs.Spec.Resources = &corev1.ResourceRequirements{Limits: corev1.ResourceList{corev1.ResourceMemory: resource.MustParse("2Gi")}} if err := r.Update(t.Context(), gs); err != nil { t.Fatal(err) @@ -134,11 +136,52 @@ func TestGameWorkloadPolicyRendersMergedResourcesAndWorkerPlacement(t *testing.T game := pod.Containers[0] if game.Name != gameContainerName || game.Resources.Requests.Cpu().String() != "250m" || game.Resources.Limits.Memory().String() != "2Gi" || !game.Resources.Limits.Cpu().IsZero() || - pod.NodeSelector[p.PoolLabel] != p.PoolValue || len(pod.Tolerations) != 1 || pod.Tolerations[0].Key != p.PoolLabel { + pod.NodeSelector[p.PoolLabel] != p.PoolValue || pod.NodeSelector[corev1.LabelArchStable] != "amd64" || + pod.NodeSelector["rack"] != "west" || len(gs.Spec.NodeSelector) != 1 || + len(pod.Tolerations) != 1 || pod.Tolerations[0].Key != p.PoolLabel { t.Fatalf("wrong game resources or placement: %+v / %+v / %+v", game.Resources, pod.NodeSelector, pod.Tolerations) } } +func TestTemplateArchitectureRejectsConflictingPlacement(t *testing.T) { + for _, conflict := range []string{"server", "worker pool"} { + t.Run(conflict, func(t *testing.T) { + r, gs, tmpl := revisionFixture(t) + tmpl.Spec.RequiredNodeArchitecture = "amd64" + if conflict == "worker pool" { + p, _, valid := gamePolicyFixture(t) + p.PoolLabel, p.PoolValue = corev1.LabelArchStable, "arm64" + r.GameWorkloadPolicy, tmpl.Spec.Resources = p, valid.Spec.Resources + } else { + gs.Spec.NodeSelector = map[string]string{corev1.LabelArchStable: "arm64"} + } + delete(gs.Annotations, effectiveTemplateAnnotation) + ctx := t.Context() + if err := r.Update(ctx, tmpl); err != nil { + t.Fatal(err) + } + if err := r.Update(ctx, gs); err != nil { + t.Fatal(err) + } + key := client.ObjectKeyFromObject(gs) + if _, err := r.Reconcile(ctx, ctrl.Request{NamespacedName: key}); err != nil { + t.Fatal(err) + } + if err := r.Get(ctx, key, gs); err != nil { + t.Fatal(err) + } + ready := meta.FindStatusCondition(gs.Status.Conditions, "Ready") + if ready == nil || ready.Status != metav1.ConditionFalse || !strings.Contains(ready.Message, "amd64") || + gs.Annotations[lifecycleOperationAnnotation] != "" { + t.Fatalf("conflicting placement was admitted or not explained: %+v", gs) + } + if err := r.Get(ctx, key, &appsv1.StatefulSet{}); !apierrors.IsNotFound(err) { + t.Fatalf("conflicting placement produced a workload: %v", err) + } + }) + } +} + // TestStoredGameCannotCreateWorkloadOutsideWorkerPolicy checks direct-CR rejection without creating a StatefulSet. func TestStoredGameCannotCreateWorkloadOutsideWorkerPolicy(t *testing.T) { r, gs, _ := revisionFixture(t) @@ -287,13 +330,17 @@ func TestWorkerPolicyRefusesUnsafeProbeInHistoricalBaseline(t *testing.T) { // A catalog snapshot saved during migration is not proof of the legacy Pod's stop contract. func TestWorkerPolicyDrainsLegacyPodBeforeFirstPin(t *testing.T) { - for _, contract := range []string{"unversioned", "verified", "previously pinned baseline"} { + for _, contract := range []string{"unversioned", "verified", "previously pinned baseline", "template architecture only"} { t.Run(contract, func(t *testing.T) { ctx := t.Context() r, gs, catalog := revisionFixture(t) policy, _, valid := gamePolicyFixture(t) r.GameWorkloadPolicy = policy catalog.Spec.Resources = valid.Spec.Resources + if contract == "template architecture only" { + r.GameWorkloadPolicy = nil + catalog.Spec.RequiredNodeArchitecture = "amd64" + } catalog.Spec.RCON = &gameplanev1alpha1.RCONSpec{Protocol: "source"} catalog.Spec.Capabilities = &gameplanev1alpha1.CapabilitiesSpec{Lifecycle: &gameplanev1alpha1.LifecycleSpec{Stop: []string{"save", "stop"}}} oldRevision, err := r.saveTemplateSnapshot(ctx, gs, catalog) @@ -418,7 +465,11 @@ func TestWorkerPolicyDrainsLegacyPodBeforeFirstPin(t *testing.T) { for range 5 { step() } - if *ss.Spec.Replicas != 1 || ss.Spec.Template.Spec.NodeSelector[r.GameWorkloadPolicy.PoolLabel] != r.GameWorkloadPolicy.PoolValue || + selector := ss.Spec.Template.Spec.NodeSelector + if contract == "template architecture only" && selector[corev1.LabelArchStable] != "amd64" { + t.Fatalf("replacement lacks the required architecture: %v", selector) + } + if *ss.Spec.Replicas != 1 || (r.GameWorkloadPolicy != nil && selector[policy.PoolLabel] != policy.PoolValue) || !validTemplateRevision(ss.Spec.Template.Annotations[templateRevisionAnnotation]) || ss.Spec.Template.Spec.Containers[0].Image != catalog.Spec.Image { t.Fatal("drained workload did not resume on its policy-compliant revision") } diff --git a/operator/internal/controller/gameserver_controller.go b/operator/internal/controller/gameserver_controller.go index a788c467f..26172dbbd 100644 --- a/operator/internal/controller/gameserver_controller.go +++ b/operator/internal/controller/gameserver_controller.go @@ -1335,7 +1335,7 @@ func (r *GameServerReconciler) desiredReplicas( if op, held, err := lifecycleOwner(&live); err != nil { return 0, 0, err } else if held && op.Kind == "Rollout" && len(op.Recovery) == 0 && - ((op.Baseline && r.GameWorkloadPolicy != nil) || (!op.Baseline && op.Token != live.Annotations[effectiveTemplateAnnotation])) { + (r.baselineNeedsDrain(op) || (!op.Baseline && op.Token != live.Annotations[effectiveTemplateAnnotation])) { if op.Baseline && live.Annotations[lifecycleOperationAnnotation] != gs.Annotations[lifecycleOperationAnnotation] { return 1, restartDrainPoll, nil } @@ -1493,12 +1493,12 @@ func selectStopTransport(tmpl *gameplanev1alpha1.GameTemplate) stopTransport { func (r *GameServerReconciler) softStop( ctx context.Context, gs *gameplanev1alpha1.GameServer, tmpl *gameplanev1alpha1.GameTemplate, ) (int32, time.Duration, error) { - if r.GameWorkloadPolicy != nil && gs.Annotations[lifecycleOperationAnnotation] != "" { + if gs.Annotations[lifecycleOperationAnnotation] != "" { op, _, err := lifecycleOwner(gs) if err != nil { return 0, 0, err } - if op.Kind == "Rollout" && op.Baseline { + if op.Kind == "Rollout" && r.baselineNeedsDrain(op) { // This also applies when a Hostport node disappears during migration. tmpl, err = r.baselineStopTemplate(ctx, gs) if err != nil { @@ -1704,7 +1704,7 @@ func (r *GameServerReconciler) reconcileStatefulSet( ss.Annotations = map[string]string{} } ss.Annotations[lifecycleOperationAnnotation] = lifecycleOperationJSON(op) - if op.Kind == "Rollout" && op.Baseline && r.GameWorkloadPolicy != nil && ss.ResourceVersion == "" { + if op.Kind == "Rollout" && r.baselineNeedsDrain(op) && ss.ResourceVersion == "" { // A stale scale-up can race recreation while the old world // writer is terminating. Create the fenced replacement stopped. actualReplicas, replicas = 0, 0 @@ -1780,7 +1780,7 @@ func (r *GameServerReconciler) reconcileStatefulSet( } } } - if held && op.Baseline && r.GameWorkloadPolicy != nil && ss.ResourceVersion != "" { + if held && r.baselineNeedsDrain(op) && ss.ResourceVersion != "" { // A stale pre-admission decision may stamp the owner but cannot // change replicas. During the drain, never raise replicas or roll // the live Pod's template, including on previously pinned baselines. @@ -1913,7 +1913,7 @@ func (r *GameServerReconciler) reconcileStatefulSet( // Assign unconditionally so clearing spec.nodeSelector also clears the // pod template's selector (nil resets it); the previous nil-guard left // a removed scheduling pin active on the StatefulSet. - ss.Spec.Template.Spec.NodeSelector, ss.Spec.Template.Spec.Tolerations = r.GameWorkloadPolicy.placement(gs) + ss.Spec.Template.Spec.NodeSelector, ss.Spec.Template.Spec.Tolerations = r.GameWorkloadPolicy.placement(gs, tmpl) // Do not change a live Pod's template merely because its node was // recorded while a graceful stop is still saving the game. Apply the // endpoint pin at zero replicas, then retain it on every future wake. diff --git a/operator/internal/controller/gameserver_sentinel.go b/operator/internal/controller/gameserver_sentinel.go index dd0650f4c..219dced35 100644 --- a/operator/internal/controller/gameserver_sentinel.go +++ b/operator/internal/controller/gameserver_sentinel.go @@ -337,7 +337,7 @@ func (r *GameServerReconciler) reconcileSentinel( dep.Spec.Template.Spec.ServiceAccountName = sentinelSAName(gs) if hostPort { - dep.Spec.Template.Spec.NodeSelector, dep.Spec.Template.Spec.Tolerations = r.GameWorkloadPolicy.placement(gs) + dep.Spec.Template.Spec.NodeSelector, dep.Spec.Template.Spec.Tolerations = r.GameWorkloadPolicy.placement(gs, tmpl) dep.Spec.Template.Spec.Affinity = hostportAffinity(gs) dep.Spec.Strategy = appsv1.DeploymentStrategy{Type: appsv1.RecreateDeploymentStrategyType} } else { diff --git a/operator/internal/controller/gameserver_sentinel_envtest_test.go b/operator/internal/controller/gameserver_sentinel_envtest_test.go index f8e1d9d60..fa5629935 100644 --- a/operator/internal/controller/gameserver_sentinel_envtest_test.go +++ b/operator/internal/controller/gameserver_sentinel_envtest_test.go @@ -177,13 +177,14 @@ func TestSentinelReconciliation(t *testing.T) { ns := newNamespace(t) tmpl := wakeableTestTemplate(uniqueName("sentinel-tmpl"), "minecraft") + tmpl.Spec.RequiredNodeArchitecture = "amd64" if err := k8sClient.Create(ctx, tmpl); err != nil { t.Fatalf("create template: %v", err) } deleteCleanup(t, tmpl) policy, _, _ := gamePolicyFixture(t) - node := &corev1.Node{ObjectMeta: metav1.ObjectMeta{Name: uniqueName("sentinel-node"), Labels: map[string]string{policy.PoolLabel: policy.PoolValue}}} + node := &corev1.Node{ObjectMeta: metav1.ObjectMeta{Name: uniqueName("sentinel-node"), Labels: map[string]string{policy.PoolLabel: policy.PoolValue, corev1.LabelArchStable: "amd64"}}} if err := k8sClient.Create(ctx, node); err != nil { t.Fatalf("create node: %v", err) } @@ -220,7 +221,7 @@ func TestSentinelReconciliation(t *testing.T) { t.Fatalf("get sentinel deployment: %v", err) } pod := dep.Spec.Template.Spec - if pod.NodeSelector[policy.PoolLabel] != policy.PoolValue || len(pod.Tolerations) != 1 || pod.Tolerations[0].Value != policy.PoolValue || + if pod.NodeSelector[corev1.LabelArchStable] != "amd64" || pod.NodeSelector[policy.PoolLabel] != policy.PoolValue || len(pod.Tolerations) != 1 || pod.Tolerations[0].Value != policy.PoolValue || pod.Affinity == nil || pod.Affinity.NodeAffinity == nil { t.Fatalf("hostport listener lost game pool or endpoint affinity: %+v", pod) } diff --git a/operator/internal/controller/gameserver_template_revision.go b/operator/internal/controller/gameserver_template_revision.go index 81824e794..d715c140d 100644 --- a/operator/internal/controller/gameserver_template_revision.go +++ b/operator/internal/controller/gameserver_template_revision.go @@ -184,7 +184,7 @@ func (r *GameServerReconciler) reconcileTemplateRevision(ctx context.Context, gs return effective, true, err } if op.Baseline { - if r.GameWorkloadPolicy != nil { + if r.baselineNeedsDrain(op) { drained, err := r.templateWorkloadDrained(ctx, gs) if !drained || err != nil { // Continue to desiredReplicas with the durable owner held. The @@ -250,7 +250,8 @@ func (r *GameServerReconciler) reconcileTemplateRevision(ctx context.Context, gs // An earlier operator may have recorded a first pin while preserving the // original, unversioned Pod. Migrate that baseline under the same fence // when the worker policy is enabled later, even with OnRequest updates. - migrateBaseline := r.GameWorkloadPolicy != nil && pin != "" && gs.Annotations[baselineTemplateAnnotation] == pin + migrateBaseline := (r.GameWorkloadPolicy != nil || effective.Spec.RequiredNodeArchitecture != "") && + pin != "" && gs.Annotations[baselineTemplateAnnotation] == pin if (desired != "" && desired != pin) || migrateBaseline { target, revision := &installed, desired if migrateBaseline { @@ -289,6 +290,7 @@ func (r *GameServerReconciler) reconcileTemplateRevision(ctx context.Context, gs return nil, false, err } want := lifecycleIdentity{Kind: "Rollout", Name: gs.Name, UID: gs.UID, TargetUID: gs.UID, Generation: gs.Generation, Token: revision, Baseline: pin == "" || migrateBaseline} + want.ArchitectureDrain = want.Baseline && target.Spec.RequiredNodeArchitecture != "" claimed, err := claimLifecycleOperation(ctx, r.Client, r.wipeReader(), gs, want, r.OperationQuiescer) return effective, claimed, err } @@ -296,6 +298,10 @@ func (r *GameServerReconciler) reconcileTemplateRevision(ctx context.Context, gs return effective, false, r.pruneTemplateSnapshots(ctx, gs) } +func (r *GameServerReconciler) baselineNeedsDrain(op lifecycleOperation) bool { + return op.Baseline && (r.GameWorkloadPolicy != nil || op.ArchitectureDrain) +} + // baselineStopTemplate uses only an owned running Pod and its verified snapshot. // An unversioned game retains its Kubernetes termination grace and receives no catalog commands. func (r *GameServerReconciler) baselineStopTemplate(ctx context.Context, gs *gameplanev1alpha1.GameServer) (*gameplanev1alpha1.GameTemplate, error) { @@ -362,7 +368,7 @@ func (r *GameServerReconciler) initializeTemplateBaseline(ctx context.Context, g } // A real spec edit after admission must render normally. Recording // its new inputs against the old workload would silently swallow it. - if r.GameWorkloadPolicy == nil && gs.Generation == op.Generation { + if !r.baselineNeedsDrain(op) && gs.Generation == op.Generation { inputs, err := r.baselineRenderInputs(gs, op.Token) if err != nil { return err @@ -372,7 +378,7 @@ func (r *GameServerReconciler) initializeTemplateBaseline(ctx context.Context, g gs.Annotations[baselineInputsAnnotation] = inputs } } - if r.GameWorkloadPolicy != nil { + if r.baselineNeedsDrain(op) { delete(gs.Annotations, baselineTemplateAnnotation) delete(gs.Annotations, baselineWorkloadAnnotation) delete(gs.Annotations, baselineInputsAnnotation) @@ -515,12 +521,12 @@ func observedTemplateRevision(ctx context.Context, reader client.Reader, gs *gam func (r *GameServerReconciler) templateWorkloadDrained(ctx context.Context, gs *gameplanev1alpha1.GameServer) (bool, error) { var ss appsv1.StatefulSet if err := r.wipeReader().Get(ctx, client.ObjectKeyFromObject(gs), &ss); err != nil { - if apierrors.IsNotFound(err) && r.GameWorkloadPolicy != nil { + if apierrors.IsNotFound(err) { op, held, err := lifecycleOwner(gs) if err != nil { return false, err } - if held && op.Kind == "Rollout" && op.Baseline { + if held && op.Kind == "Rollout" && r.baselineNeedsDrain(op) { // A new server has no workload to fence. A deleted StatefulSet // can leave a terminating Pod that still holds the world. return r.templateWritersGone(ctx, gs, nil) diff --git a/operator/internal/controller/gameserver_wipe.go b/operator/internal/controller/gameserver_wipe.go index e3414336a..aa4780e92 100644 --- a/operator/internal/controller/gameserver_wipe.go +++ b/operator/internal/controller/gameserver_wipe.go @@ -226,6 +226,9 @@ func (r *GameServerReconciler) createWipeJob( }, }, } + if err := r.GameWorkloadPolicy.placeFirstVolumeConsumer(ctx, r.wipeReader(), gs, tmpl, &job.Spec.Template.Spec); err != nil { + return err + } if err := controllerutil.SetControllerReference(gs, job, r.Scheme); err != nil { return err } diff --git a/operator/internal/controller/gameserver_wipe_test.go b/operator/internal/controller/gameserver_wipe_test.go index 7dd764961..be8d74f2c 100644 --- a/operator/internal/controller/gameserver_wipe_test.go +++ b/operator/internal/controller/gameserver_wipe_test.go @@ -224,13 +224,19 @@ func TestReconcileWipe_CreatesJobWhenPodGone(t *testing.T) { gs := wipeGameServer(true, "tok1") tmpl := &gameplanev1alpha1.GameTemplate{} tmpl.Name = "mc" + tmpl.Spec.RequiredNodeArchitecture = "amd64" // StatefulSet exists with replicas == 0 (pod is gone). ss := wipeStoppedSet(gs) ss.Status.Replicas = 0 - cl := fake.NewClientBuilder().WithScheme(s).WithObjects(gs, ss).Build() + pvc := &corev1.PersistentVolumeClaim{ObjectMeta: metav1.ObjectMeta{Name: "alpha-data", Namespace: "ns"}} + cl := fake.NewClientBuilder().WithScheme(s).WithObjects(gs, ss, pvc).Build() r := &GameServerReconciler{Client: cl, APIReader: cl, Scheme: s} - wipePasses(t, r, gs, 4) + for range 4 { + if err := r.reconcileWipe(t.Context(), gs, tmpl); err != nil { + t.Fatal(err) + } + } // Wipe job should be created once the pod is gone. var job batchv1.Job @@ -240,4 +246,7 @@ func TestReconcileWipe_CreatesJobWhenPodGone(t *testing.T) { if job.Labels[wipeTokenLabel] != "tok1" { t.Errorf("token label = %q, want tok1", job.Labels[wipeTokenLabel]) } + if job.Spec.Template.Spec.NodeSelector[corev1.LabelArchStable] != "amd64" { + t.Fatalf("wipe can bind an incompatible local volume: %v", job.Spec.Template.Spec.NodeSelector) + } } diff --git a/operator/internal/controller/lifecycle_operation.go b/operator/internal/controller/lifecycle_operation.go index c69078143..c2bbae359 100644 --- a/operator/internal/controller/lifecycle_operation.go +++ b/operator/internal/controller/lifecycle_operation.go @@ -45,6 +45,10 @@ type lifecycleIdentity struct { // Baseline establishes a first template pin without replacing an existing // workload. Durable intent prevents a leader restart turning it into a drain. Baseline bool `json:"baseline,omitempty"` + // ArchitectureDrain fences an existing unversioned Pod before first + // applying its template's architecture requirement. Keep this with the + // owner so stale renders and a new leader see the same decision. + ArchitectureDrain bool `json:"architectureDrain,omitempty"` } type lifecycleOperation struct { diff --git a/operator/internal/controller/restore_controller.go b/operator/internal/controller/restore_controller.go index 68c0eeb47..ab3c635cd 100644 --- a/operator/internal/controller/restore_controller.go +++ b/operator/internal/controller/restore_controller.go @@ -39,7 +39,8 @@ type RestoreReconciler struct { // registry mirror. Empty falls back to DefaultResticImage. ResticImage string // BackupResources shares the backup worker resource configuration. - BackupResources *corev1.ResourceRequirements + BackupResources *corev1.ResourceRequirements + GameWorkloadPolicy *GameWorkloadPolicy // JobBackoffLimit / JobActiveDeadlineSeconds bound the restic restore Job. // Set from operator flags; nil / zero fall back to // DefaultBackupJobBackoffLimit / DefaultBackupJobActiveDeadlineSeconds. @@ -274,6 +275,9 @@ func (r *RestoreReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ct job.Annotations = map[string]string{restoreTargetAnnotation: rs.Annotations[restoreTargetAnnotation]} job.Spec.Template.Labels = map[string]string{backupRestoreJobLabel: backupRestoreJobValue, restoreUIDLabel: string(rs.UID)} job.Spec.Template.Spec = r.buildRestorePodSpec(&rs, &src, &tmpl) + if err := r.GameWorkloadPolicy.placeFirstVolumeConsumer(ctx, r.apiReader(), &gs, &tmpl, &job.Spec.Template.Spec); err != nil { + return ctrl.Result{}, err + } if err := r.prepareRecoveryRestorePod(ctx, &rs, &job.Spec.Template.Spec); err != nil { return r.fail(ctx, &rs, err.Error()) } diff --git a/operator/internal/controller/restore_lifecycle_test.go b/operator/internal/controller/restore_lifecycle_test.go index dd4bc3627..ee55ab3cc 100644 --- a/operator/internal/controller/restore_lifecycle_test.go +++ b/operator/internal/controller/restore_lifecycle_test.go @@ -72,6 +72,43 @@ func lifecycleRestore(name string, uid types.UID) *gameplanev1alpha1.Restore { } } +func TestRestoreUsesGamePlacementOnlyForFirstVolumeConsumer(t *testing.T) { + for _, volume := range []string{"", "legacy-arm64-volume"} { + t.Run("volume="+volume, func(t *testing.T) { + policy, _, tmpl := gamePolicyFixture(t) + tmpl.Name = "game-template" + tmpl.Spec.RequiredNodeArchitecture = "amd64" + pvc := &corev1.PersistentVolumeClaim{ObjectMeta: metav1.ObjectMeta{Namespace: "ns", Name: "server-data"}, + Spec: corev1.PersistentVolumeClaimSpec{VolumeName: volume}} + r, gs, _ := restoreLifecycleFixture(t, tmpl, pvc) + r.GameWorkloadPolicy = policy + gs.Spec.TemplateRef.Name = tmpl.Name + gs.Spec.NodeSelector = map[string]string{"rack": "west"} + gs.Spec.Affinity = &corev1.Affinity{PodAntiAffinity: &corev1.PodAntiAffinity{}} + if err := r.Update(t.Context(), gs); err != nil { + t.Fatal(err) + } + lifecyclePasses(t, r, "first", 10) + jobs := lifecycleJobs(t, r) + if len(jobs) != 1 { + t.Fatalf("restore jobs: %v", jobs) + } + pod := jobs[0].Spec.Template.Spec + if volume != "" { + if len(pod.NodeSelector) != 0 || pod.Affinity != nil { + t.Fatalf("bound volume recovery acquired game node constraints: %+v", pod) + } + return + } + if pod.NodeSelector[corev1.LabelArchStable] != "amd64" || pod.NodeSelector["rack"] != "west" || + pod.NodeSelector[policy.PoolLabel] != policy.PoolValue || len(pod.Tolerations) != 1 || + pod.Affinity == nil || pod.Affinity.PodAntiAffinity == nil { + t.Fatalf("first consumer can bind outside game placement: %+v", pod) + } + }) + } +} + func TestPendingRestoreTemplateBindsBeforeCopyFailure(t *testing.T) { r, gs, rs := restoreLifecycleFixture(t) gs.Annotations = map[string]string{restoreGuardAnnotation: restoreIdentityJSON(rs.Name, rs.UID), restoreTemplateAnnotation: "missing-plan"} From b2997bdc8bfc9da1331a6817c442ea267788ffc6 Mon Sep 17 00:00:00 2001 From: Baylem Date: Sat, 14 Nov 2026 13:30:29 -0500 Subject: [PATCH 3/7] fix(operator): release backup and restore guards on placement conflicts Signed-off-by: Baylem --- .../controller/backup_budgets_test.go | 23 +++++++++++++ operator/internal/controller/backup_worker.go | 4 +++ .../controller/game_workload_policy.go | 10 +++--- .../internal/controller/restore_controller.go | 4 +++ .../controller/restore_lifecycle_test.go | 32 +++++++++++++++---- 5 files changed, 63 insertions(+), 10 deletions(-) diff --git a/operator/internal/controller/backup_budgets_test.go b/operator/internal/controller/backup_budgets_test.go index 14930e620..1d7e67ba4 100644 --- a/operator/internal/controller/backup_budgets_test.go +++ b/operator/internal/controller/backup_budgets_test.go @@ -327,6 +327,29 @@ func TestStoppedBackupFirstConsumerUsesGameArchitecture(t *testing.T) { } } +func TestStoppedBackupReleasesGuardOnFirstConsumerConflict(t *testing.T) { + r, _ := stoppedBackupFixture(t, true) + tmpl := &gameplanev1alpha1.GameTemplate{ObjectMeta: metav1.ObjectMeta{Name: "template"}, + Spec: gameplanev1alpha1.GameTemplateSpec{RequiredNodeArchitecture: "amd64"}} + if err := r.Create(t.Context(), tmpl); err != nil { + t.Fatal(err) + } + policy, _, _ := gamePolicyFixture(t) + policy.PoolLabel, policy.PoolValue = corev1.LabelArchStable, "arm64" + r.GameWorkloadPolicy = policy + budgetPass(t, r, "first") + budgetPass(t, r, "first") + b := guardGetBackup(t, r, "first") + var gs gameplanev1alpha1.GameServer + if err := r.Get(t.Context(), client.ObjectKey{Namespace: "ns", Name: "server"}, &gs); err != nil { + t.Fatal(err) + } + if b.Status.Phase != gameplanev1alpha1.BackupPhaseFailed || !strings.Contains(b.Status.Message, "amd64") || + gs.Annotations[lifecycleOperationAnnotation] != "" || gs.Annotations[backupGuardAnnotation] != "" { + t.Fatalf("placement conflict failed to release backup: %+v, %v", b.Status, gs.Annotations) + } +} + func TestBackupPreparedWorkerFailurePreservesJobMessage(t *testing.T) { r, _ := guardFixtureWorkers(t, false, guardBackup("failed-worker")) budgetPass(t, r, "failed-worker") diff --git a/operator/internal/controller/backup_worker.go b/operator/internal/controller/backup_worker.go index 30bac3d2d..0b6f65491 100644 --- a/operator/internal/controller/backup_worker.go +++ b/operator/internal/controller/backup_worker.go @@ -308,6 +308,10 @@ func (r *BackupReconciler) reconcilePreparedRestic(ctx context.Context, b *gamep if source.NodeName == "" { // A scheduled game Pod has already bound its mounted claims. if err := r.GameWorkloadPolicy.placeFirstVolumeConsumer(ctx, r.backupAPIReader(), bound, tmpl, &job.Spec.Template.Spec); err != nil { + var rejected workloadPolicyRejection + if errors.As(err, &rejected) { + return r.abortResticCopy(ctx, b, rejected.Error()) + } return ctrl.Result{}, err } } diff --git a/operator/internal/controller/game_workload_policy.go b/operator/internal/controller/game_workload_policy.go index b750bc24d..56f176c03 100644 --- a/operator/internal/controller/game_workload_policy.go +++ b/operator/internal/controller/game_workload_policy.go @@ -31,8 +31,8 @@ type GameWorkloadPolicy struct { MaxMemoryLimit resource.Quantity `json:"maxMemoryLimit"` } -// A rejected rollout must retain the effective template for the running -// game's stop sequence. The rejected target is never rendered or executed. +// A workload policy rejection is a permanent configuration error. Callers +// can safely stop the effective workload or release a failed worker's guard. type workloadPolicyRejection struct{ error } // reconcileRejectedGameWorkload permits a suspended, owned server to drain while its requested configuration is invalid. @@ -193,12 +193,14 @@ func (p *GameWorkloadPolicy) placeFirstVolumeConsumer(ctx context.Context, reade } var pvc corev1.PersistentVolumeClaim key := client.ObjectKey{Namespace: gs.Namespace, Name: volume.PersistentVolumeClaim.ClaimName} - if err := reader.Get(ctx, key, &pvc); err != nil { + // A claim can be created after the Job. Treat absence as unbound + // so the worker can wait for it within the ordinary Job deadline. + if err := reader.Get(ctx, key, &pvc); err != nil && !apierrors.IsNotFound(err) { return fmt.Errorf("read game volume %s before scheduling worker: %w", key, err) } if pvc.Spec.VolumeName == "" { if err := p.validatePlacement(gs, tmpl); err != nil { - return err + return workloadPolicyRejection{err} } pod.NodeSelector, pod.Tolerations = p.placement(gs, tmpl) pod.Affinity = hostportAffinity(gs) diff --git a/operator/internal/controller/restore_controller.go b/operator/internal/controller/restore_controller.go index ab3c635cd..1fee91a2d 100644 --- a/operator/internal/controller/restore_controller.go +++ b/operator/internal/controller/restore_controller.go @@ -276,6 +276,10 @@ func (r *RestoreReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ct job.Spec.Template.Labels = map[string]string{backupRestoreJobLabel: backupRestoreJobValue, restoreUIDLabel: string(rs.UID)} job.Spec.Template.Spec = r.buildRestorePodSpec(&rs, &src, &tmpl) if err := r.GameWorkloadPolicy.placeFirstVolumeConsumer(ctx, r.apiReader(), &gs, &tmpl, &job.Spec.Template.Spec); err != nil { + var rejected workloadPolicyRejection + if errors.As(err, &rejected) { + return r.fail(ctx, &rs, rejected.Error()) + } return ctrl.Result{}, err } if err := r.prepareRecoveryRestorePod(ctx, &rs, &job.Spec.Template.Spec); err != nil { diff --git a/operator/internal/controller/restore_lifecycle_test.go b/operator/internal/controller/restore_lifecycle_test.go index ee55ab3cc..84df44843 100644 --- a/operator/internal/controller/restore_lifecycle_test.go +++ b/operator/internal/controller/restore_lifecycle_test.go @@ -73,28 +73,48 @@ func lifecycleRestore(name string, uid types.UID) *gameplanev1alpha1.Restore { } func TestRestoreUsesGamePlacementOnlyForFirstVolumeConsumer(t *testing.T) { - for _, volume := range []string{"", "legacy-arm64-volume"} { - t.Run("volume="+volume, func(t *testing.T) { + for _, state := range []string{"unbound", "missing", "bound", "conflict"} { + t.Run(state, func(t *testing.T) { policy, _, tmpl := gamePolicyFixture(t) tmpl.Name = "game-template" tmpl.Spec.RequiredNodeArchitecture = "amd64" - pvc := &corev1.PersistentVolumeClaim{ObjectMeta: metav1.ObjectMeta{Namespace: "ns", Name: "server-data"}, - Spec: corev1.PersistentVolumeClaimSpec{VolumeName: volume}} - r, gs, _ := restoreLifecycleFixture(t, tmpl, pvc) + extras := []client.Object{tmpl} + if state != "missing" { + pvc := &corev1.PersistentVolumeClaim{ObjectMeta: metav1.ObjectMeta{Namespace: "ns", Name: "server-data"}} + if state == "bound" { + pvc.Spec.VolumeName = "legacy-arm64-volume" + } + extras = append(extras, pvc) + } + r, gs, rs := restoreLifecycleFixture(t, extras...) r.GameWorkloadPolicy = policy gs.Spec.TemplateRef.Name = tmpl.Name gs.Spec.NodeSelector = map[string]string{"rack": "west"} + if state == "conflict" { + gs.Spec.NodeSelector[corev1.LabelArchStable] = "arm64" + } gs.Spec.Affinity = &corev1.Affinity{PodAntiAffinity: &corev1.PodAntiAffinity{}} if err := r.Update(t.Context(), gs); err != nil { t.Fatal(err) } lifecyclePasses(t, r, "first", 10) jobs := lifecycleJobs(t, r) + if state == "conflict" { + if err := r.Get(t.Context(), client.ObjectKeyFromObject(rs), rs); err != nil { + t.Fatal(err) + } + target := lifecycleServer(t, r) + if rs.Status.Phase != gameplanev1alpha1.RestorePhaseFailed || len(jobs) != 0 || + target.Annotations[lifecycleOperationAnnotation] != "" || target.Annotations[restoreGuardAnnotation] != "" { + t.Fatalf("placement conflict failed to release restore: %+v, %v", rs.Status, target.Annotations) + } + return + } if len(jobs) != 1 { t.Fatalf("restore jobs: %v", jobs) } pod := jobs[0].Spec.Template.Spec - if volume != "" { + if state == "bound" { if len(pod.NodeSelector) != 0 || pod.Affinity != nil { t.Fatalf("bound volume recovery acquired game node constraints: %+v", pod) } From df69168a2301cd7d447585865cfa41ab95746a32 Mon Sep 17 00:00:00 2001 From: Baylem Date: Sat, 14 Nov 2026 13:58:10 -0500 Subject: [PATCH 4/7] fix(ci): defer the catalog pin until module PR 68 lands Keep the released catalog ancestry on the platform branch. Document the placement workaround until operators can install the updated templates. Signed-off-by: Baylem --- containers/README.md | 2 +- modules | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/containers/README.md b/containers/README.md index d0f9db787..1cc3d90b4 100644 --- a/containers/README.md +++ b/containers/README.md @@ -228,7 +228,7 @@ docker run -it \ The SteamCMD base requires `linux/amd64`. Bash and dpkg are x86-64 executables, and SteamCMD is a 32-bit Intel executable. Workers must support both x86 ABIs. The published game images in this workflow also target `linux/amd64`. -Squad, The Isle, Mount & Blade II Bannerlord and Nuclear Option inherit this base. ARK Survival Evolved moved to `hermsi/ark-server`; its catalog pin also requires amd64. On mixed clusters these games need an eligible amd64 worker with access to their volume. The official templates declare `spec.requiredNodeArchitecture: amd64`. For older templates and operators, set `spec.nodeSelector["kubernetes.io/arch"]` to `amd64` on each affected GameServer before starting it. +Squad, The Isle, Mount & Blade II Bannerlord and Nuclear Option inherit this base. ARK Survival Evolved moved to `hermsi/ark-server`; its catalog pin also requires amd64. On mixed clusters these games need an eligible amd64 worker with access to their volume. Check the installed GameTemplate for `spec.requiredNodeArchitecture: amd64`. Until both the operator and the installed template enforce that requirement, set `spec.nodeSelector["kubernetes.io/arch"]` to `amd64` on each affected GameServer before starting it. Publishing a corrected base changes future builds. Previously published indices and digest-pinned game images retain their original contents. In particular, the old common-base index `sha256:7cc7c2a9f45a6f0f69654517666de75db944e08ff110028a2586eaca77287801` advertises an ARM64 child containing Intel executables. Rebuild downstream images from the corrected signed base, record their signed digests, and update the module pins and any local overrides. Install the compatible operator and CRDs before adopting the updated module bundles. diff --git a/modules b/modules index 4590865ed..a660997ca 160000 --- a/modules +++ b/modules @@ -1 +1 @@ -Subproject commit 4590865ed27bd845d241aa47caa61bdea396b221 +Subproject commit a660997ca02987d3ff3ea0f2c635d2e29f074cdb From e68aba25c9184a8a33d042f0c6144814d16aed97 Mon Sep 17 00:00:00 2001 From: Baylem Date: Sat, 14 Nov 2026 17:09:48 -0500 Subject: [PATCH 5/7] fix(operator): guard Hostport rollouts and first volume placement Check the recorded endpoint before draining a game, apply effective placement to first volume consumers on legacy templates, and settle unstarted or canceled wipes under rejected placement. Document the admission and recovery rules and exercise each path. Signed-off-by: Baylem --- containers/README.md | 2 +- i18n/locales/en/app.json | 4 + i18n/locales/fr/.review.json | 1 + i18n/locales/fr/app.json | 4 + operator/hack/condition-ids/main.go | 1 + .../controller/game_workload_policy.go | 35 +++++++- .../controller/gameserver_hostport.go | 19 +++++ .../controller/gameserver_hostport_test.go | 80 +++++++++++++++++++ .../gameserver_template_revision.go | 22 +++-- .../gameserver_template_revision_test.go | 75 +++++++++++++++++ .../internal/controller/gameserver_wipe.go | 46 ++++++++++- .../controller/gameserver_wipe_guard_test.go | 80 +++++++++++++++++++ operator/internal/controller/owned_delete.go | 4 +- .../controller/restore_lifecycle_test.go | 38 +++++++++ operator/specs.md | 47 +++++++++-- 15 files changed, 437 insertions(+), 21 deletions(-) diff --git a/containers/README.md b/containers/README.md index 1cc3d90b4..97ab701f3 100644 --- a/containers/README.md +++ b/containers/README.md @@ -228,7 +228,7 @@ docker run -it \ The SteamCMD base requires `linux/amd64`. Bash and dpkg are x86-64 executables, and SteamCMD is a 32-bit Intel executable. Workers must support both x86 ABIs. The published game images in this workflow also target `linux/amd64`. -Squad, The Isle, Mount & Blade II Bannerlord and Nuclear Option inherit this base. ARK Survival Evolved moved to `hermsi/ark-server`; its catalog pin also requires amd64. On mixed clusters these games need an eligible amd64 worker with access to their volume. Check the installed GameTemplate for `spec.requiredNodeArchitecture: amd64`. Until both the operator and the installed template enforce that requirement, set `spec.nodeSelector["kubernetes.io/arch"]` to `amd64` on each affected GameServer before starting it. +Squad, The Isle, Mount & Blade II Bannerlord and Nuclear Option inherit this base. ARK Survival Evolved moved to `hermsi/ark-server`; its catalog pin also requires amd64. On mixed clusters these games need an eligible amd64 worker with access to their volume. Check the installed GameTemplate for `spec.requiredNodeArchitecture: amd64`. For older templates, set `spec.nodeSelector["kubernetes.io/arch"]` to `amd64` on each affected GameServer. Upgrade the operator before allowing a restore, wipe, or stopped-server backup to provision local storage. Older operators can bind an empty claim on a worker outside the game's selector. Publishing a corrected base changes future builds. Previously published indices and digest-pinned game images retain their original contents. In particular, the old common-base index `sha256:7cc7c2a9f45a6f0f69654517666de75db944e08ff110028a2586eaca77287801` advertises an ARM64 child containing Intel executables. Rebuild downstream images from the corrected signed base, record their signed digests, and update the module pins and any local overrides. Install the compatible operator and CRDs before adopting the updated module bundles. diff --git a/i18n/locales/en/app.json b/i18n/locales/en/app.json index 24391550f..c8a25aed4 100644 --- a/i18n/locales/en/app.json +++ b/i18n/locales/en/app.json @@ -243,6 +243,10 @@ "defaultMessage": "The data wipe job did not complete. The volume may not be fully cleared.", "description": "DataWipe condition when the wipe job fails." }, + "condition.datawipe.placementrejected": { + "defaultMessage": "The data wipe could not start. Correct the worker placement settings before requesting another wipe.", + "description": "DataWipe condition when worker placement prevents the wipe from starting." + }, "condition.failed.capture_already_in_progress": { "defaultMessage": "Another capture is already running on this server.", "description": "Failed condition when two captures target one server." diff --git a/i18n/locales/fr/.review.json b/i18n/locales/fr/.review.json index c967f3b3c..f2fd0d718 100644 --- a/i18n/locales/fr/.review.json +++ b/i18n/locales/fr/.review.json @@ -49,6 +49,7 @@ "condition.consistency.quiesced": "7bf8d77f8a05", "condition.consistency.stoppedsource": "f1233d8fcfd7", "condition.datawipe.jobfailed": "f1c100d69216", + "condition.datawipe.placementrejected": "de596cdac055", "condition.failed.capture_already_in_progress": "8c6c3fb2a7bb", "condition.failed.failed": "a2f668070978", "condition.failed.podrestarted": "3db5afb8b7de", diff --git a/i18n/locales/fr/app.json b/i18n/locales/fr/app.json index 3054a67b6..00599fd64 100644 --- a/i18n/locales/fr/app.json +++ b/i18n/locales/fr/app.json @@ -183,6 +183,10 @@ "defaultMessage": "La tâche d'effacement des données ne s'est pas terminée. Le volume n'est peut-être pas entièrement vidé.", "description": "DataWipe condition when the wipe job fails." }, + "condition.datawipe.placementrejected": { + "defaultMessage": "L’effacement des données n’a pas pu démarrer. Corrigez les paramètres de placement sur les nœuds avant de demander un nouvel effacement.", + "description": "DataWipe condition when worker placement prevents the wipe from starting." + }, "condition.failed.capture_already_in_progress": { "defaultMessage": "Une autre capture est déjà en cours sur ce serveur.", "description": "Failed condition when two captures target one server." diff --git a/operator/hack/condition-ids/main.go b/operator/hack/condition-ids/main.go index ce35a46aa..d682ae7be 100644 --- a/operator/hack/condition-ids/main.go +++ b/operator/hack/condition-ids/main.go @@ -164,6 +164,7 @@ var rows = []row{ {types: []string{"TunnelAddressInvalid"}, reason: "ValidationFailed", english: "Some tunnel endpoints were rejected: {details}", description: "Condition when endpoints reported by the playit tunnel pod fail validation. details is the English validation text."}, {types: []string{"IdleScheduleInvalid"}, reason: "WakeWindowUnparseable", english: "A wake window in the idle schedule cannot be parsed: {details}", description: "Condition when spec.idle has an invalid wake window. details is the English parse error."}, {types: []string{"DataWipe"}, reason: "JobFailed", english: "The data wipe job did not complete. The volume may not be fully cleared.", description: "DataWipe condition when the wipe job fails."}, + {types: []string{"DataWipe"}, reason: "PlacementRejected", english: "The data wipe could not start. Correct the worker placement settings before requesting another wipe.", description: "DataWipe condition when worker placement prevents the wipe from starting."}, // Backup, Restore, Unquiesced, SnapshotForgotten (Type Completed is shared) {types: []string{"Completed"}, reason: "Succeeded", english: "The backup or restore completed successfully.", description: "Completed condition on a Backup or Restore that finished."}, diff --git a/operator/internal/controller/game_workload_policy.go b/operator/internal/controller/game_workload_policy.go index 56f176c03..5dde276a1 100644 --- a/operator/internal/controller/game_workload_policy.go +++ b/operator/internal/controller/game_workload_policy.go @@ -40,6 +40,18 @@ func (r *GameServerReconciler) reconcileRejectedGameWorkload(ctx context.Context effective *gameplanev1alpha1.GameTemplate, rejection error, ) (ctrl.Result, error) { var result ctrl.Result + var wipeState wipeWorkerState + if gs.Annotations[wipeGuardAnnotation] != "" { + // Validation normally returns before the wipe controller gets a turn. + // Settle cancellation or failure under the existing owner without launching a Job. + version := gs.ResourceVersion + if err := r.advanceWipe(ctx, gs, effective, &wipeState, false); err != nil { + return requeueOnConflict(result, err) + } + if gs.ResourceVersion != version { + return ctrl.Result{RequeueAfter: reconcileRetryInterval}, nil + } + } if gs.Spec.Suspend { key := client.ObjectKeyFromObject(gs) var live gameplanev1alpha1.GameServer @@ -50,6 +62,14 @@ func (r *GameServerReconciler) reconcileRejectedGameWorkload(ctx context.Context live.Annotations[effectiveTemplateAnnotation] != gs.Annotations[effectiveTemplateAnnotation] { return ctrl.Result{RequeueAfter: reconcileRetryInterval}, nil } + if live.Spec.Networking.Expose == "Hostport" { + // Explicit endpoint migration must be able to release a sleeping + // server's host ports even while its template is inadmissible. + waker := &appsv1.Deployment{ObjectMeta: metav1.ObjectMeta{Namespace: live.Namespace, Name: live.Name + "-waker"}} + if err := r.deleteIfControlledBy(ctx, &live, waker, client.PropagationPolicy(metav1.DeletePropagationForeground)); err != nil { + return requeueOnConflict(result, err) + } + } var ss appsv1.StatefulSet err := r.wipeReader().Get(ctx, key, &ss) if err != nil && !apierrors.IsNotFound(err) { @@ -72,7 +92,7 @@ func (r *GameServerReconciler) reconcileRejectedGameWorkload(ctx context.Context // stop can still drain it while the new baseline is inadmissible. replicas, result.RequeueAfter, err = r.softStop(ctx, &live, effective) } else { - replicas, result.RequeueAfter, err = r.desiredReplicas(ctx, &live, effective, idleAwake) + replicas, result.RequeueAfter, err = r.desiredReplicas(ctx, &live, effective, idleAwake, &wipeState) } if err != nil { return requeueOnConflict(result, err) @@ -88,6 +108,12 @@ func (r *GameServerReconciler) reconcileRejectedGameWorkload(ctx context.Context } } } + // Orphan wipe Pods do not enqueue this server after their Job is gone. + // Continue polling their drain even after the StatefulSet has scaled to zero. + if gs.Annotations[wipeGuardAnnotation] != "" && (result.RequeueAfter == 0 || result.RequeueAfter > wipeDrainPoll) && + !r.settledWipeFailure(ctx, gs, &wipeState) { + result.RequeueAfter = wipeDrainPoll + } return result, r.setPhase(ctx, gs, rejection.Error()) } @@ -184,7 +210,9 @@ func (p *GameWorkloadPolicy) placement(gs *gameplanev1alpha1.GameServer, tmpl *g // A worker can be the first consumer of a suspended game's local storage. // Already-bound claims retain their volume topology so legacy data can be recovered. func (p *GameWorkloadPolicy) placeFirstVolumeConsumer(ctx context.Context, reader client.Reader, gs *gameplanev1alpha1.GameServer, tmpl *gameplanev1alpha1.GameTemplate, pod *corev1.PodSpec) error { - if tmpl.Spec.RequiredNodeArchitecture == "" { + selector, tolerations := p.placement(gs, tmpl) + affinity := hostportAffinity(gs) + if len(selector) == 0 && len(tolerations) == 0 && affinity == nil { return nil } for _, volume := range pod.Volumes { @@ -202,8 +230,7 @@ func (p *GameWorkloadPolicy) placeFirstVolumeConsumer(ctx context.Context, reade if err := p.validatePlacement(gs, tmpl); err != nil { return workloadPolicyRejection{err} } - pod.NodeSelector, pod.Tolerations = p.placement(gs, tmpl) - pod.Affinity = hostportAffinity(gs) + pod.NodeSelector, pod.Tolerations, pod.Affinity = selector, tolerations, affinity break } } diff --git a/operator/internal/controller/gameserver_hostport.go b/operator/internal/controller/gameserver_hostport.go index 13e3ebe44..3c61136a3 100644 --- a/operator/internal/controller/gameserver_hostport.go +++ b/operator/internal/controller/gameserver_hostport.go @@ -48,6 +48,25 @@ func (r *GameServerReconciler) hostportEndpointNode(ctx context.Context, gs *gam return &node, nil } +// An architecture change cannot silently move the address players use. +// Missing, replaced and deleting nodes still follow the Hostport identity-loss fence. +func (r *GameServerReconciler) validateHostportArchitecture(ctx context.Context, gs *gameplanev1alpha1.GameServer, tmpl *gameplanev1alpha1.GameTemplate) error { + required := tmpl.Spec.RequiredNodeArchitecture + if required == "" || gs.Spec.Networking.Expose != "Hostport" || gs.Annotations[hostportNodeAnnotation] == "" { + return nil + } + node, err := r.hostportEndpointNode(ctx, gs) + if err != nil || node == nil { + return err + } + if arch := node.Labels[corev1.LabelArchStable]; arch != required { + return workloadPolicyRejection{fmt.Errorf( + "recorded Hostport endpoint node %q has %s=%q but the template requires %q. Explicitly migrate the endpoint to a compatible worker", + node.Name, corev1.LabelArchStable, arch, required)} + } + return nil +} + func hostportNodeReady(node *corev1.Node) bool { for _, condition := range node.Status.Conditions { if condition.Type == corev1.NodeReady { diff --git a/operator/internal/controller/gameserver_hostport_test.go b/operator/internal/controller/gameserver_hostport_test.go index fc19f5116..3a22d8058 100644 --- a/operator/internal/controller/gameserver_hostport_test.go +++ b/operator/internal/controller/gameserver_hostport_test.go @@ -1,6 +1,8 @@ package controller import ( + "context" + "errors" "testing" appsv1 "k8s.io/api/apps/v1" @@ -8,6 +10,7 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/client/interceptor" gameplanev1alpha1 "github.com/GameplanePanel/gameplane/operator/api/v1alpha1" ) @@ -113,6 +116,83 @@ func TestHostportNodeLossAndUnschedulableListenerStayUnavailable(t *testing.T) { } } +func TestHostportArchitectureDefersToEndpointIdentityChecks(t *testing.T) { + r, gs, tmpl := hostportFixture(t) + tmpl.Spec.RequiredNodeArchitecture = "amd64" + gs.Annotations = map[string]string{hostportNodeAnnotation: "node-a", hostportNodeUIDAnnotation: "previous-uid"} + // A replacement with the same name must still trigger the identity-loss + // stop, even when the replacement lacks the required architecture label. + if err := r.validateHostportArchitecture(t.Context(), gs, tmpl); err != nil { + t.Fatal(err) + } + plan, err := r.planHostportSentinel(t.Context(), gs, idleAwake) + if err != nil || !plan.blockGame || plan.hostportCondition.Reason != "EndpointNodeUnavailable" { + t.Fatalf("lost the endpoint identity fence: %+v, %v", plan, err) + } + + lookupErr := errors.New("node read temporarily unavailable") + r.APIReader = fake.NewClientBuilder().WithScheme(r.Scheme).WithInterceptorFuncs(interceptor.Funcs{ + Get: func(context.Context, client.WithWatch, client.ObjectKey, client.Object, ...client.GetOption) error { + return lookupErr + }, + }).Build() + var rejected workloadPolicyRejection + err = r.validateHostportArchitecture(t.Context(), gs, tmpl) + if !errors.Is(err, lookupErr) || errors.As(err, &rejected) { + t.Fatalf("node lookup failure must remain retryable: %v", err) + } +} + +func TestRejectedHostportDrainsOnlySuspendedOwnedWaker(t *testing.T) { + for _, tc := range []struct { + name string + suspended bool + foreign bool + }{ + {name: "sleeping server keeps its listener"}, + {name: "suspending drains the listener", suspended: true}, + {name: "foreign listener retained", suspended: true, foreign: true}, + } { + t.Run(tc.name, func(t *testing.T) { + ctx := t.Context() + r, gs, tmpl := revisionFixture(t) + gs.Spec.Networking.Expose = "Hostport" + gs.Spec.Suspend = tc.suspended + if err := r.Update(ctx, gs); err != nil { + t.Fatal(err) + } + owner := metav1.NewControllerRef(gs, gameplanev1alpha1.GroupVersion.WithKind("GameServer")) + if tc.foreign { + owner.UID = "foreign" + } + waker := &appsv1.Deployment{ObjectMeta: metav1.ObjectMeta{Name: gs.Name + "-waker", Namespace: gs.Namespace, + UID: "waker", OwnerReferences: []metav1.OwnerReference{*owner}}} + if err := r.Create(ctx, waker); err != nil { + t.Fatal(err) + } + deleted := false + r.Client = interceptor.NewClient(r.Client.(client.WithWatch), interceptor.Funcs{ + Delete: func(ctx context.Context, c client.WithWatch, obj client.Object, opts ...client.DeleteOption) error { + options := (&client.DeleteOptions{}).ApplyOptions(opts) + if options.PropagationPolicy == nil || *options.PropagationPolicy != metav1.DeletePropagationForeground || + options.Preconditions == nil || options.Preconditions.UID == nil || *options.Preconditions.UID != waker.UID || + options.Preconditions.ResourceVersion == nil || *options.Preconditions.ResourceVersion != waker.ResourceVersion { + t.Fatalf("missing foreground or identity preconditions: %+v", options) + } + deleted = true + return c.Delete(ctx, obj, opts...) + }, + }) + if _, err := r.reconcileRejectedGameWorkload(ctx, gs, tmpl, errors.New("endpoint architecture mismatch")); err != nil { + t.Fatal(err) + } + if deleted != (tc.suspended && !tc.foreign) { + t.Fatalf("unexpected listener deletion: %t", deleted) + } + }) + } +} + func TestHostportAffinityConjoinsEveryAlternativeAndPreservesOtherConstraints(t *testing.T) { gs := &gameplanev1alpha1.GameServer{ObjectMeta: metav1.ObjectMeta{Annotations: map[string]string{hostportNodeAnnotation: "node-a"}}, Spec: gameplanev1alpha1.GameServerSpec{Networking: gameplanev1alpha1.GameServerNetworking{Expose: "Hostport"}, Affinity: &corev1.Affinity{NodeAffinity: &corev1.NodeAffinity{RequiredDuringSchedulingIgnoredDuringExecution: &corev1.NodeSelector{NodeSelectorTerms: []corev1.NodeSelectorTerm{{MatchExpressions: []corev1.NodeSelectorRequirement{{Key: "pool", Operator: corev1.NodeSelectorOpIn, Values: []string{"a"}}}}, {MatchExpressions: []corev1.NodeSelectorRequirement{{Key: "pool", Operator: corev1.NodeSelectorOpIn, Values: []string{"b"}}}}}}}, PodAntiAffinity: &corev1.PodAntiAffinity{}}}} got := hostportAffinity(gs) diff --git a/operator/internal/controller/gameserver_template_revision.go b/operator/internal/controller/gameserver_template_revision.go index d715c140d..ff5aefc6f 100644 --- a/operator/internal/controller/gameserver_template_revision.go +++ b/operator/internal/controller/gameserver_template_revision.go @@ -183,6 +183,17 @@ func (r *GameServerReconciler) reconcileTemplateRevision(ctx context.Context, gs if err != nil || !ready { return effective, true, err } + target := effective + if !op.Baseline && op.Token != pin { + // The admitted target survives a subsequent catalog update. + target, err = loadTemplateSnapshot(ctx, r.wipeReader(), gs, op.Token) + if err != nil { + return nil, false, err + } + } + if err := r.validateHostportArchitecture(ctx, gs, target); err != nil { + return effective, false, err + } if op.Baseline { if r.baselineNeedsDrain(op) { drained, err := r.templateWorkloadDrained(ctx, gs) @@ -195,11 +206,6 @@ func (r *GameServerReconciler) reconcileTemplateRevision(ctx context.Context, gs return effective, true, r.initializeTemplateBaseline(ctx, gs, op) } if op.Token != pin { - // The admitted target survives a subsequent catalog update. - target, err := loadTemplateSnapshot(ctx, r.wipeReader(), gs, op.Token) - if err != nil { - return nil, false, err - } if err := validateTemplateTransition(gs, effective, target); err != nil { return nil, false, err } @@ -263,6 +269,9 @@ func (r *GameServerReconciler) reconcileTemplateRevision(ctx context.Context, gs admit = false } if admit { + if err := r.validateHostportArchitecture(ctx, gs, target); err != nil { + return effective, false, err + } if err := validateTemplateTransition(gs, effective, target); err != nil { return nil, false, err } @@ -295,6 +304,9 @@ func (r *GameServerReconciler) reconcileTemplateRevision(ctx context.Context, gs return effective, claimed, err } } + if err := r.validateHostportArchitecture(ctx, gs, effective); err != nil { + return effective, false, err + } return effective, false, r.pruneTemplateSnapshots(ctx, gs) } diff --git a/operator/internal/controller/gameserver_template_revision_test.go b/operator/internal/controller/gameserver_template_revision_test.go index 53e73271b..5ddb69e52 100644 --- a/operator/internal/controller/gameserver_template_revision_test.go +++ b/operator/internal/controller/gameserver_template_revision_test.go @@ -3,6 +3,7 @@ package controller import ( "context" "encoding/json" + "strings" "testing" appsv1 "k8s.io/api/apps/v1" @@ -13,6 +14,7 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/util/intstr" + ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client/fake" @@ -859,3 +861,76 @@ func TestTemplateRevisionRejectsRestrictedIncompatibleTargetBeforeAdmission(t *t t.Fatal("invalid security profile changed the pin or admitted a drain") } } + +func TestHostportTemplateArchitectureRejectsRolloutBeforeDrain(t *testing.T) { + for _, tc := range []struct { + name string + baseline bool + admitted bool + }{ + {name: "initial baseline", baseline: true}, + {name: "revision upgrade"}, + {name: "resumed baseline", baseline: true, admitted: true}, + {name: "resumed revision upgrade", admitted: true}, + } { + t.Run(tc.name, func(t *testing.T) { + ctx := t.Context() + r, gs, tmpl := revisionFixture(t) + if err := r.reconcileStatefulSet(ctx, gs, tmpl, nil, &materializedConfig{}, 1); err != nil { + t.Fatal(err) + } + if tc.baseline { + delete(gs.Annotations, effectiveTemplateAnnotation) + } + pin := gs.Annotations[effectiveTemplateAnnotation] + node := &corev1.Node{ObjectMeta: metav1.ObjectMeta{Name: "worker", UID: "original", Labels: map[string]string{corev1.LabelArchStable: "amd64"}}} + if err := r.Create(ctx, node); err != nil { + t.Fatal(err) + } + gs.Spec.Networking.Expose = "Hostport" + gs.Spec.TemplateRollout.Policy = "Automatic" + gs.Annotations[hostportNodeAnnotation] = node.Name + gs.Annotations[hostportNodeUIDAnnotation] = string(node.UID) + if err := r.Update(ctx, gs); err != nil { + t.Fatal(err) + } + tmpl.Spec.RequiredNodeArchitecture = "amd64" + if err := r.Update(ctx, tmpl); err != nil { + t.Fatal(err) + } + if tc.admitted { + if _, changed, err := r.reconcileTemplateRevision(ctx, gs); err != nil || !changed || gs.Annotations[lifecycleOperationAnnotation] == "" { + t.Fatalf("matching endpoint was not admitted: %v", err) + } + } + owner := gs.Annotations[lifecycleOperationAnnotation] + node.Labels[corev1.LabelArchStable] = "arm64" + if err := r.Update(ctx, node); err != nil { + t.Fatal(err) + } + key := client.ObjectKeyFromObject(gs) + if _, err := r.Reconcile(ctx, ctrl.Request{NamespacedName: key}); err != nil { + t.Fatal(err) + } + if err := r.Get(ctx, key, gs); err != nil { + t.Fatal(err) + } + ready := meta.FindStatusCondition(gs.Status.Conditions, "Ready") + if ready == nil || ready.Status != metav1.ConditionFalse || !strings.Contains(ready.Message, "arm64") || + !strings.Contains(ready.Message, "amd64") || !strings.Contains(ready.Message, "migrate") { + t.Fatalf("missing endpoint migration instructions: %+v", ready) + } + if gs.Annotations[effectiveTemplateAnnotation] != pin || gs.Annotations[lifecycleOperationAnnotation] != owner || + gs.Annotations[hostportNodeAnnotation] != node.Name || gs.Annotations[hostportNodeUIDAnnotation] != string(node.UID) { + t.Fatalf("incompatible revision changed the pin, rollout owner or endpoint: %+v", gs.Annotations) + } + var ss appsv1.StatefulSet + if err := r.Get(ctx, key, &ss); err != nil { + t.Fatal(err) + } + if ss.Spec.Replicas == nil || *ss.Spec.Replicas != 1 || ss.Spec.Template.Spec.NodeSelector[corev1.LabelArchStable] != "" { + t.Fatalf("incompatible rollout changed the existing StatefulSet: %+v", ss.Spec) + } + }) + } +} diff --git a/operator/internal/controller/gameserver_wipe.go b/operator/internal/controller/gameserver_wipe.go index aa4780e92..28f90e76e 100644 --- a/operator/internal/controller/gameserver_wipe.go +++ b/operator/internal/controller/gameserver_wipe.go @@ -2,6 +2,7 @@ package controller import ( "context" + "errors" "fmt" batchv1 "k8s.io/api/batch/v1" @@ -43,7 +44,13 @@ func (r *GameServerReconciler) reconcileWipe( ctx context.Context, gs *gameplanev1alpha1.GameServer, tmpl *gameplanev1alpha1.GameTemplate, inventory ...*wipeWorkerState, ) error { - state := wipeInventory(inventory) + return r.advanceWipe(ctx, gs, tmpl, wipeInventory(inventory), true) +} + +func (r *GameServerReconciler) advanceWipe(ctx context.Context, gs *gameplanev1alpha1.GameServer, + tmpl *gameplanev1alpha1.GameTemplate, state *wipeWorkerState, allowLaunch bool, +) error { + version := gs.ResourceVersion changed, err := r.ensureWipeGuard(ctx, gs, state) if apierrors.IsNotFound(err) { return nil @@ -51,6 +58,10 @@ func (r *GameServerReconciler) reconcileWipe( if err != nil { return err } + if !allowLaunch && gs.ResourceVersion != version { + // A fresh pass must validate the changed server before rejecting its wipe. + return nil + } if gs.Annotations[restoreGuardAnnotation] != "" || gs.Annotations[backupGuardAnnotation] != "" { return nil } @@ -132,6 +143,12 @@ func (r *GameServerReconciler) reconcileWipe( if state.busy { return nil } + if !allowLaunch { + if err := r.GameWorkloadPolicy.validatePlacement(gs, tmpl); err != nil { + return r.rejectUnstartedWipe(ctx, gs, guard, err) + } + return nil + } stopped, err := r.wipeTargetStopped(ctx, gs) if err != nil || !stopped { return err @@ -148,7 +165,32 @@ func (r *GameServerReconciler) reconcileWipe( if ready, err := wipeLifecycleReady(&live, guard); err != nil || !ready { return err } - return r.createWipeJob(ctx, &live, tmpl, jobName, guard) + err = r.createWipeJob(ctx, &live, tmpl, jobName, guard) + var rejected workloadPolicyRejection + if errors.As(err, &rejected) { + err = r.rejectUnstartedWipe(ctx, &live, guard, rejected) + *gs = live + } + return err +} + +// The current owner is ready, and inventory found no Job or live wipe worker. +// Record rejection before consuming the request. A crash after the checked +// Update resumes ordinary cancellation, never success or another wipe launch. +func (r *GameServerReconciler) rejectUnstartedWipe(ctx context.Context, gs *gameplanev1alpha1.GameServer, token string, reason error) error { + base := gs.DeepCopy() + meta.SetStatusCondition(&gs.Status.Conditions, metav1.Condition{ + Type: gameplanev1alpha1.GameServerConditionDataWipe, Status: metav1.ConditionFalse, + Reason: "PlacementRejected", Message: reason.Error(), ObservedGeneration: gs.Generation, + }) + if err := r.Status().Patch(ctx, gs, client.MergeFromWithOptions(base, client.MergeFromWithOptimisticLock{})); err != nil { + return err + } + delete(gs.Annotations, WipeRequestedAnnotation) + if err := r.Update(ctx, gs); err != nil { + return err + } + return r.releaseWipeGuard(ctx, gs, token, false) } func (r *GameServerReconciler) createWipeJob( diff --git a/operator/internal/controller/gameserver_wipe_guard_test.go b/operator/internal/controller/gameserver_wipe_guard_test.go index 330786b28..19f031d3c 100644 --- a/operator/internal/controller/gameserver_wipe_guard_test.go +++ b/operator/internal/controller/gameserver_wipe_guard_test.go @@ -10,6 +10,7 @@ import ( batchv1 "k8s.io/api/batch/v1" corev1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" @@ -49,6 +50,85 @@ func wipeCurrent(t *testing.T, c client.Client, gs *gameplanev1alpha1.GameServer return ¤t } +func TestWipePlacementRejectionSettlesUnstartedRequest(t *testing.T) { + for _, scenario := range []string{"pending", "canceled", "failed job", "orphan pod"} { + t.Run(scenario, func(t *testing.T) { + gs := wipeGameServer(true, "current") + gs.Spec.NodeSelector = map[string]string{corev1.LabelArchStable: "arm64"} + gs.Annotations[wipeGuardAnnotation] = "current" + gs.Annotations[lifecycleOperationAnnotation] = lifecycleOperationJSON(lifecycleOperation{lifecycleIdentity: wipeLifecycleIdentity(gs, "current")}) + tmpl := &gameplanev1alpha1.GameTemplate{ObjectMeta: metav1.ObjectMeta{Name: gs.Spec.TemplateRef.Name}} + tmpl.Spec.RequiredNodeArchitecture = "amd64" + objects := []client.Object{gs, tmpl, wipeStoppedSet(gs)} + s := wipeScheme(t) + switch scenario { + case "canceled": + delete(gs.Annotations, WipeRequestedAnnotation) + case "failed job": + job := &batchv1.Job{ObjectMeta: metav1.ObjectMeta{Namespace: gs.Namespace, Name: gs.Name + "-wipe", Labels: map[string]string{wipeTokenLabel: "current"}}} + if err := controllerutil.SetControllerReference(gs, job, s); err != nil { + t.Fatal(err) + } + job.Status.Conditions = []batchv1.JobCondition{{Type: batchv1.JobFailed, Status: corev1.ConditionTrue}} + objects = append(objects, job) + case "orphan pod": + objects = append(objects, &corev1.Pod{ObjectMeta: metav1.ObjectMeta{Namespace: gs.Namespace, Name: "orphan", Labels: map[string]string{wipeUIDLabel: string(gs.UID)}}, Status: corev1.PodStatus{Phase: corev1.PodRunning}}) + } + c := fake.NewClientBuilder().WithScheme(s).WithObjects(objects...).WithStatusSubresource(gs).Build() + r := &GameServerReconciler{Client: c, APIReader: c, Scheme: s} + for range 2 { + if _, err := r.Reconcile(t.Context(), ctrl.Request{NamespacedName: client.ObjectKeyFromObject(gs)}); err != nil { + t.Fatal(err) + } + } + live := wipeCurrent(t, c, gs) + if !live.Spec.Suspend || live.Annotations[WipeCompletedAnnotation] != "" { + t.Fatal("unsuccessful wipe acknowledged or game resumed") + } + if scenario == "failed job" || scenario == "orphan pod" { + if live.Annotations[wipeGuardAnnotation] != "current" || !pendingWipe(live) { + t.Fatal("existing worker lost its guard") + } + if scenario == "failed job" { + return + } + delete(live.Annotations, WipeRequestedAnnotation) + if err := c.Update(t.Context(), live); err != nil { + t.Fatal(err) + } + req := ctrl.Request{NamespacedName: client.ObjectKeyFromObject(gs)} + result, err := r.Reconcile(t.Context(), req) + if err != nil || result.RequeueAfter != wipeDrainPoll { + t.Fatalf("canceled wipe must poll while its orphan pod drains: result=%+v err=%v", result, err) + } + if wipeCurrent(t, c, gs).Annotations[wipeGuardAnnotation] != "current" { + t.Fatal("cancellation released the guard before the orphan drained") + } + pod := &corev1.Pod{ObjectMeta: metav1.ObjectMeta{Namespace: gs.Namespace, Name: "orphan"}} + if err := c.Delete(t.Context(), pod); err != nil { + t.Fatal(err) + } + if _, err := r.Reconcile(t.Context(), req); err != nil { + t.Fatal(err) + } + live = wipeCurrent(t, c, gs) + if !live.Spec.Suspend || live.Annotations[WipeCompletedAnnotation] != "" { + t.Fatal("canceled wipe acknowledged or game resumed after the orphan drained") + } + } + if live.Annotations[wipeGuardAnnotation] != "" || live.Annotations[lifecycleOperationAnnotation] != "" || pendingWipe(live) { + t.Fatalf("unstarted wipe still holds the server: %v", live.Annotations) + } + if scenario == "pending" { + condition := meta.FindStatusCondition(live.Status.Conditions, gameplanev1alpha1.GameServerConditionDataWipe) + if condition == nil || condition.Reason != "PlacementRejected" || condition.Status != metav1.ConditionFalse { + t.Fatalf("wipe rejection not reported: %+v", condition) + } + } + }) + } +} + func TestWipePendingStartAcquiresGuardBeforeLaunching(t *testing.T) { s := wipeScheme(t) gs := wipeGameServer(false, "current") diff --git a/operator/internal/controller/owned_delete.go b/operator/internal/controller/owned_delete.go index 84e9e340e..5e0fce05b 100644 --- a/operator/internal/controller/owned_delete.go +++ b/operator/internal/controller/owned_delete.go @@ -16,6 +16,7 @@ import ( // Returns no error if the object doesn't exist or is not owned by gs. func (r *GameServerReconciler) deleteIfControlledBy( ctx context.Context, gs *gameplanev1alpha1.GameServer, obj client.Object, + opts ...client.DeleteOption, ) error { // Read from the cache to check ownership. if err := r.Get(ctx, client.ObjectKeyFromObject(obj), obj); err != nil { @@ -40,5 +41,6 @@ func (r *GameServerReconciler) deleteIfControlledBy( // never controlled the replacement. // Also fence ownership changes to the same object between the read and delete. uid, version := obj.GetUID(), obj.GetResourceVersion() - return client.IgnoreNotFound(r.Delete(ctx, obj, client.Preconditions{UID: &uid, ResourceVersion: &version})) + opts = append(opts, client.Preconditions{UID: &uid, ResourceVersion: &version}) + return client.IgnoreNotFound(r.Delete(ctx, obj, opts...)) } diff --git a/operator/internal/controller/restore_lifecycle_test.go b/operator/internal/controller/restore_lifecycle_test.go index 84df44843..2bafd3f48 100644 --- a/operator/internal/controller/restore_lifecycle_test.go +++ b/operator/internal/controller/restore_lifecycle_test.go @@ -129,6 +129,44 @@ func TestRestoreUsesGamePlacementOnlyForFirstVolumeConsumer(t *testing.T) { } } +func TestLegacyTemplateRestoreUsesGamePlacementOnUnboundVolume(t *testing.T) { + policy, _, tmpl := gamePolicyFixture(t) + tmpl.Name = "legacy-template" + for _, tc := range []struct { + name string + policy *GameWorkloadPolicy + selector map[string]string + wantKey string + want string + }{ + {"server architecture selector", nil, map[string]string{corev1.LabelArchStable: "amd64"}, corev1.LabelArchStable, "amd64"}, + {"administrator pool", policy, nil, policy.PoolLabel, policy.PoolValue}, + } { + t.Run(tc.name, func(t *testing.T) { + pvc := &corev1.PersistentVolumeClaim{ObjectMeta: metav1.ObjectMeta{Namespace: "ns", Name: "server-data"}} + r, gs, _ := restoreLifecycleFixture(t, tmpl.DeepCopy(), pvc) + r.GameWorkloadPolicy = tc.policy + gs.Spec.TemplateRef.Name = tmpl.Name + gs.Spec.NodeSelector = tc.selector + if err := r.Update(t.Context(), gs); err != nil { + t.Fatal(err) + } + lifecyclePasses(t, r, "first", 10) + jobs := lifecycleJobs(t, r) + if len(jobs) != 1 { + t.Fatalf("got %d restore jobs, want one", len(jobs)) + } + pod := jobs[0].Spec.Template.Spec + if pod.NodeSelector[tc.wantKey] != tc.want { + t.Fatalf("restore worker selector %v, want %s=%s", pod.NodeSelector, tc.wantKey, tc.want) + } + if tc.policy != nil && (len(pod.Tolerations) != 1 || pod.Tolerations[0].Key != tc.wantKey || pod.Tolerations[0].Value != tc.want) { + t.Fatalf("restore worker missing pool toleration: %v", pod.Tolerations) + } + }) + } +} + func TestPendingRestoreTemplateBindsBeforeCopyFailure(t *testing.T) { r, gs, rs := restoreLifecycleFixture(t) gs.Annotations = map[string]string{restoreGuardAnnotation: restoreIdentityJSON(rs.Name, rs.UID), restoreTemplateAnnotation: "missing-plan"} diff --git a/operator/specs.md b/operator/specs.md index 0ba25358f..7336ed59c 100644 --- a/operator/specs.md +++ b/operator/specs.md @@ -155,6 +155,11 @@ rolling the template or raising replicas while the node is NotReady. Pending or terminating Pods do not authorize a wake or a new sleep listener. After restoring node capacity/readiness, reconciliation resumes automatically. +Before a template rollout drains a Hostport game, the operator reads the +recorded endpoint Node and compares its `kubernetes.io/arch` label with the +target template's `requiredNodeArchitecture`. A missing or different label on +that Node rejects adoption and reports the required migration. The game keeps +its current revision and endpoint. A resumed rollout rechecks the same constraint. For intentional migration, suspend the server, wait for both game and sentinel Pods to disappear, clear both durable endpoint annotations, update scheduling, storage placement and the client-facing node address, then resume the game before @@ -190,11 +195,15 @@ worker, and established TCP sessions use the longer session/drain context. - `GameServer.spec.templateRollout.policy` defaults to Automatic; OnRequest admits only `requestedRevision == status.templateRevision.desired`. Initial - provisioning/baseline always adopts the installed content. No fleet scheduler, + provisioning/baseline uses the installed content once admission succeeds. No fleet scheduler, canary or maintenance-window controller is implied. -- First-pin initialization uses shared ownership and a checked metadata update - without stopping an existing workload. Its StatefulSet UID and render-input - fingerprint preserve the existing Pod template byte-for-byte, including API +- First-pin initialization uses shared ownership and a checked metadata update. + A configured game worker policy or a template with `requiredNodeArchitecture` + requires the existing workload to drain before the first pin takes effect. + For an architecture requirement, the rollout owner records `architectureDrain` + at admission so a controller restart continues the same operation. Other + baselines can keep running. Their StatefulSet UID and render-input fingerprint + preserve the existing Pod template byte-for-byte, including API defaults/admission fields, while those inputs are unchanged. A real workload input change, replaced StatefulSet or observed stopped drain allows revision stamping. An existing unannotated Pod never receives inferred provenance. @@ -363,10 +372,25 @@ direct and stored GameServers and before template revision adoption. An explicit suspend on a rejected configuration gracefully drains an existing owned StatefulSet using its pinned template, subject to lifecycle ownership. A legacy workload without a pin uses its Kubernetes termination grace. -Only its replica count can change. Correct the reported policy violation -before starting or rolling out the game. -When the worker policy takes over a legacy StatefulSet, a Rollout owner -keeps its Pod template intact until the StatefulSet observes zero replicas +Only the StatefulSet replica count can change. For a suspended Hostport server, +the operator also removes its owned wake listener to release the endpoint. +Correct the reported policy violation before starting or rolling out the game. + +`GameTemplate.spec.requiredNodeArchitecture` adds a `kubernetes.io/arch` +selector to the game Pod and its Hostport wake sentinel. The requirement covers +every version and GameServer image override. Server selectors and affinity +still apply. An explicit architecture selector or worker pool that contradicts +the template fails placement validation before the operator adopts it. + +Restic restore, wipe, and stopped-server backup Jobs can be the first Pods to +mount a game volume. For a missing or unbound claim they inherit the game's +placement, including server selectors, tolerations, worker pool and affinity. +This also applies to older templates that rely on a GameServer selector to +choose amd64 workers. Once all mounted claims are bound, recovery can use the +existing volume topology. A backup of a running game uses its source node. + +When a worker policy or architecture requirement takes over a legacy StatefulSet, +a Rollout owner keeps its Pod template intact until the StatefulSet observes zero replicas and the old Pod and world-volume writers have gone. A running game with a verified Pod revision uses its own saved stop sequence. An unversioned Pod uses its existing Kubernetes termination grace. The operator then @@ -544,6 +568,13 @@ failed/canceled restores remain suspended. Generation changes to active Backup or Restore specs fail the operation and enter cleanup rather than authorizing a different copy under the old owner. See [operator operation recovery](../docs/operator-operations.md). +If placement rejects a wipe before launch, the operator checks that the current +request owns the wipe and that no wipe Job or live worker remains. It records +`DataWipe=False` with reason `PlacementRejected`, consumes the rejected request, +and releases its guard. A canceled request can also finish cleanup while the +server's placement is invalid. A failed wipe Job retains its guard and logs +until cancellation or replacement because it may have partially cleared data. + ### ModuleSourceReconciler - **Responsibility:** Index module sources and surface available modules into status. - **Key functions:** From fe270eb110ef5f25a18207d0ed184905aa143b78 Mon Sep 17 00:00:00 2001 From: Baylem Date: Sat, 14 Nov 2026 17:28:00 -0500 Subject: [PATCH 6/7] fix(operator): allow guarded wipes on bound game volumes Use the first-consumer check to distinguish an unbound claim from existing storage. A placement-only failure can proceed after graceful drain and fresh ownership checks. Retain guards on transient reads and reject an incompatible first consumer before launch. Signed-off-by: Baylem --- .../controller/game_workload_policy.go | 20 ++- .../internal/controller/gameserver_wipe.go | 52 +++---- .../controller/gameserver_wipe_guard.go | 9 +- .../controller/gameserver_wipe_guard_test.go | 129 +++++++++++++++++- operator/specs.md | 9 +- 5 files changed, 184 insertions(+), 35 deletions(-) diff --git a/operator/internal/controller/game_workload_policy.go b/operator/internal/controller/game_workload_policy.go index 5dde276a1..84b789588 100644 --- a/operator/internal/controller/game_workload_policy.go +++ b/operator/internal/controller/game_workload_policy.go @@ -35,6 +35,10 @@ type GameWorkloadPolicy struct { // can safely stop the effective workload or release a failed worker's guard. type workloadPolicyRejection struct{ error } +// Only a placement rejection of the effective workload permits a wipe to +// recover data on an already-bound volume independently of game scheduling. +type gamePlacementRejection struct{ error } + // reconcileRejectedGameWorkload permits a suspended, owned server to drain while its requested configuration is invalid. func (r *GameServerReconciler) reconcileRejectedGameWorkload(ctx context.Context, gs *gameplanev1alpha1.GameServer, effective *gameplanev1alpha1.GameTemplate, rejection error, @@ -43,9 +47,9 @@ func (r *GameServerReconciler) reconcileRejectedGameWorkload(ctx context.Context var wipeState wipeWorkerState if gs.Annotations[wipeGuardAnnotation] != "" { // Validation normally returns before the wipe controller gets a turn. - // Settle cancellation or failure under the existing owner without launching a Job. + // Continue under the existing owner, including maintenance on a bound volume. version := gs.ResourceVersion - if err := r.advanceWipe(ctx, gs, effective, &wipeState, false); err != nil { + if err := r.advanceWipe(ctx, gs, effective, &wipeState, rejection); err != nil { return requeueOnConflict(result, err) } if gs.ResourceVersion != version { @@ -145,9 +149,16 @@ func ParseGameWorkloadPolicy(raw string) (*GameWorkloadPolicy, error) { // validate checks the merged game resources and placement before the controller can create or change a workload. func (p *GameWorkloadPolicy) validate(gs *gameplanev1alpha1.GameServer, tmpl *gameplanev1alpha1.GameTemplate) error { - if err := p.validatePlacement(gs, tmpl); err != nil { + if err := p.validateResources(gs, tmpl); err != nil { return err } + if err := p.validatePlacement(gs, tmpl); err != nil { + return gamePlacementRejection{err} + } + return nil +} + +func (p *GameWorkloadPolicy) validateResources(gs *gameplanev1alpha1.GameServer, tmpl *gameplanev1alpha1.GameTemplate) error { res := effectiveResources(gs, tmpl) for name, request := range res.Requests { if limit, ok := res.Limits[name]; ok && request.Cmp(limit) > 0 { @@ -226,6 +237,9 @@ func (p *GameWorkloadPolicy) placeFirstVolumeConsumer(ctx context.Context, reade if err := reader.Get(ctx, key, &pvc); err != nil && !apierrors.IsNotFound(err) { return fmt.Errorf("read game volume %s before scheduling worker: %w", key, err) } + if !pvc.DeletionTimestamp.IsZero() { + return fmt.Errorf("game volume %s is being deleted", key) + } if pvc.Spec.VolumeName == "" { if err := p.validatePlacement(gs, tmpl); err != nil { return workloadPolicyRejection{err} diff --git a/operator/internal/controller/gameserver_wipe.go b/operator/internal/controller/gameserver_wipe.go index 28f90e76e..c6bf51eb2 100644 --- a/operator/internal/controller/gameserver_wipe.go +++ b/operator/internal/controller/gameserver_wipe.go @@ -26,7 +26,7 @@ const ( wipeTokenLabel = "gameplane.local/wipe-token" // wipeScript empties the directory given as $1 and verifies it is empty - // afterwards; see the comment at its use in createWipeJob for why the + // afterwards; see the comment at its use in prepareWipeJob for why the // verification step is required. wipeScript = `find "$1" -mindepth 1 -delete left=$(ls -A "$1") || exit 1 @@ -44,11 +44,11 @@ func (r *GameServerReconciler) reconcileWipe( ctx context.Context, gs *gameplanev1alpha1.GameServer, tmpl *gameplanev1alpha1.GameTemplate, inventory ...*wipeWorkerState, ) error { - return r.advanceWipe(ctx, gs, tmpl, wipeInventory(inventory), true) + return r.advanceWipe(ctx, gs, tmpl, wipeInventory(inventory), nil) } func (r *GameServerReconciler) advanceWipe(ctx context.Context, gs *gameplanev1alpha1.GameServer, - tmpl *gameplanev1alpha1.GameTemplate, state *wipeWorkerState, allowLaunch bool, + tmpl *gameplanev1alpha1.GameTemplate, state *wipeWorkerState, rejection error, ) error { version := gs.ResourceVersion changed, err := r.ensureWipeGuard(ctx, gs, state) @@ -58,7 +58,7 @@ func (r *GameServerReconciler) advanceWipe(ctx context.Context, gs *gameplanev1a if err != nil { return err } - if !allowLaunch && gs.ResourceVersion != version { + if rejection != nil && gs.ResourceVersion != version { // A fresh pass must validate the changed server before rejecting its wipe. return nil } @@ -143,14 +143,24 @@ func (r *GameServerReconciler) advanceWipe(ctx context.Context, gs *gameplanev1a if state.busy { return nil } - if !allowLaunch { - if err := r.GameWorkloadPolicy.validatePlacement(gs, tmpl); err != nil { - return r.rejectUnstartedWipe(ctx, gs, guard, err) - } + _, placementOnly := rejection.(gamePlacementRejection) + if rejection != nil && !placementOnly && r.GameWorkloadPolicy.validatePlacement(gs, tmpl) == nil { + // No effective first-consumer conflict to settle. Resource limits and + // other admission errors cannot authorize a worker. return nil } stopped, err := r.wipeTargetStopped(ctx, gs) - if err != nil || !stopped { + if err != nil || (!stopped && rejection == nil) { + return err + } + // Check the actual claim through the same first-consumer decision in both + // paths. Reject an unbound conflict even if the workload has yet to drain. + job, err = r.prepareWipeJob(ctx, gs, tmpl, jobName, guard) + var rejected workloadPolicyRejection + if errors.As(err, &rejected) { + return r.rejectUnstartedWipe(ctx, gs, guard, rejected) + } + if err != nil || !stopped || (rejection != nil && !placementOnly) { return err } // Revalidate immediately before launch. Another GameServer reconcile for @@ -159,19 +169,16 @@ func (r *GameServerReconciler) advanceWipe(ctx context.Context, gs *gameplanev1a if err := r.wipeReader().Get(ctx, client.ObjectKeyFromObject(gs), &live); err != nil { return client.IgnoreNotFound(err) } - if live.UID != gs.UID || live.Annotations[wipeGuardAnnotation] != guard || live.Annotations[WipeRequestedAnnotation] != guard || !pendingWipe(&live) || live.Annotations[restoreGuardAnnotation] != "" || live.Annotations[backupGuardAnnotation] != "" { + if live.ResourceVersion != gs.ResourceVersion || !live.Spec.Suspend || live.UID != gs.UID || live.Annotations[wipeGuardAnnotation] != guard || live.Annotations[WipeRequestedAnnotation] != guard || !pendingWipe(&live) || live.Annotations[restoreGuardAnnotation] != "" || live.Annotations[backupGuardAnnotation] != "" { return nil } if ready, err := wipeLifecycleReady(&live, guard); err != nil || !ready { return err } - err = r.createWipeJob(ctx, &live, tmpl, jobName, guard) - var rejected workloadPolicyRejection - if errors.As(err, &rejected) { - err = r.rejectUnstartedWipe(ctx, &live, guard, rejected) - *gs = live + if err := r.Create(ctx, job); err != nil && !apierrors.IsAlreadyExists(err) { + return err } - return err + return nil } // The current owner is ready, and inventory found no Job or live wipe worker. @@ -193,10 +200,10 @@ func (r *GameServerReconciler) rejectUnstartedWipe(ctx context.Context, gs *game return r.releaseWipeGuard(ctx, gs, token, false) } -func (r *GameServerReconciler) createWipeJob( +func (r *GameServerReconciler) prepareWipeJob( ctx context.Context, gs *gameplanev1alpha1.GameServer, tmpl *gameplanev1alpha1.GameTemplate, name, token string, -) error { +) (*batchv1.Job, error) { mountPath := effectiveMountPath(tmpl) uid := int64(65532) // same non-root UID the game + backup jobs use nonRoot := true @@ -269,15 +276,12 @@ func (r *GameServerReconciler) createWipeJob( }, } if err := r.GameWorkloadPolicy.placeFirstVolumeConsumer(ctx, r.wipeReader(), gs, tmpl, &job.Spec.Template.Spec); err != nil { - return err + return nil, err } if err := controllerutil.SetControllerReference(gs, job, r.Scheme); err != nil { - return err + return nil, err } - if err := r.Create(ctx, job); err != nil && !apierrors.IsAlreadyExists(err) { - return err - } - return nil + return job, nil } func (r *GameServerReconciler) ackWipe(ctx context.Context, gs *gameplanev1alpha1.GameServer, token string) error { diff --git a/operator/internal/controller/gameserver_wipe_guard.go b/operator/internal/controller/gameserver_wipe_guard.go index 45a6becc4..7b3be886d 100644 --- a/operator/internal/controller/gameserver_wipe_guard.go +++ b/operator/internal/controller/gameserver_wipe_guard.go @@ -226,16 +226,19 @@ func (r *GameServerReconciler) wipeTargetStopped(ctx context.Context, gs *gamepl if !metav1.IsControlledBy(&ss, gs) { return false, fmt.Errorf("wipe target StatefulSet is not controlled by this GameServer") } + // The workload reconciler owns graceful scale-down, including while game + // placement is rejected. Fencing the stopped workload must not bypass it. + if ss.Spec.Replicas == nil || *ss.Spec.Replicas != 0 { + return false, nil + } if ss.Annotations[wipeGuardAnnotation] != gs.Annotations[wipeGuardAnnotation] { if ss.Annotations == nil { ss.Annotations = make(map[string]string) } ss.Annotations[wipeGuardAnnotation] = gs.Annotations[wipeGuardAnnotation] - zero := int32(0) - ss.Spec.Replicas = &zero return false, r.Update(ctx, &ss) } - if ss.Spec.Replicas == nil || *ss.Spec.Replicas != 0 || ss.Status.Replicas != 0 || ss.Status.ObservedGeneration < ss.Generation { + if ss.Status.Replicas != 0 || ss.Status.ObservedGeneration < ss.Generation { return false, nil } var pods corev1.PodList diff --git a/operator/internal/controller/gameserver_wipe_guard_test.go b/operator/internal/controller/gameserver_wipe_guard_test.go index 19f031d3c..41fe56f5a 100644 --- a/operator/internal/controller/gameserver_wipe_guard_test.go +++ b/operator/internal/controller/gameserver_wipe_guard_test.go @@ -11,6 +11,7 @@ import ( corev1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/api/meta" + "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" @@ -51,7 +52,7 @@ func wipeCurrent(t *testing.T, c client.Client, gs *gameplanev1alpha1.GameServer } func TestWipePlacementRejectionSettlesUnstartedRequest(t *testing.T) { - for _, scenario := range []string{"pending", "canceled", "failed job", "orphan pod"} { + for _, scenario := range []string{"pending", "placement and resource rejection", "canceled", "failed job", "orphan pod"} { t.Run(scenario, func(t *testing.T) { gs := wipeGameServer(true, "current") gs.Spec.NodeSelector = map[string]string{corev1.LabelArchStable: "arm64"} @@ -62,6 +63,11 @@ func TestWipePlacementRejectionSettlesUnstartedRequest(t *testing.T) { objects := []client.Object{gs, tmpl, wipeStoppedSet(gs)} s := wipeScheme(t) switch scenario { + case "placement and resource rejection": + gs.Spec.Resources = &corev1.ResourceRequirements{ + Requests: corev1.ResourceList{corev1.ResourceCPU: resource.MustParse("2")}, + Limits: corev1.ResourceList{corev1.ResourceCPU: resource.MustParse("1")}, + } case "canceled": delete(gs.Annotations, WipeRequestedAnnotation) case "failed job": @@ -119,7 +125,7 @@ func TestWipePlacementRejectionSettlesUnstartedRequest(t *testing.T) { if live.Annotations[wipeGuardAnnotation] != "" || live.Annotations[lifecycleOperationAnnotation] != "" || pendingWipe(live) { t.Fatalf("unstarted wipe still holds the server: %v", live.Annotations) } - if scenario == "pending" { + if scenario == "pending" || scenario == "placement and resource rejection" { condition := meta.FindStatusCondition(live.Status.Conditions, gameplanev1alpha1.GameServerConditionDataWipe) if condition == nil || condition.Reason != "PlacementRejected" || condition.Status != metav1.ConditionFalse { t.Fatalf("wipe rejection not reported: %+v", condition) @@ -129,6 +135,125 @@ func TestWipePlacementRejectionSettlesUnstartedRequest(t *testing.T) { } } +func TestRejectedWipeUsesBoundVolumeTopologyAfterDrain(t *testing.T) { + for _, scenario := range []string{"bound", "replaced by unbound claim", "deleting claim", "resource rejection", "request canceled at launch"} { + t.Run(scenario, func(t *testing.T) { + s := wipeScheme(t) + gs := wipeGameServer(true, "current") + gs.Annotations[wipeGuardAnnotation] = "current" + gs.Annotations[lifecycleOperationAnnotation] = lifecycleOperationJSON(lifecycleOperation{lifecycleIdentity: wipeLifecycleIdentity(gs, "current")}) + gs.Spec.NodeSelector = map[string]string{corev1.LabelArchStable: "arm64"} + tmpl := &gameplanev1alpha1.GameTemplate{ObjectMeta: metav1.ObjectMeta{Name: gs.Spec.TemplateRef.Name}} + tmpl.Spec.RequiredNodeArchitecture = "amd64" + if scenario == "resource rejection" { + gs.Spec.Resources = &corev1.ResourceRequirements{ + Requests: corev1.ResourceList{corev1.ResourceCPU: resource.MustParse("2")}, + Limits: corev1.ResourceList{corev1.ResourceCPU: resource.MustParse("1")}, + } + } + pvc := &corev1.PersistentVolumeClaim{ObjectMeta: metav1.ObjectMeta{Namespace: gs.Namespace, Name: gs.Name + "-data"}, + Spec: corev1.PersistentVolumeClaimSpec{VolumeName: "legacy-volume"}} + pod := &corev1.Pod{ObjectMeta: metav1.ObjectMeta{Namespace: gs.Namespace, Name: gs.Name + "-0"}, Status: corev1.PodStatus{Phase: corev1.PodRunning}} + c := fake.NewClientBuilder().WithScheme(s).WithObjects(gs, tmpl, wipeStoppedSet(gs), pvc, pod).WithStatusSubresource(gs).Build() + r := &GameServerReconciler{Client: c, APIReader: c, Scheme: s} + req := ctrl.Request{NamespacedName: client.ObjectKeyFromObject(gs)} + jobKey := client.ObjectKey{Namespace: gs.Namespace, Name: gs.Name + "-wipe"} + var job batchv1.Job + if _, err := r.Reconcile(t.Context(), req); err != nil { + t.Fatal(err) + } + if err := c.Get(t.Context(), jobKey, &job); !apierrors.IsNotFound(err) { + t.Fatalf("worker launched before game drained: %v", err) + } + live := wipeCurrent(t, c, gs) + if !live.Spec.Suspend || live.Annotations[wipeGuardAnnotation] != "current" || !pendingWipe(live) { + t.Fatalf("bound volume lost its pending wipe during drain: %v", live.Annotations) + } + if err := c.Delete(t.Context(), pod); err != nil { + t.Fatal(err) + } + switch scenario { + case "replaced by unbound claim": + if err := c.Delete(t.Context(), pvc); err != nil { + t.Fatal(err) + } + if err := c.Create(t.Context(), &corev1.PersistentVolumeClaim{ObjectMeta: metav1.ObjectMeta{Namespace: pvc.Namespace, Name: pvc.Name}}); err != nil { + t.Fatal(err) + } + case "deleting claim": + if err := c.Get(t.Context(), client.ObjectKeyFromObject(pvc), pvc); err != nil { + t.Fatal(err) + } + pvc.Finalizers = []string{"test/drain"} + if err := c.Update(t.Context(), pvc); err != nil { + t.Fatal(err) + } + if err := c.Delete(t.Context(), pvc); err != nil { + t.Fatal(err) + } + case "request canceled at launch": + r.APIReader = interceptor.NewClient(c, interceptor.Funcs{ + Get: func(ctx context.Context, c client.WithWatch, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error { + if _, ok := obj.(*corev1.PersistentVolumeClaim); ok { + current := wipeCurrent(t, c, gs) + delete(current.Annotations, WipeRequestedAnnotation) + if err := c.Update(ctx, current); err != nil { + return err + } + } + return c.Get(ctx, key, obj, opts...) + }, + }) + } + _, err := r.Reconcile(t.Context(), req) + if (scenario == "deleting claim") != (err != nil) { + t.Fatalf("expected retry only for a deleting claim: %v", err) + } + err = c.Get(t.Context(), jobKey, &job) + live = wipeCurrent(t, c, gs) + if scenario == "bound" { + if err != nil || !metav1.IsControlledBy(&job, gs) || job.Labels[wipeTokenLabel] != "current" { + t.Fatalf("missing owned wipe for the bound volume: %v", err) + } + podSpec := job.Spec.Template.Spec + if len(podSpec.NodeSelector) != 0 || len(podSpec.Tolerations) != 0 || podSpec.Affinity != nil || podSpec.Volumes[0].PersistentVolumeClaim.ClaimName != pvc.Name { + t.Fatalf("wipe did not retain the bound volume's topology: %+v", podSpec) + } + } else if !apierrors.IsNotFound(err) { + t.Fatalf("ineligible worker launched: %v", err) + } + if !live.Spec.Suspend || live.Annotations[WipeCompletedAnnotation] != "" { + t.Fatal("unfinished wipe acknowledged or game resumed") + } + if scenario == "replaced by unbound claim" { + condition := meta.FindStatusCondition(live.Status.Conditions, gameplanev1alpha1.GameServerConditionDataWipe) + if condition == nil || condition.Reason != "PlacementRejected" || live.Annotations[wipeGuardAnnotation] != "" || pendingWipe(live) { + t.Fatalf("replacement claim was not rejected before the first consumer: %v", live.Annotations) + } + } + }) + } +} + +func TestWipeFenceWaitsForGracefulScaleDown(t *testing.T) { + s := wipeScheme(t) + gs := wipeGameServer(true, "current") + ss := wipeStoppedSet(gs) + gs.Annotations[wipeGuardAnnotation] = "current" + *ss.Spec.Replicas = 1 + c := fake.NewClientBuilder().WithScheme(s).WithObjects(gs, ss).Build() + r := &GameServerReconciler{Client: c, APIReader: c, Scheme: s} + if stopped, err := r.wipeTargetStopped(t.Context(), gs); err != nil || stopped { + t.Fatalf("running game accepted for wipe: stopped=%v err=%v", stopped, err) + } + if err := c.Get(t.Context(), client.ObjectKeyFromObject(ss), ss); err != nil { + t.Fatal(err) + } + if *ss.Spec.Replicas != 1 || ss.Annotations[wipeGuardAnnotation] != "" { + t.Fatal("wipe fence bypassed graceful scale-down") + } +} + func TestWipePendingStartAcquiresGuardBeforeLaunching(t *testing.T) { s := wipeScheme(t) gs := wipeGameServer(false, "current") diff --git a/operator/specs.md b/operator/specs.md index 7336ed59c..ffada4f84 100644 --- a/operator/specs.md +++ b/operator/specs.md @@ -568,11 +568,14 @@ failed/canceled restores remain suspended. Generation changes to active Backup or Restore specs fail the operation and enter cleanup rather than authorizing a different copy under the old owner. See [operator operation recovery](../docs/operator-operations.md). -If placement rejects a wipe before launch, the operator checks that the current -request owns the wipe and that no wipe Job or live worker remains. It records +If placement rejects a wipe that would first bind the data volume, the operator +checks that the current request owns the wipe and that no wipe Job or live +worker remains. It records `DataWipe=False` with reason `PlacementRejected`, consumes the rejected request, and releases its guard. A canceled request can also finish cleanup while the -server's placement is invalid. A failed wipe Job retains its guard and logs +server's placement is invalid. A suspended server with an already-bound data +volume can complete its wipe on the existing volume topology once the game +and other writers have stopped. A failed wipe Job retains its guard and logs until cancellation or replacement because it may have partially cleared data. ### ModuleSourceReconciler From b14ef375199bf6dfc9eabaee4951cc47fcc616c3 Mon Sep 17 00:00:00 2001 From: Baylem Date: Sat, 14 Nov 2026 17:37:47 -0500 Subject: [PATCH 7/7] fix(operator): preserve placement and wipe ownership diagnostics Report placement first when resource limits also fail and reserve bound-wipe recovery for placement-only errors. Validate the live lifecycle owner before discarding stale work so a malformed owner remains observable. Propagate the interceptor context in the cancellation regression. Signed-off-by: Baylem --- .../internal/controller/game_workload_policy.go | 16 +++++++++------- operator/internal/controller/gameserver_wipe.go | 8 ++++++-- .../controller/gameserver_wipe_guard_test.go | 7 +++++-- 3 files changed, 20 insertions(+), 11 deletions(-) diff --git a/operator/internal/controller/game_workload_policy.go b/operator/internal/controller/game_workload_policy.go index 84b789588..d1445193d 100644 --- a/operator/internal/controller/game_workload_policy.go +++ b/operator/internal/controller/game_workload_policy.go @@ -35,7 +35,7 @@ type GameWorkloadPolicy struct { // can safely stop the effective workload or release a failed worker's guard. type workloadPolicyRejection struct{ error } -// Only a placement rejection of the effective workload permits a wipe to +// A placement rejection with valid game resources permits a wipe to // recover data on an already-bound volume independently of game scheduling. type gamePlacementRejection struct{ error } @@ -149,13 +149,15 @@ func ParseGameWorkloadPolicy(raw string) (*GameWorkloadPolicy, error) { // validate checks the merged game resources and placement before the controller can create or change a workload. func (p *GameWorkloadPolicy) validate(gs *gameplanev1alpha1.GameServer, tmpl *gameplanev1alpha1.GameTemplate) error { - if err := p.validateResources(gs, tmpl); err != nil { - return err - } - if err := p.validatePlacement(gs, tmpl); err != nil { - return gamePlacementRejection{err} + resourceErr := p.validateResources(gs, tmpl) + if placementErr := p.validatePlacement(gs, tmpl); placementErr != nil { + if resourceErr != nil { + // Report placement first, even when resource limits also block recovery. + return placementErr + } + return gamePlacementRejection{placementErr} } - return nil + return resourceErr } func (p *GameWorkloadPolicy) validateResources(gs *gameplanev1alpha1.GameServer, tmpl *gameplanev1alpha1.GameTemplate) error { diff --git a/operator/internal/controller/gameserver_wipe.go b/operator/internal/controller/gameserver_wipe.go index c6bf51eb2..ae916dce9 100644 --- a/operator/internal/controller/gameserver_wipe.go +++ b/operator/internal/controller/gameserver_wipe.go @@ -143,7 +143,8 @@ func (r *GameServerReconciler) advanceWipe(ctx context.Context, gs *gameplanev1a if state.busy { return nil } - _, placementOnly := rejection.(gamePlacementRejection) + var placement gamePlacementRejection + placementOnly := errors.As(rejection, &placement) if rejection != nil && !placementOnly && r.GameWorkloadPolicy.validatePlacement(gs, tmpl) == nil { // No effective first-consumer conflict to settle. Resource limits and // other admission errors cannot authorize a worker. @@ -169,12 +170,15 @@ func (r *GameServerReconciler) advanceWipe(ctx context.Context, gs *gameplanev1a if err := r.wipeReader().Get(ctx, client.ObjectKeyFromObject(gs), &live); err != nil { return client.IgnoreNotFound(err) } - if live.ResourceVersion != gs.ResourceVersion || !live.Spec.Suspend || live.UID != gs.UID || live.Annotations[wipeGuardAnnotation] != guard || live.Annotations[WipeRequestedAnnotation] != guard || !pendingWipe(&live) || live.Annotations[restoreGuardAnnotation] != "" || live.Annotations[backupGuardAnnotation] != "" { + if live.UID != gs.UID || live.Annotations[wipeGuardAnnotation] != guard || live.Annotations[WipeRequestedAnnotation] != guard || !pendingWipe(&live) || live.Annotations[restoreGuardAnnotation] != "" || live.Annotations[backupGuardAnnotation] != "" { return nil } if ready, err := wipeLifecycleReady(&live, guard); err != nil || !ready { return err } + if live.ResourceVersion != gs.ResourceVersion || !live.Spec.Suspend { + return nil + } if err := r.Create(ctx, job); err != nil && !apierrors.IsAlreadyExists(err) { return err } diff --git a/operator/internal/controller/gameserver_wipe_guard_test.go b/operator/internal/controller/gameserver_wipe_guard_test.go index 41fe56f5a..a79488968 100644 --- a/operator/internal/controller/gameserver_wipe_guard_test.go +++ b/operator/internal/controller/gameserver_wipe_guard_test.go @@ -195,9 +195,12 @@ func TestRejectedWipeUsesBoundVolumeTopologyAfterDrain(t *testing.T) { r.APIReader = interceptor.NewClient(c, interceptor.Funcs{ Get: func(ctx context.Context, c client.WithWatch, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error { if _, ok := obj.(*corev1.PersistentVolumeClaim); ok { - current := wipeCurrent(t, c, gs) + var current gameplanev1alpha1.GameServer + if err := c.Get(ctx, client.ObjectKeyFromObject(gs), ¤t); err != nil { + return err + } delete(current.Annotations, WipeRequestedAnnotation) - if err := c.Update(ctx, current); err != nil { + if err := c.Update(ctx, ¤t); err != nil { return err } }