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>
This commit is contained in:
parent
87b92f8332
commit
51db28f3d5
5 changed files with 429 additions and 12 deletions
169
app/app.py
169
app/app.py
|
|
@ -10,6 +10,7 @@ import re
|
|||
import secrets
|
||||
import shutil
|
||||
import socket
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import zipfile
|
||||
|
|
@ -314,16 +315,19 @@ def _session_notes(c, pending):
|
|||
|
||||
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") or busy_ops.get(c.name):
|
||||
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)
|
||||
busy_ops[c.name] = "Backing up world…"
|
||||
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})
|
||||
|
|
@ -475,6 +479,7 @@ def _server_info(c):
|
|||
"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,
|
||||
}
|
||||
|
||||
|
|
@ -513,6 +518,16 @@ def _summary(c):
|
|||
|
||||
# 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):
|
||||
|
|
@ -890,6 +905,137 @@ async def create_server(
|
|||
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)
|
||||
|
|
@ -919,10 +1065,10 @@ def server_action(cid: str, action: str):
|
|||
def delete_server(cid: str, delete_data: bool = False):
|
||||
c = _get(cid)
|
||||
name = c.name
|
||||
if busy_ops.get(name):
|
||||
raise HTTPException(409, f"Busy: {busy_ops[name]}")
|
||||
_require_no_players(c, "Delete")
|
||||
busy_ops[name] = "Deleting…" # keeps the stats loop from backing up while files are removed
|
||||
# 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)
|
||||
|
|
@ -1097,12 +1243,12 @@ def _backup_files(c):
|
|||
raise HTTPException(400, "Backups are not supported for this game")
|
||||
|
||||
|
||||
def _make_backup(c, kind, session=None):
|
||||
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,
|
||||
"world": l.get("gsm.world") or None, "session": session, **(extra or {}),
|
||||
})
|
||||
|
||||
|
||||
|
|
@ -1122,6 +1268,8 @@ def download_world(cid: str):
|
|||
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)
|
||||
|
|
@ -1130,7 +1278,12 @@ def download_world(cid: str):
|
|||
@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")]
|
||||
return {"games": games, "backups": backups.list(), "keep": 5}
|
||||
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)])
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue