Phase 8: back up & restore remote (agent) stacks (0.8.0)

- Agent: GET /agent/stacks/{id}/backup + POST /agent/stacks/restore (reuse
  backup_service). backup_service gains backup_basename/backup_filename helpers.
- Main proxy streams agent <-> main <-> destination (creds stay central):
  agent_service download_to_file/upload_file; routers/agents.py backup download,
  backup/push, restore upload, restore-from.
- Schedules: BackupSchedule.agent_id; schedule_service downloads from the agent
  when set; per-host filename prefix isolates retention across hosts.
- Frontend: agents api backup/restore; BackupButton/RestoreButton agent-aware
  (Backup on remote stack detail, Restore per host section); schedule form host
  selector (local or an online agent) + host shown on schedule rows.

Rough-verified (per request): py_compile, frontend tsc build, image imports
(main 99 / agent 16 routes). Full live agent round-trip to be tested post-deploy.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
menzelj
2026-06-07 22:26:20 +00:00
co-authored by Claude Opus 4.8
parent 84ef3df59e
commit 5cd55382ed
16 changed files with 561 additions and 59 deletions
+65
View File
@@ -27,4 +27,69 @@ export const agentsApi = {
api.put(`/api/agents/${id}/stacks/${stackId}`, body).then((r) => r.data),
action: (id: number, stackId: string, action: string) =>
api.post(`/api/agents/${id}/stacks/${stackId}/${action}`).then((r) => r.data),
backupDownload: async (
id: number,
stackId: string,
opts: { includeVolumes: boolean; stopFirst: boolean }
) => {
const res = await api.get(`/api/agents/${id}/stacks/${stackId}/backup`, {
params: { include_volumes: opts.includeVolumes, stop_first: opts.stopFirst },
responseType: "blob",
});
const cd = res.headers["content-disposition"] as string | undefined;
const name = cd?.match(/filename="?([^"]+)"?/)?.[1] ?? `backup-${stackId}.tar.gz`;
const url = URL.createObjectURL(res.data as Blob);
const a = document.createElement("a");
a.href = url;
a.download = name;
document.body.appendChild(a);
a.click();
a.remove();
URL.revokeObjectURL(url);
},
backupPush: (
id: number,
stackId: string,
body: { destination_id: number; include_volumes: boolean; stop_first: boolean }
) =>
api
.post<{ ok: boolean; destination: string; name: string }>(
`/api/agents/${id}/stacks/${stackId}/backup/push`,
body
)
.then((r) => r.data),
restoreUpload: (
id: number,
file: File,
opts: { targetId?: string; overwrite: boolean; restoreVolumes: boolean }
) => {
const form = new FormData();
form.append("file", file);
if (opts.targetId) form.append("target_id", opts.targetId);
form.append("overwrite", String(opts.overwrite));
form.append("restore_volumes", String(opts.restoreVolumes));
return api
.post<{ stack_id: string; name: string; volumes_restored: number }>(
`/api/agents/${id}/stacks/restore`,
form
)
.then((r) => r.data);
},
restoreFrom: (
id: number,
body: {
destination_id: number;
name: string;
target_id?: string;
overwrite: boolean;
restore_volumes: boolean;
}
) =>
api
.post<{ stack_id: string; name: string; volumes_restored: number }>(
`/api/agents/${id}/stacks/restore-from`,
body
)
.then((r) => r.data),
};
+3
View File
@@ -5,6 +5,8 @@ export interface BackupSchedule {
stack_id: string;
destination_id: number;
destination_name: string | null;
agent_id: number | null;
agent_name: string | null;
frequency: "hourly" | "daily" | "weekly";
hour: number;
minute: number;
@@ -22,6 +24,7 @@ export interface BackupSchedule {
export interface ScheduleInput {
stack_id: string;
destination_id: number;
agent_id?: number | null;
frequency: string;
hour: number;
minute: number;
@@ -4,6 +4,7 @@ import { Server } from "lucide-react";
import { toast } from "sonner";
import { Card } from "@/components/ui";
import { StackCard } from "@/components/stacks/StackCard";
import { RestoreButton } from "@/components/stacks/BackupRestore";
import { HostDot } from "@/components/hosts/HostDot";
import { agentsApi } from "@/api/agents";
import { apiErrorMessage } from "@/api/client";
@@ -37,14 +38,17 @@ export function AgentStacksSection({ agent, isAdmin }: { agent: Agent; isAdmin:
return (
<section>
<h2 className="mb-3 flex items-center gap-2 text-sm font-semibold uppercase tracking-wide text-slate-500">
<Server className="h-4 w-4" />
{agent.name}
<HostDot status={agent.status} />
{agent.hostname && (
<span className="font-mono text-xs normal-case text-slate-400">{agent.hostname}</span>
)}
</h2>
<div className="mb-3 flex items-center justify-between gap-2">
<h2 className="flex items-center gap-2 text-sm font-semibold uppercase tracking-wide text-slate-500">
<Server className="h-4 w-4" />
{agent.name}
<HostDot status={agent.status} />
{agent.hostname && (
<span className="font-mono text-xs normal-case text-slate-400">{agent.hostname}</span>
)}
</h2>
{isAdmin && online && <RestoreButton agentId={agent.id} />}
</div>
{!online ? (
<Card>
@@ -4,6 +4,7 @@ import { Archive, Upload } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui";
import { backupsApi, destinationsApi } from "@/api/backups";
import { agentsApi } from "@/api/agents";
import { apiErrorMessage } from "@/api/client";
import { formatBytes } from "@/lib/utils";
@@ -50,7 +51,13 @@ function Modal({ children, onClose }: { children: React.ReactNode; onClose: () =
);
}
export function BackupButton({ stackId }: { stackId: string }) {
export function BackupButton({
stackId,
agentId,
}: {
stackId: string;
agentId?: number;
}) {
const [open, setOpen] = useState(false);
const [includeVolumes, setIncludeVolumes] = useState(true);
const [stopFirst, setStopFirst] = useState(true);
@@ -68,14 +75,22 @@ export function BackupButton({ stackId }: { stackId: string }) {
const tid = toast.loading("Creating backup…");
try {
if (target === "download") {
await backupsApi.download(stackId, { includeVolumes, stopFirst });
if (agentId != null) {
await agentsApi.backupDownload(agentId, stackId, { includeVolumes, stopFirst });
} else {
await backupsApi.download(stackId, { includeVolumes, stopFirst });
}
toast.success("Backup downloaded", { id: tid });
} else {
const res = await backupsApi.push(stackId, {
const body = {
destination_id: Number(target),
include_volumes: includeVolumes,
stop_first: stopFirst,
});
};
const res =
agentId != null
? await agentsApi.backupPush(agentId, stackId, body)
: await backupsApi.push(stackId, body);
toast.success(`Backup pushed to ${res.destination}`, { id: tid });
}
setOpen(false);
@@ -133,7 +148,7 @@ export function BackupButton({ stackId }: { stackId: string }) {
);
}
export function RestoreButton() {
export function RestoreButton({ agentId }: { agentId?: number }) {
const qc = useQueryClient();
const [open, setOpen] = useState(false);
const [mode, setMode] = useState<"upload" | "destination">("upload");
@@ -167,27 +182,31 @@ export function RestoreButton() {
setBusy(false);
return;
}
res = await backupsApi.restore(file, {
targetId: targetId.trim() || undefined,
overwrite,
restoreVolumes,
});
const opts = { targetId: targetId.trim() || undefined, overwrite, restoreVolumes };
res =
agentId != null
? await agentsApi.restoreUpload(agentId, file, opts)
: await backupsApi.restore(file, opts);
} else {
if (!destId || !remoteName) {
toast.error("Pick a destination and a backup", { id: tid });
setBusy(false);
return;
}
res = await backupsApi.restoreFrom({
const body = {
destination_id: Number(destId),
name: remoteName,
target_id: targetId.trim() || undefined,
overwrite,
restore_volumes: restoreVolumes,
});
};
res =
agentId != null
? await agentsApi.restoreFrom(agentId, body)
: await backupsApi.restoreFrom(body);
}
toast.success(`Restored '${res.stack_id}' (${res.volumes_restored} volume(s))`, { id: tid });
qc.invalidateQueries({ queryKey: ["stacks"] });
qc.invalidateQueries({ queryKey: agentId != null ? ["agent-stacks", agentId] : ["stacks"] });
setOpen(false);
setFile(null);
setTargetId("");
+2
View File
@@ -14,6 +14,7 @@ import {
import { toast } from "sonner";
import { Badge, Button, Card, Spinner, StatusDot } from "@/components/ui";
import { HostDot } from "@/components/hosts/HostDot";
import { BackupButton } from "@/components/stacks/BackupRestore";
import { agentsApi } from "@/api/agents";
import { apiErrorMessage } from "@/api/client";
import { useAuthStore } from "@/store/auth";
@@ -92,6 +93,7 @@ export function RemoteStackDetail() {
<Button variant="outline" onClick={() => run("down", "Tearing down")} loading={busy}>
<Power className="h-4 w-4" /> Down
</Button>
<BackupButton stackId={id} agentId={aid} />
</div>
)}
</div>
+41 -3
View File
@@ -78,6 +78,7 @@ function SchedulesSection() {
const { data, isLoading } = useQuery({ queryKey: ["schedules"], queryFn: schedulesApi.list });
const destinations = useQuery({ queryKey: ["destinations"], queryFn: destinationsApi.list });
const stacks = useQuery({ queryKey: ["stacks"], queryFn: stacksApi.list });
const agents = useQuery({ queryKey: ["agents"], queryFn: () => agentsApi.list() });
const [adding, setAdding] = useState(false);
const invalidate = () => qc.invalidateQueries({ queryKey: ["schedules"] });
const noDest = (destinations.data?.length ?? 0) === 0;
@@ -103,6 +104,7 @@ function SchedulesSection() {
<ScheduleForm
stacks={stacks.data ?? []}
destinations={destinations.data ?? []}
agents={agents.data ?? []}
onDone={() => { setAdding(false); invalidate(); }}
onCancel={() => setAdding(false)}
/>
@@ -143,6 +145,7 @@ function ScheduleRow({ schedule, onChange }: { schedule: BackupSchedule; onChang
<Card className="space-y-2">
<div className="flex flex-wrap items-center justify-between gap-2">
<div className="flex items-center gap-2">
{schedule.agent_name && <Badge>{schedule.agent_name}</Badge>}
<span className="font-mono text-sm font-medium">{schedule.stack_id}</span>
<span className="text-slate-400"></span>
<Badge>{schedule.destination_name ?? `dest ${schedule.destination_id}`}</Badge>
@@ -178,14 +181,17 @@ function ScheduleRow({ schedule, onChange }: { schedule: BackupSchedule; onChang
function ScheduleForm({
stacks,
destinations,
agents,
onDone,
onCancel,
}: {
stacks: { id: string; name: string }[];
destinations: BackupDestination[];
agents: Agent[];
onDone: () => void;
onCancel: () => void;
}) {
const [host, setHost] = useState("local"); // "local" | agent id (string)
const [form, setForm] = useState({
stack_id: stacks[0]?.id ?? "",
destination_id: destinations[0]?.id ?? 0,
@@ -200,19 +206,51 @@ function ScheduleForm({
});
const set = (k: string, v: unknown) => setForm((f) => ({ ...f, [k]: v }));
const isRemote = host !== "local";
const agentId = isRemote ? Number(host) : undefined;
// When a remote host is selected, pull its stacks for the picker.
const remoteStacks = useQuery({
queryKey: ["agent-stacks", agentId],
queryFn: () => agentsApi.stacks(agentId!),
enabled: isRemote,
});
const stackOptions = isRemote
? (remoteStacks.data ?? []).map((s) => ({ id: s.id, name: s.name }))
: stacks;
// Keep stack_id valid as host/options change.
useEffect(() => {
if (stackOptions.length && !stackOptions.some((s) => s.id === form.stack_id)) {
set("stack_id", stackOptions[0].id);
}
}, [stackOptions]); // eslint-disable-line react-hooks/exhaustive-deps
const onlineAgents = agents.filter((a) => a.status === "online");
const create = useMutation({
mutationFn: () => schedulesApi.create(form),
mutationFn: () => schedulesApi.create({ ...form, agent_id: agentId ?? null }),
onSuccess: () => { toast.success("Schedule added"); onDone(); },
onError: (e) => toast.error(apiErrorMessage(e)),
});
return (
<Card className="space-y-3">
<div className="grid gap-3 sm:grid-cols-2">
<div className="grid gap-3 sm:grid-cols-3">
<label className="space-y-1">
<span className="text-xs font-medium text-slate-500">Host</span>
<select className={selectClass} value={host} onChange={(e) => setHost(e.target.value)}>
<option value="local">This host</option>
{onlineAgents.map((a) => (
<option key={a.id} value={String(a.id)}>{a.name}</option>
))}
</select>
</label>
<label className="space-y-1">
<span className="text-xs font-medium text-slate-500">Stack</span>
<select className={selectClass} value={form.stack_id} onChange={(e) => set("stack_id", e.target.value)}>
{stacks.map((s) => (
{stackOptions.length === 0 && <option value="">{isRemote ? "no stacks" : "—"}</option>}
{stackOptions.map((s) => (
<option key={s.id} value={s.id}>{s.name}</option>
))}
</select>