game-servers/app/backups.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

119 lines
5.3 KiB
Python

"""World backups, stored as zips under DATA_DIR/backups/<game>/<auto|manual>/.
Each zip has a .json sidecar with what the list page shows. Backups live outside the server's own
folder so they survive deleting a server together with its files.
<game>/<container>.current names the backup ("<kind>/<zip name>") that holds the server's world as it is
now: set by each automatic backup and by a rollback. If that backup has been pruned, none is current.
Without the file, the newest automatic backup is current.
"""
import json
import os
import re
import tempfile
import time
import zipfile
from pathlib import Path
KINDS = ("auto", "manual")
KEEP = 5 # newest backups kept per server and kind
NAME_RE = re.compile(r"^[a-z0-9-]+__\d{8}-\d{6}\.zip$")
class Backups:
def __init__(self, data_dir):
self.root = Path(data_dir) / "backups"
def create(self, game, kind, cname, files, meta):
"""Zip `files` ([(path, name in zip)]) as a new backup and prune old ones. Returns its metadata."""
assert kind in KINDS
folder = self.root / game / kind
folder.mkdir(parents=True, exist_ok=True)
stamp = time.strftime("%Y%m%d-%H%M%S", time.gmtime())
zpath = folder / f"{cname}__{stamp}.zip"
fd, tmp = tempfile.mkstemp(suffix=".tmp", dir=folder)
try:
with os.fdopen(fd, "wb") as f, zipfile.ZipFile(f, "w", zipfile.ZIP_DEFLATED) as z:
for path, arcname in files:
z.write(path, arcname)
os.replace(tmp, zpath) # never list a half-written zip
except BaseException:
os.unlink(tmp)
raise
meta = {**meta, "game": game, "type": kind, "container": cname,
"created": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "size": zpath.stat().st_size}
zpath.with_suffix(".json").write_text(json.dumps(meta))
bid = f"{game}/{kind}/{zpath.name}"
if kind == "auto": # taken when a run ends, so it is the world as it is now
self.set_current(game, cname, bid)
self._prune(folder, cname)
return {**meta, "id": bid}
def _current_path(self, game, cname):
return self.root / game / f"{cname}.current"
def current(self, game, cname):
"""Id of the backup holding the server's world as it is now (see the module docstring), or None."""
try:
ref = self._current_path(game, cname).read_text().strip()
except OSError:
zips = sorted((self.root / game / "auto").glob(f"{cname}__*.zip"), reverse=True)
return f"{game}/auto/{zips[0].name}" if zips else None
if not ref:
return None
kind, _, name = ref.partition("/")
return f"{game}/{ref}" if self.path(game, kind, name) else None # pruned: nothing is current
def set_current(self, game, cname, bid):
p = self._current_path(game, cname)
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text(bid.split("/", 1)[1] if bid else "")
def _prune(self, folder, cname):
zips = sorted(folder.glob(f"{cname}__*.zip"), reverse=True) # names sort by time
for old in zips[KEEP:]:
old.unlink(missing_ok=True)
old.with_suffix(".json").unlink(missing_ok=True)
def list(self):
out = []
for zpath in self.root.glob("*/*/*.zip"):
game, kind = zpath.parent.parent.name, zpath.parent.name
try:
meta = json.loads(zpath.with_suffix(".json").read_text())
except (OSError, ValueError):
meta = {"container": zpath.name.split("__")[0], "size": zpath.stat().st_size}
out.append({**meta, "game": game, "type": kind, "id": f"{game}/{kind}/{zpath.name}"})
return sorted(out, key=lambda b: b["id"].rsplit("__", 1)[-1], reverse=True)
def path(self, game, kind, name):
"""The zip for a backup id, or None if the id isn't a valid existing backup."""
if kind not in KINDS or not re.fullmatch(r"[a-z0-9]+", game) or not NAME_RE.match(name):
return None
p = self.root / game / kind / name
return p if p.is_file() else None
def promote(self, zpath):
"""Move an automatic backup into the manual list (so newer auto backups can't prune it)."""
game, cname = zpath.parent.parent.name, zpath.name.split("__")[0]
folder = self.root / game / "manual"
folder.mkdir(parents=True, exist_ok=True)
try:
meta = json.loads(zpath.with_suffix(".json").read_text())
except (OSError, ValueError):
meta = {"container": cname, "size": zpath.stat().st_size}
meta.update(type="manual", promoted=time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()))
# Named by promotion time: pruning keeps the newest names, and this is the newest manual backup.
t = time.time()
while (dest := folder / f"{cname}__{time.strftime('%Y%m%d-%H%M%S', time.gmtime(t))}.zip").exists():
t += 1
was_current = self.current(game, cname) == f"{game}/auto/{zpath.name}"
os.replace(zpath, dest)
dest.with_suffix(".json").write_text(json.dumps(meta))
zpath.with_suffix(".json").unlink(missing_ok=True)
bid = f"{game}/manual/{dest.name}"
if was_current:
self.set_current(game, cname, bid)
self._prune(folder, cname)
return {**meta, "id": bid}