diff --git a/.github/workflows/validate.yml b/.github/workflows/validate.yml index 5dcd655..6c6cdfd 100644 --- a/.github/workflows/validate.yml +++ b/.github/workflows/validate.yml @@ -71,6 +71,10 @@ jobs: with: go-version: "1.26" + - name: Check Minecraft proxy startup, console and persistence + timeout-minutes: 20 + run: python3 test-minecraft-proxy.py + - name: Check module locales run: | set -euo pipefail diff --git a/README.md b/README.md index 9781afd..0c7891f 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,9 @@ OCI game templates for Gameplane. Each `/` folder holds `module.yaml`, `template.yaml`, `README.md` and optional `icon.png`, `specs.md`, `samples/`. `build.sh push` publishes them; `validate.py` preflight-checks them in CI. +Use the [Minecraft Proxy module](minecraft-proxy/) to route Minecraft Java +players to backend servers through Velocity, Waterfall, or BungeeCord. + ## Mixed-architecture clusters Squad, The Isle, Mount & Blade II: Bannerlord, Nuclear Option and ARK: Survival diff --git a/minecraft-proxy/README.md b/minecraft-proxy/README.md new file mode 100644 index 0000000..c7e299f --- /dev/null +++ b/minecraft-proxy/README.md @@ -0,0 +1,108 @@ +# Minecraft Proxy + +Route Minecraft Java Edition players to one or more backend servers. The +module requires Gameplane 0.4.1 or later. + +## Create the proxy + +1. Select **Minecraft Proxy** in the New Server wizard. Choose **Velocity** + (the default), **Waterfall**, or **BungeeCord**. PaperMC has ended support + for Waterfall. [Waterfall end-of-life notice](https://papermc.io/software/waterfall/) +2. In **Initial lobby address**, enter a `host:port` reachable from the proxy + pod. The default `lobby:25565` fits a GameServer named `lobby` in the same + namespace. Use the backend's internal Service DNS name across namespaces. +3. Expose the proxy's `game` port (TCP 25565) to players. Keep TCP 25575 + private for RCON and restrict the backend game ports to the proxy. + +For a local install, run this command from the modules repository root with +the Gameplane CRDs installed and the operator at version 0.4.1 or later. + +```sh +kubectl apply -f minecraft-proxy/template.yaml +``` + +For Kubernetes manifests, start with the [Velocity sample](samples/velocity.yaml), +[Waterfall sample](samples/waterfall.yaml), or [BungeeCord sample](samples/bungeecord.yaml). +Set the namespace and lobby address for your cluster. + +## Configure backend forwarding + +Keep the proxy in online mode so it authenticates players. Give backends +private addresses and enforce access to their game ports at the network layer. +Gameplane's default ingress policy allows `0.0.0.0/0` to advertised backend +game ports, including on ClusterIP services. Kubernetes combines the allow +rules from all applicable NetworkPolicies. If you use NetworkPolicy for +isolation, change Gameplane's ingress configuration to narrow or remove its +broad rule and check the other effective rules. You can also restrict access +with network or firewall rules that enforce the proxy-only path. +[Kubernetes NetworkPolicy rules](https://kubernetes.io/docs/concepts/services-networking/network-policies/#the-two-sorts-of-pod-isolation), [PaperMC backend security guide](https://docs.papermc.io/velocity/security/) + +Verify that the proxy can connect and that direct connections from clients +and other untrusted workloads fail. Then set `online-mode=false` in the +backend's `server.properties`. For a Gameplane Minecraft Java backend, set +**Online mode** to `false`. + +- **Velocity** uses modern forwarding. On a current Paper backend, disable + `settings.bungeecord` in `spigot.yml`. In `config/paper-global.yml`, enable + `proxies.velocity.enabled`, set `proxies.velocity.online-mode` to `true`, + and set `proxies.velocity.secret` to the contents of the proxy's + `forwarding.secret`. The image creates that file on Velocity's first + launch and keeps it on the data volume. Use a backend that supports modern + forwarding. [Velocity forwarding guide](https://docs.papermc.io/velocity/player-information-forwarding/#configuring-modern-forwarding) +- **Waterfall and BungeeCord** use `ip_forward: true` in the proxy's + `config.yml`. On Paper or Spigot, set `settings.bungeecord: true` in + `spigot.yml` and disable Velocity forwarding if enabled. Legacy forwarding + trusts the proxy connection, so the backend network restriction is + essential. [Legacy forwarding guide](https://docs.papermc.io/velocity/player-information-forwarding/#configuring-legacy-bungeecord-compatible-forwarding) + +Restart each backend after updating its settings. Keep the forwarding secret +private and update every Velocity backend when you rotate it. + +## Edit routing and plugins + +Use **Files** to edit `velocity.toml` or `config.yml` in the data root, then +restart the proxy. In Velocity, declare your backends and fallback order in +`[servers]` and map hostnames in `[forced-hosts]`. In Waterfall and BungeeCord, +declare your backends in `servers` and set `priorities` and `forced_hosts` on +the listener. Keep the listener on TCP 25565 so the Gameplane service and +health probes reach it. + +**Initial lobby address** only takes effect when the active routing file is +missing. Gameplane refreshes the seed files under `gameplane-defaults/` on pod +startup. Use the live file for routing changes. Waterfall and BungeeCord share +`config.yml`, while Velocity uses `velocity.toml`. + +In **Mods**, upload a proxy-compatible `.jar` or install one from an allowed +release URL, then restart. The active proxy type gets its own plugin volume, +including plugin settings. Gameplane retains each volume when you change types. +Back up the plugin volumes separately from the primary GameServer backup, +which covers the routing files and Velocity forwarding secret. + +Waterfall uses the archived `1.21` build `615`. On startup the launcher +downloads its six default core modules from PaperMC as needed and verifies +their checksums. If startup reports a checksum mismatch in an installed core +JAR, remove that JAR and restart to fetch a fresh copy. Waterfall and +BungeeCord keep separate core modules in their plugin volumes. When importing +existing proxy data, move `modules/` and `modules.yml` out of the data root +before starting the Gameplane proxy so it can initialize these paths for the +selected type. [PaperMC build metadata](https://fill.papermc.io/v3/projects/waterfall/versions/1.21/builds/615) + +## Console and updates + +Use **Console** to run commands supported by the selected proxy. Use the +backend GameServers for player statistics and idle detection. + +Gameplane generates the RCON password under the `password` key in the +Kubernetes Secret `-rcon` and uses RCON for Console and graceful +shutdown. The image writes the password to `plugins/velocircon/rcon.yml` +for Velocity or `plugins/bungee-rcon/config.yml` for Waterfall and BungeeCord. +It writes these files only when absent. After rotation or a restore, make +sure the Secret and the active plugin configuration use the same password, +then restart. Repeat for each retained plugin volume before switching back +to its proxy type. Treat these plugin files and backups as credentials. + +The image digest pins the launcher and Java 25 runtime. The launcher resolves +and downloads the selected proxy and RCON plugin from upstream. Velocity and +BungeeCord build selection can change independently of the image digest. +Check upstream availability and client, backend, and plugin compatibility +before switching types. [itzg/mc-proxy documentation](https://github.com/itzg/docker-mc-proxy/tree/2026.11.1) diff --git a/minecraft-proxy/module.yaml b/minecraft-proxy/module.yaml new file mode 100644 index 0000000..447ab0b --- /dev/null +++ b/minecraft-proxy/module.yaml @@ -0,0 +1,11 @@ +# yaml-language-server: $schema=../.schema/module.schema.json +apiVersion: gameplane.local/module/v1 +name: minecraft-proxy +displayName: Minecraft Proxy +version: 1.0.0 +game: minecraft-proxy +categories: [Sandbox, Modded] +summary: Velocity, Waterfall, and BungeeCord proxies for Minecraft Java networks, with persistent routing and per-proxy plugins. +homepage: https://github.com/itzg/docker-mc-proxy +license: MIT +gameplaneMinVersion: 0.4.1 diff --git a/minecraft-proxy/samples/bungeecord.yaml b/minecraft-proxy/samples/bungeecord.yaml new file mode 100644 index 0000000..d22e9f1 --- /dev/null +++ b/minecraft-proxy/samples/bungeecord.yaml @@ -0,0 +1,12 @@ +apiVersion: gameplane.local/v1alpha1 +kind: GameServer +metadata: + name: bungeecord-01 + namespace: gameplane-games +spec: + templateRef: + name: minecraft-proxy + version: bungeecord + config: + # Replace with the private address of your first backend. + INITIAL_BACKEND: "lobby:25565" diff --git a/minecraft-proxy/samples/velocity.yaml b/minecraft-proxy/samples/velocity.yaml new file mode 100644 index 0000000..426c191 --- /dev/null +++ b/minecraft-proxy/samples/velocity.yaml @@ -0,0 +1,12 @@ +apiVersion: gameplane.local/v1alpha1 +kind: GameServer +metadata: + name: velocity-01 + namespace: gameplane-games +spec: + templateRef: + name: minecraft-proxy + version: velocity + config: + # Replace with the private address of your first backend. + INITIAL_BACKEND: "lobby:25565" diff --git a/minecraft-proxy/samples/waterfall.yaml b/minecraft-proxy/samples/waterfall.yaml new file mode 100644 index 0000000..9c87d15 --- /dev/null +++ b/minecraft-proxy/samples/waterfall.yaml @@ -0,0 +1,12 @@ +apiVersion: gameplane.local/v1alpha1 +kind: GameServer +metadata: + name: waterfall-01 + namespace: gameplane-games +spec: + templateRef: + name: minecraft-proxy + version: waterfall + config: + # Replace with the private address of your first backend. + INITIAL_BACKEND: "lobby:25565" diff --git a/minecraft-proxy/specs.md b/minecraft-proxy/specs.md new file mode 100644 index 0000000..fae2bd4 --- /dev/null +++ b/minecraft-proxy/specs.md @@ -0,0 +1,75 @@ +# Minecraft Proxy module specification + +## Template and runtime + +| Setting | Value | +| --- | --- | +| Module, template and game ID | `minecraft-proxy` | +| Module and template version | `1.0.0` | +| Minimum Gameplane version | `0.4.1` | +| Image | `itzg/mc-proxy:2026.11.1-java25@sha256:8efdaa9d990f4c509f21b7ced003dd959060777784422fd72fdd537d613c1813` | +| Linux architectures | `amd64`, `arm64` | +| User, group and filesystem group | `1000` | +| Working directory and `HOME` | `/server` | +| Primary volume | `1Gi` at `/server` | +| CPU request and limit | `100m` and `1` | +| Memory request and limit | `256Mi` and `1Gi` | + +| `spec.version` | Image `TYPE` | Loader | Active routing file | +| --- | --- | --- | --- | +| `velocity` (default) | `VELOCITY` | `velocity` | `/server/velocity.toml` | +| `waterfall` | `WATERFALL` | `waterfall` | `/server/config.yml` | +| `bungeecord` | `BUNGEECORD` | `bungeecord` | `/server/config.yml` | + +The fallback image environment selects `VELOCITY`. Each loader mounts its own +plugin PVC at `/server/plugins` and accepts `.jar` uploads and allowlisted +URL installs. Switching types retains the other PVCs. The primary GameServer +backup covers the data PVC. Back up each plugin PVC separately. + +## Startup, routing and persistence + +The operator renders `gameplane-defaults/config.yml` and +`gameplane-defaults/velocity.toml` on the data PVC every pod start. Both use +`INITIAL_BACKEND` (default `lobby:25565`) for the seed route named `lobby`. +The wrapper copies the active seed when its routing file is absent, then +hands off to `/usr/bin/run-bungeecord.sh`. It sets `umask 0007` to allow +shared group access and restrict permissions for other users. + +The two live routing files persist independently. Waterfall and BungeeCord +read the same `config.yml`. Existing live files take precedence over seeds, +including after a change to `INITIAL_BACKEND`. Edit the live routing file to +add backend servers, fallback priorities, or forced hosts. + +Both seeds bind TCP `0.0.0.0:25565`, authenticate clients, route to `lobby`, +and disable query. The Bungee-family seed enables legacy IP forwarding with +`ip_forward: true`. The Velocity 2.7 seed enables modern forwarding with +`forwarding.secret`. The upstream launcher creates the secret if it is absent +and reuses it on later starts. Restrict direct access to the offline-mode +backends and configure them for the matching forwarding format. + +Waterfall runs archived `1.21` build `615`. Its bundled module downloader +uses the legacy PaperMC API. The wrapper fetches six matching JARs from +PaperMC's content-addressed store and checks them against the operator-rendered +`gameplane-defaults/waterfall-modules.sha256` before starting the proxy. +For Waterfall and BungeeCord, the wrapper creates `modules` and `modules.yml` +links at the data root when absent. These resolve under +`plugins/.gameplane-proxy-modules` in the active type's plugin PVC. +[Waterfall module downloader source](https://github.com/PaperMC/Waterfall/blob/150a002/BungeeCord-Patches/0006-Fetch-modules-from-the-Waterfall-API-endpoint.patch), [PaperMC build metadata](https://fill.papermc.io/v3/projects/waterfall/versions/1.21/builds/615) + +## Probes, console and JVM + +- The public port is `game` on TCP 25565. Startup, readiness and liveness use + `/usr/bin/health.sh` with `SERVER_PORT=25565`. The startup probe budgets + 60 attempts at 10-second intervals for installation and startup. +- The internal `rcon` port is TCP 25575 and uses the Source RCON protocol. + Gameplane injects `RCON_PASSWORD` from its generated Secret and the + upstream launcher enables the appropriate RCON plugin. Lifecycle stop + sends the `end` command. +- `INIT_MEMORY` defaults to `128M`. `MAX_MEMORY` defaults to 75% of the + effective memory limit, computed by Gameplane as a Java heap size in + mebibytes. `JVM_OPTS` and `JVM_XX_OPTS` pass optional JVM arguments. All + four settings apply at restart. + +See the [setup guide](README.md) for credential rotation and backend +configuration. The image's [pinned launcher source](https://github.com/itzg/docker-mc-proxy/blob/89a7d3ad7dc6f9e8a93d52224c3899e06f8a89ac/scripts/run-bungeecord.sh) +defines upstream downloads and initialization behavior. diff --git a/minecraft-proxy/template.yaml b/minecraft-proxy/template.yaml new file mode 100644 index 0000000..7cddd8e --- /dev/null +++ b/minecraft-proxy/template.yaml @@ -0,0 +1,251 @@ +# yaml-language-server: $schema=../.schema/gametemplate.schema.json +apiVersion: gameplane.local/v1alpha1 +kind: GameTemplate +metadata: + name: minecraft-proxy + labels: + gameplane.local/module: minecraft-proxy +spec: + displayName: Minecraft Proxy + game: minecraft-proxy + version: 1.0.0 + categories: [Sandbox, Modded] + accentColor: "#36988e" + description: | + Route Minecraft Java players to your backend servers with Velocity, + Waterfall, or BungeeCord. Set the first lobby address in the wizard and + manage routing in Files. Each proxy type has its own plugin volume. + + image: itzg/mc-proxy:2026.11.1-java25@sha256:8efdaa9d990f4c509f21b7ced003dd959060777784422fd72fdd537d613c1813 + versions: + - id: velocity + displayName: Velocity + image: itzg/mc-proxy:2026.11.1-java25@sha256:8efdaa9d990f4c509f21b7ced003dd959060777784422fd72fdd537d613c1813 + default: true + loader: velocity + env: + - { name: TYPE, value: VELOCITY } + - id: waterfall + displayName: Waterfall + image: itzg/mc-proxy:2026.11.1-java25@sha256:8efdaa9d990f4c509f21b7ced003dd959060777784422fd72fdd537d613c1813 + loader: waterfall + env: + - { name: TYPE, value: WATERFALL } + - { name: WATERFALL_VERSION, value: "1.21" } + - { name: WATERFALL_BUILD_ID, value: "615" } + - id: bungeecord + displayName: BungeeCord + image: itzg/mc-proxy:2026.11.1-java25@sha256:8efdaa9d990f4c509f21b7ced003dd959060777784422fd72fdd537d613c1813 + loader: bungeecord + env: + - { name: TYPE, value: BUNGEECORD } + + security: + runAsUser: 1000 + runAsGroup: 1000 + fsGroup: 1000 + env: + - { name: HOME, value: /server } + - { name: TYPE, value: VELOCITY } + - { name: SERVER_PORT, value: "25565" } + - { name: ENABLE_RCON, value: "true" } + - { name: RCON_PORT, value: "25575" } + + # The operator refreshes the seeds on pod startup. Copy only the active + # seed, so the routing file under /server stays editable in Files. + command: ["/bin/bash", "-ec"] + args: + - | + cd /server + umask 0007 + case "${TYPE^^}" in + VELOCITY) config_file=velocity.toml ;; + WATERFALL|BUNGEECORD) config_file=config.yml ;; + *) printf 'Unsupported proxy type: %s\n' "$TYPE" >&2; exit 1 ;; + esac + if [[ ! -e "$config_file" && ! -L "$config_file" ]]; then + cp --update=none --no-target-directory "gameplane-defaults/$config_file" "$config_file" + fi + + # Both Bungee-family proxies look for core modules at the data root. + # Resolve those paths through the active type's plugin volume. + if [[ "$config_file" == config.yml ]]; then + module_dir=plugins/.gameplane-proxy-modules + mkdir -p "$module_dir" + if [[ ! -e "$module_dir/modules.yml" && ! -L "$module_dir/modules.yml" ]]; then + touch "$module_dir/modules.yml" + fi + if [[ ! -e modules && ! -L modules ]]; then + ln --symbolic --no-target-directory "$module_dir" modules + fi + if [[ ! -e modules.yml && ! -L modules.yml ]]; then + ln --symbolic --no-target-directory "$module_dir/modules.yml" modules.yml + fi + fi + + # Waterfall's former v2 API no longer serves the core modules. Stage + # the matching build from PaperMC's content-addressed artifact store. + if [[ "${TYPE^^}" == WATERFALL ]]; then + while read -r checksum module_file; do + if [[ -e "$module_file" || -L "$module_file" ]]; then + continue + fi + module_name=${module_file##*/} + artifact="${module_name%.jar}-${WATERFALL_VERSION}-${WATERFALL_BUILD_ID}.jar" + download=$(mktemp "$module_file.XXXXXX") + trap 'rm -f -- "$download"' EXIT + curl --fail --silent --show-error --location --retry 2 --connect-timeout 10 --max-time 30 \ + --output "$download" "https://fill-data.papermc.io/v1/objects/$checksum/$artifact" + printf '%s %s\n' "$checksum" "$download" | sha256sum --check + mv --update=none --no-target-directory "$download" "$module_file" + rm -f -- "$download" + trap - EXIT + done < gameplane-defaults/waterfall-modules.sha256 + sha256sum --check --quiet gameplane-defaults/waterfall-modules.sha256 + fi + exec /usr/bin/run-bungeecord.sh + + ports: + - name: game + containerPort: 25565 + protocol: TCP + advertise: true + - name: rcon + containerPort: 25575 + protocol: TCP + advertise: false + + storage: + size: 1Gi + mountPath: /server + resources: + requests: + cpu: 100m + memory: 256Mi + limits: + cpu: "1" + memory: 1Gi + + rcon: + protocol: source + port: 25575 + passwordEnv: RCON_PASSWORD + + capabilities: + lifecycle: + stop: ["end"] + mods: + loaders: + velocity: { displayName: Plugins (Velocity), path: plugins, extensions: [".jar"] } + waterfall: { displayName: Plugins (Waterfall), path: plugins, extensions: [".jar"] } + bungeecord: { displayName: Plugins (BungeeCord), path: plugins, extensions: [".jar"] } + install: + allowedHosts: + - cdn.modrinth.com + - hangarcdn.papermc.io + - github.com + - release-assets.githubusercontent.com + - objects.githubusercontent.com + + probes: + startup: + exec: + command: ["/usr/bin/health.sh"] + initialDelaySeconds: 10 + periodSeconds: 10 + timeoutSeconds: 5 + failureThreshold: 60 + readiness: + exec: + command: ["/usr/bin/health.sh"] + periodSeconds: 10 + timeoutSeconds: 5 + failureThreshold: 3 + liveness: + exec: + command: ["/usr/bin/health.sh"] + periodSeconds: 30 + timeoutSeconds: 5 + failureThreshold: 3 + + configFiles: + - path: gameplane-defaults/config.yml + template: | + online_mode: true + ip_forward: true + player_limit: -1 + groups: {} + servers: + lobby: + address: {{printf "%q" .Values.INITIAL_BACKEND}} + restricted: false + listeners: + - host: "0.0.0.0:25565" + motd: "A Gameplane Minecraft proxy" + max_players: 100 + priorities: [lobby] + force_default_server: true + forced_hosts: {} + query_enabled: false + proxy_protocol: false + - path: gameplane-defaults/velocity.toml + template: | + config-version = "2.7" + bind = "0.0.0.0:25565" + motd = "A Gameplane Minecraft proxy" + show-max-players = 100 + online-mode = true + player-info-forwarding-mode = "modern" + forwarding-secret-file = "forwarding.secret" + + [servers] + lobby = {{printf "%q" .Values.INITIAL_BACKEND}} + try = ["lobby"] + + [forced-hosts] + + [query] + enabled = false + - path: gameplane-defaults/waterfall-modules.sha256 + template: | + 17d013baf57a10001ef72b2806cdefc1e151da1ab98ffd5ed395f1eabdb0582e modules/cmd_alert.jar + 7cf964eaa2f2365e09751c81d11c57ca3fb6927b67d4c61f96f8a2ba58a664d6 modules/cmd_find.jar + 995dea7f1821618059b02c4cc97e827790e028b1324add362f418a2be4897172 modules/cmd_list.jar + f5e0a10d6028f4835969e7731889c98f3b82e9c9d2f2981ffdb6c200d978d7df modules/cmd_send.jar + d1c68f7c0469e61c83939a37abae08f8ad231fc5bb4c7f455065af42f7950710 modules/cmd_server.jar + 5c952eac34a69e19d7667cb6ddb0c9525809e7c072ed044f8bb9ee6a76722826 modules/reconnect_yaml.jar + + configSchema: + - name: INITIAL_BACKEND + displayName: Initial lobby address + description: >- + Use host:port, reachable from the proxy. This seeds the lobby when the + routing file is first created. Edit the live routing file in Files to + change backends afterward. + type: string + default: "lobby:25565" + required: true + target: file + - name: INIT_MEMORY + displayName: JVM initial heap + description: Starting heap, for example 128M. Keep it at or below the maximum. + type: string + default: "128M" + applyOnRestart: true + - name: MAX_MEMORY + displayName: JVM max heap + description: Heap ceiling, for example 768M. Leave empty for 75% of the container memory limit. + type: string + applyOnRestart: true + autoFromMemoryLimit: + percent: 75 + - name: JVM_OPTS + displayName: Additional JVM options + description: Space-separated Java options, for example -Dfile.encoding=UTF-8. + type: string + applyOnRestart: true + - name: JVM_XX_OPTS + displayName: Additional JVM tuning options + description: Space-separated JVM tuning options, for example -XX:+PrintCommandLineFlags. + type: string + applyOnRestart: true diff --git a/test-minecraft-proxy.py b/test-minecraft-proxy.py new file mode 100644 index 0000000..b382995 --- /dev/null +++ b/test-minecraft-proxy.py @@ -0,0 +1,219 @@ +"""Exercise the proxy module's real configs, image, probes, RCON, and restart. + +Requires Python 3.11+, PyYAML, Go, Docker, and upstream download access. +No host ports are published. Only uniquely named test containers/volumes are removed. +""" + +from pathlib import Path, PurePosixPath +import json +import os +import secrets +import subprocess +import tempfile +import time +import tomllib +import unittest +import uuid + +import yaml + + +ROOT = Path(__file__).resolve().parent + + +def run(*args, check=True, **kwargs): + return subprocess.run(args, check=check, capture_output=True, text=True, + encoding="utf-8", timeout=180, **kwargs) + + +class MinecraftProxy(unittest.TestCase): + @classmethod + def setUpClass(cls): + path = ROOT / "minecraft-proxy/template.yaml" + if not path.exists(): + raise AssertionError("Minecraft Proxy module is missing") + cls.spec = yaml.safe_load(path.read_text(encoding="utf-8"))["spec"] + # A GameServer keeps the same generated secret when switching loaders. + cls.rcon_password = secrets.token_urlsafe(24) + cls.temp = tempfile.TemporaryDirectory(prefix="gameplane-proxy-") + cls.addClassCleanup(cls.temp.cleanup) + cls.renderer = str(Path(cls.temp.name) / ("render.exe" if os.name == "nt" else "render")) + run("go", "build", "-o", cls.renderer, str(ROOT / "testdata/render-config.go")) + + def render(self, **overrides): + values = {f["name"]: f.get("default", "") for f in self.spec["configSchema"]} + values.update(overrides) + result = run(self.renderer, input=json.dumps({ + "Files": self.spec["configFiles"], "Values": values, + "Server": {"Name": "proxy-test", "Namespace": "games"}, + })) + return json.loads(result.stdout) + + def test_seed_configs_route_to_initial_backend(self): + # Wrong quoting, field binding, listener port or default host routing + # would prevent an operator-generated config from working. + files = self.render(INITIAL_BACKEND="lobby.games.svc.cluster.local:25565") + bungee = yaml.safe_load(files["gameplane-defaults/config.yml"]) + velocity = tomllib.loads(files["gameplane-defaults/velocity.toml"]) + self.assertEqual(bungee["servers"]["lobby"]["address"], "lobby.games.svc.cluster.local:25565") + self.assertEqual(velocity["servers"]["lobby"], "lobby.games.svc.cluster.local:25565") + self.assertEqual(bungee["listeners"][0]["host"], "0.0.0.0:25565") + self.assertEqual(velocity["bind"], "0.0.0.0:25565") + self.assertEqual(bungee["listeners"][0]["forced_hosts"], {}) + self.assertEqual(velocity["forced-hosts"], {}) + self.assertTrue(bungee["online_mode"]) + self.assertTrue(velocity["online-mode"]) + self.assertEqual(velocity["player-info-forwarding-mode"], "modern") + # Input must remain a scalar, never become executable config syntax. + odd = 'backend"\\name:25565\n[next]' + files = self.render(INITIAL_BACKEND=odd) + self.assertEqual(yaml.safe_load(files["gameplane-defaults/config.yml"])["servers"]["lobby"]["address"], odd) + self.assertEqual(tomllib.loads(files["gameplane-defaults/velocity.toml"])["servers"]["lobby"], odd) + + def wait_ready(self, name): + command = self.spec["probes"]["readiness"]["exec"]["command"] + deadline = time.monotonic() + 300 + while time.monotonic() < deadline: + state = run("docker", "inspect", "--format", "{{.State.Running}}", name).stdout.strip() + if state != "true": + logs = run("docker", "logs", name) + self.fail("Proxy exited during startup:\n" + logs.stdout + logs.stderr) + if run("docker", "exec", name, *command, check=False).returncode == 0: + # The game listener may open just before the RCON plugin. + response = run("docker", "exec", name, "rcon-cli", "help", check=False) + if response.returncode == 0 and response.stdout.strip(): + return + time.sleep(2) + logs = run("docker", "logs", name) + self.fail("Proxy did not become ready:\n" + logs.stdout + logs.stderr) + + def stop_gracefully(self, name): + for command in self.spec["capabilities"]["lifecycle"]["stop"]: + # A successful shutdown can close RCON before it sends a reply. + run("docker", "exec", name, "rcon-cli", command, check=False) + deadline = time.monotonic() + 30 + while time.monotonic() < deadline: + state = json.loads(run("docker", "inspect", "--format", "{{json .State}}", name).stdout) + if not state["Running"]: + self.assertEqual(state["ExitCode"], 0) + return + time.sleep(1) + self.fail("Declared lifecycle command did not stop the proxy") + + def exercise_proxy(self, version, retained_volumes=None): + image = version["image"] + data_path = PurePosixPath(self.spec["storage"]["mountPath"]) + loader = self.spec["capabilities"]["mods"]["loaders"][version["loader"]] + plugin_path = data_path / loader["path"] + security = self.spec["security"] + user = f"{security['runAsUser']}:{security['runAsGroup']}" + token = "gp-proxy-test-" + uuid.uuid4().hex[:12] + data, plugins = retained_volumes or (token + "-data", token + "-plugins") + containers, volumes = [], [] + try: + if retained_volumes is None: + for volume in (data, plugins): + run("docker", "volume", "create", volume) + volumes.append(volume) + mounts = ["-v", f"{data}:{data_path}", "-v", f"{plugins}:{plugin_path}"] + # Give disposable volumes writable ownership for the declared game user. + run("docker", "run", "--rm", "--user", "0:0", *mounts, + "--entrypoint", "/bin/bash", image, "-ec", + 'mkdir -p "$1/gameplane-defaults"; chown -R -- "$2" "$1"', + "test", str(data_path), user) + env = {e["name"]: e["value"] for e in self.spec.get("env", [])} + env.update({e["name"]: e["value"] for e in version.get("env", [])}) + for field in self.spec["configSchema"]: + if field.get("target", "env") == "env" and field.get("default"): + env[field.get("envName", field["name"])] = field["default"] + env.update(MAX_MEMORY="512M", RCON_PASSWORD=self.rcon_password) + args = ["docker", "create", "--name", token, "--memory", "1g", + "--user", user, *mounts] + for key, value in env.items(): + args.extend(["-e", key + "=" + value]) + command = self.spec["command"] + self.spec.get("args", []) + args.extend(["--entrypoint", command[0], image, *command[1:]]) + run(*args) + containers.append(token) + files = self.render(INITIAL_BACKEND="127.0.0.1:25566") + with tempfile.TemporaryDirectory(prefix="proxy-config-") as directory: + for index, (path, content) in enumerate(files.items()): + source = Path(directory) / str(index) + source.write_bytes(content.encode("utf-8")) + run("docker", "cp", str(source), f"{token}:{data_path / path}") + run("docker", "start", token) + self.wait_ready(token) + # A healthy listener can still be missing bundled proxy commands + # when Waterfall's retired module download API fails. + online = run("docker", "exec", token, "rcon-cli", "glist").stdout + self.assertRegex(online, r"\b0\b", "Proxy player-list command is unavailable: " + online) + transfer = run("docker", "exec", token, "rcon-cli", "send").stdout + self.assertRegex(transfer.lower(), r"send\s+<", "Proxy transfer command is unavailable: " + transfer) + # Both advertised game port and local-only RCON are now exercised. + config = "velocity.toml" if version["id"] == "velocity" else "config.yml" + run("docker", "exec", token, "bash", "-ec", + 'sed -i s/127.0.0.1:25566/127.0.0.1:25567/g "$1"; ' + 'printf "preserved plugin data" > /server/plugins/persistence-proof.txt', "test", "/server/" + config) + parse = tomllib.loads if version["id"] == "velocity" else yaml.safe_load + original = parse(run("docker", "exec", token, "cat", "/server/" + config).stdout) + address = original["servers"]["lobby"] + self.assertEqual(address if isinstance(address, str) else address["address"], "127.0.0.1:25567") + secret = None + if version["id"] == "velocity": + secret = run("docker", "exec", token, "cat", "/server/forwarding.secret").stdout + self.assertTrue(secret.strip(), "Velocity did not generate a forwarding secret") + self.stop_gracefully(token) + run("docker", "start", token) + self.wait_ready(token) + # Bungee-family proxies reserialize YAML, including key ordering + # and comments. Routing values, rather than formatting, must survive. + self.assertEqual(parse(run("docker", "exec", token, "cat", "/server/" + config).stdout), original) + self.assertEqual(run("docker", "exec", token, "cat", str(plugin_path / "persistence-proof.txt")).stdout, + "preserved plugin data") + if secret is not None: + self.assertEqual(run("docker", "exec", token, "cat", "/server/forwarding.secret").stdout, secret) + self.stop_gracefully(token) + except BaseException: + for container in containers: + logs = run("docker", "logs", container, check=False) + print(logs.stdout, logs.stderr) + raise + finally: + for container in containers: + run("docker", "rm", "-f", container, check=False) + for volume in volumes: + run("docker", "volume", "rm", volume, check=False) + + def test_velocity_boot_console_stop_and_preserve_edits(self): + self.exercise_proxy(next(v for v in self.spec["versions"] if v["id"] == "velocity")) + + def test_waterfall_boot_console_stop_and_preserve_edits(self): + self.exercise_proxy(next(v for v in self.spec["versions"] if v["id"] == "waterfall")) + + def test_bungeecord_boot_console_stop_and_preserve_edits(self): + self.exercise_proxy(next(v for v in self.spec["versions"] if v["id"] == "bungeecord")) + + def test_switching_bungee_family_keeps_core_modules_compatible(self): + # The operator retains the data PVC but swaps the plugin PVC by loader. + # BungeeCord bootstrap modules and Waterfall Jenkins modules must not + # inherit each other's modules.yml or command jars after a type switch. + token = "gp-proxy-test-" + uuid.uuid4().hex[:12] + data = token + "-data" + versions = {v["id"]: v for v in self.spec["versions"]} + sequence = [versions[name] for name in ("bungeecord", "waterfall", "bungeecord")] + plugins = {version["id"]: token + "-" + version["id"] for version in sequence} + volumes = [] + try: + for volume in (data, *plugins.values()): + run("docker", "volume", "create", volume) + volumes.append(volume) + for version in sequence: + with self.subTest(proxy=version["id"]): + self.exercise_proxy(version, (data, plugins[version["id"]])) + finally: + for volume in volumes: + run("docker", "volume", "rm", volume, check=False) + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/testdata/render-config.go b/testdata/render-config.go new file mode 100644 index 0000000..c7be6d3 --- /dev/null +++ b/testdata/render-config.go @@ -0,0 +1,38 @@ +// Render module configFiles using the operator's standard text/template context. +// This helper has no module-specific substitutions or template functions. +package main + +import ( + "bytes" + "encoding/json" + "fmt" + "os" + "text/template" +) + +func main() { + var input struct { + Files []struct{ Path, Template string } + Values map[string]string + Server struct{ Name, Namespace string } + } + if err := json.NewDecoder(os.Stdin).Decode(&input); err != nil { + panic(err) + } + output := make(map[string]string) + for _, file := range input.Files { + t, err := template.New(file.Path).Option("missingkey=error").Parse(file.Template) + if err != nil { + panic(err) + } + var buffer bytes.Buffer + if err := t.Execute(&buffer, input); err != nil { + panic(err) + } + output[file.Path] = buffer.String() + } + if err := json.NewEncoder(os.Stdout).Encode(output); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } +}