Make backup and restore reliable, and keep NFS out of them (0.64.0)
A review of the backup path found several ways a backup was not one, and a restore could destroy data it did not contain. Data loss: - Restore with overwrite rmtree'd the whole stack directory, including folders the backup had left out (over 2 GiB, deselected, an NFS share mounted inside). It now clears only what the backup holds, keeps the excluded paths (recorded in the manifest) and never crosses into another filesystem. - The stack was only stopped when named volumes were selected, so data folders inside the stack directory were archived while in use. Any selected data now stops it. - Retention matched by prefix: pruning "app" deleted "app-db"'s backups. It now matches backup-<id>-(full|config)-<date>.tar.gz exactly. - A restore under a new name wrote into the original's volumes when they had an explicit name, and into its folders outside the stack directory. Both are skipped now; a volume owned by another stack or mounted by a running container is never overwritten. - A truncated archive was only noticed after the old stack was gone. The whole archive is verified first, and the stack directory is unpacked next to the old one and swapped in. Remote storage: - Bind folders on a mounted share (fstab/autofs), bind-type volumes pointing at one and shares mounted inside the stack folder are detected by filesystem type and not selected; a folder du cannot measure in 20s is no longer selected by default either. Reliability: - After a backup exactly the containers that ran are started again with compose start (falling back to the Docker API), instead of up -d, which started services stopped on purpose and applied undeployed edits. A stack that cannot be stopped is not backed up. - Backup and restore hold the stack lock; a scheduled backup that finds the stack busy retries after 10 minutes. Restore stops the stack while replacing its data and brings it back up. - external: true volumes are backed up; anonymous ones are listed, not selected. Restored volumes get their original driver and options. - A backup with uncaptured data or a stack that did not restart is reported as incomplete: in the dialog, and for schedules as a warning with a notification and without rotating older backups out. - Archive writing and restore run off the event loop; downloads delete their temp file; helper containers use the long-timeout client; S3 listing is paginated; a file changing mid-read no longer corrupts the archive. Manifest format 3 records compose_binds/excluded and volume driver/options/external; format 1/2 backups still restore. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
ee98d0da6d
commit
8f0a01c4f5
12 files changed
+1938
-276
No files matched your search
+28
-10
@@ -8,6 +8,7 @@ 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
|
||||
from sqlmodel import Session
|
||||
|
||||
@@ -41,15 +42,32 @@ def _compact(report: dict) -> dict:
|
||||
"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"),
|
||||
}
|
||||
|
||||
|
||||
def _summary(report: dict) -> str:
|
||||
return (
|
||||
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 or already exists, 400 for the rest.
|
||||
conflict = isinstance(exc, backup_service.StackBusyError) or "already exists" in str(exc)
|
||||
return HTTPException(status_code=409 if conflict else 400, detail=str(exc))
|
||||
|
||||
|
||||
@router.get("/{stack_id}/backup/inventory")
|
||||
@@ -88,7 +106,7 @@ async def backup_stack(
|
||||
binds=binds, volumes=volumes,
|
||||
)
|
||||
except backup_service.BackupError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from 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),
|
||||
@@ -100,6 +118,9 @@ async def backup_stack(
|
||||
# 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": json.dumps(_compact(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),
|
||||
)
|
||||
|
||||
|
||||
@@ -122,7 +143,7 @@ async def restore_stack(
|
||||
|
||||
target = compose_service.slugify(target_id) if target_id else None
|
||||
try:
|
||||
result = backup_service.restore_backup(
|
||||
result = await backup_service.restore(
|
||||
tmp.name,
|
||||
target_id=target,
|
||||
overwrite=overwrite,
|
||||
@@ -130,9 +151,7 @@ async def restore_stack(
|
||||
restore_binds=restore_binds,
|
||||
)
|
||||
except backup_service.BackupError as exc:
|
||||
# 409 for the "already exists" conflict, 400 for malformed backups.
|
||||
code = 409 if "already exists" in str(exc) else 400
|
||||
raise HTTPException(status_code=code, detail=str(exc)) from exc
|
||||
raise _backup_http_error(exc) from exc
|
||||
|
||||
stack_id = result["stack_id"]
|
||||
stack = session.get(Stack, stack_id)
|
||||
@@ -199,7 +218,7 @@ async def push_backup(
|
||||
include_binds=body.include_binds, binds=body.binds, volumes=body.volumes,
|
||||
)
|
||||
except backup_service.BackupError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
raise _backup_http_error(exc) from exc
|
||||
|
||||
filename = _backup_filename(stack_id, body.include_volumes)
|
||||
try:
|
||||
@@ -238,14 +257,13 @@ async def restore_from_destination(
|
||||
|
||||
target = compose_service.slugify(body.target_id) if body.target_id else None
|
||||
try:
|
||||
result = backup_service.restore_backup(
|
||||
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:
|
||||
code = 409 if "already exists" in str(exc) else 400
|
||||
raise HTTPException(status_code=code, detail=str(exc)) from exc
|
||||
raise _backup_http_error(exc) from exc
|
||||
|
||||
stack_id = result["stack_id"]
|
||||
if not session.get(Stack, stack_id):
|
||||
|
||||
Reference in new issue
Block a user