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:
neil 2026-11-02 22:53:25 -08:00
parent 87b92f8332
commit 51db28f3d5
No known key found for this signature in database
5 changed files with 429 additions and 12 deletions

View file

@ -10,6 +10,7 @@ import re
import secrets import secrets
import shutil import shutil
import socket import socket
import tempfile
import threading import threading
import time import time
import zipfile import zipfile
@ -314,16 +315,19 @@ def _session_notes(c, pending):
def _auto_backup_check(new_stats): def _auto_backup_check(new_stats):
for c in client.containers.list(all=True, filters={"label": LABEL}): 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 continue
started = c.attrs.get("State", {}).get("StartedAt") started = c.attrs.get("State", {}).get("StartedAt")
running = c.status == "running" running = c.status == "running"
pending = _read_pending(c.name) pending = _read_pending(c.name)
if pending and (not running or pending["started"] != started): 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) _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() threading.Thread(target=_auto_backup, args=(c, _session_notes(c, pending)), daemon=True).start()
continue continue
if busy_ops.get(c.name):
continue
online = len((new_stats.get(c.id) or {}).get("players") or []) online = len((new_stats.get(c.id) or {}).get("players") or [])
if running and online and (not pending or online > pending.get("peak", 0)): if running and online and (not pending or online > pending.get("peak", 0)):
_write_pending(c.name, {"started": started, "peak": online}) _write_pending(c.name, {"started": started, "peak": online})
@ -475,6 +479,7 @@ def _server_info(c):
"created": l.get("gsm.created"), "created": l.get("gsm.created"),
"summary": _summary(c), "summary": _summary(c),
"busy": busy_ops.get(c.name), "busy": busy_ops.get(c.name),
"backup_pending": _pending_path(c.name).exists(),
"last_online": _last_online(c) if c.status != "running" else None, "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. # Long-running operations per container name, e.g. "Restarting in 60s…", shown on the server card.
busy_ops: dict = {} 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): def _cfg_path(cname):
@ -890,6 +905,137 @@ async def create_server(
return _server_info(c) 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)]) @app.post("/api/servers/{cid}/{action}", dependencies=[Depends(require_auth)])
def server_action(cid: str, action: str): def server_action(cid: str, action: str):
c = _get(cid) c = _get(cid)
@ -919,10 +1065,10 @@ def server_action(cid: str, action: str):
def delete_server(cid: str, delete_data: bool = False): def delete_server(cid: str, delete_data: bool = False):
c = _get(cid) c = _get(cid)
name = c.name name = c.name
if busy_ops.get(name):
raise HTTPException(409, f"Busy: {busy_ops[name]}")
_require_no_players(c, "Delete") _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: try:
if c.status == "running": if c.status == "running":
c.stop(timeout=120) c.stop(timeout=120)
@ -1097,12 +1243,12 @@ def _backup_files(c):
raise HTTPException(400, "Backups are not supported for this game") 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 l = c.labels
game = l.get("gsm.game") game = l.get("gsm.game")
return backups.create(game, kind, c.name, _backup_files(c), { 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"), "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 = {**_session_notes(c, pending), "running": True}
session["peak"] = max(session["peak"], online) session["peak"] = max(session["peak"], online)
b = _make_backup(c, "manual", session) 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"]) 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" filename = f"{label}_{time.strftime('%Y-%m-%d', time.gmtime())}.zip"
return FileResponse(backups.path(*b["id"].split("/")), media_type="application/zip", filename=filename) 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)]) @app.get("/api/backups", dependencies=[Depends(require_auth)])
def list_backups(): def list_backups():
games = [{"id": k, "name": g["name"]} for k, g in GAMES.items() if g.get("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)]) @app.get("/api/backups/{game}/{kind}/{name}", dependencies=[Depends(require_auth)])

View file

@ -2,6 +2,10 @@
Each zip has a .json sidecar with what the list page shows. Backups live outside the server's own 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. 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 json
@ -40,8 +44,31 @@ class Backups:
meta = {**meta, "game": game, "type": kind, "container": cname, meta = {**meta, "game": game, "type": kind, "container": cname,
"created": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "size": zpath.stat().st_size} "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)) 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) self._prune(folder, cname)
return {**meta, "id": f"{game}/{kind}/{zpath.name}"} 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): def _prune(self, folder, cname):
zips = sorted(folder.glob(f"{cname}__*.zip"), reverse=True) # names sort by time zips = sorted(folder.glob(f"{cname}__*.zip"), reverse=True) # names sort by time
@ -66,3 +93,27 @@ class Backups:
return None return None
p = self.root / game / kind / name p = self.root / game / kind / name
return p if p.is_file() else None 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}

View file

@ -240,6 +240,25 @@ function applyManageGuard() {
btn.disabled = !!why; btn.disabled = !!why;
$(`#${id}-tip`).title = why; $(`#${id}-tip`).title = why;
} }
const why = rollbackBlockReason();
for (const btn of document.querySelectorAll('#rollback-list .rollback-btn')) {
btn.disabled = rollingBack || !!why;
btn.parentElement.title = rollingBack ? '' : why;
}
if ($('#rollback-dialog').open && !rollingBack) {
$('#rollback-confirm').disabled = !!why;
$('#rollback-blocked').textContent = why;
$('#rollback-blocked').classList.toggle('hidden', !why);
}
// An automatic backup (or another job) just finished: show the new list.
const s = servers.find((x) => x.id === managed?.id);
const busyNow = !!(s?.busy || busy.has(managed?.id));
// Players joining (the world moves past every backup) changes which backup is current too.
const pendingNow = !!s?.backup_pending;
if (((managedWasBusy && !busyNow) || pendingNow !== managedWasPending) && !rollingBack
&& !$('#rollback-section').classList.contains('hidden')) loadRollbackList();
managedWasBusy = busyNow;
managedWasPending = pendingNow;
} }
// Official Steam library art, stored in static/art/ (<game>-poster.jpg 300x450, <game>-header.jpg 460x215). // Official Steam library art, stored in static/art/ (<game>-poster.jpg 300x450, <game>-header.jpg 460x215).
@ -348,11 +367,16 @@ async function openManage(s) {
$('#settings-error').textContent = ''; $('#settings-error').textContent = '';
$('#delete-data').checked = false; $('#delete-data').checked = false;
$('#autostop-error').textContent = ''; $('#autostop-error').textContent = '';
$('#rollback-section').classList.add('hidden');
$('#rollback-list').innerHTML = '';
$('#rollback-messages').innerHTML = '';
renderPlayers(); renderPlayers();
$('#settings-fields').innerHTML = '<p class="muted small">Loading…</p>'; $('#settings-fields').innerHTML = '<p class="muted small">Loading…</p>';
$('#manage-dialog').showModal(); $('#manage-dialog').showModal();
try { try {
const { fields, values, backups, mods, auto_stop } = await api(`/api/servers/${s.id}/settings`); const { fields, values, backups, mods, auto_stop } = await api(`/api/servers/${s.id}/settings`);
$('#rollback-section').classList.toggle('hidden', !backups);
if (backups) loadRollbackList();
$('#autostop-enabled').checked = auto_stop.enabled; $('#autostop-enabled').checked = auto_stop.enabled;
$('#autostop-minutes').value = auto_stop.minutes; $('#autostop-minutes').value = auto_stop.minutes;
$('#mods-section').classList.toggle('hidden', !mods); $('#mods-section').classList.toggle('hidden', !mods);
@ -428,6 +452,151 @@ $('#world-download').addEventListener('click', async (e) => {
delete a.dataset.busy; a.textContent = 'Download'; delete a.dataset.busy; a.textContent = 'Download';
}); });
// ---------- rollback (manage dialog) ----------
let serverBackups = { auto: [], manual: [], keep: 5 }; // the managed server's backups, newest first
let managedWasBusy = false;
let managedWasPending = false;
let currentBackupId = null; // the backup holding the managed server's world as it is now
let rollbackTarget = null;
let rollingBack = false;
// Rolling back is only allowed while the server is stopped and nothing else (an automatic backup,
// a start, a delete...) is running on it; the server checks this too.
function rollbackBlockReason() {
const s = servers.find((x) => x.id === managed?.id) || managed;
if (!s) return '';
if (s.busy) return `Rolling back is disabled while this runs: ${s.busy}`;
if (busy.has(s.id)) return 'Rolling back is disabled while another action on this server finishes.';
if (!['exited', 'created'].includes(s.state)) return 'Stop the server before rolling back.';
return '';
}
const fmtWhen = (iso) => (iso ? new Date(iso).toLocaleString() : 'unknown time');
async function loadRollbackList() {
const s = managed;
let data;
try { data = await api('/api/backups'); } catch (err) {
$('#rollback-list').innerHTML = `<p class="error">${esc(err.message)}</p>`;
return;
}
if (managed !== s) return;
const mine = data.backups.filter((b) => b.container === s.container);
serverBackups = { auto: mine.filter((b) => b.type === 'auto'), manual: mine.filter((b) => b.type === 'manual'), keep: data.keep };
currentBackupId = data.current?.[s.container] || null;
if (!mine.length) {
$('#rollback-list').innerHTML = '<p class="muted small" style="margin:0">This server has no backups yet. See <b>About Backups</b> on the Backups page for when they are made.</p>';
return;
}
$('#rollback-list').innerHTML = BACKUP_KINDS.map(([kind, label]) => {
const rows = serverBackups[kind];
if (!rows.length) return '';
return `<div class="backup-kind">
<h4>${label} <span class="muted small">${rows.length} of ${data.keep} kept</span></h4>
<table class="backups-table">
<tr><th>Created</th><th>Session notes</th><th></th></tr>
${rows.map((b) => `<tr>
<td>${esc(fmtWhen(b.created))}</td>
<td class="muted">${esc(sessionNotes(b))}</td>
<td class="row-end">${b.id === currentBackupId
? '<span class="tip" title="The server\'s world is this backup, so rolling back to it would change nothing."><button class="small" disabled>Current</button></span>'
: `<span class="tip"><button class="small rollback-btn" data-id="${esc(b.id)}">Roll back</button></span>`}</td>
</tr>`).join('')}
</table>
</div>`;
}).join('');
applyManageGuard();
}
$('#rollback-list').addEventListener('click', (e) => {
const btn = e.target.closest('.rollback-btn');
if (!btn) return;
const b = [...serverBackups.auto, ...serverBackups.manual].find((x) => x.id === btn.dataset.id);
if (b) openRollback(b);
});
function openRollback(b) {
rollbackTarget = b;
const s = servers.find((x) => x.id === managed.id) || managed;
const backupPending = !!s.backup_pending; // players were on since the last automatic backup
const kindLabel = b.type === 'auto' ? 'automatic' : 'manual';
$('#rollback-title').textContent = `Roll back ${s.server_name}?`;
$('#rollback-what').innerHTML = `The current world is replaced with the ${kindLabel} backup from <b>${esc(fmtWhen(b.created))}</b>`
+ ` <span class="muted">(${esc(sessionNotes(b))})</span>.`;
// Auto: offer to keep the world being rolled back from as a manual backup. That's the current
// backup if it's automatic, the backup of the run players were just on, or a fresh manual backup
// when no backup holds it. A manual current backup is kept already.
const cur = [...serverBackups.auto, ...serverBackups.manual].find((x) => x.id === currentBackupId);
const alreadyKept = b.type === 'auto' && !backupPending && cur?.type === 'manual';
const canPromote = b.type === 'auto' && !alreadyKept;
$('#rollback-promote').classList.toggle('hidden', !canPromote);
const keptNote = $('#rollback-kept-note');
keptNote.classList.toggle('hidden', !alreadyKept);
if (alreadyKept) {
keptNote.textContent = `The world you're rolling back from is already kept as the manual backup from ${fmtWhen(cur.created)}.`;
}
if (canPromote) {
$('#rollback-promote-check').checked = true;
const keep = ', so you can return to the point you rolled back from without newer automatic backups pushing it out.';
$('#rollback-promote-help').textContent = backupPending
? `Players were on since the last automatic backup, so the current world is backed up first and that backup is moved to the manual backups${keep}`
: cur
? `The current world's backup (automatic, from ${fmtWhen(cur.created)}) is moved to the manual backups${keep}`
: `No backup holds the current world, so a manual backup of it is made${keep}`;
const manual = serverBackups.manual;
const full = manual.length >= serverBackups.keep;
$('#rollback-promote-full').classList.toggle('hidden', !full);
if (full) {
$('#rollback-promote-full').textContent = `There are already ${manual.length} manual backups, so this pushes the`
+ ` oldest one (from ${fmtWhen(manual[manual.length - 1].created)}) out of the list.`;
}
}
$('#rollback-running').textContent = 'The server stays stopped; start it when you\'re ready. '
+ (backupPending && !canPromote ? 'Players were on since the last automatic backup, so the current world is backed up automatically first.' : '');
$('#rollback-confirm').textContent = 'Roll back';
$('#rollback-error').textContent = '';
applyManageGuard(); // sets the confirm button and the reason it's disabled, if any
$('#rollback-dialog').showModal();
}
$('#rollback-cancel').addEventListener('click', () => { if (!rollingBack) $('#rollback-dialog').close(); });
$('#rollback-dialog').addEventListener('cancel', (e) => { if (rollingBack) e.preventDefault(); });
$('#rollback-confirm').addEventListener('click', async () => {
const b = rollbackTarget;
const promote = !$('#rollback-promote').classList.contains('hidden') && $('#rollback-promote-check').checked;
const btn = $('#rollback-confirm');
btn.disabled = true; btn.textContent = 'Rolling back…';
$('#rollback-cancel').disabled = true;
$('#rollback-error').textContent = '';
$('#rollback-blocked').classList.add('hidden');
rollingBack = true;
const id = managed.id;
busy.add(id); renderServers(); applyManageGuard();
try {
const res = await api(`/api/servers/${id}/rollback`, {
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ id: b.id, promote }),
});
managed = res.server; // a Project Zomboid server with pending changes is recreated, so its id can change
$('#rollback-dialog').close();
let msg = `Rolled back to the ${b.type === 'auto' ? 'automatic' : 'manual'} backup from ${fmtWhen(b.created)}.`;
if (res.promoted) msg += ` The world you rolled back from (backup from ${fmtWhen(res.promoted.created)}) is now a manual backup.`;
$('#rollback-messages').innerHTML = `<div class="msg msg-success">${esc(msg)}</div>`;
} catch (err) {
$('#rollback-error').textContent = err.message;
btn.textContent = 'Roll back';
btn.disabled = false;
} finally {
busy.delete(id);
rollingBack = false;
$('#rollback-cancel').disabled = false;
loadRollbackList();
refresh();
}
});
$('#manage-logs').addEventListener('click', () => openLogs(managed)); $('#manage-logs').addEventListener('click', () => openLogs(managed));
$('#open-mods').addEventListener('click', () => openMods(managed)); $('#open-mods').addEventListener('click', () => openMods(managed));
@ -498,7 +667,9 @@ const BACKUP_KINDS = [['auto', 'Automatic'], ['manual', 'Manual']];
function sessionNotes(b) { function sessionNotes(b) {
const sn = b.session; const sn = b.session;
if (!sn) return b.type === 'manual' && 'session' in b ? 'Server was stopped' : '–'; const promoted = b.promoted ? 'Kept from a rollback' : '';
if (!sn) return promoted || (b.type === 'manual' && 'session' in b ? 'Server was stopped' : '–');
if (promoted) return `${promoted} · ${fmtDuration(sn.length)} session · peak ${sn.peak} player${sn.peak === 1 ? '' : 's'}`;
const peak = `peak ${sn.peak} player${sn.peak === 1 ? '' : 's'}`; const peak = `peak ${sn.peak} player${sn.peak === 1 ? '' : 's'}`;
return sn.running ? `${fmtDuration(sn.length)} into a running session · ${peak}` : `${fmtDuration(sn.length)} session · ${peak}`; return sn.running ? `${fmtDuration(sn.length)} into a running session · ${peak}` : `${fmtDuration(sn.length)} session · ${peak}`;
} }
@ -506,7 +677,7 @@ function sessionNotes(b) {
async function loadBackups() { async function loadBackups() {
let data; let data;
try { data = await api('/api/backups'); } catch (e) { return; } try { data = await api('/api/backups'); } catch (e) { return; }
const { backups, keep } = data; const { backups, keep, current } = data;
// One card per server, ordered by its newest backup (the list arrives newest first). // One card per server, ordered by its newest backup (the list arrives newest first).
const byServer = new Map(); const byServer = new Map();
for (const b of backups) { for (const b of backups) {
@ -525,7 +696,8 @@ async function loadBackups() {
<table class="backups-table"> <table class="backups-table">
<tr><th>Created</th><th>Session notes</th><th>Size</th><th></th></tr> <tr><th>Created</th><th>Session notes</th><th>Size</th><th></th></tr>
${rows.map((b) => `<tr> ${rows.map((b) => `<tr>
<td>${b.created ? esc(new Date(b.created).toLocaleString()) : ''}</td> <td>${b.created ? esc(new Date(b.created).toLocaleString()) : ''}${current?.[b.container] === b.id
? ' <span class="current-tag" title="Holds the server\'s world as it is now">Current</span>' : ''}</td>
<td class="muted">${esc(sessionNotes(b))}</td> <td class="muted">${esc(sessionNotes(b))}</td>
<td>${fmtBytes(b.size)}</td> <td>${fmtBytes(b.size)}</td>
<td class="row-end"><a class="button ghost small" href="/api/backups/${b.id.split('/').map(encodeURIComponent).join('/')}" download>Download</a></td> <td class="row-end"><a class="button ghost small" href="/api/backups/${b.id.split('/').map(encodeURIComponent).join('/')}" download>Download</a></td>

View file

@ -97,6 +97,17 @@
<li>While the server is running this is its last autosave (Valheim saves about every 30 minutes). Stop the <li>While the server is running this is its last autosave (Valheim saves about every 30 minutes). Stop the
server first for an up-to-the-minute copy.</li> server first for an up-to-the-minute copy.</li>
</ul> </ul>
<h3>Rolling back</h3>
<ul class="about-list">
<li>Use the <b>Backup</b> section of a server's Manage panel to replace its world with one of its backups.
The server must be stopped, and rolling back waits until any automatic backup in progress has finished.</li>
<li>If players were on since the last automatic backup, that world is backed up automatically first.</li>
<li>Rolling back to an <b>automatic</b> backup can keep the world you roll back from (the <b>Current</b> backup)
as a manual backup, so you can return to it later without newer automatic backups pushing it out.</li>
<li>The backup marked <b>Current</b> holds the server's world as it is now, so it can't be rolled back to. That's
the newest automatic backup, or the backup last rolled back to. Once players join, the world moves past every
backup and nothing is marked Current until the next automatic backup.</li>
</ul>
<h3>Retention</h3> <h3>Retention</h3>
<ul class="about-list"> <ul class="about-list">
<li>The newest <b>5 automatic</b> and newest <b>5 manual</b> backups are kept for each server. Older ones are <li>The newest <b>5 automatic</b> and newest <b>5 manual</b> backups are kept for each server. Older ones are
@ -237,6 +248,14 @@
</div> </div>
</div> </div>
<div class="manage-section hidden" id="rollback-section">
<h3>Backup</h3>
<p class="muted small" style="margin-top:0">Roll the world back to one of this server's automatic or manual backups.
Stop the server first: rolling back is only available while it is stopped and no backup is being made.</p>
<div id="rollback-list"></div>
<div id="rollback-messages" class="msgs"></div>
</div>
<div class="manage-section"> <div class="manage-section">
<h3>Logs</h3> <h3>Logs</h3>
<div class="row-between"><span class="muted small">Live, color-coded output from the game server.</span><button class="ghost" id="manage-logs">View logs</button></div> <div class="row-between"><span class="muted small">Live, color-coded output from the game server.</span><button class="ghost" id="manage-logs">View logs</button></div>
@ -249,6 +268,26 @@
</div> </div>
</dialog> </dialog>
<!-- Rollback confirmation -->
<dialog id="rollback-dialog">
<h2 style="margin-top:0" id="rollback-title">Roll back?</h2>
<p id="rollback-what"></p>
<div id="rollback-promote" class="hidden">
<label class="radio"><input type="checkbox" id="rollback-promote-check" checked> Keep the world I'm rolling back from as a manual backup</label>
<p class="muted small" id="rollback-promote-help"></p>
<p class="msg msg-warning hidden" id="rollback-promote-full"></p>
</div>
<p class="msg msg-info hidden" id="rollback-kept-note"></p>
<p class="muted small" id="rollback-running"></p>
<p class="msg msg-warning hidden" id="rollback-blocked"></p>
<p class="error" id="rollback-error"></p>
<div class="wiz-actions">
<button type="button" class="ghost" id="rollback-cancel">Cancel</button>
<span class="spacer"></span>
<button type="button" class="danger" id="rollback-confirm">Roll back</button>
</div>
</dialog>
<!-- Mod manager (Project Zomboid) --> <!-- Mod manager (Project Zomboid) -->
<dialog id="mods-dialog" class="wide"> <dialog id="mods-dialog" class="wide">
<div class="logs-head"> <div class="logs-head">

View file

@ -69,6 +69,8 @@ header { display: flex; justify-content: space-between; align-items: center; gap
.backups-table th { text-align: left; color: var(--muted); font-weight: normal; padding: 0 8px 6px 0; } .backups-table th { text-align: left; color: var(--muted); font-weight: normal; padding: 0 8px 6px 0; }
.backups-table td { padding: 6px 8px 6px 0; border-top: 1px solid var(--border); vertical-align: middle; } .backups-table td { padding: 6px 8px 6px 0; border-top: 1px solid var(--border); vertical-align: middle; }
.backups-table a.button.small { padding: 4px 10px; font-size: 13px; } .backups-table a.button.small { padding: 4px 10px; font-size: 13px; }
.current-tag { display: inline-block; margin-left: 6px; padding: 1px 7px; border-radius: 999px; font-size: 11px;
color: var(--ok); border: 1px solid currentColor; vertical-align: 1px; }
#about-backups h3 { font-size: 15px; margin: 16px 0 6px; } #about-backups h3 { font-size: 15px; margin: 16px 0 6px; }
.about-list { margin: 0; padding-left: 20px; font-size: 14px; } .about-list { margin: 0; padding-left: 20px; font-size: 14px; }
.about-list li { margin: 4px 0; } .about-list li { margin: 4px 0; }