# acemod/docker-reforger ## Project Overview This repository packages an Arma Reforger dedicated server as a production-ready Docker image (ghcr.io/acemod/arma-reforger). Its purpose is to let operators run, configure, and keep the game server up to date with a single container rather than hand-managing SteamCMD, config files, and startup flags. The container installs or updates the server through SteamCMD on every restart (supporting the stable app ID 1874900 and the experimental 1890870, including the one-time Windows SteamCMD pass for the experimental branch) and then launches the ArmaReforgerServer binary. Configuration is environment-driven: at startup the bundled Python tooling regenerates a config file (Configs/docker_generated.json) from a template, translating variables that control networking and A2S query settings, RCON (bind address, port, permissions, client limits, command whitelists/blacklists), game options (name, passwords, admins, scenario, player limits, supported platforms, BattlEye and gameplay properties), workshop mods (via ID lists or JSON files, with optional version pinning and auto-pruning of unused mods), persistence settings, operating parameters, and mission header overrides. Alternatively, operators can supply a hand-edited config through ARMA_CONFIG, which is used as-is. Key components are the Dockerfile and docker-compose.yml that build and orchestrate the image, the src/ directory holding the Python launch-config generation logic (the launch_config package) copied to /app in the image, persistence_default.json as a bundled persistence template, scripts/build.sh for local builds, and tests/ plus CI/pre-commit configuration (black, isort, pylint, pytest, hadolint) that validate the tooling. The server runs as root by design because SteamCMD requires it, and the container health check leverages A2S when that query interface is enabled. Re-implement this repository from scratch so that the original test suite passes. The sections below document the language/environment, the project structure, the public API the tests exercise, and per-capability implementation guidance. ## Submission Constraints (read carefully — the evaluation depends on these) This is a **closed-book** task. The graded test suite is **hidden** and will be injected into the workspace at evaluation time. To be scored correctly you MUST follow these rules: 1. **Do NOT create or modify any files under the test directories** (e.g. `tests/`, `test/`, `testing/`, or files named `test_*.py` / `conftest.py`). The grader injects its own test files at those paths; any file you place there will collide with the injected suite and cause the whole evaluation to score 0. Implement **only** the library/source code — never the tests. 2. **Your package MUST be importable by the name the tests use.** The hidden tests `import` your package by its documented top-level name (see the Project Directory Structure and API Usage Guide below). Provide a valid `pyproject.toml` / `setup.py` / `setup.cfg` and lay out your modules so that `pip install -e .` succeeds and the package imports cleanly. If your package is not installable/importable, every test errors out and the reward is 0. 3. **Match the documented module paths and public API exactly** (names, signatures, and any literal error/exception strings). Internal helpers not listed in the API guide may be implemented however you like. ## Install / Reconstruction Contract Follow this contract before implementing the documented APIs: - **Project root**: `/workspace/repo` at runtime; the submitted repository root is `.`. - **Package/distribution name**: `(unnamed project)` - **Package roots**: `src` - **Install strategy**: `source-roots` - **Import/entry**: use the package and public entry points listed in the API Usage Guide; do not invent a different top-level package. - **Provision commands**: ```bash python3 -I -c 'import base64; from pathlib import Path; Path('"'"'/tmp/programgen-pip-compat-v1.py'"'"').write_bytes(base64.b64decode('"'"'aW1wb3J0IG9zCmZyb20gcGF0aGxpYiBpbXBvcnQgUGF0aAppbXBvcnQgc3VicHJvY2VzcwppbXBvcnQgc3lzCmltcG9ydCB0ZW1wZmlsZQoKZGVmIGNvbnN0cmFpbmVkX2J1aWxkX2luc3RhbGwoY29tbWFuZCwgcnVuKToKICAgIGNvbnN0cmFpbnQgPSBvcy5lbnZpcm9uLmdldCgnUFJPR1JBTUdFTl9CVUlMRF9DT05TVFJBSU5UJykKICAgIGlmIG5vdCBjb25zdHJhaW50IG9yICctLW5vLWJ1aWxkLWlzb2xhdGlvbicgaW4gY29tbWFuZDoKICAgICAgICByZXR1cm4gTm9uZQogICAgaWYgc3lzLnZlcnNpb25faW5mb1s6Ml0gPCAoMywgOSk6CiAgICAgICAgcHJpbnQoJ1twcm9ncmFtZ2VuXSBpc29sYXRlZCBidWlsZCBjb25zdHJhaW50cyByZXF1aXJlIFB5dGhvbiA+PTMuOScsIGZsdXNoPVRydWUpCiAgICAgICAgcmV0dXJuIDEKICAgICMgQSBkZWRpY2F0ZWQgaW5zdGFsbGVyIGNvbnRyb2xzIFBFUCA1MTcgYnVpbGQgZGVwZW5kZW5jaWVzIG9ubHkuIEl0IGRvZXMKICAgICMgbm90IHVwZ3JhZGUgcGlwL3NldHVwdG9vbHMgaW4gdGhlIG1lYXN1cmVkIHByb2plY3QncyBydW50aW1lIGVudmlyb25tZW50LgogICAgd2l0aCB0ZW1wZmlsZS5UZW1wb3JhcnlEaXJlY3RvcnkocHJlZml4PSdwcm9ncmFtZ2VuLWJ1aWxkLWluc3RhbGxlci0nKSBhcyBkaXJlY3Rvcnk6CiAgICAgICAgcnVubmVyID0gc3RyKFBhdGgoZGlyZWN0b3J5KSAvICdiaW4nIC8gJ3B5dGhvbicpCiAgICAgICAgZm9yIHNldHVwIGluIChbc3lzLmV4ZWN1dGFibGUsICctbScsICd2ZW52JywgZGlyZWN0b3J5XSwKICAgICAgICAgICAgICAgICAgICAgIFtydW5uZXIsICctbScsICdwaXAnLCAnaW5zdGFsbCcsICctLW5vLWNhY2hlLWRpcicsICdwaXA9PTI1LjMnXSk6CiAgICAgICAgICAgIHJlc3VsdCA9IHJ1bihzZXR1cCkKICAgICAgICAgICAgaWYgcmVzdWx0LnJldHVybmNvZGU6CiAgICAgICAgICAgICAgICByZXR1cm4gcmVzdWx0LnJldHVybmNvZGUKICAgICAgICBpZiBjb21tYW5kWzo0XSAhPSBbc3lzLmV4ZWN1dGFibGUsICctbScsICdwaXAnLCAnaW5zdGFsbCddIGFuZCBjb21tYW5kWzo0XSAhPSBbJ3B5dGhvbjMnLCAnLW0nLCAncGlwJywgJ2luc3RhbGwnXToKICAgICAgICAgICAgcHJpbnQoJ1twcm9ncmFtZ2VuXSB1bnN1cHBvcnRlZCBjb25zdHJhaW5lZCBpbnN0YWxsZXIgY29tbWFuZCcsIGZsdXNoPVRydWUpCiAgICAgICAgICAgIHJldHVybiAxCiAgICAgICAgdGFyZ2V0ID0gW3J1bm5lciwgJy1tJywgJ3BpcCcsICctLXB5dGhvbicsIHN5cy5leGVjdXRhYmxlLCAnaW5zdGFsbCcsCiAgICAgICAgICAgICAgICAgICctLWJ1aWxkLWNvbnN0cmFpbnQnLCBjb25zdHJhaW50XSArIGNvbW1hbmRbNDpdCiAgICAgICAgcmV0dXJuIHJ1bih0YXJnZXQpLnJldHVybmNvZGUKCmRlZiBpbnN0YWxsKGNvbW1hbmQsIHJ1bj1zdWJwcm9jZXNzLnJ1bik6CiAgICBmb3IgdmFyaWFibGUgaW4gKCdQUk9HUkFNR0VOX1JVTlRJTUVfQ09OU1RSQUlOVCcsICdQUk9HUkFNR0VOX1JVTlRJTUVfUkVQQUlSX0NPTlNUUkFJTlQnKToKICAgICAgICBydW50aW1lX2NvbnN0cmFpbnQgPSBvcy5lbnZpcm9uLmdldCh2YXJpYWJsZSkKICAgICAgICBpZiBydW50aW1lX2NvbnN0cmFpbnQ6CiAgICAgICAgICAgIGNvbW1hbmQgPSBsaXN0KGNvbW1hbmQpICsgWyctYycsIHJ1bnRpbWVfY29uc3RyYWludF0KICAgIGNvbnN0cmFpbmVkID0gY29uc3RyYWluZWRfYnVpbGRfaW5zdGFsbChjb21tYW5kLCBydW4pCiAgICBpZiBjb25zdHJhaW5lZCBpcyBub3QgTm9uZToKICAgICAgICByZXR1cm4gY29uc3RyYWluZWQKICAgIHJlc3VsdCA9IHJ1bihjb21tYW5kLCBzdGRvdXQ9c3VicHJvY2Vzcy5QSVBFLCBzdGRlcnI9c3VicHJvY2Vzcy5TVERPVVQsIHRleHQ9VHJ1ZSkKICAgIG91dHB1dCA9IHJlc3VsdC5zdGRvdXQgb3IgJycKICAgIHN5cy5zdGRvdXQud3JpdGUob3V0cHV0KQogICAgc3lzLnN0ZG91dC5mbHVzaCgpCiAgICBpZiByZXN1bHQucmV0dXJuY29kZSA9PSAwOgogICAgICAgIHJldHVybiAwCiAgICBsZWdhY3kgPSAnaW52YWxpZCBtZXRhZGF0YScgaW4gb3V0cHV0Lmxvd2VyKCkgYW5kICdwbGVhc2UgdXNlIHBpcDwyNC4xJyBpbiBvdXRwdXQubG93ZXIoKQogICAgaWYgbm90IGxlZ2FjeSBvciBub3QgKDMsIDgpIDw9IHN5cy52ZXJzaW9uX2luZm9bOjJdIDw9ICgzLCAxMik6CiAgICAgICAgcmV0dXJuIHJlc3VsdC5yZXR1cm5jb2RlCiAgICBwcmludCgnW3Byb2dyYW1nZW5dIGxlZ2FjeSBkaXN0cmlidXRpb24gbWV0YWRhdGE6IHJldHJ5aW5nIHRoZSB1bmNoYW5nZWQgcmVxdWlyZW1lbnRzIHdpdGggcGlwPDI0LjEnLCBmbHVzaD1UcnVlKQogICAgY2hhbmdlZCA9IHJ1bihbc3lzLmV4ZWN1dGFibGUsICctbScsICdwaXAnLCAnaW5zdGFsbCcsICdwaXA8MjQuMSddKQogICAgaWYgY2hhbmdlZC5yZXR1cm5jb2RlOgogICAgICAgIHJldHVybiBjaGFuZ2VkLnJldHVybmNvZGUKICAgIHJldHVybiBydW4oY29tbWFuZCkucmV0dXJuY29kZQoKaWYgX19uYW1lX18gPT0gJ19fbWFpbl9fJzoKICAgIHJhaXNlIFN5c3RlbUV4aXQoaW5zdGFsbChzeXMuYXJndlsxOl0pKQo='"'"'))' programgen_pip_install() { python3 -I /tmp/programgen-pip-compat-v1.py "$@"; } export -f programgen_pip_install programgen_pip_install python3 -m pip install -U pip 'setuptools<82' wheel ``` - **Runtime setup**: ```bash export PYTHONPATH="$PWD/src:${PYTHONPATH:-}" ``` - **Project root for installation**: `.` - **Build-version environment**: `SETUPTOOLS_SCM_PRETEND_VERSION=0.0.0`, `PDM_BUILD_SCM_VERSION=0.0.0`, `POETRY_DYNAMIC_VERSIONING_BYPASS=0.0.0`, `UV_DYNAMIC_VERSIONING_BYPASS=0.0.0` - **Test directory**: `tests` - **Test command**: `bash -lc 'set -uo pipefail run=(python3 -m pytest -vv -o addopts= tests/test_launch_config.py tests/test_mod_pruning.py) if [ -n "${COVERAGE_FILE:-}" ]; then run=(python3 -m coverage run --source=. -m pytest -vv -o addopts= tests/test_launch_config.py tests/test_mod_pruning.py); fi collect=(python3 -m pytest -q -o addopts= tests/test_launch_config.py tests/test_mod_pruning.py) collected_output=$("${collect[@]}" --collect-only) collect_rc=$? if [ "$collect_rc" -ne 0 ] && [ "$collect_rc" -ne 5 ]; then printf "%s\n" "$collected_output" >&2 printf "[programgen] test collection failed with exit code %s\n" "$collect_rc" >&2 exit "$collect_rc" fi mapfile -t collected < <(printf "%s\n" "$collected_output" | sed -n '"'"'/::/p'"'"' | sed '"'"'s/[[:space:]]*$//'"'"') if [ "${#collected[@]}" -gt 500 ]; then while IFS= read -r id; do run+=("--deselect=$id"); done < <(printf "%s\n" "${collected[@]}" | awk -F'"'"'::'"'"' -v limit=500 '"'"'{f=$1; n[f]++; idx[f,n[f]]=NR; all[NR]=$0; if(!(f in seen)){seen[f]=1; order[++m]=f}} END{d=1; c=0; while(c=limit) break}} if(!a) break; d++} for(r=1;r<=NR;r++) if(!(r in keep)) print all[r]}'"'"') fi "${run[@]}"; exit $?'` - **Test startup**: run the exact test command above from the project root after installation; hidden tests are injected separately. ## Environment & Project Structure - **Language**: python - **Build system**: python - **Test command**: `bash -lc set -uo pipefail run=(python3 -m pytest -vv -o addopts= tests/test_launch_config.py tests/test_mod_pruning.py) if [ -n "${COVERAGE_FILE:-}" ]; then run=(python3 -m coverage run --source=. -m pytest -vv -o addopts= tests/test_launch_config.py tests/test_mod_pruning.py); fi collect=(python3 -m pytest -q -o addopts= tests/test_launch_config.py tests/test_mod_pruning.py) collected_output=$("${collect[@]}" --collect-only) collect_rc=$? if [ "$collect_rc" -ne 0 ] && [ "$collect_rc" -ne 5 ]; then printf "%s\n" "$collected_output" >&2 printf "[programgen] test collection failed with exit code %s\n" "$collect_rc" >&2 exit "$collect_rc" fi mapfile -t collected < <(printf "%s\n" "$collected_output" | sed -n '/::/p' | sed 's/[[:space:]]*$//') if [ "${#collected[@]}" -gt 500 ]; then while IFS= read -r id; do run+=("--deselect=$id"); done < <(printf "%s\n" "${collected[@]}" | awk -F'::' -v limit=500 '{f=$1; n[f]++; idx[f,n[f]]=NR; all[NR]=$0; if(!(f in seen)){seen[f]=1; order[++m]=f}} END{d=1; c=0; while(c=limit) break}} if(!a) break; d++} for(r=1;r<=NR;r++) if(!(r in keep)) print all[r]}') fi "${run[@]}"; exit $?` ### Project Directory Structure ``` .dockerignore .github/ISSUE_TEMPLATE/bug_report.md .github/linters/.hadolint.yaml .github/linters/.yaml-lint.yml .github/scripts/steam_query.py .github/workflows/ci.yaml .github/workflows/ghcr.yaml .gitignore .pre-commit-config.yaml Dockerfile LICENSE README.md docker-compose.yml persistence_default.json pyproject.toml scripts/build.sh src/docker_default.json src/healthcheck.py src/launch.py src/launch_config.py ``` ## API Usage Guide Each capability below lists the components the tests exercise with their exact signatures and behavior. Re-create these so the tests pass; internal helpers not listed here may be implemented freely. ### Capability: Environment variable parsing helpers # api_guide ## Purpose and shape The parsing helpers are the typed boundary between raw container environment strings and the strongly typed JSON config that `launch.py` builds at startup. Every value the operator exports is a string, but the generated config needs booleans, integers, and lists; these accessors perform that conversion lazily, one key at a time, and only for keys the operator actually set. They are intentionally stateless: they take the environment as a plain mapping (so tests can pass a `dict` instead of `os.environ`) and return plain Python values that drop straight into the config structure. ## The `env_defined` gate All conversions are guarded by `env_defined`, which requires the key to be present *and* non-empty. This is the most important ordering rule in the capability: an accessor such as `env_str` or `parse_int` is never called for an unset or empty variable, because `apply_env_overrides` (and the rcon/persistence predicates) check `env_defined` first. Consequently: - A variable exported as an empty string behaves exactly like an unset variable — the template default survives. This is deliberate: it lets compose files declare variables with empty values without crashing the launch. - `env_str`, `env_bool`, and `env_csv` index directly (`env[key]`) and do not normalize errors, so calling one without the gate on an absent key is a caller error and raises `KeyError`. `parse_int` is the exception — it reads through `env.get`, so a gateless call with a missing key does not raise a bare `KeyError` but a `ValueError` with the literal message `Invalid : None`, with the underlying `KeyError` chained as `__cause__`. Tests exercise the helpers through the gate, not in isolation for missing keys. ## Typed conversions **Strings** (`env_str`): pass-through of the raw value, no trimming or validation. Whatever whitespace the operator exported is what lands in the config. **Booleans** (`env_bool` / `bool_str`): the comparison is `text.lower() == "true"`. This is a strict, non-erroring parse: - `"true"`, `"True"`, `"TRUE"` → `True`. - Everything else — `"false"`, `"1"`, `"yes"`, `"on"`, or even a typo like `"ture"` — silently becomes `False`. There is no validation error for a misspelled boolean; the value just disables the feature. This silent-false behavior is test-sensitive: do not expect a `ValueError` for `"false"`. **Integers** (`parse_int`): delegates to Python's `int()`, so leading/trailing whitespace and a leading sign are accepted (`" 80 "` → `80`), and negatives work. Any failure — missing key, non-numeric text, or a `None` value — is normalized to a single `ValueError` with the literal message `Invalid : ` (for a missing key the repr shows `None`, because the message is built with `env.get`). The original exception is chained as `__cause__`. This error string is asserted verbatim in tests, including the quoting produced by `!r` (e.g. `Invalid SERVER_BIND_PORT: 'not-a-port'`). **CSV lists** (`env_csv` / `split_csv`): splits on `,`, strips whitespace from each item, and drops items that are empty after stripping. So `" a , ,b "` → `["a", "b"]`. Order is preserved and duplicates are *not* removed — `"a,a"` yields `["a", "a"]`. A value of only commas/whitespace yields `[]`. Used for `admins`, `supportedPlatforms`, and the RCON blacklist/whitelist (the latter two call `split_csv` directly inside `apply_rcon_config` after the either/or validation that forbids setting both). **Navmesh streaming** (`env_navmesh_streaming`): a small policy wrapper over `split_csv`. If the value is `"all"` — matched case-insensitively, so `"All"` and `"ALL"` count — it returns `[]`; otherwise it returns the CSV parse. The empty list is the significant part: it is assigned to `operating.disableNavmeshStreaming`, where an empty list means *no* regions are disabled, i.e. streaming stays enabled everywhere. So the string encodes two opposite intents: `all` → stream everything (empty disable-list), a region list → disable only those regions. Note the special value is only recognized after lowercasing; `"all "` with a trailing space would be treated as a region name instead. Because it is wired through `OPERATING_ENV_MAP` and `apply_env_overrides`, it is only invoked when `OPERATING_DISABLE_NAVMESH_STREAMING` is defined and non-empty; it never receives a missing key in normal flow. ## How they plug into config generation `build_config` deep-copies the template config, then runs the application passes in a fixed order: server bindings, rcon, game settings, game properties, mods, persistence, operating. Within each pass, `apply_env_overrides` iterates the env-map tuples in declaration order and, for each defined key, calls the mapped converter and writes the result into the target dict. The helpers are therefore the only place type conversion happens; the pass logic decides *whether* and *where* the converted value is written. Two structural consequences: - A conversion failure aborts the whole build with its `ValueError`; there is no per-key fallback. A bad integer in any section prevents the server from starting rather than silently defaulting. - Because conversions run only for defined keys, the generated config contains only operator-provided overrides plus whatever the template and the pass logic add; unset sections are pruned (e.g. an entirely empty `operating` mapping removes the `operating` key). The navmesh helper illustrates the pattern for future values with sentinel semantics: parse the raw string, check a case-insensitive sentinel first, then fall back to the shared CSV parser. It returns a fresh list every call and never mutates the environment. ## Edge cases worth asserting - `env_defined` is true exactly when the key is present and its value is non-empty; whitespace-only strings (`" "`) therefore count as defined, so `env_bool(" ")` is `False` and `split_csv(" ")` is `[]`, while `parse_int` would fail with `Invalid ...: ' '`. The len-based test behind the gate is indistinguishable from plain truthiness for string values — the difference is only observable on non-string entries: `env_defined` on a dict holding `None` raises `TypeError`, whereas a truthiness test would return `False` and treat the entry as undefined. - Booleans never raise; integers always raise with the same message shape regardless of the underlying cause (`KeyError`, `TypeError`, `ValueError`). - CSV parsing never raises on ordinary input; validation of list *contents* (e.g. admin IDs, mod IDs) happens downstream in the mods path, not in the CSV helper. - The `"all"` sentinel returns `[]` rather than some wildcard marker, so consumers can treat the result uniformly as a list of region names to disable. - Converters are called at build time, once per restart — the config file is regenerated from the template on every container start, so changes to these variables take effect on restart, not dynamically. #### Exact API Reference #### `launch_config.env_navmesh_streaming` - **Import Path**: `from launch_config import env_navmesh_streaming` - **Signature**: ```python def env_navmesh_streaming(env, key) ``` ### Capability: Safe file-descriptor-based filesystem primitives ## Safe file-descriptor-based filesystem primitives ### Purpose The mod pruner deletes untrusted directory trees from the Steam workshop volume while the container runs as root. Path-string navigation is unsafe there: a component can be swapped for a symlink (TOCTOU), or a subtree replaced by a bind mount, between inspection and deletion. Every operation in this capability is therefore anchored to file descriptors: directories are opened relative to a validated parent with `O_NOFOLLOW`, every descriptor is checked against a captured inode identity and a kernel mount ID, and all reads and writes are size-bounded, so deletion can never be redirected outside the pinned workshop root. ### Node records and `open_directory_node` Navigation uses node records, not path strings: `{'name': , 'parent': , 'path': , 'stat': }`. `open_directory_node(root_fd, node, expected_mount_id)` rebuilds trust from the anchor on every call: it walks `node['parent']` links up to the root, then re-descends from `root_fd`, opening each component with `os.open(name, O_RDONLY|O_DIRECTORY|O_NOFOLLOW|O_CLOEXEC, dir_fd=)`. Each level is reopened and revalidated, so a stale or swapped ancestor cannot poison the descent. - A symlinked or non-directory component fails the open itself (`ELOOP`/`ENOTDIR`/`ENOENT` family); it is never followed. - `root_fd` is duplicated first (`os.dup`), so the caller's descriptor is never closed by this function, even on failure. - On any exception the working descriptor (the dup or the last opened fd) is closed and the error re-raised; on success the returned fd belongs to the caller, who must close it. ### Two-layer validation `validate_open_entry(fd, expected_stat, expected_mount_id, path)` is applied to every descriptor opened during pruning — mod directories, staged copies, quarantine directories: 1. **Inode identity.** `os.fstat` must match `expected_stat` on both `st_dev` and `st_ino` (`same_entry`), else `ValueError('Filesystem entry changed before pruning: {path}')`. This catches replacement between the scan snapshot and the open. 2. **Mount ID.** `fd_mount_id(fd)` parses the `mnt_id:` line of `/proc/self/fdinfo/{fd}`; a mismatch with `expected_mount_id` raises `ValueError('Refusing to prune mounted content: {path}')`. Mount IDs distinguish bind mounts that share `st_dev`, which inode checks alone cannot see. `fd_mount_id` raises `OSError('Failed to read mount ID for file descriptor {fd}: {err}')` when fdinfo is unreadable and `OSError('Mount ID is missing from {fdinfo_path}')` when the line is absent — environments without mount IDs fail loudly rather than silently skipping the check. The expected mount ID is always `fd_mount_id` of the workshop root descriptor, computed once per run. ### Inspection helpers `fd_path(fd)` resolves `/proc/self/fd/{fd}` via readlink (failure: `OSError('Failed to resolve file descriptor {fd}: {err}')`) and supplies display paths plus the paths used by mount containment. `mounted_paths()` parses `/proc/self/mountinfo`, takes field index 4, and decodes octal escapes (`\040`-style) into real characters; fewer than five fields raises `ValueError('Invalid entry in /proc/self/mountinfo: {line!r}')`, and a read failure becomes `OSError('Failed to read /proc/self/mountinfo: {err}')`. `contains_mount(path, mount_paths)` is true when the path equals a mount point or lies beneath one. ### Bounded reads and writes - `read_json_at(directory_fd, name, size_limit)`: opens with `O_RDONLY|O_NONBLOCK|O_NOFOLLOW|O_CLOEXEC` relative to the fd, requires `S_ISREG` (`'{name}' is not a regular file`), rejects `st_size > size_limit`, then reads `size_limit + 1` bytes and rechecks the length — growth between stat and read is caught too. Decodes plain utf-8. `FileNotFoundError` propagates unwrapped; every other `OSError`/`UnicodeError`/`ValueError` is wrapped as `ValueError('Failed to load {name}: {err}')`. Limits: `MAX_SERVER_DATA_SIZE` (1 MiB) for per-mod `ServerData.json`, `MAX_PRUNE_MANIFEST_SIZE` (16 MiB) for `.mod-prune.json`. - `write_json_at(directory_fd, name, content, size_limit)`: serializes first and refuses over-limit output (`'{name}' exceeds the metadata size limit`), then creates the file with `O_WRONLY|O_CREAT|O_EXCL|O_NOFOLLOW|O_CLOEXEC`, mode 0o600 — it never truncates or overwrites — and fsyncs the file. - `sync_directory(directory_fd)` fsyncs the parent directory after every structural mutation (mkdir, rename, unlink, rmdir) so crash recovery sees consistent on-disk state. - `load_server_data` applies the same read pattern with utf-8-sig decoding (BOM tolerated), then applies the per-mod identity checks: the parsed payload must be a JSON object whose mod/published-file ID — the value of its `'modId'`, `'id'`, or `'publishedFileId'` field (numeric or string), stringified and uppercased — equals the mod's 16-uppercase-hex directory name; a non-object payload, a missing ID field, or a mismatch raises `ValueError('ServerData mod ID mismatch: {path}')`. ### The workflow they serve `prune_mods(config_path, workshop_dir)`: 1. Opens the workshop with `O_RDONLY|O_DIRECTORY|O_CLOEXEC` — deliberately without `O_NOFOLLOW`, because the operator-supplied root may legitimately be a symlink; the resulting fd pins the target directory for the whole run, so retargeting the symlink mid-run cannot redirect deletion. A missing directory is a no-op returning `[]`. 2. Locks with `flock(LOCK_EX|LOCK_NB)`; a concurrent pruner surfaces as `BlockingIOError`. 3. Captures `fd_path` and `fd_mount_id` of the root; an `fd_path` failure still closes the fd (no leaks). 4. Recovers leftover quarantines (below) before scanning. 5. `scan_installed_mods` scandirs the root fd; only names of 16 uppercase hex characters are mod candidates; each must be a real directory (`follow_symlinks=False`) and open under the no-follow flags; `ServerData.json` is validated per mod via `load_server_data` (identity checks above). Any such failure — unreadable/oversized/non-regular file, unparseable JSON, or an identity mismatch — is an invalid entry: recorded and skipped — unless a configured (required) mod or one of its dependencies is invalid, which aborts the run before any staging with that recorded error. 6. `retained_mod_ids` computes the closure of configured mods plus declared dependencies (string entries or `{'id'/'modId': ...}` objects); cycles terminate. Configured-mod validity is enforced at config load — before scanning and staging: each configured entry must be a 16-uppercase-hex string or an object whose `'id'`/`'modId'` value is one; anything else (wrong shape or format) raises `ValueError('Invalid configured mod ID: {entry!r}')`. A configured mod that is absent from the workshop scan is tolerated: its ID still joins the closure (with its dependencies), nothing is staged for it, and pruning proceeds. 7. Candidates are pruned in sorted mod-ID order — deterministic and observable. 8. `validate_prune_candidates` re-stats each candidate and refuses any whose path is, or contains, a mount point per `mounted_paths()`. The refusal is a whole-run abort, not a per-candidate skip: the first mount-contained candidate raises `ValueError('Refusing to prune mounted content: {path}')` — same literal as the fdinfo check, but raised here by the path-based `contains_mount` mechanism — before staging begins, so no renames have occurred and nothing needs rollback. 9. `delete_prune_candidates` stages, deletes inside the quarantine, removes the manifest, then removes the quarantine. ### Quarantine staging, rollback, recovery `create_quarantine` creates `.mod-prune-<16 hex>` (ten attempts, mode 0o700), fsyncs the parent, reopens the new directory with the no-follow flags, and validates even that fd. `stage_prune_candidates` writes the manifest (mod ID → device/inode), renames each candidate from the workshop fd to the quarantine fd, then re-stats and revalidates the staged entry against the scan-time identity; mismatch raises the `Mod directory changed before pruning` error. Any staging failure rolls back — reverse-order, identity-checked renames back, manifest removal, quarantine rmdir — and rollback failure surfaces as `OSError('Failed to roll back staged mods: ...')` with the quarantine left for recovery. Because deletion happens only inside the quarantine, a crash leaves one of three states, and `recover_prune_quarantines` handles each: manifest present → delete quarantined mods per manifest (each must match its recorded device/inode, else `ValueError('Invalid quarantined mod entry: {mod_id}')`) and remove the quarantine; empty → remove it; non-empty without a manifest → `ValueError('Incomplete mod pruning quarantine: {path}')`. Two further cases complete the contract: (a) a manifest entry whose quarantined directory no longer exists (crash between per-mod deletions) counts as already deleted and is skipped — recovery continues with the remaining entries and still removes the quarantine; the `Invalid quarantined mod entry` check applies only to entries still present but changed. (b) A truncated or unreadable manifest (crash during manifest creation) is not treated as absent: `read_json_at`'s unwrapped `FileNotFoundError` is the only no-manifest signal (→ the `Incomplete mod pruning quarantine` error), so a present-but-corrupt manifest propagates its wrapped `ValueError('Failed to load .mod-prune.json: {err}')`, recovery stops, and the quarantine is preserved for a later run. Tree deletion itself is iterative: `remove_directory_tree` processes exactly one entry per pass (scandir, take one entry), reopening the current directory from the root via `open_directory_node` each pass — which is why trees far deeper than the recursion limit are handled. Files are opened `O_PATH|O_NOFOLLOW`, identity- and mount-validated, then unlinked by name, so a symlink inside a mod directory is unlinked as an entry while its target survives. Empty directories are re-statted with `follow_symlinks=False` and must match the recorded identity before `rmdir`. ### Test-sensitive edge cases - Required-mod invalidity, invalid config mod IDs, and non-list `dependencies` abort before staging; nothing is deleted. A `ServerData` identity mismatch is invalid-entry invalidity: recorded-and-skipped for unconfigured mods, abort-before-staging when the mod is configured or in a configured mod's dependency closure; an absent (well-formed) configured mod never aborts. - A candidate replaced between scan and staging aborts staging (rollback), and the next run reports the quarantined mismatch. - Deletion failure mid-tree leaves the quarantine in place; the next run retries from it. - `fd_path` failure must not leak the workshop fd. - Directory names that are not valid mod IDs are ignored entirely. #### Exact API Reference #### `launch_config.open_directory_node` - **Import Path**: `from launch_config import open_directory_node` - **Signature**: ```python def open_directory_node(root_fd, node, expected_mount_id) ``` ### Capability: Server process launch orchestration ## Purpose and execution model `launch.py` (installed at `/app/launch.py`, the image `CMD`) is the container's main process and the game server's direct parent. Everything runs at module top level — there is no `main()` — so the phase order below is the execution order, and any failure aborts start-up (via `SystemExit` or an uncaught exception) before the server is spawned. The script indexes `os.environ` directly (`STEAM_APPID`, `SKIP_INSTALL`, `ARMA_CONFIG`, `ARMA_WORKSHOP_DIR`, `ARMA_PROFILE`, `ARMA_MAX_FPS`, `ARMA_PARAMS`, `GAME_MODS_AUTO_PRUNE`), so outside the image, where the Dockerfile `ENV` defaults are absent, a missing variable is a `KeyError`; only values passed into `launch_config` functions get the tolerant `env_defined` treatment (non-empty counts as set). ## Phase order 1. **Signal setup.** `SIGTERM` is remapped to `signal.default_int_handler` before anything else, converting a stop signal into a `KeyboardInterrupt` inside the launcher (see shutdown path). 2. **SteamCMD install/update — skippable.** Runs unless `SKIP_INSTALL` is `""` or `"false"` (exact membership test — *not* `bool_str`; any other value, including `"True"`, skips the install). Sequence: a warm-up `steamcmd +login anonymous +quit` absorbs SteamCMD's self-update (its non-zero exit is tolerated), then the real command: `+force_install_dir /reforger`, `+login` from `STEAM_USER`/`STEAM_PASSWORD` (anonymous when `STEAM_USER` is empty), optional `+@sSteamCmdForcePlatformType`, `+app_update $STEAM_APPID`, optional `-beta`/`-betapassword`, then `validate +quit`. SteamCMD exit codes are ignored throughout. For the experimental app ID `1890870`, a one-time `windows`-platform pass runs first, gated by the sentinel file `/reforger/.windows_fix_done`; the sentinel is deleted whenever `STEAM_APPID` is not `1890870`, so re-entering experimental re-runs the Windows pass exactly once. 3. **Config resolution.** `ARMA_CONFIG` is a bare name under `/reforger/Configs/` with no extension appended. Any value other than `docker_generated` is handed to the server as-is (`/reforger/Configs/`). With auto-prune enabled, a missing or invalid file aborts start-up during the prune phase, before the server spawns: `prune_mods` loads it via `configured_mod_ids`, which requires the file to load, contain a `game` object, and have `game.mods` as an array of valid 16-hex modIds; any failure raises `ValueError` (e.g. `Failed to load : ...`) and start-up exits with `SystemExit("Failed to prune mods: ...")` — even when the workshop is empty or absent. Only with pruning disabled does a missing file merely surface when the game reads it. `docker_generated` regenerates `/reforger/Configs/docker_generated.json` on *every* start: load `/app/docker_default.json`, apply `build_config(os.environ, config)`, and when `GAME_PASSWORD_ADMIN` is undefined/empty replace `passwordAdmin` with a random two-word passphrase drawn from `/usr/share/dict/american-english` (lowercased, `-`-joined, apostrophe-bearing words rejected) and print `Admin password: ` to stdout — the only place the generated password appears. Output is written with `indent=4`; hand edits to this specific filename never survive a restart. 4. **Optional prune.** Only when `bool_str(GAME_MODS_AUTO_PRUNE)` — the value being exactly `true`, case-insensitive — does `prune_mods(CONFIG_PATH, ARMA_WORKSHOP_DIR)` run, against the config resolved in step 3. Any `OSError`/`ValueError` becomes `SystemExit("Failed to prune mods: ...")`. 5. **Launch and supervise.** ## Command line assembly Exact argv order: `ARMA_BINARY`, `-config `, `-backendlog`, `-nothrow`, `-maxFPS `, `-profile `, `-addonDownloadDir `, `-addonsDir `, then `*shlex.split(ARMA_PARAMS)`. Non-obvious details: there is no `-workshop` flag — the workshop directory reaches the server twice, as `-addonDownloadDir` and `-addonsDir`; `-maxFPS` precedes `-profile`; `-backendlog` and `-nothrow` are fixed and non-configurable; `ARMA_PARAMS` is shlex-tokenized (quotes honored) with no shell expansion, so `$VAR`, globs and pipes stay literal, and operator flags always trail the fixed ones. The assembled command is echoed as one `shlex.join`-ed, flushed stdout line before `Popen` — a test-visible trace. The launcher exits with the child's exit code (`sys.exit(proc.wait())`). ## Shutdown path A stop signal (the image `STOPSIGNAL` is SIGINT; SIGTERM is equally remapped) raises `KeyboardInterrupt` in `proc.wait()`; the launcher then sends **SIGINT** to the child, waits again for a graceful exit, and adopts the child's status. A second signal arriving during the relay — or any other exception — falls into `except BaseException: proc.kill()` and re-raises: one signal means graceful relay, two mean SIGKILL escalation. ## build_config behavior the launcher relies on `build_config` deep-copies the base document (never mutating it) and layers sections in fixed order: server/A2S → RCON → game → gameProperties → mods → persistence → operating. Because `env_defined` requires a non-empty value, the image's empty-string defaults keep optional sections at base defaults — and whole sections disappear when their enabling variables are absent: `a2s` unless both `SERVER_A2S_ADDRESS` and `SERVER_A2S_PORT` are set; `rcon` unless `RCON_PASSWORD`, `RCON_ADDRESS` and `RCON_PORT` are all set; `persistence` unless any `PERSISTENCE_*` variable is set; `operating` if it would end up empty. Start-up aborts with `ValueError` on bad integers (`Invalid : `), malformed mod IDs (16 hex characters) or versions (`N.N.N`), and the mutually exclusive pair (`"RCON_BLACKLIST and RCON_WHITELIST cannot both be set"`). Mods: `apply_mods_config` unconditionally replaces `game.mods`, merging `GAME_MODS_IDS_LIST` then `GAME_MODS_JSON_FILE_PATH` with first definition winning per ID — with neither source set the result is an empty array, so base mods in `docker_default.json` are always discarded. Mod IDs are uppercase-only 16-hex (`[0-9A-F]{16}`); lowercase IDs are rejected everywhere, including `GAME_MODS_IDS_LIST`, the JSON file, the config, `ServerData.json` and the prune manifest. `GAME_MODS_IDS_LIST` must fully match `^[A-Z0-9,=.]+$` or start-up aborts with `Illegal characters in GAME_MODS_IDS_LIST env` (lowercase letters rejected), and each entry may contain at most one `=` (` mod not defined properly`). `GAME_MODS_REQUIRED_BY_DEFAULT` is dual-purpose: besides mapping to `game.modsRequiredByDefault`, when defined it injects `required` — via `bool_str`, so any value other than case-insensitive `true` yields `false` — into every IDS_LIST entry and into JSON entries lacking a `required` key; when undefined, no `required` key is added. File-based sources (`GAME_MODS_JSON_FILE_PATH`, `PERSISTENCE_JSON_FILE_PATH`, `GAME_MISSION_HEADER_JSON_FILE_PATH`) abort with `Failed to load : ...` on missing/unreadable/malformed JSON. ## prune_mods contract `prune_mods(config_path, workshop_dir)` returns the list of pruned mod paths. It returns `[]` when the workshop directory does not exist (`FileNotFoundError` swallowed — not an error) or nothing is unconfigured; it never fails on an empty/absent workshop. It holds a non-blocking exclusive `flock` on the workshop directory for the whole operation. Retention is the configured `game.mods` IDs plus their transitive `ServerData.json` dependencies; a configured or dependency ID whose on-disk entry is malformed aborts the entire prune (nothing is deleted), while invalid *unconfigured* mod directories are merely skipped with a printed warning — but only directories named with exactly 16 uppercase hex characters are inspected at all: workshop entries with any other name are ignored silently, as neither candidates nor invalid directories. Candidates — and the returned pruned-path list — are processed in ascending mod-ID string order, and each successful deletion prints `Pruned mod () from ` to stdout. Deletion is two-phase: candidates are renamed into a `.mod-prune-<16 hex>` quarantine with a `.mod-prune.json` manifest, then removed from within it; a staging failure rolls staged mods back before re-raising. Mounted-content refusal has two independent gates. The `/proc/self/mountinfo` scan refuses only a candidate that *is* a mount point or *contains* one anywhere beneath it (the candidate is an ancestor of the mount); a candidate that merely lies *beneath* a mount point passes this scan. Independently, during staging and deletion every opened directory or file has its fdinfo `mnt_id` compared against the workshop fd's mount id, and a mismatch aborts with `Refusing to prune mounted content: `. Content on the same mount as the workshop — including paths beneath a shared mount point, the normal bind-mounted deployment — is deleted normally. Orphaned quarantines are recovered only as part of `prune_mods` execution, so recovery happens only when auto-prune is enabled; with pruning disabled, orphans persist untouched. Only directory names matching `^.mod-prune-[0-9a-f]{16}$` are considered. A manifest-bearing quarantine is finished (its remaining mods deleted) then removed; a manifest-less quarantine is removed only when empty, while one containing any entry raises `ValueError("Incomplete mod pruning quarantine: ")` and aborts the whole prune (`SystemExit` at launch). Each recovery prints `Recovered interrupted mod pruning quarantine ` to stdout. #### Exact API Reference #### `launch_config.env_defined` - **Import Path**: `from launch_config import env_defined` - **Required Test Import Paths**: - launch_config.env_defined - **Exact Test Import Statements**: - from launch_config import bool_str, build_config, env_defined - **Signature**: ```python def env_defined(env, key) ``` #### `launch_config.bool_str` - **Import Path**: `from launch_config import bool_str` - **Required Test Import Paths**: - launch_config.bool_str - **Exact Test Import Statements**: - from launch_config import bool_str, build_config, env_defined - **Signature**: ```python def bool_str(text) ``` #### `launch_config.split_csv` - **Import Path**: `from launch_config import split_csv` - **Signature**: ```python def split_csv(text) ``` #### `launch_config.parse_int` - **Import Path**: `from launch_config import parse_int` - **Signature**: ```python def parse_int(env, key) ``` #### `launch_config.env_str` - **Import Path**: `from launch_config import env_str` - **Signature**: ```python def env_str(env, key) ``` #### `launch_config.env_bool` - **Import Path**: `from launch_config import env_bool` - **Signature**: ```python def env_bool(env, key) ``` #### `launch_config.env_csv` - **Import Path**: `from launch_config import env_csv` - **Signature**: ```python def env_csv(env, key) ``` #### `launch_config.validate_mod_id` - **Import Path**: `from launch_config import validate_mod_id` - **Signature**: ```python def validate_mod_id(mod_id, source) ``` #### `launch_config.configured_mod_ids` - **Import Path**: `from launch_config import configured_mod_ids` - **Signature**: ```python def configured_mod_ids(config_path) ``` #### `launch_config.load_server_data` - **Import Path**: `from launch_config import load_server_data` - **Signature**: ```python def load_server_data(mod_fd, server_data_path) ``` #### `launch_config.decode_mount_path` - **Import Path**: `from launch_config import decode_mount_path` - **Signature**: ```python def decode_mount_path(path) ``` #### `launch_config.mounted_paths` - **Import Path**: `from launch_config import mounted_paths` - **Required Test Import Paths**: - launch_config.mounted_paths - **Exact Test Import Statements**: - import launch_config - **Signature**: ```python def mounted_paths() ``` #### `launch_config.contains_mount` - **Import Path**: `from launch_config import contains_mount` - **Signature**: ```python def contains_mount(path, mount_paths) ``` #### `launch_config.fd_mount_id` - **Import Path**: `from launch_config import fd_mount_id` - **Required Test Import Paths**: - launch_config.fd_mount_id - **Exact Test Import Statements**: - import launch_config - **Signature**: ```python def fd_mount_id(file_descriptor) ``` #### `launch_config.validate_open_entry` - **Import Path**: `from launch_config import validate_open_entry` - **Signature**: ```python def validate_open_entry(file_descriptor, expected_stat, expected_mount_id, path) ``` #### `launch_config.same_entry` - **Import Path**: `from launch_config import same_entry` - **Signature**: ```python def same_entry(actual_stat, expected_stat) ``` #### `launch_config.fd_path` - **Import Path**: `from launch_config import fd_path` - **Signature**: ```python def fd_path(file_descriptor) ``` #### `launch_config.remove_empty_directory` - **Import Path**: `from launch_config import remove_empty_directory` - **Signature**: ```python def remove_empty_directory(root_fd, node, expected_mount_id) ``` #### `launch_config.remove_file_entry` - **Import Path**: `from launch_config import remove_file_entry` - **Signature**: ```python def remove_file_entry(directory_fd, name, expected_stat, expected_mount_id, path) ``` #### `launch_config.remove_directory_tree` - **Import Path**: `from launch_config import remove_directory_tree` - **Required Test Import Paths**: - launch_config.remove_directory_tree - **Exact Test Import Statements**: - import launch_config - **Signature**: ```python def remove_directory_tree(root_fd, name, expected_stat, expected_mount_id, path) ``` #### `launch_config.create_quarantine` - **Import Path**: `from launch_config import create_quarantine` - **Signature**: ```python def create_quarantine(workshop_fd, expected_mount_id) ``` - **Raises** (implementation must reproduce these exact messages): - `Failed to create a unique mod pruning quarantine` #### `launch_config.write_json_at` - **Import Path**: `from launch_config import write_json_at` - **Signature**: ```python def write_json_at(directory_fd, name, content, size_limit) ``` #### `launch_config.read_json_at` - **Import Path**: `from launch_config import read_json_at` - **Signature**: ```python def read_json_at(directory_fd, name, size_limit) ``` #### `launch_config.sync_directory` - **Import Path**: `from launch_config import sync_directory` - **Signature**: ```python def sync_directory(directory_fd) ``` #### `launch_config.prune_manifest` - **Import Path**: `from launch_config import prune_manifest` - **Signature**: ```python def prune_manifest(candidates) ``` #### `launch_config.load_prune_manifest` - **Import Path**: `from launch_config import load_prune_manifest` - **Signature**: ```python def load_prune_manifest(quarantine_fd) ``` #### `launch_config.delete_quarantined_mods` - **Import Path**: `from launch_config import delete_quarantined_mods` - **Signature**: ```python def delete_quarantined_mods(quarantine_fd, manifest, expected_mount_id, quarantine_path) ``` #### `launch_config.rollback_staged_mods` - **Import Path**: `from launch_config import rollback_staged_mods` - **Signature**: ```python def rollback_staged_mods(workshop_fd, quarantine_fd, staged_mods) ``` #### `launch_config.stage_prune_candidates` - **Import Path**: `from launch_config import stage_prune_candidates` - **Required Test Import Paths**: - launch_config.stage_prune_candidates - **Exact Test Import Statements**: - import launch_config - **Signature**: ```python def stage_prune_candidates(workshop_fd, expected_mount_id, candidates) ``` #### `launch_config.retained_mod_ids` - **Import Path**: `from launch_config import retained_mod_ids` - **Signature**: ```python def retained_mod_ids(configured_ids, installed_mods, invalid_mods) ``` #### `launch_config.validate_prune_candidates` - **Import Path**: `from launch_config import validate_prune_candidates` - **Signature**: ```python def validate_prune_candidates(workshop_fd, candidates) ``` #### `launch_config.delete_prune_candidates` - **Import Path**: `from launch_config import delete_prune_candidates` - **Signature**: ```python def delete_prune_candidates(workshop_fd, expected_mount_id, candidates) ``` #### `launch_config.prune_mods` - **Import Path**: `from launch_config import prune_mods` - **Required Test Import Paths**: - launch_config.prune_mods - **Exact Test Import Statements**: - from launch_config import prune_mods - **Signature**: ```python def prune_mods(config_path, workshop_dir) ``` #### `launch_config.apply_env_overrides` - **Import Path**: `from launch_config import apply_env_overrides` - **Signature**: ```python def apply_env_overrides(target, env, env_map) ``` #### `launch_config.apply_server_config` - **Import Path**: `from launch_config import apply_server_config` - **Signature**: ```python def apply_server_config(config, env) ``` #### `launch_config.apply_rcon_config` - **Import Path**: `from launch_config import apply_rcon_config` - **Signature**: ```python def apply_rcon_config(config, env) ``` - **Raises** (implementation must reproduce these exact messages): - `RCON_BLACKLIST and RCON_WHITELIST cannot both be set` #### `launch_config.apply_game_properties` - **Import Path**: `from launch_config import apply_game_properties` - **Signature**: ```python def apply_game_properties(config, env) ``` #### `launch_config.default_mod_required` - **Import Path**: `from launch_config import default_mod_required` - **Signature**: ```python def default_mod_required(env) ``` #### `launch_config.apply_mods_config` - **Import Path**: `from launch_config import apply_mods_config` - **Signature**: ```python def apply_mods_config(config, env) ``` #### `launch_config.apply_persistence_config` - **Import Path**: `from launch_config import apply_persistence_config` - **Signature**: ```python def apply_persistence_config(config, env) ``` #### `launch_config.apply_operating_config` - **Import Path**: `from launch_config import apply_operating_config` - **Signature**: ```python def apply_operating_config(config, env) ``` #### `launch_config.build_config` - **Import Path**: `from launch_config import build_config` - **Required Test Import Paths**: - launch_config.build_config - **Exact Test Import Statements**: - from launch_config import bool_str, build_config, env_defined - **Signature**: ```python def build_config(env, base_config) ``` #### `launch_config` - **Import Path**: `launch_config` - **Required Test Import Paths**: - launch_config - **Exact Test Import Statements**: - import launch_config - **Kind**: module - **Behavior**: Module required during hidden-test collection. #### `launch_config.DIRECTORY_OPEN_FLAGS` - **Import Path**: `from launch_config import DIRECTORY_OPEN_FLAGS` - **Required Test Import Paths**: - launch_config.DIRECTORY_OPEN_FLAGS - **Exact Test Import Statements**: - import launch_config - **Kind**: constant - **Signature**: ```python DIRECTORY_OPEN_FLAGS: Any ``` - **Behavior**: Module-level value required by the test import contract. #### `launch_config.MAX_SERVER_DATA_SIZE` - **Import Path**: `from launch_config import MAX_SERVER_DATA_SIZE` - **Required Test Import Paths**: - launch_config.MAX_SERVER_DATA_SIZE - **Exact Test Import Statements**: - import launch_config - **Kind**: constant - **Signature**: ```python MAX_SERVER_DATA_SIZE: Any ``` - **Behavior**: Module-level value required by the test import contract. #### `launch_config.PRUNE_QUARANTINE_PREFIX` - **Import Path**: `from launch_config import PRUNE_QUARANTINE_PREFIX` - **Required Test Import Paths**: - launch_config.PRUNE_QUARANTINE_PREFIX - **Exact Test Import Statements**: - import launch_config - **Kind**: constant - **Signature**: ```python PRUNE_QUARANTINE_PREFIX: str ``` - **Behavior**: Module-level value required by the test import contract. #### `launch_config.SERVER_DATA_FILE` - **Import Path**: `from launch_config import SERVER_DATA_FILE` - **Required Test Import Paths**: - launch_config.SERVER_DATA_FILE - **Exact Test Import Statements**: - import launch_config - **Kind**: constant - **Signature**: ```python SERVER_DATA_FILE: str ``` - **Behavior**: Module-level value required by the test import contract. #### `launch_config.WORKSHOP_OPEN_FLAGS` - **Import Path**: `from launch_config import WORKSHOP_OPEN_FLAGS` - **Required Test Import Paths**: - launch_config.WORKSHOP_OPEN_FLAGS - **Exact Test Import Statements**: - import launch_config - **Kind**: constant - **Signature**: ```python WORKSHOP_OPEN_FLAGS: Any ``` - **Behavior**: Module-level value required by the test import contract. ### Capability: Workshop mod scanning and metadata validation ## Purpose At startup the tooling may prune workshop mods the current configuration no longer needs. Before anything is deleted it must know exactly what is installed and whether each installation's metadata is trustworthy. This capability provides that inventory: it scans the workshop directory through a directory file descriptor, loads and size-limits each mod's `ServerData.json`, validates IDs, names, revisions, download state, and dependency lists, and compares the result against the mod IDs declared in the generated config. ## Pipeline position and ordering `prune_mods(config_path, workshop_dir)` drives the flow: 1. `configured_mod_ids(config_path)` (via `load_json_file`) extracts the declared `game.mods` IDs. This is the first statement of `prune_mods`, so every config error — missing or malformed config file, missing `game` object, invalid `game.mods` entries — raises before the workshop directory is touched. 2. Open the workshop directory (a `FileNotFoundError` short-circuits to "nothing to prune") and take a non-blocking exclusive `flock`, failing closed if another process holds it. The missing-directory short-circuit applies only after config validation succeeds: a missing workshop directory combined with an invalid config still raises instead of returning no candidates. 3. Recover interrupted pruning quarantines. 4. `scan_installed_mods(workshop_fd, workshop_root)` builds the `installed`/`invalid` inventories. 5. Retention computes the keep-set as a worklist closure seeded with the configured IDs (see "Retention and validation against declared mods"). 6. Installed-but-not-retained mods, iterated in sorted-ID order, become prune candidates whose deletion re-verifies both the `stat` identity captured during the scan and the mount-boundary guards below. Ordering matters: the scan must complete before any mutation, because the `stat` snapshot (`st_dev`/`st_ino` of the directory fd) recorded per mod is the identity re-checked before deletion; anything that changed in between aborts pruning. Deletion is additionally guarded against mount boundaries: candidate paths are checked against mountinfo-derived mount paths, and a candidate that sits at a mountpoint or has one beneath it aborts with "Refusing to prune mounted content"; in addition, the `/proc/self/fdinfo` mount ID of every directory or file opened during staging and deletion is re-verified against the workshop fd's mount ID, so an otherwise stat-identical candidate on a mounted subvolume still aborts. ## Scanning semantics - Directory entries whose names are not 16 uppercase hex characters (`MOD_ID_RE`) are skipped silently — this is what keeps quarantine directories (`.mod-prune-…`) and other noise out of both maps. - A matching name that is not a real directory (regular file or symlink; `is_dir` with `follow_symlinks=False`) is recorded in `invalid_mods` with "is not a regular directory". - The mod directory is opened relative to `workshop_fd` with `O_DIRECTORY|O_NOFOLLOW`; races surface as `OSError` and land in `invalid_mods`. Every skip prints `Skipping invalid mod directory {path}: {err}`. Per-entry failures never propagate out of `scan_installed_mods`; only a failing `scandir` on the workshop fd itself raises. ## Metadata loading and limits `load_installed_mod` reads `ServerData.json` relative to the mod's fd with `O_NOFOLLOW|O_NONBLOCK` (symlinks fail, FIFOs cannot block), requires a regular file, and enforces the 1 MiB limit twice: a pre-read `st_size` check and a post-read length check reading at most limit+1 bytes (catches files that grow or misreport size). Content is decoded `utf-8-sig`, so BOM-prefixed files are accepted, and must parse to a JSON object. All load failures are wrapped as `ValueError("Failed to load {mod_path}/ServerData.json: …")`. Field predicates, evaluated in order: - `id`: a string equal to the directory name and matching the hex ID pattern, else "does not match its directory". - `name`: a non-empty string. - `revision`: a dict; `revision.version` a non-empty string (no version-pattern check here, unlike `GAME_MODS_IDS_LIST` versions); `revision.downloaded` must be the boolean `True` — missing, `False`, or the string `"true"` fails with "is not fully downloaded", so partially downloaded mods are always invalid. - `dependencies`: validated from `revision.dependencies`, not a top-level `ServerData.json` key — a top-level `dependencies` array is silently ignored. Missing or non-list fails with "dependencies in {path} must be an array". Entries may be ID strings or objects exposing `id` or `modId` (`id` wins unless falsy, then `modId` is tried). Any other shape, or an ID failing validation, raises `Invalid dependency in {path}: {entry!r}`. The result is a set, so duplicate dependencies collapse and dependency-driven retention terminates even with cycles. On success the returned record is `{id, name, dependencies, path, stat}`, where `stat` is `os.fstat(mod_fd)` captured after the field predicates pass. The mod fd is closed even when validation raises. ## Retention and validation against declared mods `configured_mod_ids` requires a `game` object and a `game.mods` array (a missing key defaults to `[]`); each entry must be a dict exposing a pattern-valid `modId`; duplicates collapse into a set. Retention itself is a worklist closure, not a flat diff: the keep-set is seeded with the configured IDs, and each popped ID is first checked, then expanded — if it appears in `invalid_mods`, `Cannot safely prune because required mod {id} is invalid: …` is raised; if it is present in `installed`, its dependency set extends the frontier. Two coupled consequences: - An invalid mod that is config-declared or reachable as a transitive dependency of a configured mod aborts pruning of everything — the intended fail-safe. - Dependencies are followed only for installed mods already in the keep-set. An invalid mod referenced only by an unretained installed mod does not freeze pruning, and the dependencies of unretained installed mods are ignored entirely: they can neither retain nor block anything. Configured IDs absent from both maps are treated as retained (a not-yet-downloaded mod is not an error there), while extra installed mods become candidates. ## Config-side mods parsing The declared IDs are produced by `apply_mods_config`, which fills `game.mods` from two optional sources processed in a fixed order against one shared `seen_ids` set: 1. `GAME_MODS_IDS_LIST` (env list, first): the raw value must match the character whitelist `^[A-Z\d,=.]+$` (uppercase letters, digits, comma, equals, dot) or `Illegal characters in GAME_MODS_IDS_LIST env` is raised; it is then split on commas, and each entry must be `modId` or `modId=version` (a second `=` raises `{mod} mod not defined properly`). A version must match the three-part numeric pattern `^\d+\.\d+\.\d+$`. 2. `GAME_MODS_JSON_FILE_PATH` (JSON file, second): read via `load_json_file` and must be an array (`GAME_MODS_JSON_FILE_PATH must contain an array`); every entry must be a dict containing `modId` (validated against the hex ID pattern); keys outside `modId`/`name`/`version`/`required` are discarded. Because the env list is processed first, an entry in the JSON file whose ID was already seen (from the env list or an earlier file entry) is silently dropped rather than rejected. When `GAME_MODS_REQUIRED_BY_DEFAULT` is set, its boolean value is the optional `required` default injected into entries that do not set it. ## Cross-cutting `load_json_file` behavior `load_json_file` is the single reader for JSON side inputs (mods JSON file, mission header, persistence JSON, the server config). It opens with `utf-8-sig` and wraps any `OSError`/`ValueError` as `ValueError("Failed to load {path}: …")` — callers and tests must expect `ValueError`, not `FileNotFoundError`, for missing or malformed files. ## Edge cases - Empty workshop → `({}, {})`; scanning never mutates the filesystem or takes locks (the `flock` belongs to the prune driver). - A `ServerData.json` of exactly 1,048,576 bytes passes; one byte more fails. - `revision.dependencies: []` is valid; a top-level `dependencies` key is ignored. - `invalid_mods` keys are directory names and values are the raised exceptions; only hex-ID-shaped names ever appear there. - An entry recorded as invalid is never also present in `installed`. #### Exact API Reference #### `launch_config.load_json_file` - **Import Path**: `from launch_config import load_json_file` - **Required Test Import Paths**: - launch_config.load_json_file - **Exact Test Import Statements**: - from launch_config import load_json_file - **Signature**: ```python def load_json_file(path) ``` #### `launch_config.dependency_ids` - **Import Path**: `from launch_config import dependency_ids` - **Signature**: ```python def dependency_ids(server_data_path, dependencies) ``` #### `launch_config.load_installed_mod` - **Import Path**: `from launch_config import load_installed_mod` - **Required Test Import Paths**: - launch_config.load_installed_mod - **Exact Test Import Statements**: - import launch_config - **Signature**: ```python def load_installed_mod(mod_id, mod_fd, mod_path) ``` #### `launch_config.scan_installed_mods` - **Import Path**: `from launch_config import scan_installed_mods` - **Signature**: ```python def scan_installed_mods(workshop_fd, workshop_root) ``` #### `launch_config.parse_mods_ids_list` - **Import Path**: `from launch_config import parse_mods_ids_list` - **Signature**: ```python def parse_mods_ids_list(env, required_default, seen_ids) ``` - **Raises** (implementation must reproduce these exact messages): - `Illegal characters in GAME_MODS_IDS_LIST env` #### `launch_config.parse_mods_json_file` - **Import Path**: `from launch_config import parse_mods_json_file` - **Signature**: ```python def parse_mods_json_file(env, required_default, seen_ids) ``` - **Raises** (implementation must reproduce these exact messages): - `GAME_MODS_JSON_FILE_PATH must contain an array` ### Capability: Transactional mod pruning with quarantine and recovery # Transactional mod pruning with quarantine and recovery This capability makes deletion of unwanted workshop mods crash-safe. Mods are never deleted in place: they are first renamed into a hidden quarantine directory inside the workshop, together with a manifest that records the device/inode identity of every staged entry. If the process dies at any point, the next startup finds the quarantine and deterministically finishes the removal. Nothing is ever deleted unless the manifest-recorded identity — device and inode — of every entry still matches (the quarantine directory itself is additionally checked against the workshop's mount ID), so a quarantined entry whose recorded identity changed is refused, not destroyed. Identity is the recorded device/inode, not file contents: edits inside a quarantined mod do not change its recorded identity and are still deleted. ## Lifecycle and ordering `prune_mods(config_path, workshop_dir)` is invoked by the launcher when `GAME_MODS_AUTO_PRUNE` is truthy, before the server binary starts. In order it: 1. Opens the workshop directory with `WORKSHOP_OPEN_FLAGS` (`O_RDONLY | O_DIRECTORY | O_CLOEXEC`; the top-level path may be a symlink — it is resolved once and everything afterward operates on the file descriptor). A missing workshop is a no-op returning `[]`. 2. Takes `fcntl.flock(fd, LOCK_EX | LOCK_NB)`. A second concurrent pruner gets `BlockingIOError`. 3. Resolves `workshop_root = fd_path(fd)` (via `/proc/self/fd`) and `workshop_mount_id = fd_mount_id(fd)` (the `mnt_id` line of `/proc/self/fdinfo/`). Because the root string is captured up front, retargeting the workshop symlink mid-run cannot redirect deletions to a different tree. 4. **Runs `recover_prune_quarantines(workshop_fd, expected_mount_id, workshop_root)` first**, before scanning or planning. This ordering is mandatory: recovery must settle leftovers from a previous crash before a fresh prune can stage new ones, otherwise two quarantines for the same mod could coexist. 5. Scans installed mods, computes the retention set (configured mods plus transitive dependencies), sorts the candidates by mod ID, validates them against `/proc/self/mountinfo`, and stages + deletes them transactionally. Every failure path is fatal by design: errors propagate out of `prune_mods`, and the launcher converts them into `SystemExit("Failed to prune mods: ...")`. Startup aborts rather than running the server with an ambiguous workshop. ## Quarantine layout - Name: `".mod-prune-" + secrets.token_hex(8)`, i.e. `.mod-prune-` followed by 16 lowercase hex chars (`PRUNE_QUARANTINE_RE` requires exactly this shape; other dot-directories are ignored). Created mode `0o700` relative to the workshop fd; up to 10 collision retries before `OSError("Failed to create a unique mod pruning quarantine")`. - Manifest: `.mod-prune.json` inside the quarantine, `{"mods": {"": {"device": st_dev, "inode": st_ino}}}`. Size limit `MAX_PRUNE_MANIFEST_SIZE` = 16 MiB. The manifest is written **before** any mod is renamed, so a crash after the write but during staging still leaves a fully recoverable state. - Staged mod directories keep their 16-hex-char mod ID names inside the quarantine, renamed with `os.rename(..., src_dir_fd=workshop_fd, dst_dir_fd=quarantine_fd)` and re-validated (dev/ino + mount ID) after each rename. ## Staging protocol (commit path) `stage_prune_candidates` writes the manifest, then renames each candidate in. On any failure it runs `rollback_staged_mods`: mods are renamed back to the workshop in **reversed** staging order, each verified via `same_entry` against the originally scanned stat. A mod whose quarantined identity changed is reported as `": quarantined entry changed"` and left in quarantine — rollback cannot restore an entry that no longer matches — and the rollback then raises `OSError("Failed to roll back staged mods: ...")` chained from the original error. A **successful** rollback unlinks the manifest and removes the quarantine directory, leaving no residue; a **failed** rollback intentionally leaves the quarantine in place — manifest plus any changed entries — for the next run's recovery to settle. The replacement-content test relies on exactly this failed-rollback residue being re-validated, and refused with `Invalid quarantined mod entry: `, on the next run. After staging succeeds, `delete_prune_candidates` removes each mod tree from the quarantine (via `remove_directory_tree`, an iterative, deepest-first walker that validates dev/ino and mount ID at every node and never follows symlinks), fsyncs, unlinks the manifest, and `rmdir`s the now-empty quarantine from the workshop. It returns the pruned paths in sorted mod-ID order. ## Recovery protocol `recover_prune_quarantines` handles each leftover quarantine independently: 1. One `os.scandir(workshop_fd)` pass collects names matching `PRUNE_QUARANTINE_RE`. 2. The entry must `os.stat` (no symlink follow; a stat `OSError` aborts with `Failed to inspect `) and be a real directory, else `Invalid mod pruning quarantine: `. It is opened with `O_NOFOLLOW` flags and validated: fstat dev/ino must match the just-taken stat and `fd_mount_id` must equal the workshop mount ID (guarding against a mount point smuggled into quarantine). 3. The manifest is loaded and structurally validated (dict with a `mods` dict; keys valid mod IDs; values with int `device`/`inode`). None of these manifest failures is tolerated: a manifest larger than `MAX_PRUNE_MANIFEST_SIZE`, one that is not a regular file, or one that is structurally invalid rejects the quarantine with `Invalid mod pruning quarantine: ` and aborts the run. 4. **Manifest present** → `delete_quarantined_mods` finishes the prune: each recorded entry is deleted if its current dev/ino still matches the manifest (`FileNotFoundError` means already deleted and is skipped); any mismatch raises `Invalid quarantined mod entry: ` instead of deleting an entry whose recorded identity changed. Then the manifest is unlinked. 5. **Manifest absent** → the quarantine is only acceptable if completely empty; any other content raises `Incomplete mod pruning quarantine`. Recovery never restores mods into the workshop — rollback is a staging-time mechanism only; recovery can commit or abort. 6. Finally the empty quarantine is `rmdir`ed, the workshop fd is fsynced, and `Recovered interrupted mod pruning quarantine ` is printed. Only manifest-recorded entries are ever deleted, so unrecorded content prevents this: the `rmdir` then fails with `ENOTEMPTY`, and that `OSError` propagates as a fatal error — with the manifest already unlinked, the stranded non-empty quarantine is rejected as `Incomplete mod pruning quarantine` on the next run. ## Test-sensitive behaviors - Interruption at any point converges: crash mid-deletion → recovery skips missing entries and finishes; crash after manifest unlink → empty-quarantine path completes; crash mid-staging → valid manifest makes recovery finish the prune (a mod already moved into quarantine is deleted even if the files inside were modified afterwards — identity is the manifest-recorded device/inode, not file contents). - A candidate replaced in the workshop after it was scanned and recorded in the manifest but before it is renamed into the quarantine cannot be pruned safely: the rename stages the replacement, the post-rename dev/ino re-validation detects the mismatch and aborts staging (`": quarantined entry changed"`), rollback cannot restore the entry and leaves it in quarantine, and the orphaned quarantine fails the next startup with `Invalid quarantined mod entry: ` — the replacement's sentinel survives. - Non-mod-named directories, symlinked mod dirs, and unreadable metadata are skipped or abort pruning earlier; recovery only ever touches exact `.mod-prune-<16hex>` siblings. - Directory fds are closed on every path, including when `fd_path` fails, so no descriptor leak survives a failed run. #### Exact API Reference #### `launch_config.recover_prune_quarantines` - **Import Path**: `from launch_config import recover_prune_quarantines` - **Signature**: ```python def recover_prune_quarantines(workshop_fd, expected_mount_id, workshop_root) ``` ## Detailed Implementation Nodes ### Node: Environment variable parsing helpers ## Functional constraints - Accessors are stateless and take the environment as any mapping (`dict` in tests, `os.environ` in the container). They never mutate it and return fresh values. - `env_defined(env, key)` is the sole gate: true only when the key exists *and* its length > 0. Empty string ≡ unset; whitespace-only counts as defined. - `env_str` returns the raw value verbatim (no strip, no validation); it indexes directly, so calling it for an absent key raises `KeyError`. - `bool_str`/`env_bool` compare `text.lower() == "true"`: case-insensitive true, everything else silently `False`. Booleans never raise. - `split_csv`/`env_csv`: split on commas, strip each item, drop empties. Order and duplicates preserved; commas-only input yields `[]`; never raises. - `parse_int` delegates to `int()`, so surrounding whitespace and signs are accepted. Any `KeyError`/`TypeError`/`ValueError` is re-raised as `ValueError` with the literal message `Invalid : ` (missing key renders as `None` via `env.get`) and chained as `__cause__`. Tests assert the message verbatim. - `env_navmesh_streaming` returns `[]` when the value lowercased is `all` (sentinel meaning "disable nothing" = streaming enabled everywhere), otherwise `split_csv`. The sentinel check is not whitespace-tolerant (`"all "` parses as a region name). It never receives a missing key through `apply_env_overrides`, which calls it only for defined, non-empty variables. - A converter failure inside `build_config` aborts the whole config build — there is no per-key fallback or defaulting. ## Usage example ```python from launch_config import ( env_defined, env_str, env_bool, env_csv, parse_int, env_navmesh_streaming, ) env = {"GAME_NAME": "My Server", "GAME_VISIBLE": "TRUE", "GAME_ADMINS": " a1 , , b2 ", "SERVER_BIND_PORT": " 2001 ", "OPERATING_DISABLE_NAVMESH_STREAMING": "All"} if env_defined(env, "GAME_NAME"): name = env_str(env, "GAME_NAME") # "My Server" ok = env_bool(env, "GAME_VISIBLE") # True (case-insensitive) admins = env_csv(env, "GAME_ADMINS") # ["a1", "b2"] port = parse_int(env, "SERVER_BIND_PORT") # 2001 (int() trims spaces) regions = env_navmesh_streaming( env, "OPERATING_DISABLE_NAVMESH_STREAMING") # [] because "all" ``` ### Node: Safe file-descriptor-based filesystem primitives ### Functional constraints - `open_directory_node(root_fd, node, expected_mount_id)`: `node` is a record `{'name': str, 'parent': record|None, 'path': Path, 'stat': os.stat_result}` — never a bare name. Walk `parent` links to the root, then re-descend from `root_fd`, opening each component with `os.open(name, O_RDONLY|O_DIRECTORY|O_NOFOLLOW|O_CLOEXEC, dir_fd=)`. Symlinked or non-directory components fail the open; they are never followed. - Validate each level via `validate_open_entry(fd, node['stat'], expected_mount_id, node['path'])`: `os.fstat` must match the captured `st_dev` and `st_ino` (`same_entry`), else `ValueError('Filesystem entry changed before pruning: {path}')`; the fd's mount ID must equal `expected_mount_id`, else `ValueError('Refusing to prune mounted content: {path}')`. - `fd_mount_id(fd)` parses the `mnt_id:` line of `/proc/self/fdinfo/{fd}`; unreadable → `OSError('Failed to read mount ID for file descriptor {fd}: {err}')`; line missing → `OSError('Mount ID is missing from {fdinfo_path}')`. The expected ID is `fd_mount_id` of the workshop root, taken once per run. - Lifetime: `root_fd` is duplicated and never closed; on any exception the working fd is closed and the error re-raised; the returned fd belongs to the caller. - Reads (`read_json_at`): `O_RDONLY|O_NONBLOCK|O_NOFOLLOW|O_CLOEXEC`, `S_ISREG` required, `st_size ≤ size_limit`, then `read(size_limit + 1)` with a length recheck. `FileNotFoundError` passes through unwrapped; other errors become `ValueError('Failed to load {name}: {err}')`. Limits: 1 MiB (ServerData.json), 16 MiB (prune manifest). - Identity/config/recovery checks: `load_server_data` compares the parsed metadata's mod/published-file ID (`'modId'`/`'id'`/`'publishedFileId'`, stringified, uppercased) with the 16-uppercase-hex directory name — non-object, missing field, or mismatch → `ValueError('ServerData mod ID mismatch: {path}')` (invalid entry: record-and-skip, or abort for configured/dependency mods). Configured entries are 16-uppercase-hex strings or `{'id'/'modId': <16-hex>}` objects, validated at config load (`ValueError('Invalid configured mod ID: {entry!r}')`); absent configured mods are tolerated and only join the closure. `validate_prune_candidates` mount containment aborts the whole run with `ValueError('Refusing to prune mounted content: {path}')` before any staging/renames. Recovery skips quarantined entries already deleted; a present-but-unreadable manifest propagates `ValueError('Failed to load .mod-prune.json: {err}')` and preserves the quarantine; only unwrapped `FileNotFoundError` means no manifest (`ValueError('Incomplete mod pruning quarantine: {path}')`). - Writes (`write_json_at`): serialize first, enforce the limit, create with `O_WRONLY|O_CREAT|O_EXCL|O_NOFOLLOW|O_CLOEXEC`, mode 0o600, fsync; never overwrite. - Every structural mutation (mkdir/rename/unlink/rmdir) is followed by `sync_directory` (fsync of the directory fd). - Deletion: files are opened `O_PATH|O_NOFOLLOW`, identity- and mount-validated, then unlinked by name (symlinks removed, never traversed); empty directories are re-statted with `follow_symlinks=False` and must match the recorded identity before `rmdir`. Parent-chain walk and tree removal are iterative — depth is unbounded. - Concurrency/ordering: workshop root opened without `O_NOFOLLOW` (the pinned fd is the anchor), locked `flock(LOCK_EX|LOCK_NB)` → `BlockingIOError` on contention; recover quarantines → scan → dependency closure → sorted candidates → mount-containment refusal → stage → delete → cleanup. ### Usage example ```python import fcntl, os, pathlib import launch_config workshop_fd = os.open(workshop_dir, launch_config.WORKSHOP_OPEN_FLAGS) try: fcntl.flock(workshop_fd, fcntl.LOCK_EX | fcntl.LOCK_NB) mount_id = launch_config.fd_mount_id(workshop_fd) mod_stat = os.stat(mod_id, dir_fd=workshop_fd, follow_symlinks=False) node = {'name': mod_id, 'parent': None, 'path': pathlib.Path(mod_id), 'stat': mod_stat} mod_fd = launch_config.open_directory_node(workshop_fd, node, mount_id) try: data = launch_config.read_json_at(mod_fd, launch_config.SERVER_DATA_FILE, launch_config.MAX_SERVER_DATA_SIZE) finally: os.close(mod_fd) finally: os.close(workshop_fd) ``` A symlinked `mod_id` component, a swapped directory, or a bind-mounted subtree raises instead of returning a usable descriptor. ### Node: Server process launch orchestration ## Functional constraints - Module-top-level execution, no `main()`; direct `os.environ[...]` indexing assumes the Dockerfile ENV defaults (missing variable → `KeyError`). - Fixed phase order: SIGTERM→`default_int_handler` remap → SteamCMD (skipped iff `SKIP_INSTALL in {"", "false"}`; warm-up `+login anonymous +quit` first; SteamCMD exit codes ignored; experimental `1890870` = one-time windows pass gated by the `/reforger/.windows_fix_done` sentinel, which is deleted when leaving experimental) → config path → optional prune → spawn. - Config: `ARMA_CONFIG != "docker_generated"` → `/reforger/Configs/` used as-is; with auto-prune enabled, a missing or invalid file aborts during the prune phase via `configured_mod_ids` (must load, contain a `game` object with `game.mods` an array of valid 16-hex modIds; `Failed to load : ...` → `SystemExit("Failed to prune mods: ...")`), even with an empty/absent workshop; only with pruning disabled does a missing file surface when the game reads it; else regenerate `/reforger/Configs/docker_generated.json` from `/app/docker_default.json` via `build_config(os.environ, cfg)`, inject a random admin passphrase when `GAME_PASSWORD_ADMIN` is unset/empty (printed to stdout), write with `indent=4`, every start. - Prune gate: `bool_str(GAME_MODS_AUTO_PRUNE)`; `OSError`/`ValueError` → `SystemExit("Failed to prune mods: ...")`. `prune_mods` returns pruned paths; `[]` for a missing workshop (`FileNotFoundError` swallowed) or no candidates; takes `LOCK_EX|LOCK_NB` flock; candidates and returned paths are in ascending mod-ID string order, each deletion printing `Pruned mod () from `; workshop entries not named with exactly 16 uppercase hex characters are skipped silently (the printed warning applies only to 16-hex names failing `ServerData.json` validation); retention = configured IDs + transitive `ServerData.json` dependencies; an invalid required mod aborts; mounted-content refusal = candidates that are or contain a mount point (`/proc/self/mountinfo` scan in `validate_prune_candidates`) plus any staged/deleted entry whose fdinfo `mnt_id` differs from the workshop fd's (`Refusing to prune mounted content: `) — same-mount content beneath a mount point is pruned; two-phase `.mod-prune-<16hex>` quarantine + `.mod-prune.json` manifest, rollback on staging failure; crash recovery runs only inside `prune_mods` (auto-prune-gated; orphans persist untouched when pruning is disabled), considers only names `^.mod-prune-[0-9a-f]{16}$`, finishes-then-removes manifest-bearing quarantines, removes manifest-less ones only when empty (otherwise `ValueError("Incomplete mod pruning quarantine: ")` aborts the prune), each printing `Recovered interrupted mod pruning quarantine `. - argv (exact order): `ARMA_BINARY, -config , -backendlog, -nothrow, -maxFPS , -profile , -addonDownloadDir , -addonsDir , *shlex.split(ARMA_PARAMS)`; echoed via `print(shlex.join(launch), flush=True)`; no shell, no expansion. - Shutdown: `KeyboardInterrupt` in `proc.wait()` → `proc.send_signal(SIGINT)` → wait → `sys.exit(child exit code)`; second signal or other exception → `proc.kill()` and re-raise. - `build_config`: deep-copies base (no mutation), fixed section order server→rcon→game→gameProperties→mods→persistence→operating; `env_defined` = non-empty; `a2s` dropped unless both A2S vars set; `rcon` dropped unless password+address+port set, blacklist XOR whitelist else the literal `ValueError`; `persistence`/`operating` dropped when empty; `game.mods` unconditionally replaced — merged IDS_LIST→JSON file, first-wins per ID, empty array with no sources (base mods always discarded); `GAME_MODS_REQUIRED_BY_DEFAULT` dual role: maps to `game.modsRequiredByDefault` and, when defined, injects `required` (`bool_str`; anything but case-insensitive `true` → `false`) into every IDS_LIST entry and JSON entries lacking the key (undefined → no key added); IDS_LIST must fully match `^[A-Z0-9,=.]+$` (`Illegal characters in GAME_MODS_IDS_LIST env`, lowercase rejected) with ≤1 `=` per entry (` mod not defined properly`); mod IDs uppercase-only 16-hex `[0-9A-F]{16}` (lowercase rejected in IDS_LIST, JSON file, config, `ServerData.json`, prune manifest); JSON file loads (`GAME_MODS_JSON_FILE_PATH`, `PERSISTENCE_JSON_FILE_PATH`, `GAME_MISSION_HEADER_JSON_FILE_PATH`) abort with `Failed to load : ...`. - `env_defined`: `key in env and len(env[key]) > 0`. `bool_str`: `text.lower() == "true"` — only `SKIP_INSTALL` bypasses it (membership test). ## Usage example ```text docker run -e GAME_MODS_AUTO_PRUNE=true -e ARMA_PARAMS='-nologs' \ ghcr.io/acemod/arma-reforger # stdout trace emitted by launch.py before spawning: # ./ArmaReforgerServer -config /reforger/Configs/docker_generated.json # -backendlog -nothrow -maxFPS 120 -profile /home/profile # -addonDownloadDir /reforger/workshop -addonsDir /reforger/workshop -nologs # docker stop -> SIGINT relayed to child; child exit code becomes container exit code ``` ### Node: Workshop mod scanning and metadata validation ## Functional constraints - `scan_installed_mods(workshop_fd, workshop_root)` → `(installed, invalid)` dicts keyed by mod ID. `workshop_fd` must be an open directory fd; `workshop_root` is used only to build paths for messages and later checks. Names not matching `^[0-9A-F]{16}$` are skipped without any record; matching names that are not real directories, or whose metadata load fails, go to `invalid` with the exception object as the value and a printed skip line. Per-entry errors never propagate. - `load_installed_mod(mod_id, mod_fd, mod_path)` → `{id, name, dependencies, path, stat}`. Requires `ServerData.json` directly inside the mod directory: regular file, at most 1 MiB (enforced via both `st_size` and post-read length), BOM-tolerant UTF-8 JSON object. `id` must equal `mod_id` and match the hex pattern; `name` must be a non-empty string; `revision` must be a dict with a non-empty string `version` and boolean-`True` `downloaded`; `dependencies` are read from `revision.dependencies` (missing or non-list → "must be an array"; a top-level `dependencies` key is ignored) and must be a list of strings or `{"id"|"modId"}` dicts. The returned `stat` is the directory fd's `fstat` — it is the prune-time identity, so it must be captured before any later mutation. - `dependency_ids(server_data_path, dependencies)` → set of validated IDs; called with `revision.dependencies`. A non-list raises; each entry must be a string or a dict exposing `id`/`modId`; invalid entries are re-raised with the original repr embedded; duplicates collapse; dependency cycles are safe because retention works on sets. - `load_json_file(path)` → parsed JSON. BOM tolerated; every failure (missing file, bad UTF-8, bad JSON, non-file) is re-raised as `ValueError("Failed to load {path}: …")`. - `configured_mod_ids` is the config-side counterpart: `game.mods` entries must be dicts with a valid `modId`; the result is a set. Validation against declared mods is a worklist closure over configured IDs and the dependencies of retained installed mods — never a per-mod raise during scanning. - Config-side mods parsing: `apply_mods_config` processes `GAME_MODS_IDS_LIST` before `GAME_MODS_JSON_FILE_PATH` against one shared `seen_ids` set. The env list must pass the `^[A-Z\d,=.]+$` character whitelist (`Illegal characters in GAME_MODS_IDS_LIST env`); entries are `modId` or `modId=version` with the version matching the three-part numeric pattern. The JSON file must be an array (`GAME_MODS_JSON_FILE_PATH must contain an array`) of dicts with a hex-pattern `modId`; keys outside `modId`/`name`/`version`/`required` are discarded; already-seen IDs are silently dropped from later sources. `GAME_MODS_REQUIRED_BY_DEFAULT` supplies the `required` default injected when an entry does not set it. - Failure containment rule: invalid metadata excludes a mod from pruning, but if that mod is config-declared or transitively required by a config-declared mod it blocks pruning entirely; invalid metadata never causes deletion, and dependencies of unretained installed mods are never followed. ## Example ```python import os from pathlib import Path import launch_config as lc workshop_fd = os.open(workshop_dir, lc.WORKSHOP_OPEN_FLAGS) try: installed, invalid = lc.scan_installed_mods(workshop_fd, Path(workshop_dir)) declared = lc.configured_mod_ids(config_path) for mod_id, err in invalid.items(): # full retention also raises for transitive dependencies of declared mods if mod_id in declared: raise ValueError(f"required mod unusable: {err}") for mod_id, mod in installed.items(): print(mod_id, mod["name"], sorted(mod["dependencies"])) finally: os.close(workshop_fd) ``` ### Node: Transactional mod pruning with quarantine and recovery ## Functional constraints `recover_prune_quarantines(workshop_fd, expected_mount_id, workshop_root)` — the recovery entry point — must: - List only direct children of `workshop_fd` whose names fully match `^\.mod-prune-[0-9a-f]{16}$`; ignore everything else. - For each match: stat without following symlinks (a stat `OSError` aborts with `Failed to inspect `), require a real directory (`Invalid mod pruning quarantine: ` otherwise), open it `O_NOFOLLOW`, and validate fstat dev/ino plus `fd_mount_id(fd) == expected_mount_id` before touching content. - Load `.mod-prune.json` (≤ 16 MiB, regular file only). An oversized manifest, a non-regular file, or a structurally invalid manifest (not a dict with a `mods` dict of valid mod IDs mapping to int `device`/`inode`) is never tolerated: the quarantine is rejected with `Invalid mod pruning quarantine: ` and the run aborts. A missing manifest is tolerated only if the quarantine is empty (`Incomplete mod pruning quarantine` otherwise). Entries whose current dev/ino differ from the manifest abort with `Invalid quarantined mod entry: `; missing entries are skipped and treated as done. Only manifest-recorded entries are deleted; unrecorded content is left behind, so the final `rmdir` fails with `ENOTEMPTY` and the stranded manifest-less quarantine is rejected as `Incomplete mod pruning quarantine` on the next run. - On success: unlink the manifest, `rmdir` the quarantine from the workshop fd, fsync, and print `Recovered interrupted mod pruning quarantine `. Supporting transactional pieces it depends on: `create_quarantine` (`.mod-prune-<16 hex>`, mode 0o700, 10 collision retries, fd-validated), `write_json_at`/`read_json_at` (O_EXCL/O_NOFOLLOW, size-limited manifest I/O), `stage_prune_candidates` (manifest-before-rename, per-rename dev/ino re-validation, rollback in reversed order on failure), `rollback_staged_mods` (rename back only when `same_entry` holds), and `delete_prune_candidates` (delete from quarantine, unlink manifest, rmdir, return sorted pruned paths). Ordering: recovery runs inside `prune_mods` after the exclusive `flock` and before `scan_installed_mods`; callers pass `workshop_mount_id = fd_mount_id(workshop_fd)` and `workshop_root = fd_path(workshop_fd)`. ### Usage example ```python workshop_fd = os.open(workshop_dir, launch_config.WORKSHOP_OPEN_FLAGS) fcntl.flock(workshop_fd, fcntl.LOCK_EX | fcntl.LOCK_NB) workshop_root = launch_config.fd_path(workshop_fd) mount_id = launch_config.fd_mount_id(workshop_fd) launch_config.recover_prune_quarantines(workshop_fd, mount_id, workshop_root) installed, invalid = launch_config.scan_installed_mods(workshop_fd, workshop_root) # ... build candidate list, then stage it transactionally: the manifest is # written first, each candidate is renamed into a fresh quarantine, and any # failure rolls the staged mods back in reversed order before propagating. launch_config.stage_prune_candidates(workshop_fd, mount_id, candidates) paths = launch_config.delete_prune_candidates(workshop_fd, mount_id, candidates) ```