Files
romm/backend/tests/test_web_server_config.py
Georges-Antoine Assi c413c066c6 refactor(docker): supervise the container with s6-overlay (#4019)
* refactor(docker): supervise the container with s6-overlay

The init script was a hand-rolled supervisor: PID files, /proc polling, a
5s watchdog loop and a trap-based shutdown. Its shutdown wait was unbounded,
so a process that refused to exit stranded PID 1 and left the container up
and serving nothing, which no restart policy can detect.

s6-rc replaces it with a declared service graph. Ordering and readiness
gates that were sequential bash become dependencies, and the failure modes
become configuration:

- timeout-kill bounds SIGTERM before SIGKILL, and flag-timeout-killpg
  escalates to the whole process group.
- S6_BEHAVIOUR_IF_STAGE2_FAILS=2 exits the container when a startup step
  fails, so the restart policy retries instead of the container wedging.
- valkey gets --shutdown-on-sigterm force, so it stops refusing to exit
  when the snapshot it writes on shutdown cannot be written.

A crashed service is now restarted on its own instead of taking the whole
container down. Its leftover children are swept first, because children
reparented from a hard-killed master keep holding its listening sockets and
would make every replacement fail to bind.

Optional services have no conditional mechanism in s6-rc, so they start,
check their environment variable, and take themselves down with s6-svc -O.

Running with a read-only root filesystem now needs /run mounted exec, since
s6 executes its generated stage scripts from there.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(docker): always start the RQ scheduler under s6

The s6 service carried over the four-flag ENABLE_SCHEDULED_* gate from the
init script, which #4033 has since removed on master. Since this branch
deletes that script, the fix would be lost on rebase.

Nothing else respects the condition: startup.py registers the netplay,
upload-tmp and zip-cache cleanups unconditionally, three more flags gate
periodic tasks absent from the list, and the watcher defers its rescans
through the scheduler. Any of those leaves jobs in the scheduler registry
with no process to run them, and a stuck delayed scan_platforms entry reads
to the concurrent scan guard as a scan already queued, refusing every
manual scan.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(docker): port master's init changes to the s6 services

Master reworked docker/init_scripts/init while this branch replaced it,
so carry those changes into the s6-rc services:

- Replace rq-scheduler with `rq cron` (romm-rq-cron) on tasks.cron_config.
- Add romm-rq-scan-worker (scans queue) and romm-rq-streaming-worker
  (streaming queue, down unless config.yml enables streaming).
- Run every worker with --with-scheduler and the RomMRedis connection
  class, passing the Redis URL through RQ_REDIS_URL so the password stays
  off the command line, and read REDIS_SSL as a boolean.
- Bring gunicorn's flags in line: --no-control-socket, a private-range
  FORWARDED_ALLOW_IPS default, 4 workers and a 65s keep-alive.
- Check the sync folder and SSH keys path in romm-init, and switch the
  features off through the container environment when they're unusable.
- Accept the backend's truthy values for the watcher flags.
- Point the serving-layer guard tests at the gunicorn run script and
  drop the PID-file tests, which guarded the bash watchdog.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(docker): guard the s6-overlay service tree

Check that every service is in the user bundle, depends on something
that exists, and that every longrun has its finish sweep, kill timeout
and process-group flag. Also check that the dev entrypoint starts the
same RQ workers and cron scheduler as the image, since it keeps its own
launcher.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(dev): pass the image's RQ flags in the dev entrypoint

The dev image's RQ cron scheduler and workers ran without the RomMRedis
connection class, and the workers without --results-ttl, so they kept
redis-py's maintenance notification probe and RQ's default result TTL.
The s6 guard test now compares each rq command's flags with the image's.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(docker): address Greptile review on the s6 service tree

- Cut the s6 script comments to two lines, keeping the reason each
  helper exists.
- Compare the values of the dev entrypoint's RQ options with the
  image's, not only their names, allowing for the dev image's path,
  PID files and LOGLEVEL default.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* ci(docker): check every s6 service stays up after boot

The heartbeat only proves gunicorn and nginx came up. Enable both watchers
and require each longrun in the s6 tree to report up for 15s straight, so a
crashing or restart-looping worker, cron, valkey or watcher fails the job.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* ci(docker): enable streaming so its worker is checked too

The streaming worker turns itself off when streaming.enabled is false in
config.yml, which the services check read as a failure.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-11-24 08:29:06 -05:00

121 lines
4.3 KiB
Python

"""Guards the serving-layer settings that live outside Python."""
import re
from pathlib import Path
import pytest
REPO_ROOT = Path(__file__).resolve().parents[2]
NGINX_CONF = REPO_ROOT / "docker" / "nginx" / "default.conf"
DOCKERFILE = REPO_ROOT / "docker" / "Dockerfile"
GUNICORN_RUN = REPO_ROOT / "docker" / "s6-overlay" / "s6-rc.d" / "romm-gunicorn" / "run"
ENV_TEMPLATE = REPO_ROOT / "env.template"
# nginx's own default upstream keepalive_timeout, which gunicorn must outlive.
NGINX_UPSTREAM_IDLE_TIMEOUT = 60
# nginx enables upstream keepalive by default from this release. Below it the
# pool is off entirely and the timeout invariant stops meaning anything.
NGINX_UPSTREAM_KEEPALIVE_SINCE = (1, 29, 7)
# njs 0.9.7 dropped the "js vm init njs" notice it logged on every start. nginx
# 1.30.0 also shipped builds bundling njs 0.9.6, so 1.30.1 is the first release
# that never logs it.
NJS_QUIET_STARTUP_SINCE = (1, 30, 1)
REQUIRED_GZIP_TYPES = [
"application/wasm", # EmulatorJS, js-dos and FAKE-08 cores
"image/svg+xml", # player logos and favicons
"application/json",
"application/javascript",
"text/css",
]
def _gunicorn_keepalive() -> int:
match = re.search(
r'--keep-alive "\$\{WEB_SERVER_KEEPALIVE:-(\d+)\}"', GUNICORN_RUN.read_text()
)
assert match, "could not read the gunicorn --keep-alive default"
return int(match.group(1))
@pytest.fixture(scope="module")
def gzip_types() -> set[str]:
match = re.search(r"\bgzip_types\s+([^;]+);", NGINX_CONF.read_text())
assert match, "no gzip_types directive in the nginx config"
return set(match.group(1).split())
@pytest.mark.parametrize("media_type", REQUIRED_GZIP_TYPES)
def test_compressible_types_are_gzipped(gzip_types: set[str], media_type: str) -> None:
assert media_type in gzip_types, f"{media_type} would be served uncompressed"
def _format(version: tuple[int, ...]) -> str:
return ".".join(str(part) for part in version)
def _nginx_version() -> tuple[int, ...]:
match = re.search(r"^ARG NGINX_VERSION=(\S+)", DOCKERFILE.read_text(), re.M)
assert match, "docker/Dockerfile is missing an ARG NGINX_VERSION pin"
return tuple(int(part) for part in match.group(1).split("."))
def test_nginx_defaults_upstream_keepalive_on() -> None:
version = _nginx_version()
assert version >= NGINX_UPSTREAM_KEEPALIVE_SINCE, (
f"nginx {_format(version)} does not pool upstream connections by default, "
f"so every API request opens a new one"
)
def test_nginx_starts_without_the_njs_notice() -> None:
version = _nginx_version()
assert version >= NJS_QUIET_STARTUP_SINCE, (
f"nginx {_format(version)} bundles an njs that logs a 'js vm init njs' "
f"notice on every start, because the config imports a VM at the http level"
)
def test_gunicorn_outlives_nginx_upstream_idle_timeout() -> None:
assert _gunicorn_keepalive() > NGINX_UPSTREAM_IDLE_TIMEOUT
def test_env_template_documents_the_same_keepalive_default() -> None:
match = re.search(r"^WEB_SERVER_KEEPALIVE=(\d+)", ENV_TEMPLATE.read_text(), re.M)
assert match, "env.template is missing WEB_SERVER_KEEPALIVE"
assert int(match.group(1)) == _gunicorn_keepalive()
def test_image_ships_compiled_bytecode() -> None:
"""Runtime caching is off, so uncompiled modules recompile on every start."""
dockerfile = DOCKERFILE.read_text()
assert re.search(r"^ENV PYTHONDONTWRITEBYTECODE=1", dockerfile, re.M)
assert re.search(r"^ENV UV_COMPILE_BYTECODE=1", dockerfile, re.M)
assert re.search(r"^RUN python3 -m compileall -q /backend$", dockerfile, re.M)
def _gunicorn_trusted_proxies() -> str:
match = re.search(
r'--forwarded-allow-ips="\$\{FORWARDED_ALLOW_IPS:-([^}]+)\}"',
GUNICORN_RUN.read_text(),
)
assert match, "could not read the gunicorn --forwarded-allow-ips default"
return match.group(1)
def test_client_addresses_are_trusted_only_from_private_proxies() -> None:
"""A client can't choose its own address by sending X-Forwarded-For."""
trusted = _gunicorn_trusted_proxies().split(",")
assert "*" not in trusted
assert "127.0.0.1" in trusted
def test_env_template_documents_the_same_trusted_proxies() -> None:
assert (
f"FORWARDED_ALLOW_IPS={_gunicorn_trusted_proxies()} "
in ENV_TEMPLATE.read_text()
)