Download tasks/data/forward/acemod__docker-reforger.cd226c0/solution/golden.patch from Lego-X/ProgramGen: direct link, hf CLI and curl.
- Browser
- Download file 80.1 kB
-
https://huggingface.co/datasets/Lego-X/ProgramGen/resolve/main/tasks/data/forward/acemod__docker-reforger.cd226c0/solution/golden.patch
- Command line
-
hf download hf://datasets/Lego-X/ProgramGen/tasks/data/forward/acemod__docker-reforger.cd226c0/solution/golden.patch
-
curl -L -o golden.patch https://huggingface.co/datasets/Lego-X/ProgramGen/resolve/main/tasks/data/forward/acemod__docker-reforger.cd226c0/solution/golden.patch
80.1 kB
diff --git a/src/healthcheck.py b/src/healthcheck.py
new file mode 100644
index 0000000000000000000000000000000000000000..b9119ac8b6ca2917543dbc4e94bb87e7930cab79
--- /dev/null
+++ b/src/healthcheck.py
@@ -0,0 +1,78 @@
+"""Simple A2S_INFO health check for Arma Reforger server.
+
+Uses the active server configuration when available, falls back to the A2S
+environment variables before the generated config exists, and treats disabled
+A2S as a no-op so valid configurations are not marked unhealthy.
+"""
+
+import json
+import os
+import socket
+import sys
+from pathlib import Path
+
+A2S_INFO_REQUEST = b"\xff\xff\xff\xff\x54Source Engine Query\x00"
+CONFIG_GENERATED = Path("/reforger/Configs/docker_generated.json")
+CONFIG_DIR = Path("/reforger/Configs")
+TIMEOUT_SECONDS = 5
+WILDCARD_TO_LOOPBACK = {
+ "": "127.0.0.1",
+ "0.0.0.0": "127.0.0.1",
+ "::": "::1",
+}
+
+
+def resolve_config_path():
+ arma_config = os.environ.get("ARMA_CONFIG", "docker_generated")
+ if arma_config == "docker_generated":
+ return CONFIG_GENERATED
+ return CONFIG_DIR / arma_config
+
+
+def resolve_a2s_settings():
+ config_path = resolve_config_path()
+ if config_path.exists():
+ with config_path.open(encoding="utf-8-sig") as config_file:
+ config = json.load(config_file)
+ a2s_config = config.get("a2s") if isinstance(config, dict) else None
+ if not isinstance(a2s_config, dict):
+ return None
+ address = a2s_config.get("address")
+ port = a2s_config.get("port")
+ if address is None or port is None:
+ return None
+ return {"address": address, "port": int(port)}
+
+ address = os.environ.get("SERVER_A2S_ADDRESS", "")
+ port = os.environ.get("SERVER_A2S_PORT", "")
+ if not address or not port:
+ return None
+ return {"address": address, "port": int(port)}
+
+
+def probe_server(address, port):
+ probe_address = WILDCARD_TO_LOOPBACK.get(address, address)
+ addrinfos = socket.getaddrinfo(probe_address, port, type=socket.SOCK_DGRAM)
+ for family, socktype, proto, _, sockaddr in addrinfos:
+ sock = socket.socket(family, socktype, proto)
+ try:
+ sock.settimeout(TIMEOUT_SECONDS)
+ sock.sendto(A2S_INFO_REQUEST, sockaddr)
+ data, _ = sock.recvfrom(4096)
+ if data:
+ return True
+ except OSError:
+ continue
+ finally:
+ sock.close()
+ return False
+
+
+try:
+ a2s = resolve_a2s_settings()
+ if not a2s:
+ sys.exit(0)
+ sys.exit(0 if probe_server(a2s["address"], a2s["port"]) else 1)
+except (OSError, TypeError, ValueError) as err:
+ print(f"Health check failed: {err}", file=sys.stderr)
+ sys.exit(1)
diff --git a/src/launch.py b/src/launch.py
new file mode 100644
index 0000000000000000000000000000000000000000..57390a961f87d2d22d5b1b6dc84ba644cbfaa556
--- /dev/null
+++ b/src/launch.py
@@ -0,0 +1,138 @@
+import json
+import os
+import random
+import shlex
+import signal
+import subprocess
+import sys
+from pathlib import Path
+
+from launch_config import bool_str, build_config, env_defined, prune_mods
+
+# On SIGTERM, raise KeyboardInterrupt instead of exiting abruptly.
+signal.signal(signal.SIGTERM, signal.default_int_handler)
+
+CONFIG_GENERATED = "/reforger/Configs/docker_generated.json"
+DEFAULT_CONFIG = "/app/docker_default.json"
+EXPERIMENTAL_APPID = "1890870"
+STEAMCMD = "/steamcmd/steamcmd.sh"
+SENTINEL_WINDOWS_FIX = Path("/reforger/.windows_fix_done")
+
+
+def random_passphrase():
+ passphrase = "'"
+ while "'" in passphrase:
+ try:
+ with open(
+ "/usr/share/dict/american-english", encoding="utf-8"
+ ) as word_file:
+ words = word_file.readlines()
+ except OSError as err:
+ raise SystemExit(f"Failed to read word list: {err}") from err
+ passphrase = "-".join(random.sample(words, 2)).replace("\n", "").lower()
+ return passphrase
+
+
+def build_steamcmd_command(force_platform=None):
+ command = [STEAMCMD, "+force_install_dir", "/reforger"]
+ if env_defined(os.environ, "STEAM_USER"):
+ command.extend(
+ ["+login", os.environ["STEAM_USER"], os.environ["STEAM_PASSWORD"]]
+ )
+ else:
+ command.extend(["+login", "anonymous"])
+ if force_platform is not None:
+ command.extend(["+@sSteamCmdForcePlatformType", force_platform])
+ command.extend(["+app_update", os.environ["STEAM_APPID"]])
+ if env_defined(os.environ, "STEAM_BRANCH"):
+ command.extend(["-beta", os.environ["STEAM_BRANCH"]])
+ if env_defined(os.environ, "STEAM_BRANCH_PASSWORD"):
+ command.extend(["-betapassword", os.environ["STEAM_BRANCH_PASSWORD"]])
+ command.extend(["validate", "+quit"])
+ return command
+
+
+def build_generated_config():
+ try:
+ with open(DEFAULT_CONFIG, encoding="utf-8") as config_file:
+ config = json.load(config_file)
+ except (OSError, ValueError) as err:
+ raise SystemExit(f"Failed to load {DEFAULT_CONFIG}: {err}") from err
+
+ config = build_config(os.environ, config)
+
+ if not env_defined(os.environ, "GAME_PASSWORD_ADMIN"):
+ config["game"]["passwordAdmin"] = random_passphrase()
+ print(f"Admin password: {config['game']['passwordAdmin']}")
+
+ try:
+ with open(CONFIG_GENERATED, "w", encoding="utf-8") as config_file:
+ json.dump(config, config_file, indent=4)
+ except OSError as err:
+ raise SystemExit(f"Failed to write {CONFIG_GENERATED}: {err}") from err
+
+ return CONFIG_GENERATED
+
+
+is_experimental = os.environ["STEAM_APPID"] == EXPERIMENTAL_APPID
+
+# Clear Windows fix sentinel if switching away from experimental appId
+if SENTINEL_WINDOWS_FIX.exists() and not is_experimental:
+ SENTINEL_WINDOWS_FIX.unlink()
+
+if os.environ["SKIP_INSTALL"] in ["", "false"]:
+ # Warm up SteamCMD first. Its initial run self-updates and can exit non-zero,
+ # so we get that out of the way here before the real app_update calls below.
+ subprocess.call([STEAMCMD, "+login", "anonymous", "+quit"])
+
+ if is_experimental:
+ if not SENTINEL_WINDOWS_FIX.exists():
+ subprocess.call(build_steamcmd_command("windows"))
+ SENTINEL_WINDOWS_FIX.touch()
+
+ subprocess.call(build_steamcmd_command("linux"))
+ else:
+ subprocess.call(build_steamcmd_command())
+
+if os.environ["ARMA_CONFIG"] != "docker_generated":
+ CONFIG_PATH = f"/reforger/Configs/{os.environ['ARMA_CONFIG']}"
+else:
+ CONFIG_PATH = build_generated_config()
+
+if bool_str(os.environ["GAME_MODS_AUTO_PRUNE"]):
+ try:
+ prune_mods(CONFIG_PATH, os.environ["ARMA_WORKSHOP_DIR"])
+ except (OSError, ValueError) as prune_err:
+ raise SystemExit(f"Failed to prune mods: {prune_err}") from prune_err
+
+launch = [
+ os.environ["ARMA_BINARY"],
+ "-config",
+ CONFIG_PATH,
+ "-backendlog",
+ "-nothrow",
+ "-maxFPS",
+ os.environ["ARMA_MAX_FPS"],
+ "-profile",
+ os.environ["ARMA_PROFILE"],
+ "-addonDownloadDir",
+ os.environ["ARMA_WORKSHOP_DIR"],
+ "-addonsDir",
+ os.environ["ARMA_WORKSHOP_DIR"],
+ *shlex.split(os.environ["ARMA_PARAMS"]),
+]
+
+print(shlex.join(launch), flush=True)
+
+with subprocess.Popen(launch) as proc:
+ try:
+ try:
+ EXIT_CODE = proc.wait()
+ except KeyboardInterrupt:
+ proc.send_signal(signal.SIGINT)
+ EXIT_CODE = proc.wait()
+ except BaseException:
+ proc.kill()
+ raise
+
+sys.exit(EXIT_CODE)
diff --git a/src/launch_config.py b/src/launch_config.py
new file mode 100644
index 0000000000000000000000000000000000000000..5fefc466681c383295df9c7922ac6294e088fcad
--- /dev/null
+++ b/src/launch_config.py
@@ -0,0 +1,975 @@
+import copy
+import fcntl
+import json
+import os
+import re
+import secrets
+import stat
+from contextlib import suppress
+from pathlib import Path
+
+MOD_ID_LIST_RE = re.compile(r"^[A-Z\d,=.]+$")
+MOD_ID_RE = re.compile(r"^[0-9A-F]{16}$")
+MOD_VERSION_RE = re.compile(r"^\d+\.\d+\.\d+$")
+MOUNT_ESCAPE_RE = re.compile(r"\\([0-7]{3})")
+MAX_SERVER_DATA_SIZE = 1024 * 1024
+MAX_PRUNE_MANIFEST_SIZE = 16 * 1024 * 1024
+MOUNTINFO_PATH = "/proc/self/mountinfo"
+PRUNE_MANIFEST_FILE = ".mod-prune.json"
+PRUNE_QUARANTINE_PREFIX = ".mod-prune-"
+PRUNE_QUARANTINE_RE = re.compile(r"^\.mod-prune-[0-9a-f]{16}$")
+SERVER_DATA_FILE = "ServerData.json"
+DIRECTORY_OPEN_FLAGS = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_CLOEXEC
+ENTRY_OPEN_FLAGS = os.O_PATH | os.O_NOFOLLOW | os.O_CLOEXEC
+WORKSHOP_OPEN_FLAGS = os.O_RDONLY | os.O_DIRECTORY | os.O_CLOEXEC
+
+
+def env_defined(env, key):
+ return key in env and len(env[key]) > 0
+
+
+def bool_str(text):
+ return text.lower() == "true"
+
+
+def split_csv(text):
+ return [item.strip() for item in text.split(",") if item.strip()]
+
+
+def parse_int(env, key):
+ try:
+ return int(env[key])
+ except (KeyError, TypeError, ValueError) as err:
+ raise ValueError(f"Invalid {key}: {env.get(key)!r}") from err
+
+
+def env_str(env, key):
+ return env[key]
+
+
+def env_bool(env, key):
+ return bool_str(env[key])
+
+
+def env_csv(env, key):
+ return split_csv(env[key])
+
+
+def env_navmesh_streaming(env, key):
+ if env[key].lower() == "all":
+ return []
+ return split_csv(env[key])
+
+
+def load_json_file(path):
+ try:
+ with open(path, encoding="utf-8-sig") as json_file:
+ return json.load(json_file)
+ except (OSError, ValueError) as err:
+ raise ValueError(f"Failed to load {path}: {err}") from err
+
+
+def validate_mod_id(mod_id, source):
+ if not isinstance(mod_id, str) or not MOD_ID_RE.fullmatch(mod_id):
+ raise ValueError(f"Invalid mod ID in {source}: {mod_id!r}")
+ return mod_id
+
+
+def configured_mod_ids(config_path):
+ config = load_json_file(config_path)
+ game = config.get("game") if isinstance(config, dict) else None
+ if not isinstance(game, dict):
+ raise ValueError(f"{config_path} does not contain game")
+ mods = game.get("mods", [])
+ if not isinstance(mods, list):
+ raise ValueError(f"game.mods in {config_path} must be an array")
+
+ mod_ids = set()
+ for mod in mods:
+ mod_id = mod.get("modId") if isinstance(mod, dict) else None
+ mod_ids.add(validate_mod_id(mod_id, config_path))
+ return mod_ids
+
+
+def dependency_ids(server_data_path, dependencies):
+ if not isinstance(dependencies, list):
+ raise ValueError(f"dependencies in {server_data_path} must be an array")
+
+ mod_ids = set()
+ for dependency in dependencies:
+ if isinstance(dependency, str):
+ mod_id = dependency
+ elif isinstance(dependency, dict):
+ mod_id = dependency.get("id") or dependency.get("modId")
+ else:
+ mod_id = None
+ try:
+ mod_ids.add(validate_mod_id(mod_id, server_data_path))
+ except ValueError as err:
+ raise ValueError(
+ f"Invalid dependency in {server_data_path}: {dependency!r}"
+ ) from err
+ return mod_ids
+
+
+def load_server_data(mod_fd, server_data_path):
+ flags = os.O_RDONLY | os.O_NONBLOCK | os.O_NOFOLLOW | os.O_CLOEXEC
+ server_data_fd = None
+ try:
+ server_data_fd = os.open(SERVER_DATA_FILE, flags, dir_fd=mod_fd)
+ server_data_stat = os.fstat(server_data_fd)
+ if not stat.S_ISREG(server_data_stat.st_mode):
+ raise ValueError(f"{server_data_path} is not a regular file")
+ if server_data_stat.st_size > MAX_SERVER_DATA_SIZE:
+ raise ValueError(f"{server_data_path} exceeds the metadata size limit")
+ with os.fdopen(server_data_fd, "rb") as server_data_file:
+ server_data_fd = None
+ content = server_data_file.read(MAX_SERVER_DATA_SIZE + 1)
+ if len(content) > MAX_SERVER_DATA_SIZE:
+ raise ValueError(f"{server_data_path} exceeds the metadata size limit")
+ return json.loads(content.decode("utf-8-sig"))
+ except (OSError, UnicodeError, ValueError) as err:
+ raise ValueError(f"Failed to load {server_data_path}: {err}") from err
+ finally:
+ if server_data_fd is not None:
+ os.close(server_data_fd)
+
+
+def load_installed_mod(mod_id, mod_fd, mod_path):
+ server_data_path = mod_path / SERVER_DATA_FILE
+ server_data = load_server_data(mod_fd, server_data_path)
+ if not isinstance(server_data, dict):
+ raise ValueError(f"{server_data_path} must contain an object")
+
+ metadata_mod_id = server_data.get("id")
+ name = server_data.get("name")
+ revision = server_data.get("revision")
+ if (
+ not isinstance(metadata_mod_id, str)
+ or metadata_mod_id != mod_id
+ or not MOD_ID_RE.fullmatch(metadata_mod_id)
+ ):
+ raise ValueError(f"id in {server_data_path} does not match its directory")
+ if not isinstance(name, str) or not name:
+ raise ValueError(f"Invalid name in {server_data_path}")
+ if not isinstance(revision, dict):
+ raise ValueError(f"Invalid revision in {server_data_path}")
+ if not isinstance(revision.get("version"), str) or not revision["version"]:
+ raise ValueError(f"Invalid revision.version in {server_data_path}")
+ downloaded = revision.get("downloaded")
+ if not isinstance(downloaded, bool) or not downloaded:
+ raise ValueError(f"Mod in {server_data_path} is not fully downloaded")
+
+ mod_stat = os.fstat(mod_fd)
+ return {
+ "id": metadata_mod_id,
+ "name": name,
+ "dependencies": dependency_ids(server_data_path, revision.get("dependencies")),
+ "path": mod_path,
+ "stat": mod_stat,
+ }
+
+
+def decode_mount_path(path):
+ return MOUNT_ESCAPE_RE.sub(lambda match: chr(int(match.group(1), 8)), path)
+
+
+def mounted_paths():
+ try:
+ with open(
+ MOUNTINFO_PATH, encoding="utf-8", errors="surrogateescape"
+ ) as mountinfo_file:
+ paths = set()
+ for line in mountinfo_file:
+ fields = line.split()
+ if len(fields) < 5:
+ raise ValueError(f"Invalid entry in {MOUNTINFO_PATH}: {line!r}")
+ paths.add(Path(decode_mount_path(fields[4])))
+ return paths
+ except OSError as err:
+ raise OSError(f"Failed to read {MOUNTINFO_PATH}: {err}") from err
+
+
+def contains_mount(path, mount_paths):
+ return any(
+ mount_path == path or path in mount_path.parents for mount_path in mount_paths
+ )
+
+
+def fd_mount_id(file_descriptor):
+ fdinfo_path = f"/proc/self/fdinfo/{file_descriptor}"
+ try:
+ with open(fdinfo_path, encoding="utf-8") as fdinfo_file:
+ for line in fdinfo_file:
+ if line.startswith("mnt_id:"):
+ return int(line.split(":", 1)[1])
+ except (OSError, ValueError) as err:
+ raise OSError(
+ f"Failed to read mount ID for file descriptor {file_descriptor}: {err}"
+ ) from err
+ raise OSError(f"Mount ID is missing from {fdinfo_path}")
+
+
+def validate_open_entry(file_descriptor, expected_stat, expected_mount_id, path):
+ actual_stat = os.fstat(file_descriptor)
+ if (
+ actual_stat.st_dev != expected_stat.st_dev
+ or actual_stat.st_ino != expected_stat.st_ino
+ ):
+ raise ValueError(f"Filesystem entry changed before pruning: {path}")
+ if fd_mount_id(file_descriptor) != expected_mount_id:
+ raise ValueError(f"Refusing to prune mounted content: {path}")
+
+
+def same_entry(actual_stat, expected_stat):
+ return (
+ actual_stat.st_dev == expected_stat.st_dev
+ and actual_stat.st_ino == expected_stat.st_ino
+ )
+
+
+def fd_path(file_descriptor):
+ try:
+ return Path(os.readlink(f"/proc/self/fd/{file_descriptor}"))
+ except OSError as err:
+ raise OSError(
+ f"Failed to resolve file descriptor {file_descriptor}: {err}"
+ ) from err
+
+
+def open_directory_node(root_fd, node, expected_mount_id):
+ chain = []
+ current = node
+ while current is not None:
+ chain.append(current)
+ current = current["parent"]
+
+ directory_fd = os.dup(root_fd)
+ try:
+ for item in reversed(chain):
+ next_fd = os.open(item["name"], DIRECTORY_OPEN_FLAGS, dir_fd=directory_fd)
+ os.close(directory_fd)
+ directory_fd = next_fd
+ validate_open_entry(
+ directory_fd, item["stat"], expected_mount_id, item["path"]
+ )
+ return directory_fd
+ except BaseException:
+ os.close(directory_fd)
+ raise
+
+
+def remove_empty_directory(root_fd, node, expected_mount_id):
+ parent_fd = (
+ os.dup(root_fd)
+ if node["parent"] is None
+ else open_directory_node(root_fd, node["parent"], expected_mount_id)
+ )
+ try:
+ current_stat = os.stat(
+ node["name"],
+ dir_fd=parent_fd,
+ follow_symlinks=False,
+ )
+ if not same_entry(current_stat, node["stat"]):
+ raise ValueError(f"Filesystem entry changed before pruning: {node['path']}")
+ os.rmdir(node["name"], dir_fd=parent_fd)
+ except OSError as err:
+ raise OSError(f"Failed to remove directory {node['path']}: {err}") from err
+ finally:
+ os.close(parent_fd)
+
+
+def remove_file_entry(directory_fd, name, expected_stat, expected_mount_id, path):
+ child_fd = os.open(name, ENTRY_OPEN_FLAGS, dir_fd=directory_fd)
+ try:
+ validate_open_entry(child_fd, expected_stat, expected_mount_id, path)
+ os.unlink(name, dir_fd=directory_fd)
+ except OSError as err:
+ raise OSError(f"Failed to remove file {path}: {err}") from err
+ finally:
+ os.close(child_fd)
+
+
+def remove_directory_tree(root_fd, name, expected_stat, expected_mount_id, path):
+ current = {
+ "name": name,
+ "parent": None,
+ "path": path,
+ "stat": expected_stat,
+ }
+ while current is not None:
+ directory_fd = open_directory_node(root_fd, current, expected_mount_id)
+ child_node = None
+ removed_current = False
+ try:
+ with os.scandir(directory_fd) as entries:
+ entry = next(entries, None)
+ if entry is None:
+ remove_empty_directory(root_fd, current, expected_mount_id)
+ removed_current = True
+ else:
+ child_stat = entry.stat(follow_symlinks=False)
+ child_path = current["path"] / entry.name
+ if stat.S_ISDIR(child_stat.st_mode):
+ child_node = {
+ "name": entry.name,
+ "parent": current,
+ "path": child_path,
+ "stat": child_stat,
+ }
+ else:
+ remove_file_entry(
+ directory_fd,
+ entry.name,
+ child_stat,
+ expected_mount_id,
+ child_path,
+ )
+ finally:
+ os.close(directory_fd)
+
+ if child_node is not None:
+ current = child_node
+ elif removed_current:
+ current = current["parent"]
+
+
+def create_quarantine(workshop_fd, expected_mount_id):
+ for _ in range(10):
+ name = f"{PRUNE_QUARANTINE_PREFIX}{secrets.token_hex(8)}"
+ try:
+ os.mkdir(name, mode=0o700, dir_fd=workshop_fd)
+ except FileExistsError:
+ continue
+ quarantine_fd = None
+ try:
+ sync_directory(workshop_fd)
+ quarantine_stat = os.stat(name, dir_fd=workshop_fd, follow_symlinks=False)
+ quarantine_fd = os.open(name, DIRECTORY_OPEN_FLAGS, dir_fd=workshop_fd)
+ validate_open_entry(
+ quarantine_fd,
+ quarantine_stat,
+ expected_mount_id,
+ fd_path(quarantine_fd),
+ )
+ return name, quarantine_fd
+ except BaseException as err:
+ if quarantine_fd is not None:
+ os.close(quarantine_fd)
+ try:
+ os.rmdir(name, dir_fd=workshop_fd)
+ sync_directory(workshop_fd)
+ except OSError as cleanup_err:
+ raise cleanup_err from err
+ raise
+ raise OSError("Failed to create a unique mod pruning quarantine")
+
+
+def write_json_at(directory_fd, name, content, size_limit):
+ encoded = json.dumps(content).encode("utf-8")
+ if len(encoded) > size_limit:
+ raise ValueError(f"{name} exceeds the metadata size limit")
+
+ flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_CLOEXEC
+ file_fd = None
+ try:
+ file_fd = os.open(name, flags, 0o600, dir_fd=directory_fd)
+ with os.fdopen(file_fd, "wb") as output_file:
+ file_fd = None
+ output_file.write(encoded)
+ output_file.flush()
+ os.fsync(output_file.fileno())
+ except OSError as err:
+ raise OSError(f"Failed to write {name}: {err}") from err
+ finally:
+ if file_fd is not None:
+ os.close(file_fd)
+
+
+def read_json_at(directory_fd, name, size_limit):
+ flags = os.O_RDONLY | os.O_NONBLOCK | os.O_NOFOLLOW | os.O_CLOEXEC
+ file_fd = None
+ try:
+ file_fd = os.open(name, flags, dir_fd=directory_fd)
+ file_stat = os.fstat(file_fd)
+ if not stat.S_ISREG(file_stat.st_mode):
+ raise ValueError(f"{name} is not a regular file")
+ if file_stat.st_size > size_limit:
+ raise ValueError(f"{name} exceeds the metadata size limit")
+ with os.fdopen(file_fd, "rb") as input_file:
+ file_fd = None
+ content = input_file.read(size_limit + 1)
+ if len(content) > size_limit:
+ raise ValueError(f"{name} exceeds the metadata size limit")
+ return json.loads(content.decode("utf-8"))
+ except FileNotFoundError:
+ raise
+ except (OSError, UnicodeError, ValueError) as err:
+ raise ValueError(f"Failed to load {name}: {err}") from err
+ finally:
+ if file_fd is not None:
+ os.close(file_fd)
+
+
+def sync_directory(directory_fd):
+ try:
+ os.fsync(directory_fd)
+ except OSError as err:
+ raise OSError(f"Failed to sync directory: {err}") from err
+
+
+def prune_manifest(candidates):
+ return {
+ "mods": {
+ installed_mod["id"]: {
+ "device": installed_mod["stat"].st_dev,
+ "inode": installed_mod["stat"].st_ino,
+ }
+ for installed_mod in candidates
+ }
+ }
+
+
+def load_prune_manifest(quarantine_fd):
+ manifest = read_json_at(quarantine_fd, PRUNE_MANIFEST_FILE, MAX_PRUNE_MANIFEST_SIZE)
+ mods = manifest.get("mods") if isinstance(manifest, dict) else None
+ if not isinstance(mods, dict):
+ raise ValueError(f"Invalid {PRUNE_MANIFEST_FILE}")
+ for mod_id, identity in mods.items():
+ validate_mod_id(mod_id, PRUNE_MANIFEST_FILE)
+ if (
+ not isinstance(identity, dict)
+ or not isinstance(identity.get("device"), int)
+ or not isinstance(identity.get("inode"), int)
+ ):
+ raise ValueError(f"Invalid mod identity in {PRUNE_MANIFEST_FILE}")
+ return manifest
+
+
+def delete_quarantined_mods(
+ quarantine_fd,
+ manifest,
+ expected_mount_id,
+ quarantine_path,
+):
+ for mod_id, identity in manifest["mods"].items():
+ try:
+ mod_stat = os.stat(mod_id, dir_fd=quarantine_fd, follow_symlinks=False)
+ except FileNotFoundError:
+ continue
+ if (
+ not stat.S_ISDIR(mod_stat.st_mode)
+ or mod_stat.st_dev != identity["device"]
+ or mod_stat.st_ino != identity["inode"]
+ ):
+ raise ValueError(f"Invalid quarantined mod entry: {mod_id}")
+ remove_directory_tree(
+ quarantine_fd,
+ mod_id,
+ mod_stat,
+ expected_mount_id,
+ quarantine_path / mod_id,
+ )
+ sync_directory(quarantine_fd)
+ try:
+ os.unlink(PRUNE_MANIFEST_FILE, dir_fd=quarantine_fd)
+ except OSError as err:
+ raise OSError(f"Failed to remove {PRUNE_MANIFEST_FILE}: {err}") from err
+ sync_directory(quarantine_fd)
+
+
+def recover_prune_quarantines(workshop_fd, expected_mount_id, workshop_root):
+ with os.scandir(workshop_fd) as entries:
+ quarantine_names = [
+ entry.name for entry in entries if PRUNE_QUARANTINE_RE.fullmatch(entry.name)
+ ]
+
+ for quarantine_name in quarantine_names:
+ quarantine_path = workshop_root / quarantine_name
+ try:
+ quarantine_stat = os.stat(
+ quarantine_name, dir_fd=workshop_fd, follow_symlinks=False
+ )
+ except OSError as err:
+ raise OSError(f"Failed to inspect {quarantine_path}: {err}") from err
+ if not stat.S_ISDIR(quarantine_stat.st_mode):
+ raise ValueError(f"Invalid mod pruning quarantine: {quarantine_path}")
+ quarantine_fd = os.open(
+ quarantine_name, DIRECTORY_OPEN_FLAGS, dir_fd=workshop_fd
+ )
+ try:
+ validate_open_entry(
+ quarantine_fd,
+ quarantine_stat,
+ expected_mount_id,
+ quarantine_path,
+ )
+ try:
+ manifest = load_prune_manifest(quarantine_fd)
+ except FileNotFoundError as err:
+ with os.scandir(quarantine_fd) as entries:
+ if next(entries, None) is not None:
+ raise ValueError(
+ f"Incomplete mod pruning quarantine: {quarantine_path}"
+ ) from err
+ else:
+ delete_quarantined_mods(
+ quarantine_fd,
+ manifest,
+ expected_mount_id,
+ quarantine_path,
+ )
+ finally:
+ os.close(quarantine_fd)
+ try:
+ os.rmdir(quarantine_name, dir_fd=workshop_fd)
+ except OSError as err:
+ raise OSError(f"Failed to remove {quarantine_path}: {err}") from err
+ sync_directory(workshop_fd)
+ print(f"Recovered interrupted mod pruning quarantine {quarantine_path}")
+
+
+def rollback_staged_mods(workshop_fd, quarantine_fd, staged_mods):
+ failures = []
+ for installed_mod in reversed(staged_mods):
+ mod_id = installed_mod["id"]
+ try:
+ quarantined_stat = os.stat(
+ mod_id, dir_fd=quarantine_fd, follow_symlinks=False
+ )
+ except FileNotFoundError:
+ try:
+ workshop_stat = os.stat(
+ mod_id, dir_fd=workshop_fd, follow_symlinks=False
+ )
+ except OSError as err:
+ failures.append(f"{mod_id}: {err}")
+ else:
+ if not same_entry(workshop_stat, installed_mod["stat"]):
+ failures.append(f"{mod_id}: workshop entry changed")
+ continue
+ if not same_entry(quarantined_stat, installed_mod["stat"]):
+ failures.append(f"{mod_id}: quarantined entry changed")
+ continue
+ try:
+ os.rename(
+ mod_id,
+ mod_id,
+ src_dir_fd=quarantine_fd,
+ dst_dir_fd=workshop_fd,
+ )
+ except OSError as err:
+ failures.append(f"{mod_id}: {err}")
+ sync_directory(quarantine_fd)
+ sync_directory(workshop_fd)
+ if failures:
+ raise OSError(f"Failed to roll back staged mods: {', '.join(failures)}")
+
+
+def stage_prune_candidates(workshop_fd, expected_mount_id, candidates):
+ quarantine_name, quarantine_fd = create_quarantine(workshop_fd, expected_mount_id)
+ staged_mods = []
+ try:
+ write_json_at(
+ quarantine_fd,
+ PRUNE_MANIFEST_FILE,
+ prune_manifest(candidates),
+ MAX_PRUNE_MANIFEST_SIZE,
+ )
+ sync_directory(quarantine_fd)
+ for installed_mod in candidates:
+ mod_id = installed_mod["id"]
+ staged_mods.append(installed_mod)
+ os.rename(
+ mod_id,
+ mod_id,
+ src_dir_fd=workshop_fd,
+ dst_dir_fd=quarantine_fd,
+ )
+ staged_stat = os.stat(mod_id, dir_fd=quarantine_fd, follow_symlinks=False)
+ if not same_entry(staged_stat, installed_mod["stat"]):
+ raise ValueError(
+ f"Mod directory changed before pruning: {installed_mod['path']}"
+ )
+ staged_fd = os.open(mod_id, DIRECTORY_OPEN_FLAGS, dir_fd=quarantine_fd)
+ try:
+ validate_open_entry(
+ staged_fd,
+ installed_mod["stat"],
+ expected_mount_id,
+ installed_mod["path"],
+ )
+ finally:
+ os.close(staged_fd)
+ sync_directory(quarantine_fd)
+ sync_directory(workshop_fd)
+ return quarantine_name, quarantine_fd
+ except BaseException as err:
+ try:
+ rollback_staged_mods(workshop_fd, quarantine_fd, staged_mods)
+ with suppress(FileNotFoundError):
+ os.unlink(PRUNE_MANIFEST_FILE, dir_fd=quarantine_fd)
+ sync_directory(quarantine_fd)
+ os.rmdir(quarantine_name, dir_fd=workshop_fd)
+ sync_directory(workshop_fd)
+ except OSError as rollback_err:
+ raise rollback_err from err
+ finally:
+ os.close(quarantine_fd)
+ raise
+
+
+def scan_installed_mods(workshop_fd, workshop_root):
+ installed_mods = {}
+ invalid_mods = {}
+ with os.scandir(workshop_fd) as entries:
+ for entry in entries:
+ mod_id = entry.name
+ if not MOD_ID_RE.fullmatch(mod_id):
+ continue
+ mod_path = workshop_root / mod_id
+ if not entry.is_dir(follow_symlinks=False):
+ err = ValueError(f"{mod_path} is not a regular directory")
+ invalid_mods[mod_id] = err
+ print(f"Skipping invalid mod directory {mod_path}: {err}")
+ continue
+ try:
+ mod_fd = os.open(mod_id, DIRECTORY_OPEN_FLAGS, dir_fd=workshop_fd)
+ try:
+ installed_mods[mod_id] = load_installed_mod(
+ mod_id, mod_fd, mod_path
+ )
+ finally:
+ os.close(mod_fd)
+ except (OSError, ValueError) as err:
+ invalid_mods[mod_id] = err
+ print(f"Skipping invalid mod directory {mod_path}: {err}")
+ return installed_mods, invalid_mods
+
+
+def retained_mod_ids(configured_ids, installed_mods, invalid_mods):
+ retained_ids = set()
+ pending_ids = list(configured_ids)
+ while pending_ids:
+ mod_id = pending_ids.pop()
+ if mod_id in retained_ids:
+ continue
+ retained_ids.add(mod_id)
+ if mod_id in invalid_mods:
+ raise ValueError(
+ f"Cannot safely prune because required mod {mod_id} is invalid: "
+ f"{invalid_mods[mod_id]}"
+ )
+ installed_mod = installed_mods.get(mod_id)
+ if installed_mod is not None:
+ pending_ids.extend(installed_mod["dependencies"])
+ return retained_ids
+
+
+def validate_prune_candidates(workshop_fd, candidates):
+ mount_paths = mounted_paths()
+ for installed_mod in candidates:
+ mod_id = installed_mod["id"]
+ mod_path = installed_mod["path"]
+ try:
+ current_stat = os.stat(mod_id, dir_fd=workshop_fd, follow_symlinks=False)
+ except OSError as err:
+ raise ValueError(
+ f"Mod directory changed before pruning: {mod_path}"
+ ) from err
+ if not stat.S_ISDIR(current_stat.st_mode) or not same_entry(
+ current_stat, installed_mod["stat"]
+ ):
+ raise ValueError(f"Mod directory changed before pruning: {mod_path}")
+ if contains_mount(mod_path, mount_paths):
+ raise ValueError(f"Refusing to prune mounted content: {mod_path}")
+
+
+def delete_prune_candidates(workshop_fd, expected_mount_id, candidates):
+ quarantine_name, quarantine_fd = stage_prune_candidates(
+ workshop_fd, expected_mount_id, candidates
+ )
+ pruned_paths = []
+ try:
+ for installed_mod in candidates:
+ remove_directory_tree(
+ quarantine_fd,
+ installed_mod["id"],
+ installed_mod["stat"],
+ expected_mount_id,
+ installed_mod["path"],
+ )
+ print(
+ f"Pruned mod {installed_mod['name']} "
+ f"({installed_mod['id']}) from {installed_mod['path']}"
+ )
+ pruned_paths.append(installed_mod["path"])
+ sync_directory(quarantine_fd)
+ try:
+ os.unlink(PRUNE_MANIFEST_FILE, dir_fd=quarantine_fd)
+ except OSError as err:
+ raise OSError(f"Failed to remove {PRUNE_MANIFEST_FILE}: {err}") from err
+ sync_directory(quarantine_fd)
+ finally:
+ os.close(quarantine_fd)
+
+ try:
+ os.rmdir(quarantine_name, dir_fd=workshop_fd)
+ except OSError as err:
+ raise OSError(f"Failed to remove mod pruning quarantine: {err}") from err
+ sync_directory(workshop_fd)
+ return pruned_paths
+
+
+def prune_mods(config_path, workshop_dir):
+ configured_ids = configured_mod_ids(config_path)
+ try:
+ workshop_fd = os.open(workshop_dir, WORKSHOP_OPEN_FLAGS)
+ except FileNotFoundError:
+ return []
+ try:
+ fcntl.flock(workshop_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
+ except OSError:
+ os.close(workshop_fd)
+ raise
+
+ try:
+ workshop_root = fd_path(workshop_fd)
+ workshop_mount_id = fd_mount_id(workshop_fd)
+ recover_prune_quarantines(workshop_fd, workshop_mount_id, workshop_root)
+
+ installed_mods, invalid_mods = scan_installed_mods(workshop_fd, workshop_root)
+ retained_ids = retained_mod_ids(configured_ids, installed_mods, invalid_mods)
+ candidates = [
+ installed_mod
+ for mod_id, installed_mod in sorted(installed_mods.items())
+ if mod_id not in retained_ids
+ ]
+ if not candidates:
+ return []
+
+ validate_prune_candidates(workshop_fd, candidates)
+ return delete_prune_candidates(workshop_fd, workshop_mount_id, candidates)
+ finally:
+ os.close(workshop_fd)
+
+
+SERVER_ENV_MAP = (
+ ("SERVER_BIND_ADDRESS", "bindAddress", env_str),
+ ("SERVER_BIND_PORT", "bindPort", parse_int),
+ ("SERVER_PUBLIC_ADDRESS", "publicAddress", env_str),
+ ("SERVER_PUBLIC_PORT", "publicPort", parse_int),
+)
+GAME_ENV_MAP = (
+ ("GAME_NAME", "name", env_str),
+ ("GAME_PASSWORD", "password", env_str),
+ ("GAME_PASSWORD_ADMIN", "passwordAdmin", env_str),
+ ("GAME_ADMINS", "admins", env_csv),
+ ("GAME_SCENARIO_ID", "scenarioId", env_str),
+ ("GAME_MAX_PLAYERS", "maxPlayers", parse_int),
+ ("GAME_VISIBLE", "visible", env_bool),
+ ("GAME_SUPPORTED_PLATFORMS", "supportedPlatforms", env_csv),
+ ("GAME_CROSS_PLATFORM", "crossPlatform", env_bool),
+ ("GAME_MODS_REQUIRED_BY_DEFAULT", "modsRequiredByDefault", env_bool),
+)
+GAME_PROPS_ENV_MAP = (
+ ("GAME_PROPS_BATTLEYE", "battlEye", env_bool),
+ ("GAME_PROPS_DISABLE_THIRD_PERSON", "disableThirdPerson", env_bool),
+ ("GAME_PROPS_FAST_VALIDATION", "fastValidation", env_bool),
+ ("GAME_PROPS_SERVER_MAX_VIEW_DISTANCE", "serverMaxViewDistance", parse_int),
+ ("GAME_PROPS_SERVER_MIN_GRASS_DISTANCE", "serverMinGrassDistance", parse_int),
+ ("GAME_PROPS_NETWORK_VIEW_DISTANCE", "networkViewDistance", parse_int),
+ ("GAME_PROPS_VON_DISABLE_UI", "VONDisableUI", env_bool),
+ ("GAME_PROPS_VON_DISABLE_DIRECT_SPEECH_UI", "VONDisableDirectSpeechUI", env_bool),
+ (
+ "GAME_PROPS_VON_CAN_TRANSMIT_CROSS_FACTION",
+ "VONCanTransmitCrossFaction",
+ env_bool,
+ ),
+)
+PERSISTENCE_ENV_MAP = (
+ ("PERSISTENCE_AUTO_SAVE_INTERVAL", "autoSaveInterval", parse_int),
+ ("PERSISTENCE_SAVE_RETENTION", "saveRetention", parse_int),
+ ("PERSISTENCE_LOAD_SESSION_SAVE", "loadSessionSave", env_bool),
+ ("PERSISTENCE_KEEP_SESSION_SAVE", "keepSessionSave", env_bool),
+ ("PERSISTENCE_HIVE_ID", "hiveId", parse_int),
+)
+PERSISTENCE_ENV_KEYS = tuple(key for key, _, _ in PERSISTENCE_ENV_MAP) + (
+ "PERSISTENCE_JSON_FILE_PATH",
+)
+OPERATING_ENV_MAP = (
+ ("OPERATING_LOBBY_PLAYER_SYNCHRONISE", "lobbyPlayerSynchronise", env_bool),
+ ("OPERATING_DISABLE_CRASH_REPORTER", "disableCrashReporter", env_bool),
+ (
+ "OPERATING_DISABLE_NAVMESH_STREAMING",
+ "disableNavmeshStreaming",
+ env_navmesh_streaming,
+ ),
+ ("OPERATING_DISABLE_SERVER_SHUTDOWN", "disableServerShutdown", env_bool),
+ ("OPERATING_DISABLE_AI", "disableAI", env_bool),
+ ("OPERATING_PLAYER_SAVE_TIME", "playerSaveTime", parse_int),
+ ("OPERATING_AI_LIMIT", "aiLimit", parse_int),
+ ("OPERATING_SLOT_RESERVATION_TIMEOUT", "slotReservationTimeout", parse_int),
+)
+
+
+def apply_env_overrides(target, env, env_map):
+ for key, name, convert in env_map:
+ if env_defined(env, key):
+ target[name] = convert(env, key)
+
+
+def apply_server_config(config, env):
+ apply_env_overrides(config, env, SERVER_ENV_MAP)
+ if env_defined(env, "SERVER_A2S_ADDRESS") and env_defined(env, "SERVER_A2S_PORT"):
+ config["a2s"] = {
+ "address": env["SERVER_A2S_ADDRESS"],
+ "port": parse_int(env, "SERVER_A2S_PORT"),
+ }
+ else:
+ config.pop("a2s", None)
+
+
+def apply_rcon_config(config, env):
+ required_keys = ("RCON_PASSWORD", "RCON_ADDRESS", "RCON_PORT")
+ if not all(env_defined(env, key) for key in required_keys):
+ config.pop("rcon", None)
+ return
+ if env_defined(env, "RCON_BLACKLIST") and env_defined(env, "RCON_WHITELIST"):
+ raise ValueError("RCON_BLACKLIST and RCON_WHITELIST cannot both be set")
+
+ rcon = {
+ "address": env["RCON_ADDRESS"],
+ "port": parse_int(env, "RCON_PORT"),
+ "password": env["RCON_PASSWORD"],
+ "permission": env.get("RCON_PERMISSION")
+ or config.get("rcon", {}).get("permission")
+ or "admin",
+ }
+ if env_defined(env, "RCON_MAX_CLIENTS"):
+ rcon["maxClients"] = parse_int(env, "RCON_MAX_CLIENTS")
+ if env_defined(env, "RCON_BLACKLIST"):
+ rcon["blacklist"] = split_csv(env["RCON_BLACKLIST"])
+ if env_defined(env, "RCON_WHITELIST"):
+ rcon["whitelist"] = split_csv(env["RCON_WHITELIST"])
+ config["rcon"] = rcon
+
+
+def apply_game_properties(config, env):
+ game_properties = config["game"]["gameProperties"]
+ apply_env_overrides(game_properties, env, GAME_PROPS_ENV_MAP)
+ if env_defined(env, "GAME_MISSION_HEADER_JSON_FILE_PATH"):
+ game_properties["missionHeader"] = load_json_file(
+ env["GAME_MISSION_HEADER_JSON_FILE_PATH"]
+ )
+ else:
+ game_properties["missionHeader"] = {}
+
+
+def default_mod_required(env):
+ if env_defined(env, "GAME_MODS_REQUIRED_BY_DEFAULT"):
+ return bool_str(env["GAME_MODS_REQUIRED_BY_DEFAULT"])
+ return None
+
+
+def parse_mods_ids_list(env, required_default, seen_ids):
+ if not MOD_ID_LIST_RE.match(env["GAME_MODS_IDS_LIST"]):
+ raise ValueError("Illegal characters in GAME_MODS_IDS_LIST env")
+
+ mods = []
+ for mod in split_csv(env["GAME_MODS_IDS_LIST"]):
+ mod_details = mod.split("=")
+ if not 0 < len(mod_details) < 3:
+ raise ValueError(f"{mod} mod not defined properly")
+ mod_id = validate_mod_id(mod_details[0], "GAME_MODS_IDS_LIST")
+ if mod_id in seen_ids:
+ continue
+ mod_config = {"modId": mod_id}
+ if len(mod_details) == 2:
+ if not MOD_VERSION_RE.match(mod_details[1]):
+ raise ValueError(f"{mod} mod version does not match the pattern")
+ mod_config["version"] = mod_details[1]
+ if required_default is not None:
+ mod_config["required"] = required_default
+ seen_ids.add(mod_id)
+ mods.append(mod_config)
+ return mods
+
+
+def parse_mods_json_file(env, required_default, seen_ids):
+ json_mods = load_json_file(env["GAME_MODS_JSON_FILE_PATH"])
+ if not isinstance(json_mods, list):
+ raise ValueError("GAME_MODS_JSON_FILE_PATH must contain an array")
+
+ allowed_keys = ("modId", "name", "version", "required")
+ mods = []
+ for provided_mod in json_mods:
+ if not isinstance(provided_mod, dict) or "modId" not in provided_mod:
+ raise ValueError(
+ "Entry in GAME_MODS_JSON_FILE_PATH file does not contain modId: "
+ f"{provided_mod}"
+ )
+ mod_id = validate_mod_id(provided_mod["modId"], "GAME_MODS_JSON_FILE_PATH")
+ if mod_id in seen_ids:
+ continue
+ valid_mod = {
+ key: provided_mod[key] for key in allowed_keys if key in provided_mod
+ }
+ if required_default is not None and "required" not in valid_mod:
+ valid_mod["required"] = required_default
+ seen_ids.add(mod_id)
+ mods.append(valid_mod)
+ return mods
+
+
+def apply_mods_config(config, env):
+ required_default = default_mod_required(env)
+ seen_ids = set()
+ mods = []
+ if env_defined(env, "GAME_MODS_IDS_LIST"):
+ mods.extend(parse_mods_ids_list(env, required_default, seen_ids))
+ if env_defined(env, "GAME_MODS_JSON_FILE_PATH"):
+ mods.extend(parse_mods_json_file(env, required_default, seen_ids))
+ config["game"]["mods"] = mods
+
+
+def apply_persistence_config(config, env):
+ game_properties = config["game"]["gameProperties"]
+ if not any(env_defined(env, key) for key in PERSISTENCE_ENV_KEYS):
+ game_properties.pop("persistence", None)
+ return
+
+ persistence = {}
+ apply_env_overrides(persistence, env, PERSISTENCE_ENV_MAP)
+ if env_defined(env, "PERSISTENCE_JSON_FILE_PATH"):
+ persistence_json = load_json_file(env["PERSISTENCE_JSON_FILE_PATH"])
+ for key in ("databases", "storages"):
+ if key in persistence_json:
+ persistence[key] = persistence_json[key]
+ game_properties["persistence"] = persistence
+
+
+def apply_operating_config(config, env):
+ operating = {}
+ apply_env_overrides(operating, env, OPERATING_ENV_MAP)
+ if env_defined(env, "OPERATING_JOIN_QUEUE_MAX_SIZE"):
+ operating["joinQueue"] = {
+ "maxSize": parse_int(env, "OPERATING_JOIN_QUEUE_MAX_SIZE")
+ }
+ if operating:
+ config["operating"] = operating
+ else:
+ config.pop("operating", None)
+
+
+def build_config(env, base_config):
+ config = copy.deepcopy(base_config)
+ apply_server_config(config, env)
+ apply_rcon_config(config, env)
+ apply_env_overrides(config["game"], env, GAME_ENV_MAP)
+ apply_game_properties(config, env)
+ apply_mods_config(config, env)
+ apply_persistence_config(config, env)
+ apply_operating_config(config, env)
+ return config
diff --git a/tests/conftest.py b/tests/conftest.py
new file mode 100644
index 0000000000000000000000000000000000000000..02c1cec9f5222a2af0b737aee2d2dfcee41fc15f
--- /dev/null
+++ b/tests/conftest.py
@@ -0,0 +1,12 @@
+from pathlib import Path
+
+import pytest
+
+from launch_config import load_json_file
+
+REPO_ROOT = Path(__file__).resolve().parent.parent
+
+
+@pytest.fixture
+def base_config():
+ return load_json_file(REPO_ROOT / "src" / "docker_default.json")
diff --git a/tests/test_launch_config.py b/tests/test_launch_config.py
new file mode 100644
index 0000000000000000000000000000000000000000..3d13deae39c6809b79cbf68ea3aa8088e88a8e2e
--- /dev/null
+++ b/tests/test_launch_config.py
@@ -0,0 +1,457 @@
+import json
+
+import pytest
+
+from launch_config import bool_str, build_config, env_defined
+
+MOD_A = "1111111111111111"
+MOD_B = "2222222222222222"
+
+
+def write_json(tmp_path, name, content):
+ path = tmp_path / name
+ path.write_text(json.dumps(content))
+ return path
+
+
+def test_env_defined():
+ assert env_defined({"FOO": "bar"}, "FOO")
+ assert not env_defined({"FOO": ""}, "FOO")
+ assert not env_defined({}, "FOO")
+
+
+def test_bool_str():
+ assert bool_str("true")
+ assert bool_str("TRUE")
+ assert bool_str("True")
+ assert not bool_str("false")
+ assert not bool_str("")
+ assert not bool_str("yes")
+
+
+def test_defaults_preserved(base_config):
+ env = {}
+ config = build_config(env, base_config)
+ assert config["game"]["name"] == "Arma Reforger Docker Server"
+ assert config["game"]["maxPlayers"] == 64
+ assert config["bindPort"] == 2001
+
+
+def test_server_overrides(base_config):
+ env = {
+ "SERVER_BIND_ADDRESS": "127.0.0.1",
+ "SERVER_BIND_PORT": "3001",
+ "SERVER_PUBLIC_ADDRESS": "1.2.3.4",
+ "SERVER_PUBLIC_PORT": "3002",
+ }
+ config = build_config(env, base_config)
+ assert config["bindAddress"] == "127.0.0.1"
+ assert config["bindPort"] == 3001
+ assert config["publicAddress"] == "1.2.3.4"
+ assert config["publicPort"] == 3002
+
+
+def test_a2s_config(base_config):
+ env = {
+ "SERVER_A2S_ADDRESS": "0.0.0.0",
+ "SERVER_A2S_PORT": "17777",
+ }
+ config = build_config(env, base_config)
+ assert config["a2s"]["address"] == "0.0.0.0"
+ assert config["a2s"]["port"] == 17777
+
+
+def test_a2s_removed_when_partial(base_config):
+ env = {"SERVER_A2S_ADDRESS": "0.0.0.0"}
+ config = build_config(env, base_config)
+ assert "a2s" not in config
+
+
+def test_rcon_config(base_config):
+ env = {
+ "RCON_ADDRESS": "0.0.0.0",
+ "RCON_PORT": "19999",
+ "RCON_PASSWORD": "secret",
+ "RCON_PERMISSION": "admin",
+ "RCON_MAX_CLIENTS": "10",
+ }
+ config = build_config(env, base_config)
+ assert config["rcon"]["address"] == "0.0.0.0"
+ assert config["rcon"]["port"] == 19999
+ assert config["rcon"]["password"] == "secret"
+ assert config["rcon"]["permission"] == "admin"
+ assert config["rcon"]["maxClients"] == 10
+
+
+def test_rcon_permission_defaults_to_admin(base_config):
+ env = {
+ "RCON_ADDRESS": "0.0.0.0",
+ "RCON_PORT": "19999",
+ "RCON_PASSWORD": "secret",
+ }
+ config = build_config(env, base_config)
+ assert config["rcon"]["permission"] == "admin"
+
+
+def test_rcon_blacklist(base_config):
+ env = {
+ "RCON_ADDRESS": "0.0.0.0",
+ "RCON_PORT": "19999",
+ "RCON_PASSWORD": "secret",
+ "RCON_PERMISSION": "admin",
+ "RCON_BLACKLIST": "kick,ban",
+ }
+ config = build_config(env, base_config)
+ assert config["rcon"]["blacklist"] == ["kick", "ban"]
+
+
+def test_rcon_whitelist(base_config):
+ env = {
+ "RCON_ADDRESS": "0.0.0.0",
+ "RCON_PORT": "19999",
+ "RCON_PASSWORD": "secret",
+ "RCON_PERMISSION": "admin",
+ "RCON_WHITELIST": "help,status",
+ }
+ config = build_config(env, base_config)
+ assert config["rcon"]["whitelist"] == ["help", "status"]
+
+
+def test_rcon_blacklist_and_whitelist_fails(base_config):
+ env = {
+ "RCON_ADDRESS": "0.0.0.0",
+ "RCON_PORT": "19999",
+ "RCON_PASSWORD": "secret",
+ "RCON_PERMISSION": "admin",
+ "RCON_BLACKLIST": "kick",
+ "RCON_WHITELIST": "help",
+ }
+ with pytest.raises(ValueError, match="cannot both be set"):
+ build_config(env, base_config)
+
+
+def test_game_overrides(base_config):
+ env = {
+ "GAME_NAME": "My Server",
+ "GAME_PASSWORD": "mypassword",
+ "GAME_SCENARIO_ID": "{FOO}Missions/01.conf",
+ "GAME_MAX_PLAYERS": "32",
+ "GAME_VISIBLE": "false",
+ "GAME_CROSS_PLATFORM": "true",
+ }
+ config = build_config(env, base_config)
+ assert config["game"]["name"] == "My Server"
+ assert config["game"]["password"] == "mypassword"
+ assert config["game"]["scenarioId"] == "{FOO}Missions/01.conf"
+ assert config["game"]["maxPlayers"] == 32
+ assert not config["game"]["visible"]
+ assert config["game"]["crossPlatform"]
+
+
+def test_game_admins(base_config):
+ env = {"GAME_ADMINS": "admin1,admin2,,admin3"}
+ config = build_config(env, base_config)
+ assert config["game"]["admins"] == ["admin1", "admin2", "admin3"]
+
+
+def test_game_supported_platforms(base_config):
+ env = {"GAME_SUPPORTED_PLATFORMS": "PLATFORM_PC,PLATFORM_XBL"}
+ config = build_config(env, base_config)
+ assert config["game"]["supportedPlatforms"] == ["PLATFORM_PC", "PLATFORM_XBL"]
+
+
+def test_mods_required_by_default(base_config):
+ env = {"GAME_MODS_REQUIRED_BY_DEFAULT": "true"}
+ config = build_config(env, base_config)
+ assert config["game"]["modsRequiredByDefault"]
+
+
+def test_mods_ids_list(base_config):
+ env = {"GAME_MODS_IDS_LIST": f"{MOD_A}=1.0.0,{MOD_B}"}
+ config = build_config(env, base_config)
+ assert len(config["game"]["mods"]) == 2
+ assert config["game"]["mods"][0] == {"modId": MOD_A, "version": "1.0.0"}
+ assert config["game"]["mods"][1] == {"modId": MOD_B}
+
+
+def test_mods_ids_list_with_required(base_config):
+ env = {
+ "GAME_MODS_IDS_LIST": f"{MOD_A}=1.0.0",
+ "GAME_MODS_REQUIRED_BY_DEFAULT": "true",
+ }
+ config = build_config(env, base_config)
+ assert config["game"]["mods"][0]["required"]
+
+
+def test_mods_ids_list_invalid_chars(base_config):
+ env = {"GAME_MODS_IDS_LIST": f"{MOD_A}=1.0.0;bad"}
+ with pytest.raises(ValueError, match="Illegal characters"):
+ build_config(env, base_config)
+
+
+def test_mods_ids_list_invalid_id(base_config):
+ env = {"GAME_MODS_IDS_LIST": "12345"}
+ with pytest.raises(ValueError, match="Invalid mod ID"):
+ build_config(env, base_config)
+
+
+def test_mods_ids_list_invalid_version(base_config):
+ env = {"GAME_MODS_IDS_LIST": f"{MOD_A}=BADVERSION"}
+ with pytest.raises(ValueError, match="version does not match"):
+ build_config(env, base_config)
+
+
+def test_mods_json_file(base_config, tmp_path):
+ mods_file = write_json(
+ tmp_path,
+ "mods.json",
+ [
+ {"modId": MOD_A, "name": "Test Mod", "version": "1.0.0"},
+ {"modId": MOD_B, "required": False},
+ ],
+ )
+ env = {"GAME_MODS_JSON_FILE_PATH": str(mods_file)}
+ config = build_config(env, base_config)
+ assert len(config["game"]["mods"]) == 2
+ assert config["game"]["mods"][0]["name"] == "Test Mod"
+ assert not config["game"]["mods"][1]["required"]
+
+
+def test_mods_json_missing_modid(base_config, tmp_path):
+ mods_file = write_json(tmp_path, "mods.json", [{"name": "Bad Mod"}])
+ env = {"GAME_MODS_JSON_FILE_PATH": str(mods_file)}
+ with pytest.raises(ValueError, match="does not contain modId"):
+ build_config(env, base_config)
+
+
+def test_mods_json_invalid_mod_id(base_config, tmp_path):
+ mods_file = write_json(tmp_path, "mods.json", [{"modId": "12345"}])
+ env = {"GAME_MODS_JSON_FILE_PATH": str(mods_file)}
+ with pytest.raises(ValueError, match="Invalid mod ID"):
+ build_config(env, base_config)
+
+
+def test_mods_json_must_be_array(base_config, tmp_path):
+ mods_file = write_json(tmp_path, "mods.json", {"modId": MOD_A})
+ env = {"GAME_MODS_JSON_FILE_PATH": str(mods_file)}
+ with pytest.raises(ValueError, match="must contain an array"):
+ build_config(env, base_config)
+
+
+def test_mods_deduplication(base_config, tmp_path):
+ """Mod IDs from GAME_MODS_IDS_LIST should skip duplicates from JSON."""
+ mods_file = write_json(
+ tmp_path, "mods.json", [{"modId": MOD_A, "name": "From JSON"}]
+ )
+ env = {
+ "GAME_MODS_IDS_LIST": MOD_A,
+ "GAME_MODS_JSON_FILE_PATH": str(mods_file),
+ }
+ config = build_config(env, base_config)
+ assert len(config["game"]["mods"]) == 1
+
+
+def test_persistence_config(base_config):
+ env = {
+ "PERSISTENCE_AUTO_SAVE_INTERVAL": "300",
+ "PERSISTENCE_SAVE_RETENTION": "5",
+ "PERSISTENCE_LOAD_SESSION_SAVE": "true",
+ "PERSISTENCE_KEEP_SESSION_SAVE": "false",
+ "PERSISTENCE_HIVE_ID": "123",
+ }
+ config = build_config(env, base_config)
+ persistence = config["game"]["gameProperties"]["persistence"]
+ assert persistence["autoSaveInterval"] == 300
+ assert persistence["saveRetention"] == 5
+ assert persistence["loadSessionSave"]
+ assert not persistence["keepSessionSave"]
+ assert persistence["hiveId"] == 123
+
+
+def test_persistence_json_merge(base_config, tmp_path):
+ persistence_file = write_json(
+ tmp_path,
+ "persistence.json",
+ {
+ "databases": {"foo": "bar"},
+ "storages": {"baz": "qux"},
+ "ignored": "should not appear",
+ },
+ )
+ env = {"PERSISTENCE_JSON_FILE_PATH": str(persistence_file)}
+ config = build_config(env, base_config)
+ persistence = config["game"]["gameProperties"]["persistence"]
+ assert persistence["databases"] == {"foo": "bar"}
+ assert persistence["storages"] == {"baz": "qux"}
+ assert "ignored" not in persistence
+
+
+def test_persistence_not_set_when_empty(base_config):
+ """When no persistence envs are set, key should not be added."""
+ env = {}
+ config = build_config(env, base_config)
+ assert "persistence" not in config["game"]["gameProperties"]
+
+
+def test_persistence_removed_when_env_cleared(base_config):
+ previous = build_config({"PERSISTENCE_HIVE_ID": "123"}, base_config)
+ config = build_config({}, previous)
+ assert "persistence" not in config["game"]["gameProperties"]
+
+
+def test_operating_config(base_config):
+ env = {
+ "OPERATING_LOBBY_PLAYER_SYNCHRONISE": "true",
+ "OPERATING_DISABLE_CRASH_REPORTER": "false",
+ "OPERATING_DISABLE_SERVER_SHUTDOWN": "true",
+ "OPERATING_DISABLE_AI": "false",
+ "OPERATING_PLAYER_SAVE_TIME": "120",
+ "OPERATING_AI_LIMIT": "50",
+ "OPERATING_SLOT_RESERVATION_TIMEOUT": "60",
+ "OPERATING_JOIN_QUEUE_MAX_SIZE": "10",
+ }
+ config = build_config(env, base_config)
+ operating = config["operating"]
+ assert operating["lobbyPlayerSynchronise"]
+ assert not operating["disableCrashReporter"]
+ assert operating["disableServerShutdown"]
+ assert not operating["disableAI"]
+ assert operating["playerSaveTime"] == 120
+ assert operating["aiLimit"] == 50
+ assert operating["slotReservationTimeout"] == 60
+ assert operating["joinQueue"]["maxSize"] == 10
+
+
+def test_operating_navmesh_all(base_config):
+ env = {"OPERATING_DISABLE_NAVMESH_STREAMING": "all"}
+ config = build_config(env, base_config)
+ assert config["operating"]["disableNavmeshStreaming"] == []
+
+
+def test_operating_navmesh_list(base_config):
+ env = {"OPERATING_DISABLE_NAVMESH_STREAMING": "foo,bar,baz"}
+ config = build_config(env, base_config)
+ assert config["operating"]["disableNavmeshStreaming"] == ["foo", "bar", "baz"]
+
+
+def test_operating_not_set_when_empty(base_config):
+ """When no operating envs are set, key should not be added."""
+ env = {}
+ config = build_config(env, base_config)
+ assert "operating" not in config
+
+
+def test_operating_removed_when_env_cleared(base_config):
+ previous = build_config({"OPERATING_AI_LIMIT": "50"}, base_config)
+ config = build_config({}, previous)
+ assert "operating" not in config
+
+
+def test_mission_header_json(base_config, tmp_path):
+ mission_file = write_json(tmp_path, "mission.json", {"myKey": "myValue"})
+ env = {"GAME_MISSION_HEADER_JSON_FILE_PATH": str(mission_file)}
+ config = build_config(env, base_config)
+ assert config["game"]["gameProperties"]["missionHeader"] == {"myKey": "myValue"}
+
+
+def test_mission_header_reset_when_env_cleared(base_config, tmp_path):
+ mission_file = write_json(tmp_path, "mission.json", {"myKey": "myValue"})
+ previous = build_config(
+ {"GAME_MISSION_HEADER_JSON_FILE_PATH": str(mission_file)}, base_config
+ )
+ config = build_config({}, previous)
+ assert config["game"]["gameProperties"]["missionHeader"] == {}
+
+
+def test_game_properties_booleans(base_config):
+ env = {
+ "GAME_PROPS_BATTLEYE": "false",
+ "GAME_PROPS_DISABLE_THIRD_PERSON": "true",
+ "GAME_PROPS_FAST_VALIDATION": "false",
+ "GAME_PROPS_VON_DISABLE_UI": "true",
+ "GAME_PROPS_VON_DISABLE_DIRECT_SPEECH_UI": "true",
+ "GAME_PROPS_VON_CAN_TRANSMIT_CROSS_FACTION": "true",
+ }
+ config = build_config(env, base_config)
+ game_properties = config["game"]["gameProperties"]
+ assert not game_properties["battlEye"]
+ assert game_properties["disableThirdPerson"]
+ assert not game_properties["fastValidation"]
+ assert game_properties["VONDisableUI"]
+ assert game_properties["VONDisableDirectSpeechUI"]
+ assert game_properties["VONCanTransmitCrossFaction"]
+
+
+def test_game_properties_integers(base_config):
+ env = {
+ "GAME_PROPS_SERVER_MAX_VIEW_DISTANCE": "3000",
+ "GAME_PROPS_SERVER_MIN_GRASS_DISTANCE": "100",
+ "GAME_PROPS_NETWORK_VIEW_DISTANCE": "2000",
+ }
+ config = build_config(env, base_config)
+ game_properties = config["game"]["gameProperties"]
+ assert game_properties["serverMaxViewDistance"] == 3000
+ assert game_properties["serverMinGrassDistance"] == 100
+ assert game_properties["networkViewDistance"] == 2000
+
+
+RCON_ENV = {
+ "RCON_ADDRESS": "0.0.0.0",
+ "RCON_PORT": "19999",
+ "RCON_PASSWORD": "secret",
+}
+
+# Every env var build_config maps onto the config, with a value that differs
+# from the default. Anything dropped from the env maps stops having an effect,
+# which is what this catches.
+ENV_OVERRIDES = [
+ {"SERVER_BIND_ADDRESS": "127.0.0.1"},
+ {"SERVER_BIND_PORT": "3001"},
+ {"SERVER_PUBLIC_ADDRESS": "1.2.3.4"},
+ {"SERVER_PUBLIC_PORT": "3002"},
+ {"SERVER_A2S_ADDRESS": "127.0.0.1", "SERVER_A2S_PORT": "17777"},
+ RCON_ENV,
+ RCON_ENV | {"RCON_PERMISSION": "monitor"},
+ RCON_ENV | {"RCON_MAX_CLIENTS": "10"},
+ RCON_ENV | {"RCON_BLACKLIST": "kick"},
+ RCON_ENV | {"RCON_WHITELIST": "help"},
+ {"GAME_NAME": "My Server"},
+ {"GAME_PASSWORD": "mypassword"},
+ {"GAME_PASSWORD_ADMIN": "myadminpassword"},
+ {"GAME_ADMINS": "admin1,admin2"},
+ {"GAME_SCENARIO_ID": "{FOO}Missions/01.conf"},
+ {"GAME_MAX_PLAYERS": "32"},
+ {"GAME_VISIBLE": "false"},
+ {"GAME_SUPPORTED_PLATFORMS": "PLATFORM_PC"},
+ {"GAME_CROSS_PLATFORM": "true"},
+ {"GAME_MODS_REQUIRED_BY_DEFAULT": "true"},
+ {"GAME_MODS_IDS_LIST": MOD_A},
+ {"GAME_PROPS_BATTLEYE": "false"},
+ {"GAME_PROPS_DISABLE_THIRD_PERSON": "true"},
+ {"GAME_PROPS_FAST_VALIDATION": "false"},
+ {"GAME_PROPS_SERVER_MAX_VIEW_DISTANCE": "3000"},
+ {"GAME_PROPS_SERVER_MIN_GRASS_DISTANCE": "100"},
+ {"GAME_PROPS_NETWORK_VIEW_DISTANCE": "2000"},
+ {"GAME_PROPS_VON_DISABLE_UI": "true"},
+ {"GAME_PROPS_VON_DISABLE_DIRECT_SPEECH_UI": "true"},
+ {"GAME_PROPS_VON_CAN_TRANSMIT_CROSS_FACTION": "true"},
+ {"PERSISTENCE_AUTO_SAVE_INTERVAL": "300"},
+ {"PERSISTENCE_SAVE_RETENTION": "5"},
+ {"PERSISTENCE_LOAD_SESSION_SAVE": "true"},
+ {"PERSISTENCE_KEEP_SESSION_SAVE": "true"},
+ {"PERSISTENCE_HIVE_ID": "123"},
+ {"OPERATING_LOBBY_PLAYER_SYNCHRONISE": "true"},
+ {"OPERATING_DISABLE_CRASH_REPORTER": "true"},
+ {"OPERATING_DISABLE_NAVMESH_STREAMING": "all"},
+ {"OPERATING_DISABLE_SERVER_SHUTDOWN": "true"},
+ {"OPERATING_DISABLE_AI": "true"},
+ {"OPERATING_PLAYER_SAVE_TIME": "120"},
+ {"OPERATING_AI_LIMIT": "50"},
+ {"OPERATING_SLOT_RESERVATION_TIMEOUT": "60"},
+ {"OPERATING_JOIN_QUEUE_MAX_SIZE": "10"},
+]
+
+
+@pytest.mark.parametrize("env", ENV_OVERRIDES, ids=lambda env: ",".join(sorted(env)))
+def test_env_override_reaches_the_config(base_config, env):
+ assert build_config(env, base_config) != build_config({}, base_config)
diff --git a/tests/test_mod_pruning.py b/tests/test_mod_pruning.py
new file mode 100644
index 0000000000000000000000000000000000000000..c772d42ecd9a1fb0b236a350dee0523b991cd485
--- /dev/null
+++ b/tests/test_mod_pruning.py
@@ -0,0 +1,570 @@
+import json
+import os
+import sys
+
+import pytest
+
+import launch_config
+from launch_config import prune_mods
+
+MOD_A = "1111111111111111"
+MOD_B = "2222222222222222"
+MOD_C = "3333333333333333"
+MOD_D = "4444444444444444"
+MOD_E = "5555555555555555"
+
+
+def write_config(tmp_path, mod_ids):
+ path = tmp_path / "config.json"
+ path.write_text(
+ json.dumps({"game": {"mods": [{"modId": mod_id} for mod_id in mod_ids]}})
+ )
+ return path
+
+
+def write_mod(workshop, mod_id, dependencies=None, encoding="utf-8"):
+ mod_dir = workshop / mod_id
+ mod_dir.mkdir()
+ server_data = {
+ "id": mod_id,
+ "name": f"Mod {mod_id}",
+ "revision": {
+ "version": "1.0.0",
+ "dependencies": dependencies or [],
+ "downloaded": True,
+ },
+ }
+ (mod_dir / "ServerData.json").write_text(json.dumps(server_data), encoding=encoding)
+ return mod_dir
+
+
+def patch_revision(mod_dir, **changes):
+ path = mod_dir / "ServerData.json"
+ server_data = json.loads(path.read_text())
+ server_data["revision"].update(changes)
+ path.write_text(json.dumps(server_data))
+
+
+def test_prunes_only_unreferenced_mods(tmp_path):
+ workshop = tmp_path / "workshop"
+ workshop.mkdir()
+ configured = write_mod(workshop, MOD_A)
+ stale = write_mod(workshop, MOD_B)
+ nested = stale / "data"
+ nested.mkdir()
+ (nested / "content.bin").write_bytes(b"content")
+ outside_file = tmp_path / "outside.txt"
+ outside_file.write_text("keep")
+ (stale / "outside-link").symlink_to(outside_file)
+ config = write_config(tmp_path, [MOD_A])
+
+ assert prune_mods(config, workshop) == [stale]
+ assert configured.exists()
+ assert not stale.exists()
+ assert outside_file.exists()
+
+
+def test_preserves_transitive_dependencies(tmp_path):
+ workshop = tmp_path / "workshop"
+ workshop.mkdir()
+ root = write_mod(workshop, MOD_A, [{"id": MOD_B}])
+ dependency = write_mod(workshop, MOD_B, [MOD_C])
+ transitive_dependency = write_mod(workshop, MOD_C)
+ stale = write_mod(workshop, MOD_D)
+ config = write_config(tmp_path, [MOD_A])
+
+ assert prune_mods(config, workshop) == [stale]
+ assert root.exists()
+ assert dependency.exists()
+ assert transitive_dependency.exists()
+
+
+def test_skips_directories_without_valid_server_data(tmp_path):
+ workshop = tmp_path / "workshop"
+ workshop.mkdir()
+ invalid = workshop / MOD_A
+ invalid.mkdir()
+ (invalid / "ServerData.json").write_text("not json")
+ unrelated = workshop / "notes"
+ unrelated.mkdir()
+ config = write_config(tmp_path, [])
+
+ assert not prune_mods(config, workshop)
+ assert invalid.exists()
+ assert unrelated.exists()
+
+
+def test_skips_mod_with_non_string_metadata_id(tmp_path):
+ workshop = tmp_path / "workshop"
+ workshop.mkdir()
+ invalid = write_mod(workshop, MOD_A)
+ server_data_path = invalid / "ServerData.json"
+ server_data = json.loads(server_data_path.read_text())
+ server_data["id"] = 123
+ server_data_path.write_text(json.dumps(server_data))
+ config = write_config(tmp_path, [])
+
+ assert not prune_mods(config, workshop)
+ assert invalid.exists()
+
+
+def test_skips_symlinked_server_data(tmp_path):
+ workshop = tmp_path / "workshop"
+ workshop.mkdir()
+ invalid = write_mod(workshop, MOD_A)
+ server_data_path = invalid / "ServerData.json"
+ server_data_path.unlink()
+ outside_metadata = tmp_path / "outside.json"
+ outside_metadata.write_text("{}")
+ server_data_path.symlink_to(outside_metadata)
+ config = write_config(tmp_path, [])
+
+ assert not prune_mods(config, workshop)
+ assert invalid.exists()
+ assert outside_metadata.exists()
+
+
+def test_skips_oversized_server_data(tmp_path):
+ workshop = tmp_path / "workshop"
+ workshop.mkdir()
+ invalid = workshop / MOD_A
+ invalid.mkdir()
+ (invalid / "ServerData.json").write_bytes(
+ b"x" * (launch_config.MAX_SERVER_DATA_SIZE + 1)
+ )
+ config = write_config(tmp_path, [])
+
+ assert not prune_mods(config, workshop)
+ assert invalid.exists()
+
+
+def test_invalid_required_mod_aborts_before_pruning(tmp_path):
+ workshop = tmp_path / "workshop"
+ workshop.mkdir()
+ invalid = workshop / MOD_A
+ invalid.mkdir()
+ (invalid / "ServerData.json").write_text("not json")
+ stale = write_mod(workshop, MOD_B)
+ config = write_config(tmp_path, [MOD_A])
+
+ with pytest.raises(ValueError, match="required mod .* is invalid"):
+ prune_mods(config, workshop)
+ assert invalid.exists()
+ assert stale.exists()
+
+
+def test_invalid_dependency_aborts_before_pruning(tmp_path):
+ workshop = tmp_path / "workshop"
+ workshop.mkdir()
+ write_mod(workshop, MOD_A, [{"id": MOD_B}])
+ invalid_dependency = workshop / MOD_B
+ invalid_dependency.mkdir()
+ stale = write_mod(workshop, MOD_C)
+ config = write_config(tmp_path, [MOD_A])
+
+ with pytest.raises(ValueError, match="required mod .* is invalid"):
+ prune_mods(config, workshop)
+ assert invalid_dependency.exists()
+ assert stale.exists()
+
+
+@pytest.mark.parametrize("invalid_mod_id", ["invalid", 123])
+def test_invalid_config_aborts_before_pruning(tmp_path, invalid_mod_id):
+ workshop = tmp_path / "workshop"
+ workshop.mkdir()
+ stale = write_mod(workshop, MOD_A)
+ config = write_config(tmp_path, [invalid_mod_id])
+
+ with pytest.raises(ValueError, match="Invalid mod ID"):
+ prune_mods(config, workshop)
+ assert stale.exists()
+
+
+def test_custom_config_without_mods_prunes_all(tmp_path):
+ workshop = tmp_path / "workshop"
+ workshop.mkdir()
+ stale = write_mod(workshop, MOD_A)
+ config = tmp_path / "config.json"
+ config.write_text(json.dumps({"game": {"name": "Vanilla"}}))
+
+ assert prune_mods(config, workshop) == [stale]
+ assert not stale.exists()
+
+
+def test_refuses_mod_directories_containing_mounts(tmp_path, monkeypatch):
+ workshop = tmp_path / "workshop"
+ workshop.mkdir()
+ stale = write_mod(workshop, MOD_A)
+ nested_mount = stale / "mounted"
+ nested_mount.mkdir()
+ sentinel = nested_mount / "sentinel"
+ sentinel.write_text("keep")
+ config = write_config(tmp_path, [])
+ monkeypatch.setattr(launch_config, "mounted_paths", lambda: {nested_mount})
+
+ with pytest.raises(ValueError, match="mounted content"):
+ prune_mods(config, workshop)
+ assert sentinel.exists()
+
+
+def test_workshop_symlink_retarget_does_not_change_prune_root(tmp_path, monkeypatch):
+ first_workshop = tmp_path / "first"
+ first_workshop.mkdir()
+ stale = write_mod(first_workshop, MOD_A)
+ second_workshop = tmp_path / "second"
+ second_workshop.mkdir()
+ protected = write_mod(second_workshop, MOD_A)
+ workshop_link = tmp_path / "workshop"
+ workshop_link.symlink_to(first_workshop, target_is_directory=True)
+ config = write_config(tmp_path, [])
+ mount_paths = launch_config.mounted_paths()
+
+ def retarget_workshop():
+ workshop_link.unlink()
+ workshop_link.symlink_to(second_workshop, target_is_directory=True)
+ return mount_paths
+
+ monkeypatch.setattr(launch_config, "mounted_paths", retarget_workshop)
+
+ assert prune_mods(config, workshop_link) == [stale]
+ assert not stale.exists()
+ assert protected.exists()
+
+
+def test_does_not_follow_symlinked_mod_directories(tmp_path):
+ workshop = tmp_path / "workshop"
+ workshop.mkdir()
+ outside = tmp_path / "outside"
+ outside.mkdir()
+ outside_mod = write_mod(outside, MOD_A)
+ (workshop / MOD_A).symlink_to(outside_mod, target_is_directory=True)
+ config = write_config(tmp_path, [])
+
+ assert not prune_mods(config, workshop)
+ assert outside_mod.exists()
+
+
+def test_configured_symlinked_mod_aborts_before_pruning(tmp_path):
+ workshop = tmp_path / "workshop"
+ workshop.mkdir()
+ outside = tmp_path / "outside"
+ outside.mkdir()
+ outside_mod = write_mod(outside, MOD_A)
+ (workshop / MOD_A).symlink_to(outside_mod, target_is_directory=True)
+ stale = write_mod(workshop, MOD_B)
+ config = write_config(tmp_path, [MOD_A])
+
+ with pytest.raises(ValueError, match="required mod .* is invalid"):
+ prune_mods(config, workshop)
+ assert outside_mod.exists()
+ assert stale.exists()
+
+
+def test_candidate_replacement_is_not_recursively_deleted(tmp_path, monkeypatch):
+ workshop = tmp_path / "workshop"
+ workshop.mkdir()
+ stale = write_mod(workshop, MOD_A)
+ moved = workshop / "moved"
+ replacement_sentinel = stale / "sentinel"
+ config = write_config(tmp_path, [])
+ stage_candidates = launch_config.stage_prune_candidates
+
+ def replace_candidate(workshop_fd, expected_mount_id, candidates):
+ stale.rename(moved)
+ stale.mkdir()
+ replacement_sentinel.write_text("keep")
+ return stage_candidates(workshop_fd, expected_mount_id, candidates)
+
+ monkeypatch.setattr(launch_config, "stage_prune_candidates", replace_candidate)
+
+ with pytest.raises(OSError, match="roll back staged mods"):
+ prune_mods(config, workshop)
+ quarantine = next(
+ path
+ for path in workshop.iterdir()
+ if path.name.startswith(launch_config.PRUNE_QUARANTINE_PREFIX)
+ )
+ assert (quarantine / MOD_A / "sentinel").exists()
+ assert moved.exists()
+ with pytest.raises(ValueError, match="Invalid quarantined mod entry"):
+ prune_mods(config, workshop)
+
+
+def test_staging_failure_rolls_back_all_candidates(tmp_path, monkeypatch):
+ workshop = tmp_path / "workshop"
+ workshop.mkdir()
+ first = write_mod(workshop, MOD_A)
+ second = write_mod(workshop, MOD_B)
+ config = write_config(tmp_path, [])
+ rename = launch_config.os.rename
+ rename_calls = 0
+
+ def fail_second_rename(*args, **kwargs):
+ nonlocal rename_calls
+ rename_calls += 1
+ if rename_calls == 2:
+ raise OSError("staging failed")
+ return rename(*args, **kwargs)
+
+ monkeypatch.setattr(launch_config.os, "rename", fail_second_rename)
+
+ with pytest.raises(OSError, match="staging failed"):
+ prune_mods(config, workshop)
+ assert first.exists()
+ assert second.exists()
+ assert not any(
+ path.name.startswith(launch_config.PRUNE_QUARANTINE_PREFIX)
+ for path in workshop.iterdir()
+ )
+
+
+def test_deletion_failure_is_retried_from_quarantine(tmp_path, monkeypatch):
+ workshop = tmp_path / "workshop"
+ workshop.mkdir()
+ first = write_mod(workshop, MOD_A)
+ second = write_mod(workshop, MOD_B)
+ config = write_config(tmp_path, [])
+ remove_tree = launch_config.remove_directory_tree
+ remove_calls = 0
+
+ def fail_second_removal(*args, **kwargs):
+ nonlocal remove_calls
+ remove_calls += 1
+ if remove_calls == 2:
+ raise OSError("deletion failed")
+ return remove_tree(*args, **kwargs)
+
+ monkeypatch.setattr(launch_config, "remove_directory_tree", fail_second_removal)
+
+ with pytest.raises(OSError, match="deletion failed"):
+ prune_mods(config, workshop)
+ assert not first.exists()
+ assert not second.exists()
+ assert any(
+ path.name.startswith(launch_config.PRUNE_QUARANTINE_PREFIX)
+ for path in workshop.iterdir()
+ )
+
+ monkeypatch.setattr(launch_config, "remove_directory_tree", remove_tree)
+ assert not prune_mods(config, workshop)
+ assert not any(
+ path.name.startswith(launch_config.PRUNE_QUARANTINE_PREFIX)
+ for path in workshop.iterdir()
+ )
+
+
+def test_interrupted_quarantine_is_recovered(tmp_path):
+ workshop = tmp_path / "workshop"
+ workshop.mkdir()
+ stale = write_mod(workshop, MOD_A)
+ config = write_config(tmp_path, [])
+ workshop_fd = os.open(workshop, launch_config.WORKSHOP_OPEN_FLAGS)
+ try:
+ mod_fd = os.open(MOD_A, launch_config.DIRECTORY_OPEN_FLAGS, dir_fd=workshop_fd)
+ try:
+ candidate = launch_config.load_installed_mod(MOD_A, mod_fd, stale)
+ finally:
+ os.close(mod_fd)
+ quarantine_name, quarantine_fd = launch_config.stage_prune_candidates(
+ workshop_fd,
+ launch_config.fd_mount_id(workshop_fd),
+ [candidate],
+ )
+ quarantined_mod_fd = os.open(
+ MOD_A,
+ launch_config.DIRECTORY_OPEN_FLAGS,
+ dir_fd=quarantine_fd,
+ )
+ try:
+ os.unlink(launch_config.SERVER_DATA_FILE, dir_fd=quarantined_mod_fd)
+ finally:
+ os.close(quarantined_mod_fd)
+ os.close(quarantine_fd)
+ finally:
+ os.close(workshop_fd)
+
+ assert not stale.exists()
+ assert (workshop / quarantine_name).exists()
+ assert not prune_mods(config, workshop)
+ assert not stale.exists()
+ assert not (workshop / quarantine_name).exists()
+
+
+def test_workshop_descriptor_closes_when_fd_path_fails(tmp_path, monkeypatch):
+ workshop = tmp_path / "workshop"
+ workshop.mkdir()
+ config = write_config(tmp_path, [])
+ open_fd_count = len(os.listdir("/proc/self/fd"))
+
+ def fail_fd_path(_fd):
+ raise OSError("fd path failed")
+
+ monkeypatch.setattr(launch_config, "fd_path", fail_fd_path)
+
+ with pytest.raises(OSError, match="fd path failed"):
+ prune_mods(config, workshop)
+ assert len(os.listdir("/proc/self/fd")) == open_fd_count
+
+
+def test_concurrent_pruner_is_rejected(tmp_path):
+ workshop = tmp_path / "workshop"
+ workshop.mkdir()
+ config = write_config(tmp_path, [])
+ workshop_fd = os.open(workshop, launch_config.WORKSHOP_OPEN_FLAGS)
+ launch_config.fcntl.flock(workshop_fd, launch_config.fcntl.LOCK_EX)
+ try:
+ with pytest.raises(BlockingIOError):
+ prune_mods(config, workshop)
+ finally:
+ launch_config.fcntl.flock(workshop_fd, launch_config.fcntl.LOCK_UN)
+ os.close(workshop_fd)
+
+
+def test_prunes_tree_deeper_than_recursion_limit(tmp_path):
+ workshop = tmp_path / "workshop"
+ workshop.mkdir()
+ stale = write_mod(workshop, MOD_A)
+ nested = stale
+ for _ in range(350):
+ nested = nested / "d"
+ nested.mkdir()
+ config = write_config(tmp_path, [])
+ recursion_limit = sys.getrecursionlimit()
+
+ try:
+ sys.setrecursionlimit(300)
+ assert prune_mods(config, workshop) == [stale]
+ finally:
+ sys.setrecursionlimit(recursion_limit)
+ assert not stale.exists()
+
+
+def test_reads_server_data_with_utf8_bom(tmp_path):
+ workshop = tmp_path / "workshop"
+ workshop.mkdir()
+ stale = write_mod(workshop, MOD_E, encoding="utf-8-sig")
+ config = write_config(tmp_path, [])
+
+ assert prune_mods(config, workshop) == [stale]
+
+
+def test_missing_workshop_directory_is_a_no_op(tmp_path):
+ config = write_config(tmp_path, [MOD_A])
+
+ assert not prune_mods(config, tmp_path / "missing")
+
+
+def test_preserves_dependencies_declared_with_mod_id_key(tmp_path):
+ workshop = tmp_path / "workshop"
+ workshop.mkdir()
+ root = write_mod(workshop, MOD_A, [{"modId": MOD_B}])
+ dependency = write_mod(workshop, MOD_B)
+ stale = write_mod(workshop, MOD_C)
+ config = write_config(tmp_path, [MOD_A])
+
+ assert prune_mods(config, workshop) == [stale]
+ assert root.exists()
+ assert dependency.exists()
+
+
+def test_dependency_cycle_terminates(tmp_path):
+ workshop = tmp_path / "workshop"
+ workshop.mkdir()
+ first = write_mod(workshop, MOD_A, [MOD_B])
+ second = write_mod(workshop, MOD_B, [MOD_A])
+ stale = write_mod(workshop, MOD_C)
+ config = write_config(tmp_path, [MOD_A])
+
+ assert prune_mods(config, workshop) == [stale]
+ assert first.exists()
+ assert second.exists()
+
+
+def test_diamond_dependencies_are_all_retained(tmp_path):
+ workshop = tmp_path / "workshop"
+ workshop.mkdir()
+ root = write_mod(workshop, MOD_A, [MOD_B, MOD_C])
+ left = write_mod(workshop, MOD_B, [MOD_D])
+ right = write_mod(workshop, MOD_C, [MOD_D])
+ shared = write_mod(workshop, MOD_D)
+ stale = write_mod(workshop, MOD_E)
+ config = write_config(tmp_path, [MOD_A])
+
+ assert prune_mods(config, workshop) == [stale]
+ assert root.exists()
+ assert left.exists()
+ assert right.exists()
+ assert shared.exists()
+
+
+def test_configured_mod_that_is_not_installed_is_ignored(tmp_path):
+ workshop = tmp_path / "workshop"
+ workshop.mkdir()
+ stale = write_mod(workshop, MOD_B)
+ config = write_config(tmp_path, [MOD_A])
+
+ assert prune_mods(config, workshop) == [stale]
+ assert not stale.exists()
+
+
+def test_skips_mod_that_is_not_fully_downloaded(tmp_path):
+ workshop = tmp_path / "workshop"
+ workshop.mkdir()
+ partial = write_mod(workshop, MOD_A)
+ patch_revision(partial, downloaded=False)
+ config = write_config(tmp_path, [])
+
+ assert not prune_mods(config, workshop)
+ assert partial.exists()
+
+
+def test_skips_mod_with_non_list_dependencies(tmp_path):
+ workshop = tmp_path / "workshop"
+ workshop.mkdir()
+ invalid = write_mod(workshop, MOD_A)
+ patch_revision(invalid, dependencies={"id": MOD_B})
+ config = write_config(tmp_path, [])
+
+ assert not prune_mods(config, workshop)
+ assert invalid.exists()
+
+
+@pytest.mark.parametrize(
+ "directory_name",
+ ["abcdef1234567890", "111111111111111", "11111111111111111"],
+)
+def test_ignores_directories_that_are_not_mod_ids(tmp_path, directory_name):
+ workshop = tmp_path / "workshop"
+ workshop.mkdir()
+ unrelated = workshop / directory_name
+ unrelated.mkdir()
+ (unrelated / "content.bin").write_bytes(b"content")
+ config = write_config(tmp_path, [])
+
+ assert not prune_mods(config, workshop)
+ assert unrelated.exists()
+
+
+def test_prunes_every_stale_mod_in_sorted_order(tmp_path):
+ workshop = tmp_path / "workshop"
+ workshop.mkdir()
+ third = write_mod(workshop, MOD_C)
+ first = write_mod(workshop, MOD_A)
+ second = write_mod(workshop, MOD_B)
+ config = write_config(tmp_path, [])
+
+ assert prune_mods(config, workshop) == [first, second, third]
+ assert not first.exists()
+ assert not second.exists()
+ assert not third.exists()
+
+
+def test_leaves_no_quarantine_behind_when_nothing_to_prune(tmp_path):
+ workshop = tmp_path / "workshop"
+ workshop.mkdir()
+ configured = write_mod(workshop, MOD_A)
+ config = write_config(tmp_path, [MOD_A])
+
+ assert not prune_mods(config, workshop)
+ assert configured.exists()
+ assert [path.name for path in workshop.iterdir()] == [MOD_A]
diff --git a/src/healthcheck.py b/src/healthcheck.py
new file mode 100644
index 0000000000000000000000000000000000000000..b9119ac8b6ca2917543dbc4e94bb87e7930cab79
--- /dev/null
+++ b/src/healthcheck.py
+"""Simple A2S_INFO health check for Arma Reforger server.
+
+Uses the active server configuration when available, falls back to the A2S
+environment variables before the generated config exists, and treats disabled
+A2S as a no-op so valid configurations are not marked unhealthy.
+"""
+
+import json
+import os
+import socket
+import sys
+from pathlib import Path
+
+A2S_INFO_REQUEST = b"\xff\xff\xff\xff\x54Source Engine Query\x00"
+CONFIG_GENERATED = Path("/reforger/Configs/docker_generated.json")
+CONFIG_DIR = Path("/reforger/Configs")
+TIMEOUT_SECONDS = 5
+WILDCARD_TO_LOOPBACK = {
+ "": "127.0.0.1",
+ "0.0.0.0": "127.0.0.1",
+ "::": "::1",
+}
+
+
+def resolve_config_path():
+ arma_config = os.environ.get("ARMA_CONFIG", "docker_generated")
+ if arma_config == "docker_generated":
+ return CONFIG_GENERATED
+ return CONFIG_DIR / arma_config
+
+
+def resolve_a2s_settings():
+ config_path = resolve_config_path()
+ if config_path.exists():
+ with config_path.open(encoding="utf-8-sig") as config_file:
+ config = json.load(config_file)
+ a2s_config = config.get("a2s") if isinstance(config, dict) else None
+ if not isinstance(a2s_config, dict):
+ return None
+ address = a2s_config.get("address")
+ port = a2s_config.get("port")
+ if address is None or port is None:
+ return None
+ return {"address": address, "port": int(port)}
+
+ address = os.environ.get("SERVER_A2S_ADDRESS", "")
+ port = os.environ.get("SERVER_A2S_PORT", "")
+ if not address or not port:
+ return None
+ return {"address": address, "port": int(port)}
+
+
+def probe_server(address, port):
+ probe_address = WILDCARD_TO_LOOPBACK.get(address, address)
+ addrinfos = socket.getaddrinfo(probe_address, port, type=socket.SOCK_DGRAM)
+ for family, socktype, proto, _, sockaddr in addrinfos:
+ sock = socket.socket(family, socktype, proto)
+ try:
+ sock.settimeout(TIMEOUT_SECONDS)
+ sock.sendto(A2S_INFO_REQUEST, sockaddr)
+ data, _ = sock.recvfrom(4096)
+ if data:
+ return True
+ except OSError:
+ continue
+ finally:
+ sock.close()
+ return False
+
+
+try:
+ a2s = resolve_a2s_settings()
+ if not a2s:
+ sys.exit(0)
+ sys.exit(0 if probe_server(a2s["address"], a2s["port"]) else 1)
+except (OSError, TypeError, ValueError) as err:
+ print(f"Health check failed: {err}", file=sys.stderr)
+ sys.exit(1)
diff --git a/src/launch.py b/src/launch.py
new file mode 100644
index 0000000000000000000000000000000000000000..57390a961f87d2d22d5b1b6dc84ba644cbfaa556
--- /dev/null
+++ b/src/launch.py
+import json
+import os
+import random
+import shlex
+import signal
+import subprocess
+import sys
+from pathlib import Path
+
+from launch_config import bool_str, build_config, env_defined, prune_mods