Files
stackpilot/backend/routers/backups.py
T
menzeljandClaude Opus 5.5 d6cebb3371
CI / check (push) Successful in 4m9s
CI / build-and-push (push) Failing after 16m10s
Fix what a review of the whole app found, end to end (0.67.1)
A pass over every feature against a real Docker daemon, then clicking
through the UI as admin and read-only user, on a desktop and a phone.

Security. /ws/deploy ran compose up for the read-only role; it is
admin-only now. A container's inspect view, a stack's compose file
(POSTGRES_PASSWORD: hunter2) and the viewer's .env tab no longer show
credentials to that role. Git branch and URL values that git would read
as options (-x, ext::) are refused. SFTP host keys are checked: pinned
on first use or entered by hand (key line or SHA256 fingerprint), a
different key is refused before the password is sent. A backup name
from the API can no longer reach outside the destination folder. The
file browser refuses to move or rename a browse root, as delete did.

Docker lifecycle. Closing the deploy console released the stack lock
while compose was still running and logged rc=None as success; deploys
and updates are now background runs that hold the lock to the end,
report the real exit code and can be re-attached to. Every closed log
view left a `compose logs -f` behind. A dozen open tabs exhausted the
default thread pool and hung the API; event and exec streams have their
own threads. Auto-update and the update endpoint ignored failed pulls.
A deleted git stack was recreated and started by the next webhook or
poll; deleting a stack now drops its git source, auto-update policy and
schedule entries. Deleting no longer walks into mounted shares, is
refused while a backup runs, and removes the containers even when the
compose file is broken. Stack folders compose has to normalise
(Nextcloud -> nextcloud) work everywhere and group correctly on the
volumes, networks and images pages.

Detection. Host port conflicts read the container's own network
namespace; /proc/1/net is read instead. Images referenced as docker.io/…
were never update-checked; local builds no longer report "needs
credentials". NVIDIA GPUs are read from the driver's procfs. The backup
dialog's "path mismatch" warning came from mountinfo's filesystem-relative
root and fired for any stacks folder on its own disk, ZFS dataset or
btrfs subvolume; the host path now comes from Docker's mounts.

Backups and destinations. The download ignored the folder/volume
selection (axios sent binds[]). Restoring under a new name kept the old
one. A report header past nginx's buffer turned a good backup into a
502. SFTP/S3 errors were bare 500s and "Test" did not try to write.
A destination used by a schedule could be deleted. Backup file names
are in the schedule's or the browser's time zone instead of UTC.

Editor and converter. `docker run` conversion produced invalid compose
for --network host, named volumes and -dit; --gpus and --mount were
dropped; a multi-line command pasted into the one-line field became
`image: ' '` (now a textarea, and flattened continuations are read).
Validation failed for env_file stacks. The editor overwrote unsaved
edits on every container event, lost them on a stray click (now asks),
threw when closing the diff, and its helper panel listed the starter
service "app" for every existing stack. Monaco is bundled instead of
loaded from jsdelivr, so the editor works offline (and monaco-editor
0.57 drops the dompurify advisory; axios and react-router updated).

UI. All times were two hours off: offset-less UTC from SQLite was read
as local time, and "next run" always said "just now". A token refresh
mid-session duplicated deploys, reset terminals and doubled logs. A
backend restart (update, self-update) signed everyone out on reload; the
page now waits for it. The editor was unusable on a phone, tables and
tabs overflowed, dialog text was black on the dark theme, and the file
browser opened on an error with the default roots. Read-only users get
"Admin only" pages instead of 403s; in-use networks offer no delete;
"Scan all" covers StackPilot's own stacks only and runs in the
background instead of timing out at 600s.

Deployment. nginx passes the port in Host (the OIDC redirect URI lost
:5009) and keeps an outer proxy's X-Forwarded-Proto. The frontend waits
for a healthy backend (healthcheck probes every 2s while starting). The
frontend image builds with npm ci. Secrets are 0644 in a 0700 folder so
non-root containers can read them; existing files are fixed at startup.
The test suite no longer starts real containers on a host with Docker.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Fx7gcuy8d6nPd95g43rGHu
2026-10-15 13:51:26 +02:00

304 lines
11 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Stack backup (incl. volumes) and restore."""
from __future__ import annotations
import asyncio
import json
import os
import tempfile
from fastapi import APIRouter, Depends, File, Form, HTTPException, Query, Request, UploadFile
from fastapi.responses import FileResponse
from starlette.background import BackgroundTask
from pydantic import BaseModel, Field
from sqlmodel import Session
from auth import require_admin
from database import get_session
from models.backup_destination import BackupDestination
from models.stack import Stack
from models.user import User
from services import (
audit_service,
backup_destination_service as dest_service,
backup_service,
compose_service,
)
router = APIRouter(prefix="/api/stacks", tags=["backups"])
def _ip(request: Request) -> str:
return request.client.host if request.client else "unknown"
_backup_filename = backup_service.backup_filename
def _compact(report: dict) -> dict:
"""The parts of a backup report worth showing the user."""
return {
"size": report.get("size"),
"binds": report.get("binds", []),
"volumes": report.get("volumes", []),
"skipped": report.get("skipped", []),
"path_mismatch": report.get("path_mismatch"),
"stopped": report.get("stopped", []),
"errors": report.get("errors", []),
# Capped: a busy log folder can produce a warning per file, and this
# travels in a response header for downloads.
"warnings": report.get("warnings", [])[:20],
"restart_error": report.get("restart_error"),
}
#: The report rides in a response header, which a proxy refuses past its
#: header buffer (nginx: 4–8 KiB by default, then a 502 for a backup that
#: worked). Lists are cut until it fits; the counts stay in the audit log.
MAX_REPORT_HEADER = 6 * 1024
def _report_header(report: dict) -> str:
compact = _compact(report)
text = json.dumps(compact)
for key in ("warnings", "skipped", "binds", "volumes", "errors"):
while len(text) > MAX_REPORT_HEADER and compact.get(key):
compact[key] = compact[key][: len(compact[key]) // 2]
compact["truncated"] = True
text = json.dumps(compact)
return text
def _summary(report: dict) -> str:
text = (
f"binds={len(report.get('binds', []))} "
f"volumes={len(report.get('volumes', []))} "
f"skipped={len(report.get('skipped', []))}"
)
if report.get("errors"):
text += f" errors={len(report['errors'])}"
if report.get("restart_error"):
text += " restart_failed"
return text
def _backup_http_error(exc: backup_service.BackupError) -> HTTPException:
# 409 for a stack that is busy, a backup somebody stopped, or a target that
# already exists; 400 for the rest.
conflict = isinstance(
exc, (backup_service.StackBusyError, backup_service.BackupCancelled)
) or "already exists" in str(exc)
return HTTPException(status_code=409 if conflict else 400, detail=str(exc))
@router.get("/{stack_id}/backup/inventory")
async def backup_inventory(
stack_id: str,
session: Session = Depends(get_session),
user: User = Depends(require_admin),
) -> dict:
"""What a backup of this stack would capture: bind-mount sources (with size
and whether they are reachable at all), named volumes, and anything that is
skipped by default with the reason why."""
if not session.get(Stack, stack_id):
raise HTTPException(status_code=404, detail=f"Stack '{stack_id}' not found")
return await asyncio.to_thread(backup_service.plan, stack_id)
@router.get("/{stack_id}/backup")
async def backup_stack(
stack_id: str,
request: Request,
include_volumes: bool = Query(True),
include_binds: bool = Query(True),
stop_first: bool = Query(True),
binds: list[str] | None = Query(None),
volumes: list[str] | None = Query(None),
# The browser's zone, for the time in the file name.
tz: str | None = Query(None, max_length=64),
session: Session = Depends(get_session),
user: User = Depends(require_admin),
):
stack = session.get(Stack, stack_id)
if not stack:
raise HTTPException(status_code=404, detail=f"Stack '{stack_id}' not found")
try:
path, report = await backup_service.create_backup_ex(
stack_id, stack.name, include_volumes=include_volumes,
stop_first=stop_first, include_binds=include_binds,
binds=binds, volumes=volumes,
)
except backup_service.BackupError as exc:
raise _backup_http_error(exc) from exc
audit_service.record(
session, user=user.username, action="stack.backup", target=stack_id,
detail=_summary(report), ip=_ip(request),
)
return FileResponse(
path,
media_type="application/gzip",
filename=_backup_filename(stack_id, include_volumes, tz=tz),
# The browser downloads a blob, so the summary of what actually made it
# into the archive rides along in a header.
headers={"X-Stackpilot-Backup": _report_header(report)},
# The archive is a temp file; without this every download stayed in
# the container's /tmp until it filled the disk.
background=BackgroundTask(os.unlink, path),
)
@router.post("/restore")
async def restore_stack(
request: Request,
file: UploadFile = File(...),
target_id: str | None = Form(None),
overwrite: bool = Form(False),
restore_volumes: bool = Form(True),
restore_binds: bool = Form(True),
session: Session = Depends(get_session),
user: User = Depends(require_admin),
) -> dict:
tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".tar.gz")
try:
while chunk := await file.read(1024 * 1024):
tmp.write(chunk)
tmp.close()
target = compose_service.slugify(target_id) if target_id else None
try:
result = await backup_service.restore(
tmp.name,
target_id=target,
overwrite=overwrite,
restore_volumes=restore_volumes,
restore_binds=restore_binds,
)
except backup_service.BackupError as exc:
raise _backup_http_error(exc) from exc
stack_id = result["stack_id"]
stack = session.get(Stack, stack_id)
if not stack:
session.add(Stack(id=stack_id, name=result.get("name", stack_id)))
session.commit()
audit_service.record(
session, user=user.username, action="stack.restore", target=stack_id,
detail=f"volumes={result['volumes_restored']} binds={result['binds_restored']}",
ip=_ip(request),
)
return result
finally:
if os.path.exists(tmp.name):
os.unlink(tmp.name)
# --------------------------------------------------------------------------- #
# Push to / restore from a remote destination
# --------------------------------------------------------------------------- #
class PushBody(BaseModel):
destination_id: int
include_volumes: bool = True
include_binds: bool = True
stop_first: bool = True
binds: list[str] | None = None
volumes: list[str] | None = None
#: The browser's zone, for the time in the file name.
tz: str | None = Field(None, max_length=64)
class RestoreFromBody(BaseModel):
destination_id: int
name: str
target_id: str | None = None
overwrite: bool = False
restore_volumes: bool = True
restore_binds: bool = True
def _get_dest(session: Session, dest_id: int) -> BackupDestination:
d = session.get(BackupDestination, dest_id)
if not d:
raise HTTPException(status_code=404, detail=f"Destination {dest_id} not found")
return d
@router.post("/{stack_id}/backup/push")
async def push_backup(
stack_id: str,
body: PushBody,
request: Request,
session: Session = Depends(get_session),
user: User = Depends(require_admin),
) -> dict:
stack = session.get(Stack, stack_id)
if not stack:
raise HTTPException(status_code=404, detail=f"Stack '{stack_id}' not found")
dest = _get_dest(session, body.destination_id)
try:
path, report = await backup_service.create_backup_ex(
stack_id, stack.name,
include_volumes=body.include_volumes, stop_first=body.stop_first,
include_binds=body.include_binds, binds=body.binds, volumes=body.volumes,
)
except backup_service.BackupError as exc:
raise _backup_http_error(exc) from exc
filename = _backup_filename(stack_id, body.include_volumes, tz=body.tz)
try:
remote = await asyncio.to_thread(dest_service.upload, dest, path, filename)
except dest_service.DestinationError as exc:
raise HTTPException(status_code=502, detail=str(exc)) from exc
finally:
if os.path.exists(path):
os.unlink(path)
audit_service.record(
session, user=user.username, action="stack.backup.push",
target=stack_id, detail=f"{dest.name}:{filename} {_summary(report)}", ip=_ip(request),
)
return {
"ok": True, "destination": dest.name, "name": filename,
"remote": remote, "report": _compact(report),
}
@router.post("/restore-from")
async def restore_from_destination(
body: RestoreFromBody,
request: Request,
session: Session = Depends(get_session),
user: User = Depends(require_admin),
) -> dict:
dest = _get_dest(session, body.destination_id)
tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".tar.gz")
tmp.close()
try:
try:
await asyncio.to_thread(dest_service.download, dest, body.name, tmp.name)
except dest_service.DestinationError as exc:
raise HTTPException(status_code=502, detail=str(exc)) from exc
target = compose_service.slugify(body.target_id) if body.target_id else None
try:
result = await backup_service.restore(
tmp.name, target_id=target,
overwrite=body.overwrite, restore_volumes=body.restore_volumes,
restore_binds=body.restore_binds,
)
except backup_service.BackupError as exc:
raise _backup_http_error(exc) from exc
stack_id = result["stack_id"]
if not session.get(Stack, stack_id):
session.add(Stack(id=stack_id, name=result.get("name", stack_id)))
session.commit()
audit_service.record(
session, user=user.username, action="stack.restore",
target=stack_id, detail=f"from {dest.name}:{body.name}", ip=_ip(request),
)
return result
finally:
if os.path.exists(tmp.name):
os.unlink(tmp.name)