From d33edd7a7e50a1349fb24c6c2b0d943fa1c883c6 Mon Sep 17 00:00:00 2001 From: Florian Kinder Date: Mon, 2 Nov 2026 16:04:29 +0100 Subject: [PATCH] Fix entrypoint save selection, bind ports and graceful shutdown --- README.md | 10 +- docker/Dockerfile | 2 +- docker/files/docker-entrypoint-rootless.sh | 28 ++++-- docker/files/docker-entrypoint.sh | 32 ++++-- docker/files/scenario.sh | 1 + docker/files/scenario2map.sh | 5 +- tests/integration_shutdown.py | 74 ++++++++++++++ tests/test_config_paths.py | 3 +- tests/test_entrypoint_lifecycle.py | 110 +++++++++++++++++++++ 9 files changed, 242 insertions(+), 23 deletions(-) create mode 100644 tests/integration_shutdown.py create mode 100644 tests/test_entrypoint_lifecycle.py diff --git a/README.md b/README.md index 83f35ae4..632932ca 100644 --- a/README.md +++ b/README.md @@ -64,9 +64,11 @@ docker logs factorio Stop the server: ```shell -docker stop factorio +docker stop --timeout 120 factorio ``` +Allow enough time for the world to save before Docker sends SIGKILL. Increase the timeout for large saves; with Compose, configure `stop_grace_period` instead. + Now there's a `server-settings.json` file in the folder `/opt/factorio/config`. Modify this to your liking and restart the server: ```shell @@ -113,7 +115,7 @@ Now run the server as before. In about a minute the new version of Factorio shou ### Saves -A new map named `_autosave1.zip` is generated the first time the server is started. The `map-gen-settings.json` and `map-settings.json` files in `/opt/factorio/config` are used for the map settings. On subsequent runs the newest save is used. +A new map named `_autosave1.zip` (or `SAVE_NAME` when set) is generated the first time the server is started. The `map-gen-settings.json` and `map-settings.json` files in `/opt/factorio/config` are used for the map settings. On subsequent runs the newest save is used. To load an old save stop the server and run the command `touch oldsave.zip`. This resets the date. Then restart the server. Another option is to delete all saves except one. @@ -123,7 +125,7 @@ To generate a new map stop the server, delete all of the saves and restart the s You can specify a specific save to load by configuring the server through a set of environment variables: -To load an existing save set `SAVE_NAME` to the name of your existing save file located within the `saves` directory, without the `.zip` extension: +To load an existing save set `SAVE_NAME` to the name of your existing save file located within the `saves` directory, with or without the `.zip` extension. An absolute save-file path is also supported. The same path is used for initial generation and later starts; a missing selected save is reported instead of silently loading another world: ```shell sudo docker run -d \ @@ -287,7 +289,7 @@ These are the environment variables which can be specified at container run time | GENERATE_NEW_SAVE | Generate a new save if one does not exist before starting the server | false | 0.17+ | | LOAD_LATEST_SAVE | Load latest when true. Otherwise load SAVE_NAME | true | 0.17+ | | PORT | UDP port the server listens on | 34197 | 0.15+ | -| BIND | IP address (v4 or v6) the server listens on (IP\[:PORT]) | | 0.15+ | +| BIND | Listen address; an explicit port overrides PORT (e.g. `127.0.0.1:34201` or `[::1]:34201`) | | 0.15+ | | RCON_PORT | TCP port the rcon server listens on | 27015 | 0.15+ | | SAVE_NAME | Name to use for the save file | _autosave1 | 0.17+ | | PRESET | Map generation preset when GENERATE_NEW_SAVE is true | | 0.17+ | diff --git a/docker/Dockerfile b/docker/Dockerfile index 1f38a2c6..e17ea1c7 100755 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -45,7 +45,7 @@ ENV PORT=34197 \ SHELL ["/bin/bash", "-eo", "pipefail", "-c"] RUN apt-get -q update \ - && DEBIAN_FRONTEND=noninteractive apt-get -qy install ca-certificates curl jq pwgen xz-utils procps gettext-base file --no-install-recommends \ + && DEBIAN_FRONTEND=noninteractive apt-get -qy install ca-certificates curl jq pwgen xz-utils procps gettext-base file util-linux --no-install-recommends \ && if [[ "$(uname -m)" == "aarch64" && -z "${SHA256_ARM64}" ]]; then \ echo "installing ARM compatability layer" \ && DEBIAN_FRONTEND=noninteractive apt-get -qy install unzip --no-install-recommends \ diff --git a/docker/files/docker-entrypoint-rootless.sh b/docker/files/docker-entrypoint-rootless.sh index 07328945..1de8ce84 100755 --- a/docker/files/docker-entrypoint-rootless.sh +++ b/docker/files/docker-entrypoint-rootless.sh @@ -67,7 +67,13 @@ sed -i '/write-data=/c\write-data=\/factorio/' /opt/factorio/config/config.ini NRSAVES=$(find -L "$SAVES" -iname \*.zip -mindepth 1 | wc -l) if [[ $GENERATE_NEW_SAVE != true && $NRSAVES == 0 ]]; then GENERATE_NEW_SAVE=true - SAVE_NAME=_autosave1 + SAVE_NAME="${SAVE_NAME:-_autosave1}" +fi + +if [[ "$SAVE_NAME" == /* ]]; then + SAVE_FILE="$SAVE_NAME" +else + SAVE_FILE="$SAVES/${SAVE_NAME%.zip}.zip" fi if [[ $GENERATE_NEW_SAVE == true ]]; then @@ -75,18 +81,18 @@ if [[ $GENERATE_NEW_SAVE == true ]]; then echo "If \$GENERATE_NEW_SAVE is true, you must specify \$SAVE_NAME" exit 1 fi - if [[ -f "$SAVES/$SAVE_NAME.zip" ]]; then - echo "Map $SAVES/$SAVE_NAME.zip already exists, skipping map generation" + if [[ -f "$SAVE_FILE" ]]; then + echo "Map $SAVE_FILE already exists, skipping map generation" else if [[ -n "$PRESET" ]]; then $EXEC /opt/factorio/bin/x64/factorio \ - --create "$SAVES/$SAVE_NAME.zip" \ + --create "$SAVE_FILE" \ --preset "$PRESET" \ --map-gen-settings "$CONFIG/map-gen-settings.json" \ --map-settings "$CONFIG/map-settings.json" else $EXEC /opt/factorio/bin/x64/factorio \ - --create "$SAVES/$SAVE_NAME.zip" \ + --create "$SAVE_FILE" \ --map-gen-settings "$CONFIG/map-gen-settings.json" \ --map-settings "$CONFIG/map-settings.json" fi @@ -95,7 +101,6 @@ fi # Build command flags FLAGS=(\ - --port "$PORT" \ --server-settings "$SERVER_SETTINGS_FILE" \ --server-banlist "$SERVER_BANLIST_FILE" \ --rcon-port "$RCON_PORT" \ @@ -115,10 +120,19 @@ if [ -n "$BIND" ]; then FLAGS+=( --bind "$BIND" ) fi +# An explicit bind port wins; bare IPv6 addresses still use PORT. +if [[ ! "$BIND" =~ ^[^:]+:[0-9]+$ && ! "$BIND" =~ ^\[[^]]+\]:[0-9]+$ ]]; then + FLAGS+=( --port "$PORT" ) +fi + if [[ $LOAD_LATEST_SAVE == true ]]; then FLAGS+=( --start-server-load-latest ) else - FLAGS+=( --start-server "$SAVE_NAME" ) + if [[ -z "$SAVE_NAME" || ! -f "$SAVE_FILE" ]]; then + echo "Selected save does not exist: $SAVE_FILE. Set SAVE_NAME or GENERATE_NEW_SAVE=true." >&2 + exit 1 + fi + FLAGS+=( --start-server "$SAVE_FILE" ) fi # Execute factorio diff --git a/docker/files/docker-entrypoint.sh b/docker/files/docker-entrypoint.sh index 9cc983a9..2414d930 100755 --- a/docker/files/docker-entrypoint.sh +++ b/docker/files/docker-entrypoint.sh @@ -56,8 +56,8 @@ if [[ $(id -u) == 0 ]]; then groupmod -o -g "$PGID" factorio # Take ownership of factorio data if running as root chown -R factorio:factorio "$FACTORIO_VOL" - # Drop to the factorio user - EXEC="runuser -u factorio -g factorio --" + # Replace the process when dropping privileges; runuser kills slow saves after SIGTERM. + EXEC="setpriv --reuid=factorio --regid=factorio --init-groups --" fi # Setup ARM64 emulation support @@ -69,7 +69,13 @@ sed -i '/write-data=/c\write-data=\/factorio/' /opt/factorio/config/config.ini NRSAVES=$(find -L "$SAVES" -iname \*.zip -mindepth 1 | wc -l) if [[ $GENERATE_NEW_SAVE != true && $NRSAVES == 0 ]]; then GENERATE_NEW_SAVE=true - SAVE_NAME=_autosave1 + SAVE_NAME="${SAVE_NAME:-_autosave1}" +fi + +if [[ "$SAVE_NAME" == /* ]]; then + SAVE_FILE="$SAVE_NAME" +else + SAVE_FILE="$SAVES/${SAVE_NAME%.zip}.zip" fi if [[ $GENERATE_NEW_SAVE == true ]]; then @@ -77,18 +83,18 @@ if [[ $GENERATE_NEW_SAVE == true ]]; then echo "If \$GENERATE_NEW_SAVE is true, you must specify \$SAVE_NAME" exit 1 fi - if [[ -f "$SAVES/$SAVE_NAME.zip" ]]; then - echo "Map $SAVES/$SAVE_NAME.zip already exists, skipping map generation" + if [[ -f "$SAVE_FILE" ]]; then + echo "Map $SAVE_FILE already exists, skipping map generation" else if [[ -n "$PRESET" ]]; then $EXEC /opt/factorio/bin/x64/factorio \ - --create "$SAVES/$SAVE_NAME.zip" \ + --create "$SAVE_FILE" \ --preset "$PRESET" \ --map-gen-settings "$CONFIG/map-gen-settings.json" \ --map-settings "$CONFIG/map-settings.json" else $EXEC /opt/factorio/bin/x64/factorio \ - --create "$SAVES/$SAVE_NAME.zip" \ + --create "$SAVE_FILE" \ --map-gen-settings "$CONFIG/map-gen-settings.json" \ --map-settings "$CONFIG/map-settings.json" fi @@ -96,7 +102,6 @@ if [[ $GENERATE_NEW_SAVE == true ]]; then fi FLAGS=(\ - --port "$PORT" \ --server-settings "$SERVER_SETTINGS_FILE" \ --server-banlist "$SERVER_BANLIST_FILE" \ --rcon-port "$RCON_PORT" \ @@ -116,10 +121,19 @@ if [ -n "$BIND" ]; then FLAGS+=( --bind "$BIND" ) fi +# An explicit bind port wins; bare IPv6 addresses still use PORT. +if [[ ! "$BIND" =~ ^[^:]+:[0-9]+$ && ! "$BIND" =~ ^\[[^]]+\]:[0-9]+$ ]]; then + FLAGS+=( --port "$PORT" ) +fi + if [[ $LOAD_LATEST_SAVE == true ]]; then FLAGS+=( --start-server-load-latest ) else - FLAGS+=( --start-server "$SAVE_NAME" ) + if [[ -z "$SAVE_NAME" || ! -f "$SAVE_FILE" ]]; then + echo "Selected save does not exist: $SAVE_FILE. Set SAVE_NAME or GENERATE_NEW_SAVE=true." >&2 + exit 1 + fi + FLAGS+=( --start-server "$SAVE_FILE" ) fi # shellcheck disable=SC2086 diff --git a/docker/files/scenario.sh b/docker/files/scenario.sh index 1e65e380..aa6e3ab6 100755 --- a/docker/files/scenario.sh +++ b/docker/files/scenario.sh @@ -45,6 +45,7 @@ source "${INSTALLED_DIRECTORY}/setup-exec.sh" exec $EXEC /opt/factorio/bin/x64/factorio \ --port "$PORT" \ --start-server-load-scenario "$SERVER_SCENARIO" \ + --mod-directory "$MODS" \ --preset "$PRESET" \ --map-gen-settings "$CONFIG/map-gen-settings.json" \ --map-settings "$CONFIG/map-settings.json" \ diff --git a/docker/files/scenario2map.sh b/docker/files/scenario2map.sh index c996535e..5eab1106 100755 --- a/docker/files/scenario2map.sh +++ b/docker/files/scenario2map.sh @@ -27,10 +27,13 @@ if [[ ! -f $CONFIG/map-settings.json ]]; then cp /opt/factorio/data/map-settings.example.json "$CONFIG/map-settings.json" fi +"${INSTALLED_DIRECTORY}"/docker-dlc.sh + # Setup ARM64 emulation support EXEC="" # shellcheck disable=SC1091 source "${INSTALLED_DIRECTORY}/setup-exec.sh" exec $EXEC /opt/factorio/bin/x64/factorio \ - --scenario2map "$SERVER_SCENARIO" + --scenario2map "$SERVER_SCENARIO" \ + --mod-directory "$MODS" diff --git a/tests/integration_shutdown.py b/tests/integration_shutdown.py new file mode 100644 index 00000000..2f216e4f --- /dev/null +++ b/tests/integration_shutdown.py @@ -0,0 +1,74 @@ +"""Docker SIGTERM regression: python3 tests/integration_shutdown.py IMAGE. + +Uses a deliberately slow fake server to reproduce runuser's two-second kill, +without requiring a large user save. Creates/removes only its own container +and volume. The supplied image must contain the real regular entrypoint. +""" + +import json +from pathlib import Path +import subprocess +import sys +import tempfile +import time +import uuid + + +def docker(*args, **kwargs): + return subprocess.run(["docker", *args], check=True, capture_output=True, text=True, **kwargs) + + +def main(image): + name = "factorio-shutdown-" + uuid.uuid4().hex[:12] + volume = name + "-data" + docker("volume", "create", volume) + try: + with tempfile.TemporaryDirectory() as directory: + server = Path(directory) / "factorio" + server.write_text('''#!/bin/bash +if [[ "$1" == --create ]]; then + touch "$2" + exit 0 +fi +trap 'sleep 5; echo complete > /factorio/shutdown-complete; exit 0' TERM +id -u > /factorio/server-uid +echo ready > /factorio/server-ready +while true; do sleep 0.1; done +''') + server.chmod(0o755) + # The container user must be able to traverse the fixture directory. + Path(directory).chmod(0o755) + try: + docker("run", "-d", "--name", name, "--network", "none", + "--mount", f"type=volume,src={volume},dst=/factorio", + "--mount", f"type=bind,src={server},dst=/opt/factorio/bin/x64/factorio,readonly", + "-e", "DLC_SPACE_AGE=false", image) + for _ in range(100): + ready = subprocess.run(["docker", "exec", name, "test", "-f", "/factorio/server-ready"], + capture_output=True) + if ready.returncode == 0: + break + time.sleep(0.1) + else: + raise AssertionError("Server did not start: " + docker("logs", name).stdout) + start = time.monotonic() + docker("stop", "--timeout", "15", name, timeout=25) + elapsed = time.monotonic() - start + state = json.loads(docker("inspect", name).stdout)[0]["State"] + if state["ExitCode"] != 0: + raise AssertionError(f"Shutdown interrupted after {elapsed:.2f}s: {state['ExitCode']}\n" + + docker("logs", name).stderr) + docker("cp", f"{name}:/factorio/shutdown-complete", str(Path(directory) / "complete")) + docker("cp", f"{name}:/factorio/server-uid", str(Path(directory) / "uid")) + assert (Path(directory) / "complete").read_text().strip() == "complete" + assert (Path(directory) / "uid").read_text().strip() == "845" + assert elapsed >= 5, elapsed + print(f"PASS: UID 845 server completed a five-second save after SIGTERM ({elapsed:.2f}s)") + finally: + subprocess.run(["docker", "rm", "-f", name], capture_output=True) + finally: + docker("volume", "rm", volume) + + +if __name__ == "__main__": + main(sys.argv[1]) diff --git a/tests/test_config_paths.py b/tests/test_config_paths.py index 92915890..fa82bec2 100644 --- a/tests/test_config_paths.py +++ b/tests/test_config_paths.py @@ -163,7 +163,8 @@ def test_scenario_conversion_uses_custom_settings(self): settings = self.work / "conversion" / "settings.json" self.run_script("scenario2map.sh", {"SERVER_SETTINGS_FILE": str(settings)}) self.assertEqual(json.loads(settings.read_text()), self.example) - self.assertEqual(json.loads(self.calls.read_text()), ["--scenario2map", "freeplay"]) + self.assertEqual(json.loads(self.calls.read_text()), + ["--scenario2map", "freeplay", "--mod-directory", self.env["MODS"]]) if __name__ == "__main__": diff --git a/tests/test_entrypoint_lifecycle.py b/tests/test_entrypoint_lifecycle.py new file mode 100644 index 00000000..1c1e86eb --- /dev/null +++ b/tests/test_entrypoint_lifecycle.py @@ -0,0 +1,110 @@ +"""Entrypoint lifecycle regressions using the existing isolated container fixture.""" + +import json +from pathlib import Path +import unittest + +import test_config_paths as fixtures + + +class EntrypointLifecycleTests(unittest.TestCase): + def setUp(self): + self.fixture = fixtures.ConfigPathTests() + self.fixture.setUp() + self.addCleanup(self.fixture.doCleanups) + + def args(self): + return [json.loads(line) for line in self.fixture.calls.read_text().splitlines()] + + def test_named_save_survives_first_start_and_restart(self): + f = self.fixture + for script in fixtures.ENTRYPOINTS[:2]: + name = script + " world" + overrides = {"SAVE_NAME": name, "LOAD_LATEST_SAVE": "false"} + # Each variant starts with an empty saves directory. + saves = Path(f.env["SAVES"]) + saves.mkdir(exist_ok=True) + for path in saves.iterdir(): + path.unlink() + f.run_script(script, overrides) + calls = self.args() + self.assertIn("--create", calls[0]) + expected = str(saves / (name + ".zip")) + self.assertEqual(calls[0][calls[0].index("--create") + 1], expected) + self.assertEqual(calls[-1][calls[-1].index("--start-server") + 1], expected) + f.run_script(script, overrides) + self.assertEqual(len(self.args()), 1) + self.assertEqual(self.args()[0][self.args()[0].index("--start-server") + 1], expected) + + def test_zip_suffix_and_absolute_save_paths(self): + f = self.fixture + for script in fixtures.ENTRYPOINTS[:2]: + for name in ("my world.zip", str(f.work / "absolute world.zip")): + with self.subTest(script=script, name=name): + f.run_script(script, {"SAVE_NAME": name, "GENERATE_NEW_SAVE": "true", "LOAD_LATEST_SAVE": "false"}) + expected = name if name.startswith("/") else str(Path(f.env["SAVES"]) / name) + self.assertTrue(Path(expected).exists()) + args = self.args()[-1] + self.assertEqual(args[args.index("--start-server") + 1], expected) + + def test_missing_named_save_does_not_load_another_world(self): + f = self.fixture + saves = Path(f.env["SAVES"]) + saves.mkdir() + (saves / "different.zip").touch() + for script in fixtures.ENTRYPOINTS[:2]: + result = f.run_script(script, {"SAVE_NAME": "missing", "LOAD_LATEST_SAVE": "false"}, success=False) + self.assertIn("Selected save does not exist", result.stderr) + + def test_bind_port_does_not_conflict_with_port_flag(self): + f = self.fixture + cases = {"": True, "127.0.0.1": True, "127.0.0.1:34201": False, + "localhost:34201": False, "::1": True, "2001:db8::1234": True, + "[::1]": True, "[::1]:34201": False} + for script in fixtures.ENTRYPOINTS[:2]: + for bind, include_port in cases.items(): + with self.subTest(script=script, bind=bind): + f.run_script(script, {"BIND": bind, "PORT": "34198"}) + args = self.args()[-1] + self.assertEqual("--port" in args, include_port) + if include_port: + self.assertEqual(args[args.index("--port") + 1], "34198") + if bind: + self.assertEqual(args[args.index("--bind") + 1], bind) + + def test_all_entrypoints_apply_dlc_to_selected_mod_directory(self): + f = self.fixture + f.write_command(f.scripts / "docker-dlc.sh", (fixtures.FILES / "docker-dlc.sh").read_text()) + mods = f.work / "custom mods" + mods.mkdir() + for script in (*fixtures.ENTRYPOINTS, "scenario2map.sh"): + with self.subTest(script=script): + f.run_script(script, {"MODS": str(mods), "DLC_SPACE_AGE": "false"}) + enabled = {item["name"]: item["enabled"] for item in json.loads((mods / "mod-list.json").read_text())["mods"]} + for name in ("space-age", "quality", "elevated-rails", "recycler"): + self.assertFalse(enabled[name]) + args = self.args()[-1] + self.assertEqual(args[args.index("--mod-directory") + 1], str(mods)) + f.run_script(script, {"MODS": str(mods), "DLC_SPACE_AGE": "elevated-rails"}) + enabled = {item["name"]: item["enabled"] for item in json.loads((mods / "mod-list.json").read_text())["mods"]} + self.assertTrue(enabled["elevated-rails"]) + self.assertFalse(enabled["space-age"]) + self.assertFalse(enabled["recycler"]) + + def test_privilege_drop_executes_without_runuser_supervisor(self): + f = self.fixture + f.write_command(f.scripts / "id", "#!/bin/sh\necho 0\n") + for command in ("usermod", "groupmod", "chown"): + f.write_command(f.scripts / command, "#!/bin/sh\nexit 0\n") + f.write_command(f.scripts / "runuser", "#!/bin/sh\nexit 99\n") + f.write_command(f.scripts / "setpriv", '''#!/usr/bin/env python3 +import os, sys +assert sys.argv[1:5] == ["--reuid=factorio", "--regid=factorio", "--init-groups", "--"] +os.execv(sys.argv[5], sys.argv[5:]) +''') + f.run_script("docker-entrypoint.sh") + self.assertIn("--start-server-load-latest", self.args()[-1]) + + +if __name__ == "__main__": + unittest.main()