game-servers/app/app.py
neil 51db28f3d5
Rollback: restore a server's world from any of its backups, with a Current marker
Manage gets a Backup section (between World and Logs) listing the server's automatic and manual
backups. Rolling back is only allowed while the server is stopped and nothing else, such as an
automatic backup, is running on it; the server claims the busy flag atomically so the two can't race.
A run players were on is backed up first. The new world is extracted to a staging folder and checked
before the old one is deleted.

The backup that holds the world as it is now is marked Current (its button is disabled, and the
Backups page tags it). It's tracked in backups/<game>/<container>.current: set by automatic backups
and rollbacks, none while players have been on, newest automatic backup when there's no record.
Rolling back to an automatic backup can keep the Current backup as a manual one (or make one if
nothing is current), warning when that pushes out the oldest of 5 manual backups.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 22:53:25 -08:00

1509 lines
60 KiB
Python

"""Game server manager: a small password-protected web UI for running game servers in Docker."""
import asyncio
import hmac
import ipaddress
import json
import io
import os
import re
import secrets
import shutil
import socket
import tempfile
import threading
import time
import zipfile
from collections import deque
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
import docker
from starlette.concurrency import run_in_threadpool
from docker.errors import NotFound
from fastapi import Depends, FastAPI, File, Form, HTTPException, Query, Request, UploadFile
from fastapi.responses import FileResponse, StreamingResponse
from fastapi.staticfiles import StaticFiles
from starlette.middleware.sessions import SessionMiddleware
import players as pl
from backups import Backups
import zomboid
ADMIN_PASSWORD = os.environ["ADMIN_PASSWORD"]
SECRET_KEY = os.environ.get("SECRET_KEY") or secrets.token_hex(32)
DATA_DIR = Path(os.environ.get("DATA_DIR", "/srv/gameservers"))
STATIC_DIR = Path(__file__).parent / "static"
LABEL = "gsm.managed"
# Each game type describes how to build its container. Add new games here.
GAMES = {
"valheim": {
"name": "Valheim",
"image": "lloesche/valheim-server",
"default_port": 2456,
"ports_needed": 2, # game port and game port + 1, both UDP
"ready_marker": "Game server connected",
"query_ports": [1], # Steam server query (A2S) port, as an offset from the game port
"backups": True,
# Settings that can be changed later from the server's Manage dialog.
"settings": [
{"key": "password", "label": "Server password", "type": "text", "minlength": 5,
"help": "At least 5 characters, and not part of the server name."},
{"key": "port", "label": "Port", "type": "number", "min": 1024, "max": 65534,
"help": "UDP. This port and the next one are used."},
],
},
"zomboid": {
"name": "Project Zomboid",
"image": zomboid.IMAGE,
"default_port": 16261,
"ports_needed": 2, # PORT and UDPPORT (port + 1), both UDP
"ready": "health", # the image's healthcheck turns healthy once the server has started
"query_ports": [0, 1],
"mods": True,
"backups": True,
"settings": [
{"key": "password", "label": "Server password", "type": "text", "required": False,
"help": "Leave empty for no password."},
{"key": "port", "label": "Port", "type": "number", "min": 1024, "max": 65534,
"help": "UDP. This port and the next one are used."},
{"key": "memory_mb", "label": "Memory (MB)", "type": "number", "min": 1024, "max": 65536,
"help": "Java heap for the server. Build 42 with mods wants 4096 or more."},
{"key": "max_players", "label": "Max players", "type": "number", "min": 1, "max": 100},
],
},
}
backups = Backups(DATA_DIR)
client = docker.from_env()
app = FastAPI()
app.add_middleware(SessionMiddleware, secret_key=SECRET_KEY, max_age=60 * 60 * 24 * 30, same_site="strict", https_only=True)
# ---------- auth ----------
def require_auth(request: Request):
if not request.session.get("auth"):
raise HTTPException(401, "Not logged in")
@app.post("/api/login")
async def login(request: Request):
body = await request.json()
if not hmac.compare_digest(str(body.get("password", "")).encode(), ADMIN_PASSWORD.encode()):
time.sleep(1) # slow down guessing
raise HTTPException(401, "Wrong password")
request.session["auth"] = True
return {"ok": True}
@app.post("/api/logout")
def logout(request: Request):
request.session.clear()
return {"ok": True}
@app.get("/api/me")
def me(request: Request):
return {"authenticated": bool(request.session.get("auth"))}
# ---------- stats collection (background thread) ----------
stats_lock = threading.Lock()
host_stats: dict = {}
server_stats: dict = {} # container id -> stats
ready_cache: dict = {} # container id -> started_at when ready marker was seen
def _read_cpu():
parts = Path("/proc/stat").read_text().splitlines()[0].split()[1:]
vals = list(map(int, parts))
idle = vals[3] + vals[4]
return sum(vals), idle
def _read_meminfo():
info = {}
for line in Path("/proc/meminfo").read_text().splitlines():
k, v = line.split(":", 1)
info[k] = int(v.split()[0]) * 1024
return info
def _public_ip():
"""The address players connect to: PUBLIC_IP if set, else the source address of the default route
(gsm runs on the host network). None behind NAT; the UI then falls back to the page's hostname."""
if os.environ.get("PUBLIC_IP"):
return os.environ["PUBLIC_IP"]
try:
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
s.connect(("1.1.1.1", 80)) # UDP: picks a route, sends nothing
ip = s.getsockname()[0]
return ip if ipaddress.ip_address(ip).is_global else None
except OSError:
return None
PUBLIC_IP = _public_ip()
NET_HISTORY = 100 # samples (one per 3 s) kept for the VPS network graphs
def _read_net():
rx = tx = 0
for line in Path("/proc/net/dev").read_text().splitlines()[2:]:
iface, data = line.split(":", 1)
iface = iface.strip()
if iface == "lo" or iface.startswith(("veth", "docker", "br-")):
continue
f = data.split()
rx += int(f[0])
tx += int(f[8])
return rx, tx
def _container_stats(c, prev_net):
s = c.stats(stream=False)
cpu = s.get("cpu_stats", {})
pre = s.get("precpu_stats", {})
cpu_delta = cpu.get("cpu_usage", {}).get("total_usage", 0) - pre.get("cpu_usage", {}).get("total_usage", 0)
sys_delta = cpu.get("system_cpu_usage", 0) - pre.get("system_cpu_usage", 0)
ncpu = cpu.get("online_cpus") or os.cpu_count() or 1
cpu_pct = (cpu_delta / sys_delta) * ncpu * 100 if sys_delta > 0 else 0.0
mem = s.get("memory_stats", {})
mem_used = mem.get("usage", 0) - mem.get("stats", {}).get("inactive_file", 0)
nets = s.get("networks", {}) or {}
rx = sum(n.get("rx_bytes", 0) for n in nets.values())
tx = sum(n.get("tx_bytes", 0) for n in nets.values())
now = time.time()
rx_rate = tx_rate = 0.0
if prev_net:
dt = now - prev_net["t"]
if dt > 0:
rx_rate = max(0, rx - prev_net["rx"]) / dt
tx_rate = max(0, tx - prev_net["tx"]) / dt
return {
"cpu_percent": round(cpu_pct, 1),
"mem_used": max(0, mem_used),
"net_rx_rate": rx_rate,
"net_tx_rate": tx_rate,
"_net": {"t": now, "rx": rx, "tx": tx},
}
def _check_ready(c):
game = GAMES.get(c.labels.get("gsm.game", ""))
if not game:
return True
if game.get("ready") == "health":
return c.attrs.get("State", {}).get("Health", {}).get("Status") == "healthy"
started = c.attrs.get("State", {}).get("StartedAt")
if ready_cache.get(c.id) == started:
return True
# Read the log from the start until the marker shows up. A tail isn't enough: on a server that has
# been up for a while the marker has scrolled far back, and the cache is empty after a redeploy.
marker = game["ready_marker"].encode()
tail = b""
try:
for chunk in c.logs(stream=True, follow=False):
if marker in tail + chunk:
ready_cache[c.id] = started
return True
tail = chunk[-len(marker):]
except Exception:
pass
return False
vh_sessions: dict = {} # container id -> players.ValheimSessions
ping_cache: dict = {} # ip -> ms or None
idle_since: dict = {} # container name -> when the server was last seen with nobody online
AUTO_STOP_DEFAULT_MIN = 15
NEW_SERVER_AUTO_STOP = {"auto_stop": True, "auto_stop_minutes": AUTO_STOP_DEFAULT_MIN} # on for new servers
def _query_players(c):
"""A2S players and (for Valheim) log sessions for a running server. Runs in the stats pool."""
game = GAMES.get(c.labels.get("gsm.game"), {})
port = int(c.labels.get("gsm.port", 0))
a2s = None
for off in game.get("query_ports", []):
a2s = pl.a2s_players(port + off)
if a2s is not None:
break
sessions = None
if c.labels.get("gsm.game") == "valheim":
sessions = vh_sessions.setdefault(c.id, pl.ValheimSessions()).update(c)
return a2s, sessions
def _auto_stop_check(c, st, now):
"""Stop a server that has had nobody online for its auto stop timeout."""
cfg = _load_cfg(c.name)
minutes = cfg.get("auto_stop_minutes", AUTO_STOP_DEFAULT_MIN)
if not cfg.get("auto_stop") or not st.get("ready") or st.get("players") is None or busy_ops.get(c.name):
idle_since.pop(c.name, None)
return
if st["players"]:
idle_since.pop(c.name, None)
return
stop_at = idle_since.setdefault(c.name, now) + minutes * 60
st["auto_stop_in"] = max(0, round(stop_at - now))
if now >= stop_at:
busy_ops[c.name] = "Auto-stopping (no players)…"
threading.Thread(target=_auto_stop, args=(c.name, minutes), daemon=True).start()
def _auto_stop(cname, minutes):
try:
print(f"auto stop: {cname} had no players for {minutes} min, stopping", flush=True)
client.containers.get(cname).stop(timeout=120) # saves the world
except Exception as e:
print("auto stop failed:", e, flush=True)
finally:
busy_ops.pop(cname, None)
idle_since.pop(cname, None)
def ping_loop():
"""Ping connected players every few seconds; the stats loop reads the latest results."""
pool = ThreadPoolExecutor(max_workers=8)
while True:
time.sleep(5)
with stats_lock:
ips = {p["ip"] for st in server_stats.values() for p in st.get("players") or [] if p.get("ip")}
results = dict(zip(ips, pool.map(pl.ping_ms, ips)))
ping_cache.clear()
ping_cache.update(results)
# ---------- automatic backups ----------
# A run of a server (one StartedAt) becomes eligible once a player is seen online. The backup is
# taken when that run ends: the server stopped (by hand or auto stop), restarted or was recreated.
# The eligible run is kept in a file so a manager restart doesn't forget it.
def _pending_path(cname):
return DATA_DIR / cname / "backup_pending"
def _read_pending(cname):
"""{"started": StartedAt of the eligible run, "peak": most players seen online at once}, or None."""
try:
text = _pending_path(cname).read_text().strip()
except OSError:
return None
try:
return json.loads(text)
except ValueError: # older marker: just the StartedAt
return {"started": text, "peak": 1} if text else None
def _write_pending(cname, pending):
_pending_path(cname).write_text(json.dumps(pending))
def _session_notes(c, pending):
"""Length and peak player count of the run that `pending` describes, for a backup's notes."""
state = c.attrs.get("State", {})
start = _parse_time(pending["started"])
end = _parse_time(state["FinishedAt"]) if state.get("FinishedAt") else 0
if (c.status == "running" and pending["started"] == state.get("StartedAt")) or end < start:
end = time.time() # still running (a download mid-session)
return {"length": round(end - start), "peak": pending.get("peak", 0)}
def _auto_backup_check(new_stats):
for c in client.containers.list(all=True, filters={"label": LABEL}):
if not GAMES.get(c.labels.get("gsm.game"), {}).get("backups"):
continue
started = c.attrs.get("State", {}).get("StartedAt")
running = c.status == "running"
pending = _read_pending(c.name)
if pending and (not running or pending["started"] != started):
if not _claim_busy(c.name, "Backing up world…"):
continue # a rollback, delete etc. is running and backs the run up itself
_pending_path(c.name).unlink(missing_ok=True)
threading.Thread(target=_auto_backup, args=(c, _session_notes(c, pending)), daemon=True).start()
continue
if busy_ops.get(c.name):
continue
online = len((new_stats.get(c.id) or {}).get("players") or [])
if running and online and (not pending or online > pending.get("peak", 0)):
_write_pending(c.name, {"started": started, "peak": online})
def _auto_backup(c, session):
try:
b = _make_backup(c, "auto", session)
print(f"auto backup: {c.name} -> {b['id']}", flush=True)
except Exception as e:
print("auto backup failed:", c.name, getattr(e, "detail", e), flush=True)
finally:
busy_ops.pop(c.name, None)
def stats_loop():
prev_cpu = _read_cpu()
prev_net = _read_net()
prev_t = time.time()
net_history = deque(maxlen=NET_HISTORY)
pool = ThreadPoolExecutor(max_workers=8)
while True:
time.sleep(3)
try:
total, idle = _read_cpu()
dt_total = total - prev_cpu[0]
cpu_pct = 100 * (1 - (idle - prev_cpu[1]) / dt_total) if dt_total else 0
prev_cpu = (total, idle)
m = _read_meminfo()
du = shutil.disk_usage(DATA_DIR)
rx, tx = _read_net()
now = time.time()
dt = now - prev_t
net_history.append([round((rx - prev_net[0]) / dt), round((tx - prev_net[1]) / dt)])
host = {
"cpu_percent": round(cpu_pct, 1),
"cpu_count": os.cpu_count(),
"mem_total": m["MemTotal"],
"mem_used": m["MemTotal"] - m["MemAvailable"],
"swap_total": m.get("SwapTotal", 0),
"swap_used": m.get("SwapTotal", 0) - m.get("SwapFree", 0),
"disk_total": du.total,
"disk_used": du.used,
"net_rx_rate": (rx - prev_net[0]) / dt,
"net_tx_rate": (tx - prev_net[1]) / dt,
"net_history": list(net_history), # [[rx, tx] bytes/s], oldest first
"public_ip": PUBLIC_IP,
}
prev_net, prev_t = (rx, tx), now
containers = client.containers.list(filters={"label": LABEL})
futures = {c.id: pool.submit(_container_stats, c, server_stats.get(c.id, {}).get("_net")) for c in containers}
ready = {c.id: _check_ready(c) for c in containers}
pfutures = {c.id: pool.submit(_query_players, c) for c in containers if ready[c.id]}
new_stats = {}
for c in containers:
try:
st = futures[c.id].result(timeout=10)
st["ready"] = ready[c.id]
st["players"] = None
if c.id in pfutures:
a2s, sessions = pfutures[c.id].result(timeout=10)
st["players"] = pl.combine(a2s, pl.udp_flows(int(c.labels.get("gsm.port", 0))), sessions, now)
for p in st["players"] or []:
p["ping"] = ping_cache.get(p["ip"])
p["connected_for"] = round(now - p.pop("since"))
_auto_stop_check(c, st, now)
new_stats[c.id] = st
except Exception as e:
print("stats error for", c.name, e, flush=True)
for cid in [k for k in vh_sessions if k not in ready]:
del vh_sessions[cid]
_auto_backup_check(new_stats)
with stats_lock:
host_stats.clear()
host_stats.update(host)
server_stats.clear()
server_stats.update(new_stats)
except Exception as e: # keep the loop alive no matter what
print("stats error:", e, flush=True)
threading.Thread(target=stats_loop, daemon=True).start()
threading.Thread(target=ping_loop, daemon=True).start()
@app.get("/api/stats", dependencies=[Depends(require_auth)])
def get_stats():
with stats_lock:
return {
"host": dict(host_stats),
"servers": {k: {kk: vv for kk, vv in v.items() if not kk.startswith("_")} for k, v in server_stats.items()},
}
# ---------- bandwidth test ----------
# The browser downloads random bytes for `seconds` and measures the rate, so the result is the
# VPS -> browser path (the VPS's upload, what players receive), capped by the viewer's own connection.
# None while anyone is playing: a test saturates the uplink and would lag them. A new test ends the
# previous stream, which a proxy may still be reading after the browser gave up on it.
BANDWIDTH_TEST_MAX_S = 60
_bw_chunk = os.urandom(1024 * 1024) # random, so a compressing proxy can't shrink it
_bw_lock = threading.Lock()
_bw_run = 0 # id of the newest test
@app.get("/api/bandwidth-test", dependencies=[Depends(require_auth)])
def bandwidth_test(seconds: int = Query(5, ge=1, le=BANDWIDTH_TEST_MAX_S)):
global _bw_run
with stats_lock:
online = sum(len(s.get("players") or []) for s in server_stats.values())
if online:
raise HTTPException(409, f"{online} player{'s are' if online != 1 else ' is'} connected. The test would "
"use all of the VPS's bandwidth and lag them, so it's disabled until everyone has left.")
with _bw_lock:
_bw_run += 1
run = _bw_run
def stream():
end = time.monotonic() + seconds
while time.monotonic() < end and _bw_run == run:
yield _bw_chunk
return StreamingResponse(stream(), media_type="application/octet-stream",
headers={"Cache-Control": "no-store", "Content-Encoding": "identity"})
# ---------- servers ----------
def _server_info(c):
l = c.labels
port = int(l.get("gsm.port", 0))
state = c.status # running, exited, restarting, created...
with stats_lock:
st = server_stats.get(c.id)
if state == "running":
state = "online" if st and st.get("ready") else "starting"
return {
"id": c.id,
"short_id": c.short_id,
"container": c.name,
"game": l.get("gsm.game"),
"game_name": GAMES.get(l.get("gsm.game"), {}).get("name", l.get("gsm.game")),
"server_name": l.get("gsm.server_name"),
"world": l.get("gsm.world"),
"port": port,
"state": state,
"created": l.get("gsm.created"),
"summary": _summary(c),
"busy": busy_ops.get(c.name),
"backup_pending": _pending_path(c.name).exists(),
"last_online": _last_online(c) if c.status != "running" else None,
}
# When a stopped server last ran. Docker keeps this as the container's FinishedAt, but recreating the
# container (saving settings) loses it, so the old value is kept in a file for the new container.
def _last_online_path(cname):
return DATA_DIR / cname / "last_online"
def _last_online(c):
finished = c.attrs.get("State", {}).get("FinishedAt", "")
if finished and not finished.startswith("0001-"):
return finished
try:
return _last_online_path(c.name).read_text().strip() or None
except OSError:
return None
def _remember_last_online(c):
c.reload()
if last := _last_online(c):
_last_online_path(c.name).write_text(last)
def _summary(c):
if c.labels.get("gsm.game") == "zomboid":
cfg = _load_cfg(c.name)
n = len(cfg.get("mods", []))
text = f"{zomboid.BRANCHES.get(cfg.get('branch'), '')} · {n} mod{'s' if n != 1 else ''}"
return text + (" · changes pending restart" if cfg.get("dirty") else "")
return None
# Long-running operations per container name, e.g. "Restarting in 60s…", shown on the server card.
busy_ops: dict = {}
busy_lock = threading.Lock()
def _claim_busy(name, text):
"""Mark a server busy unless something else already is, atomically. Returns whether it was claimed."""
with busy_lock:
if busy_ops.get(name):
return False
busy_ops[name] = text
return True
def _cfg_path(cname):
return DATA_DIR / cname / "gsm.json"
def _load_cfg(cname):
try:
return json.loads(_cfg_path(cname).read_text())
except (OSError, ValueError):
return {}
def _save_cfg(cname, cfg):
p = _cfg_path(cname)
tmp = p.with_suffix(".tmp")
tmp.write_text(json.dumps(cfg, indent=2))
tmp.replace(p)
def _require_memory(needed_mb, what):
"""Refuse to start something that doesn't fit in free RAM, so it can't make running servers swap."""
avail = _read_meminfo()["MemAvailable"] // (1024 * 1024)
if avail < needed_mb:
raise HTTPException(400, f"Not enough free memory to start {what}: it needs about {needed_mb} MB "
f"and {avail} MB is free. Stop another server or lower its memory setting.")
def _require_no_players(c, what):
"""Refuse actions that would kick players (stop, restart, delete, settings changes) while anyone is on."""
with stats_lock:
online = len((server_stats.get(c.id) or {}).get("players") or [])
if online:
raise HTTPException(409, f"{online} player{'s are' if online != 1 else ' is'} connected. "
f"{what} is disabled until everyone has left.")
def _get(cid):
try:
c = client.containers.get(cid)
except NotFound:
raise HTTPException(404, "Server not found")
if c.labels.get(LABEL) != "true":
raise HTTPException(404, "Server not found")
return c
@app.get("/api/games", dependencies=[Depends(require_auth)])
def list_games():
avail = _read_meminfo()["MemAvailable"] // (1024 * 1024)
return [{"id": k, "name": v["name"], "default_port": v["default_port"], "ports_needed": v["ports_needed"],
"free_memory_mb": avail,
**({"mod_presets": zomboid.presets_with_updates(), "preset_branch": zomboid.PRESET_BRANCH} if k == "zomboid" else {})}
for k, v in GAMES.items()]
@app.get("/api/servers", dependencies=[Depends(require_auth)])
def list_servers():
cs = client.containers.list(all=True, filters={"label": LABEL})
return sorted((_server_info(c) for c in cs), key=lambda s: s.get("created") or "")
def _used_ports():
used = set()
for c in client.containers.list(all=True, filters={"label": LABEL}):
p = int(c.labels.get("gsm.port", 0))
n = GAMES.get(c.labels.get("gsm.game"), {}).get("ports_needed", 1)
used.update(range(p, p + n))
return used
def _udp_port_free(port):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.bind(("0.0.0.0", port))
return True
except OSError:
return False
finally:
s.close()
@app.get("/api/suggest-port", dependencies=[Depends(require_auth)])
def suggest_port(game: str = "valheim"):
g = GAMES[game]
used = _used_ports()
port = g["default_port"]
while any(p in used or not _udp_port_free(p) for p in range(port, port + g["ports_needed"])):
port += g["ports_needed"]
return {"port": port}
WORLD_RE = re.compile(r"^[A-Za-z0-9_]{1,40}$")
MAX_UPLOAD = 1024 * 1024 * 1024 # 1 GB total
def _read_world_upload(uploads):
"""Collect Valheim world files from uploaded files and/or zips.
Returns ("folder", {filename: bytes}) for the current format (a world folder holding
_main.N.db2/.fwl2/...) or ("legacy", {".db": bytes, ".fwl": bytes}) for the classic pair.
"""
found = {} # basename -> bytes
total = 0
for up in uploads:
if not up.filename:
continue
data = up.file.read()
total += len(data)
if total > MAX_UPLOAD:
raise HTTPException(400, "Upload is too large (max 1 GB)")
name = os.path.basename(up.filename.replace("\\", "/"))
if name.lower().endswith(".zip"):
try:
with zipfile.ZipFile(io.BytesIO(data)) as z:
for info in z.infolist():
if info.is_dir() or info.file_size > MAX_UPLOAD:
continue
base = os.path.basename(info.filename)
if base and not base.startswith("."):
found[base] = z.read(info)
except zipfile.BadZipFile:
raise HTTPException(400, f"{name} is not a valid zip file")
else:
found[name] = data
# Current-format worlds are a folder holding a save set _main.N.{db2,fwl2,ok,chunks} plus *.chunk files.
# Valheim deletes an incomplete save set as an "orphan" and silently generates a fresh world,
# so refuse uploads that are missing any part of it.
saves = sorted({int(m.group(1)) for n in found if (m := re.fullmatch(r"_main\.(\d+)\.db2", n))})
if saves or any(n.endswith(".fwl2") for n in found):
if not saves:
raise HTTPException(400, "The upload has a .fwl2 file but no matching .db2 world file.")
n = saves[-1] # newest save in the folder
missing = [f"_main.{n}.{ext}" for ext in ("db2", "fwl2", "ok", "chunks") if f"_main.{n}.{ext}" not in found]
if missing:
raise HTTPException(400, f"The world upload is incomplete: missing {', '.join(missing)}. Valheim discards "
"incomplete worlds and starts a new one. Upload every file in the world folder, "
"or zip the whole folder and upload the zip.")
chunk_files = {k: v for k, v in found.items() if k.endswith(".chunk")}
# An empty index is ~10 bytes; a bigger one lists chunk files that must be present.
if len(found[f"_main.{n}.chunks"]) > 16 and not chunk_files:
raise HTTPException(400, "The world upload is missing its .chunk files (where buildings and terrain "
"are stored). Upload every file in the world folder, or zip the whole folder.")
folder = {k: v for k, v in found.items() if k.startswith(f"_main.{n}.")}
folder.update(chunk_files)
return "folder", folder
db = [n for n in found if n.lower().endswith(".db")]
fwl = [n for n in found if n.lower().endswith(".fwl")]
if len(db) == 1 and len(fwl) == 1:
return "legacy", {".db": found[db[0]], ".fwl": found[fwl[0]]}
if len(db) > 1 or len(fwl) > 1:
raise HTTPException(400, "Found more than one world in the upload; upload one world at a time")
raise HTTPException(400, "Couldn't find a world in the upload. Upload every file in your world folder, "
"a zip of that folder, or a classic .db + .fwl pair")
def _validate_password(password, server_name):
if len(password) < 5:
raise HTTPException(400, "Password must be at least 5 characters")
if password in server_name:
raise HTTPException(400, "Valheim does not allow the password to appear in the server name")
def _validate_port(g, port, own=None):
"""Check that port..port+n is free. `own` is the container being edited, whose ports don't count."""
if not (1024 <= port <= 65535 - g["ports_needed"]):
raise HTTPException(400, "Port must be between 1024 and 65534")
needed = range(port, port + g["ports_needed"])
own_ports = set()
if own is not None:
p = int(own.labels.get("gsm.port", 0))
own_ports = set(range(p, p + g["ports_needed"]))
used = _used_ports() - own_ports
if any(p in used for p in needed):
raise HTTPException(400, f"Port {port} or {port + 1} is already used by another server")
if not all(p in own_ports or _udp_port_free(p) for p in needed):
raise HTTPException(400, f"Port {port} or {port + 1} is already in use on the VPS")
def _ensure_image(image):
"""containers.create doesn't pull, so fetch the image first if this VPS doesn't have it yet."""
try:
client.images.get(image)
except docker.errors.ImageNotFound:
client.images.pull(image)
def _run_valheim(cname, server_name, world_name, password, port, created, start=True):
base = DATA_DIR / cname
_ensure_image(GAMES["valheim"]["image"])
c = client.containers.create(
GAMES["valheim"]["image"],
name=cname,
detach=True,
environment={
"SERVER_NAME": server_name,
"WORLD_NAME": world_name,
"SERVER_PASS": password,
"SERVER_PORT": str(port),
"SERVER_PUBLIC": "true",
"TZ": "UTC",
},
ports={f"{p}/udp": p for p in range(port, port + 2)},
volumes={
str(base / "config"): {"bind": "/config", "mode": "rw"},
str(base / "server"): {"bind": "/opt/valheim", "mode": "rw"},
},
labels={
LABEL: "true",
"gsm.game": "valheim",
"gsm.server_name": server_name,
"gsm.world": world_name,
"gsm.port": str(port),
"gsm.created": created,
},
restart_policy={"Name": "unless-stopped"},
cap_add=["SYS_NICE"],
)
if start:
c.start()
c.reload()
return c
def _env(c):
return dict(e.split("=", 1) for e in c.attrs["Config"]["Env"] if "=" in e)
def _validate_zomboid(cfg, own=None):
if not 1024 <= cfg["memory_mb"] <= 65536:
raise HTTPException(400, "Memory must be between 1024 and 65536 MB")
if not 1 <= cfg["max_players"] <= 100:
raise HTTPException(400, "Max players must be between 1 and 100")
if len(cfg.get("password", "")) > 60 or any(ch in cfg.get("password", "") for ch in "\r\n"):
raise HTTPException(400, "Password is too long or has line breaks")
_validate_port(GAMES["zomboid"], cfg["port"], own=own)
def _run_zomboid(cname, cfg, start=True):
base = DATA_DIR / cname
for sub in ("data", "game"):
(base / sub).mkdir(parents=True, exist_ok=True)
os.chown(base / sub, 1000, 1000) # the image runs as uid 1000
_ensure_image(zomboid.IMAGE)
c = client.containers.create(
zomboid.IMAGE,
name=cname,
detach=True,
environment=zomboid.container_env(cfg),
ports={f"{p}/udp": p for p in (cfg["port"], cfg["port"] + 1)},
volumes={
str(base / "data"): {"bind": "/home/steam/Zomboid", "mode": "rw"},
str(base / "game"): {"bind": "/home/steam/pz-dedicated", "mode": "rw"},
},
labels={
LABEL: "true",
"gsm.game": "zomboid",
"gsm.server_name": cfg["server_name"],
"gsm.world": "",
"gsm.port": str(cfg["port"]),
"gsm.created": cfg["created"],
},
# unless-stopped also brings it back after the image's own restart for mod updates (exit code 0)
restart_policy={"Name": "unless-stopped"},
log_config={"type": "json-file", "config": {"max-size": "50m", "max-file": "3"}},
stop_signal="SIGTERM",
)
cfg["dirty"] = False
_save_cfg(cname, cfg)
if start:
c.start()
c.reload()
return c
def _create_zomboid(server_name, password, port, admin_password, memory_mb, max_players, branch, preset_mods):
if branch not in zomboid.BRANCHES:
raise HTTPException(400, "Unknown game version")
if preset_mods and branch != zomboid.PRESET_BRANCH:
raise HTTPException(400, "The mod presets are for Build 42 only")
try:
workshop_ids, mods = zomboid.preset_selection(preset_mods)
except ValueError as e:
raise HTTPException(400, str(e))
if len(admin_password) < 5:
raise HTTPException(400, "Admin password must be at least 5 characters")
cfg = {
"server_name": server_name, "password": password, "admin_password": admin_password,
"port": port, "memory_mb": memory_mb, "max_players": max_players, "branch": branch,
"workshop_ids": workshop_ids, "mods": mods, "auto_update": True, **NEW_SERVER_AUTO_STOP,
"created": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
}
_validate_zomboid(cfg)
_require_memory(memory_mb + zomboid.MEMORY_OVERHEAD_MB, "this server")
slug = re.sub(r"[^a-z0-9]+", "-", server_name.lower()).strip("-")[:30] or "server"
cname = f"gsm-zomboid-{slug}-{secrets.token_hex(2)}"
(DATA_DIR / cname).mkdir(parents=True)
try:
c = _run_zomboid(cname, cfg)
except Exception as e:
shutil.rmtree(DATA_DIR / cname, ignore_errors=True)
raise HTTPException(500, f"Failed to start container: {e}")
return _server_info(c)
def _recreate_zomboid(c, start):
"""Apply the stored config: Docker can't change env or ports in place, so replace the container."""
cfg = _load_cfg(c.name)
name = c.name
if c.status in ("running", "restarting"):
c.stop(timeout=120) # the server saves the world on SIGTERM
_remember_last_online(c)
c.remove()
return _run_zomboid(name, cfg, start=start)
@app.post("/api/servers", dependencies=[Depends(require_auth)])
async def create_server(
game: str = Form(...),
server_name: str = Form(...),
password: str = Form(""),
port: int = Form(...),
world_name: str = Form(""),
world_source: str = Form("new"),
world_files: list[UploadFile] | None = File(None),
admin_password: str = Form(""),
memory_mb: int = Form(4096),
max_players: int = Form(8),
branch: str = Form("public"),
preset_mods: list[str] = Form([]),
):
if game not in GAMES:
raise HTTPException(400, "Unknown game")
g = GAMES[game]
server_name = server_name.strip()
if not server_name or len(server_name) > 60:
raise HTTPException(400, "Server name is required (max 60 characters)")
if game == "zomboid":
# in a thread: the first create pulls the image, which shouldn't freeze the rest of the site
return await run_in_threadpool(_create_zomboid, server_name, password, port, admin_password, memory_mb, max_players, branch, preset_mods)
if not WORLD_RE.match(world_name):
raise HTTPException(400, "World name may only contain letters, numbers and underscores")
_validate_password(password, server_name)
_validate_port(g, port)
world = None
if world_source == "upload":
world = _read_world_upload(world_files or [])
slug = re.sub(r"[^a-z0-9]+", "-", world_name.lower()).strip("-") or "world"
cname = f"gsm-{game}-{slug}-{secrets.token_hex(2)}"
base = DATA_DIR / cname
config_dir = base / "config"
worlds_dir = config_dir / "worlds_local"
worlds_dir.mkdir(parents=True, exist_ok=True)
(base / "server").mkdir(parents=True, exist_ok=True)
_save_cfg(cname, dict(NEW_SERVER_AUTO_STOP))
if world:
kind, files = world
if kind == "folder":
(worlds_dir / world_name).mkdir()
for fname, data in files.items():
(worlds_dir / world_name / fname).write_bytes(data)
else:
for ext, data in files.items():
(worlds_dir / f"{world_name}{ext}").write_bytes(data)
try:
c = await run_in_threadpool(_run_valheim, cname, server_name, world_name, password, port,
time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()))
except Exception as e:
shutil.rmtree(base, ignore_errors=True)
raise HTTPException(500, f"Failed to start container: {e}")
return _server_info(c)
# ---------- rollback ----------
def _world_root(c):
"""The folder a server's backup zip names are relative to (see _backup_files)."""
if c.labels.get("gsm.game") == "valheim":
return DATA_DIR / c.name / "config" / "worlds_local"
return DATA_DIR / c.name / "data"
def _clear_world(c):
"""Delete the server's current world/save files: exactly what _backup_files would zip."""
root = _world_root(c)
if c.labels.get("gsm.game") == "valheim":
world = c.labels["gsm.world"]
shutil.rmtree(root / world, ignore_errors=True)
for p in root.glob(f"{world}.*"):
if p.is_file():
p.unlink()
else:
n = zomboid.SERVERNAME
shutil.rmtree(root / "Saves" / "Multiplayer" / n, ignore_errors=True)
(root / "db" / f"{n}.db").unlink(missing_ok=True)
# Server/<n>* (ini, sandbox vars, spawn regions) are overwritten by the extract; the image
# reapplies its INI_ settings from the container's environment on start.
def _restore_zip(c, zpath):
"""Replace the server's world with the contents of a backup zip. The server must be stopped."""
root = _world_root(c)
game = c.labels.get("gsm.game")
if game == "valheim":
world = c.labels["gsm.world"]
allowed = lambda name: name.split("/", 1)[0] == world or name.startswith(world + ".")
else:
n = zomboid.SERVERNAME
allowed = lambda name: (name.startswith(f"Saves/Multiplayer/{n}/") or name == f"db/{n}.db"
or (name.startswith("Server/") and "/" not in name[7:] and name[7:].startswith(n)))
owner = root.stat()
with zipfile.ZipFile(zpath) as z:
names = [i.filename for i in z.infolist() if not i.is_dir()]
bad = [m for m in names if m.startswith("/") or ".." in m.split("/") or "\\" in m or not allowed(m)]
if bad or not names:
raise HTTPException(400, "This backup doesn't hold this server's world, so it can't be restored here.")
# Extract next to the world first, so a bad zip can't leave the server with half a world.
staging = Path(tempfile.mkdtemp(prefix=".rollback-", dir=root))
try:
z.extractall(staging, names)
_clear_world(c)
for src in sorted(staging.rglob("*")):
dest = root / src.relative_to(staging)
if src.is_dir():
dest.mkdir(exist_ok=True)
else:
dest.parent.mkdir(parents=True, exist_ok=True)
os.replace(src, dest)
os.chown(dest, owner.st_uid, owner.st_gid) # the game runs as the folder's owner
finally:
shutil.rmtree(staging, ignore_errors=True)
@app.post("/api/servers/{cid}/rollback", dependencies=[Depends(require_auth)])
async def rollback(cid: str, request: Request):
body = await request.json()
return await run_in_threadpool(_rollback, cid, str(body.get("id", "")), bool(body.get("promote")))
def _current_backup(game, cname):
"""Id of the backup that holds the server's world as it is now, or None. Players being on since the
last backup means the world has moved past every backup."""
return None if _pending_path(cname).exists() else backups.current(game, cname)
def _rollback(cid, backup_id, promote):
"""Restore a backup of this stopped server.
Before the restore, a run that players were on and that isn't backed up yet is backed up as usual
(automatic). Then, rolling back to an automatic backup can keep the world being rolled back from as a
manual backup: the current backup is moved to the manual list if it's automatic (or a manual backup is
made if no backup holds it). The chosen backup becomes the current one; a manual backup stays in the list.
"""
c = _get(cid)
name = c.name
game = c.labels.get("gsm.game")
if not GAMES.get(game, {}).get("backups"):
raise HTTPException(400, "Backups are not supported for this game")
try:
b_game, kind, fname = backup_id.split("/")
except ValueError:
raise HTTPException(400, "Unknown backup")
zpath = backups.path(b_game, kind, fname)
if not zpath or b_game != game or fname.split("__")[0] != name:
raise HTTPException(404, "Backup not found for this server")
# Claimed before checking the state, so nothing (start, auto backup, another rollback) can begin in between.
if not _claim_busy(name, "Rolling back…"):
raise HTTPException(409, f"Busy: {busy_ops.get(name)}")
hold = zpath.with_name(zpath.name + ".rollback")
promoted = None
try:
c.reload()
if c.status not in ("exited", "created"):
raise HTTPException(409, "Stop the server before rolling back.")
if _current_backup(game, name) == backup_id:
raise HTTPException(409, "The server's world is already this backup, so there is nothing to roll back.")
# Hold the chosen zip by a second name: the backup below could prune it from the auto list.
os.link(zpath, hold)
pending = _read_pending(name)
if pending: # players were on since the last backup: keep the world being rolled back from
_pending_path(name).unlink(missing_ok=True)
try:
_make_backup(c, "auto", _session_notes(c, pending))
except HTTPException:
pass # nothing saved yet
if kind == "auto" and promote:
cur = backups.current(game, name) # the world being rolled back from (backed up just above if played)
if cur and cur.split("/")[1] == "auto":
promoted = backups.promote(backups.path(*cur.split("/")))
elif not cur:
try:
promoted = _make_backup(c, "manual", extra={"promoted": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())})
except HTTPException:
pass # no world saved yet
# a manual current backup is kept already
_restore_zip(c, hold)
backups.set_current(game, name, backup_id)
finally:
hold.unlink(missing_ok=True)
busy_ops.pop(name, None)
c.reload()
return {"server": _server_info(c), "promoted": promoted}
@app.post("/api/servers/{cid}/{action}", dependencies=[Depends(require_auth)])
def server_action(cid: str, action: str):
c = _get(cid)
if busy_ops.get(c.name):
raise HTTPException(409, f"Busy: {busy_ops[c.name]}")
if action in ("stop", "restart"):
_require_no_players(c, action.capitalize())
if c.labels.get("gsm.game") == "zomboid" and action in ("start", "restart"):
cfg = _load_cfg(c.name)
if action == "start":
_require_memory(cfg["memory_mb"] + zomboid.MEMORY_OVERHEAD_MB, "this server")
if cfg.get("dirty"): # saved changes waiting for a restart
return _server_info(_recreate_zomboid(c, start=True))
if action == "start":
c.start()
elif action == "stop":
c.stop(timeout=120) # give Valheim time to save the world
elif action == "restart":
c.restart(timeout=120)
else:
raise HTTPException(400, "Unknown action")
c.reload()
return _server_info(c)
@app.delete("/api/servers/{cid}", dependencies=[Depends(require_auth)])
def delete_server(cid: str, delete_data: bool = False):
c = _get(cid)
name = c.name
_require_no_players(c, "Delete")
# keeps the stats loop from backing up while files are removed
if not _claim_busy(name, "Deleting…"):
raise HTTPException(409, f"Busy: {busy_ops.get(name)}")
try:
if c.status == "running":
c.stop(timeout=120)
pending = _read_pending(name)
if pending: # players were on since the last backup: keep this world
_pending_path(name).unlink(missing_ok=True)
c.reload() # for the stop time in the session notes
try:
_make_backup(c, "auto", _session_notes(c, pending))
except Exception as e:
print("backup before delete failed:", name, getattr(e, "detail", e), flush=True)
c.remove()
finally:
busy_ops.pop(name, None)
if delete_data:
shutil.rmtree(DATA_DIR / name, ignore_errors=True)
return {"ok": True}
@app.get("/api/servers/{cid}/logs", dependencies=[Depends(require_auth)])
def server_logs(cid: str, tail: int = 200):
c = _get(cid)
return {"logs": c.logs(tail=min(tail, 2000), timestamps=False).decode(errors="replace")}
@app.get("/api/servers/{cid}/logs/stream", dependencies=[Depends(require_auth)])
async def stream_logs(cid: str, request: Request, tail: int = 500):
"""Server-sent events: the last `tail` lines, then new lines as the container writes them."""
c = _get(cid)
loop = asyncio.get_running_loop()
queue: asyncio.Queue = asyncio.Queue()
stream = c.logs(stream=True, follow=True, tail=min(tail, 2000))
def reader():
# Docker's log stream is blocking, so read it in a thread and hand chunks to the event loop.
try:
for chunk in stream:
loop.call_soon_threadsafe(queue.put_nowait, chunk)
except Exception:
pass
loop.call_soon_threadsafe(queue.put_nowait, None)
threading.Thread(target=reader, daemon=True).start()
async def events():
buf = b""
try:
while True:
try:
chunk = await asyncio.wait_for(queue.get(), timeout=15)
except asyncio.TimeoutError:
if await request.is_disconnected():
break
yield ": keepalive\n\n"
continue
if chunk is None: # container stopped or was removed
yield "event: end\ndata: {}\n\n"
break
buf += chunk
*lines, buf = buf.split(b"\n")
if lines:
text = [l.decode(errors="replace").rstrip("\r") for l in lines]
yield f"data: {json.dumps(text)}\n\n"
finally:
stream.close() # unblocks the reader thread
return StreamingResponse(events(), media_type="text/event-stream",
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"})
# ---------- frontend ----------
app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
@app.get("/")
def index():
return FileResponse(STATIC_DIR / "index.html")
@app.get("/api/servers/{cid}/settings", dependencies=[Depends(require_auth)])
def get_settings(cid: str):
c = _get(cid)
game = c.labels.get("gsm.game")
env = _env(c)
if game == "valheim":
values = {"password": env.get("SERVER_PASS", ""), "port": int(c.labels.get("gsm.port", 0))}
elif game == "zomboid":
cfg = _load_cfg(c.name)
values = {k: cfg.get(k) for k in ("password", "port", "memory_mb", "max_players")}
else:
values = {}
g = GAMES.get(game, {})
cfg = _load_cfg(c.name)
return {"fields": g.get("settings", []), "values": values, "backups": g.get("backups", False),
"mods": g.get("mods", False),
"auto_stop": {"enabled": bool(cfg.get("auto_stop")),
"minutes": cfg.get("auto_stop_minutes", AUTO_STOP_DEFAULT_MIN)}}
@app.put("/api/servers/{cid}/autostop", dependencies=[Depends(require_auth)])
async def update_auto_stop(cid: str, request: Request):
"""Saved in gsm.json and read by the stats loop, so no restart is needed."""
c = _get(cid)
body = await request.json()
try:
minutes = int(body.get("minutes"))
except (TypeError, ValueError):
raise HTTPException(400, "Timeout must be a number of minutes")
if not 5 <= minutes <= 1440:
raise HTTPException(400, "Timeout must be between 5 and 1440 minutes")
cfg = _load_cfg(c.name)
cfg.update(auto_stop=bool(body.get("enabled")), auto_stop_minutes=minutes)
_save_cfg(c.name, cfg)
idle_since.pop(c.name, None) # start the countdown over with the new setting
return {"enabled": cfg["auto_stop"], "minutes": minutes}
@app.put("/api/servers/{cid}/settings", dependencies=[Depends(require_auth)])
async def update_settings(cid: str, request: Request):
c = _get(cid)
body = await request.json()
if busy_ops.get(c.name):
raise HTTPException(409, f"Busy: {busy_ops[c.name]}")
_require_no_players(c, "Saving settings") # saving recreates the container
if c.labels.get("gsm.game") == "zomboid":
return _update_zomboid_settings(c, body)
if c.labels.get("gsm.game") != "valheim":
raise HTTPException(400, "This game has no editable settings")
l = c.labels
try:
port = int(body.get("port"))
except (TypeError, ValueError):
raise HTTPException(400, "Port must be a number")
password = str(body.get("password", ""))
_validate_password(password, l["gsm.server_name"])
_validate_port(GAMES["valheim"], port, own=c)
# Docker can't change published ports in place, so recreate the container.
# World data lives in the bind-mounted folders, so nothing is lost.
was_running = c.status in ("running", "restarting")
if was_running:
c.stop(timeout=120) # saves the world
_remember_last_online(c)
c.remove()
c = _run_valheim(c.name, l["gsm.server_name"], l["gsm.world"], password, port, l["gsm.created"], start=was_running)
return _server_info(c)
def _backup_files(c):
"""[(path, name in zip)] of the world/save files for a server; raises 404 if nothing is saved yet."""
game = c.labels.get("gsm.game")
if game == "valheim":
world = c.labels["gsm.world"]
worlds_dir = DATA_DIR / c.name / "config" / "worlds_local"
# Current format is a folder per world; older worlds are a <World>.db + <World>.fwl pair.
files = [p for p in (worlds_dir / world).rglob("*") if p.is_file()] if (worlds_dir / world).is_dir() else []
files += [p for p in worlds_dir.glob(f"{world}.*") if p.is_file()]
if not any(p.suffix in (".db2", ".db") for p in files):
raise HTTPException(404, "This world hasn't been saved yet. Valheim saves about every 30 minutes "
"and when the server stops. Try again after that.")
return [(p, p.relative_to(worlds_dir).as_posix()) for p in files]
if game == "zomboid":
data = DATA_DIR / c.name / "data"
n = zomboid.SERVERNAME
files = [p for p in (data / "Saves" / "Multiplayer" / n).rglob("*") if p.is_file()]
if not files:
raise HTTPException(404, "This server hasn't saved a world yet. Start it once and try again.")
files += [p for p in (data / "db").glob(f"{n}.db") if p.is_file()]
files += [p for p in (data / "Server").glob(f"{n}*") if p.is_file()] # ini, sandbox vars, spawn regions
return [(p, p.relative_to(data).as_posix()) for p in files]
raise HTTPException(400, "Backups are not supported for this game")
def _make_backup(c, kind, session=None, extra=None):
l = c.labels
game = l.get("gsm.game")
return backups.create(game, kind, c.name, _backup_files(c), {
"game_name": GAMES.get(game, {}).get("name", game), "server_name": l.get("gsm.server_name"),
"world": l.get("gsm.world") or None, "session": session, **(extra or {}),
})
@app.get("/api/servers/{cid}/world.zip", dependencies=[Depends(require_auth)])
def download_world(cid: str):
"""Download the saved world. Each download is also kept as a manual backup."""
c = _get(cid)
if busy_ops.get(c.name):
raise HTTPException(409, f"Busy: {busy_ops[c.name]}")
session = None
if c.status == "running":
with stats_lock:
online = len((server_stats.get(c.id) or {}).get("players") or [])
pending = _read_pending(c.name)
if not pending or pending["started"] != c.attrs["State"]["StartedAt"]:
pending = {"started": c.attrs["State"]["StartedAt"], "peak": 0}
session = {**_session_notes(c, pending), "running": True}
session["peak"] = max(session["peak"], online)
b = _make_backup(c, "manual", session)
if not _pending_path(c.name).exists() and not backups.current(b["game"], c.name):
backups.set_current(b["game"], c.name, b["id"]) # no other backup holds this world
label = re.sub(r"[^A-Za-z0-9_-]+", "", b["game_name"]) + "_" + re.sub(r"[^A-Za-z0-9_-]+", "_", b["world"] or b["server_name"])
filename = f"{label}_{time.strftime('%Y-%m-%d', time.gmtime())}.zip"
return FileResponse(backups.path(*b["id"].split("/")), media_type="application/zip", filename=filename)
@app.get("/api/backups", dependencies=[Depends(require_auth)])
def list_backups():
games = [{"id": k, "name": g["name"]} for k, g in GAMES.items() if g.get("backups")]
items = backups.list()
current = {}
for b in items:
if b.get("container") and b["container"] not in current:
current[b["container"]] = _current_backup(b["game"], b["container"])
return {"games": games, "backups": items, "keep": 5, "current": current}
@app.get("/api/backups/{game}/{kind}/{name}", dependencies=[Depends(require_auth)])
def download_backup(game: str, kind: str, name: str):
p = backups.path(game, kind, name)
if not p:
raise HTTPException(404, "Backup not found")
return FileResponse(p, media_type="application/zip", filename=name)
# ---------- Project Zomboid: settings and mods ----------
def _update_zomboid_settings(c, body):
cfg = _load_cfg(c.name)
old_mem = cfg["memory_mb"]
try:
cfg.update(password=str(body.get("password") or ""), port=int(body["port"]),
memory_mb=int(body["memory_mb"]), max_players=int(body["max_players"]))
except (KeyError, TypeError, ValueError):
raise HTTPException(400, "Port, memory and max players must be numbers")
_validate_zomboid(cfg, own=c)
running = c.status in ("running", "restarting")
if running and cfg["memory_mb"] > old_mem:
_require_memory(cfg["memory_mb"] - old_mem, "this server with more memory")
_save_cfg(c.name, cfg)
return _server_info(_recreate_zomboid(c, start=running))
def _zomboid(cid):
c = _get(cid)
if c.labels.get("gsm.game") != "zomboid":
raise HTTPException(400, "Mods are only supported for Project Zomboid")
return c
def _mods_cache_path(cname):
return DATA_DIR / cname / "mods_cache.json"
def _refresh_mod_info(cname, download_ids):
"""Background: download new workshop items into the running server, then read its mod info."""
try:
c = client.containers.get(cname)
if download_ids:
busy_ops[cname] = f"Downloading {len(download_ids)} workshop item(s)…"
res = c.exec_run(zomboid.download_command(download_ids))
if res.exit_code != 0:
print("steamcmd failed:", res.output[-2000:].decode(errors="replace"), flush=True)
busy_ops[cname] = "Reading mod info…"
res = c.exec_run(["list-mods"], demux=True)
out, err = res.output
if res.exit_code != 0:
raise RuntimeError((err or out or b"").decode(errors="replace").strip()[-500:] or "list-mods failed")
info = zomboid.parse_list_mods(out)
info["fetched"] = time.time()
info["error"] = None
except Exception as e:
info = {**_read_mods_cache(cname), "error": str(e)}
finally:
busy_ops.pop(cname, None)
_mods_cache_path(cname).write_text(json.dumps(info))
def _read_mods_cache(cname):
try:
return json.loads(_mods_cache_path(cname).read_text())
except (OSError, ValueError):
return {}
@app.get("/api/servers/{cid}/mods", dependencies=[Depends(require_auth)])
def get_mods(cid: str):
c = _zomboid(cid)
cfg = _load_cfg(c.name)
cache = _read_mods_cache(c.name)
started = c.attrs.get("State", {}).get("StartedAt", "")
try:
logs = c.logs(since=_parse_time(started), tail=5000).decode(errors="replace") if started else ""
except Exception:
logs = ""
return {
"workshop_ids": cfg.get("workshop_ids", []),
"mods": cfg.get("mods", []),
"auto_update": cfg.get("auto_update", True),
"dirty": cfg.get("dirty", False),
"branch": cfg.get("branch"),
"running": c.status == "running",
"ready": _check_ready(c) if c.status == "running" else False,
"busy": busy_ops.get(c.name),
"fetch_pending": c.name in fetch_pending,
"info": cache,
"issues": zomboid.parse_issues(logs),
}
def _parse_time(iso):
from datetime import datetime
return int(datetime.fromisoformat(iso[:26].rstrip("Z") + "+00:00").timestamp())
@app.post("/api/workshop/lookup", dependencies=[Depends(require_auth)])
async def workshop_lookup(request: Request):
body = await request.json()
try:
return await asyncio.to_thread(zomboid.lookup, str(body.get("text", "")))
except ValueError as e:
raise HTTPException(400, str(e))
except Exception as e:
raise HTTPException(502, f"Steam Workshop lookup failed: {e}")
# Servers started by "Start server and fetch mod info", waiting to come online. Not a busy_op, so
# Stop stays available; stopping the server cancels the fetch.
fetch_pending: dict = {} # container name -> time requested
FETCH_WAIT_S = 2 * 60 * 60 # a first start with a big mod list downloads gigabytes
def _start_fetch(cname):
cfg = _load_cfg(cname)
downloaded = {i["id"] for i in _read_mods_cache(cname).get("items", []) if i.get("downloaded")}
new_ids = [i for i in cfg.get("workshop_ids", []) if i not in downloaded]
busy_ops[cname] = "Starting…"
threading.Thread(target=_refresh_mod_info, args=(cname, new_ids), daemon=True).start()
def _fetch_when_ready(cname):
"""Background: wait for a server we just started to come online, then fetch its mod info."""
error = None
try:
deadline = time.time() + FETCH_WAIT_S
while time.time() < deadline:
time.sleep(5)
if busy_ops.get(cname):
continue # e.g. still being recreated
try:
c = client.containers.get(cname)
except NotFound:
error = "The server was removed before it came online."
return
if c.status not in ("running", "restarting"):
error = "The server stopped before it came online, so mod info wasn't fetched."
return
if c.status == "running" and _check_ready(c):
_start_fetch(cname)
return
error = "The server didn't come online within 2 hours, so mod info wasn't fetched."
except Exception as e:
error = str(e)
finally:
fetch_pending.pop(cname, None)
if error:
print("fetch after start:", cname, error, flush=True)
_mods_cache_path(cname).write_text(json.dumps({**_read_mods_cache(cname), "error": error}))
@app.post("/api/servers/{cid}/mods/refresh", dependencies=[Depends(require_auth)])
def refresh_mods(cid: str, start: bool = False):
c = _zomboid(cid)
if busy_ops.get(c.name):
raise HTTPException(409, f"Busy: {busy_ops[c.name]}")
if fetch_pending.get(c.name):
raise HTTPException(409, "Already waiting for the server to come online to fetch mod info.")
if c.status == "running" and _check_ready(c):
_start_fetch(c.name)
return {"ok": True}
if not start:
raise HTTPException(400, "Start the server (and wait until it's online) to download mods and read their info.")
if c.status != "running":
server_action(c.id, "start") # memory check, and applies saved changes by recreating the container
fetch_pending[c.name] = time.time()
threading.Thread(target=_fetch_when_ready, args=(c.name,), daemon=True).start()
return {"ok": True, "started": True}
@app.put("/api/servers/{cid}/mods", dependencies=[Depends(require_auth)])
async def save_mods(cid: str, request: Request):
c = _zomboid(cid)
if busy_ops.get(c.name):
raise HTTPException(409, f"Busy: {busy_ops[c.name]}")
body = await request.json()
ids = [str(i) for i in body.get("workshop_ids", [])]
mods = [str(m).strip().lstrip("\\") for m in body.get("mods", [])]
if not all(re.fullmatch(r"\d{6,12}", i) for i in ids):
raise HTTPException(400, "Workshop IDs must be numbers")
bad = [m for m in mods if not zomboid.MOD_ID_RE.match(m)]
if bad:
raise HTTPException(400, f"Invalid mod ID: {bad[0]!r}")
cfg = _load_cfg(c.name)
cfg.update(workshop_ids=list(dict.fromkeys(ids)), mods=list(dict.fromkeys(mods)),
auto_update=bool(body.get("auto_update", True)), dirty=True)
_save_cfg(c.name, cfg)
if body.get("apply") == "now":
busy_ops[c.name] = "Applying mod changes…"
threading.Thread(target=_apply_now, args=(c.name,), daemon=True).start()
return get_mods(c.id)
def _console(c, *args):
return c.exec_run(["console", *args]).exit_code == 0
def _apply_now(cname):
"""Warn players, then restart with the new mod list. With nobody online, restart at once."""
try:
c = client.containers.get(cname)
if c.status == "running" and _check_ready(c):
_console(c, "players")
time.sleep(3)
players = zomboid.player_count(c.logs(tail=200).decode(errors="replace"))
if players:
_console(c, "servermsg", "Server restarting in 60 seconds to apply mod changes.")
for left in range(60, 0, -1):
busy_ops[cname] = f"Restarting in {left}s ({players} online)…"
if left == 10:
_console(c, "servermsg", "Server restarting in 10 seconds.")
time.sleep(1)
busy_ops[cname] = "Restarting with new mods…"
c.reload()
_recreate_zomboid(c, start=c.status in ("running", "restarting"))
except Exception as e:
print("apply mods failed:", e, flush=True)
finally:
busy_ops.pop(cname, None)