"""World backups, stored as zips under DATA_DIR/backups///. 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. /.current names the backup ("/") 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}