feat(appstore): автосборка золотого LXC-шаблона из UI (Workstream B)
All checks were successful
Backend Tests / pytest (Python 3.12) (push) Successful in 57s
Deploy to Production / Trigger production update (push) Successful in 8s

Автоматизирует ручную процедуру docs/golden-template.md: pveam download
базового Debian → pct create временного CT → установка Docker/Compose →
каталоги/сеть/logrotate → (опц.) проверка nginx → vzdump в vztmpl → удаление
временного CT. При сбое недособранный CT очищается.

- backend/app/appstore/golden_template.py — сборщик поверх SSH-инфраструктуры
  пайплайна (pct/pvesm/pveam/vzdump); идемпотентность по существующему vztmpl,
  версия базового шаблона берётся из pveam (не хардкодится)
- appstore_engine: prepare_golden_template/_run_golden_template (фон, журнал
  AppOperation + WS), golden_template_status; собранный volid сохраняется в
  PanelSettings и предпочитается env при установке (_resolve_golden_template)
- API: POST /api/appstore/golden-template, GET .../golden-template/status
  (app:manage / app:view)
- Frontend: GoldenTemplateDialog (выбор сервера/ноды/хранилищ, force, живой
  прогресс опросом статуса) + admin-кнопка «Золотой шаблон» на странице App
  Store; хуки useGoldenTemplateStatus/useBuildGoldenTemplate; локали RU/EN

Проверено: роуты зарегистрированы, golden_template_status и приоритет
_resolve_golden_template (override→saved→env) корректны, tsc 0 ошибок.
Полный e2e-прогон сборки на реальной ноде — по запросу.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
markmorado
2026-07-09 01:53:47 +05:00
parent aebb726231
commit 629357a0ee
9 changed files with 617 additions and 6 deletions

View File

@@ -2,13 +2,15 @@ import { useMemo, useState } from 'react';
import { useNavigate } from 'react-router';
import { useTranslation } from 'react-i18next';
import { toast } from 'sonner';
import { Store, Search, RefreshCw, Loader2, Package } from 'lucide-react';
import { Store, Search, RefreshCw, Loader2, Package, HardDriveDownload } from 'lucide-react';
import { Card } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Select, SelectTrigger, SelectValue, SelectContent, SelectItem } from '@/components/ui/select';
import { useCatalog, useCatalogMeta, useInstalledApps, useSyncCatalog } from '@/hooks/use-appstore';
import { useAuthStore } from '@/stores/auth-store';
import GoldenTemplateDialog from './GoldenTemplateDialog';
export default function AppStorePage() {
const { t } = useTranslation();
@@ -16,6 +18,8 @@ export default function AppStorePage() {
const [search, setSearch] = useState('');
const [category, setCategory] = useState<string>('');
const [source, setSource] = useState<string>('');
const [goldenOpen, setGoldenOpen] = useState(false);
const isAdmin = useAuthStore((s) => s.user?.is_admin ?? false);
const { data: catalog, isLoading } = useCatalog(search, category, source);
const { data: meta } = useCatalogMeta();
@@ -52,6 +56,12 @@ export default function AppStorePage() {
<Package className="mr-2 h-4 w-4" />
{t('appstore.my_apps')}
</Button>
{isAdmin && (
<Button variant="outline" size="sm" onClick={() => setGoldenOpen(true)}>
<HardDriveDownload className="mr-2 h-4 w-4" />
{t('appstore.golden.button', 'Золотой шаблон')}
</Button>
)}
<Button size="sm" onClick={handleSync} disabled={sync.isPending}>
{sync.isPending
? <Loader2 className="mr-2 h-4 w-4 animate-spin" />
@@ -164,6 +174,8 @@ export default function AppStorePage() {
{t('appstore.powered_by')}
</a>
</div>
{isAdmin && <GoldenTemplateDialog open={goldenOpen} onOpenChange={setGoldenOpen} />}
</div>
);
}

View File

@@ -0,0 +1,172 @@
import { useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { toast } from 'sonner';
import { Loader2, HardDriveDownload, CheckCircle2, XCircle } from 'lucide-react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select, SelectTrigger, SelectValue, SelectContent, SelectItem } from '@/components/ui/select';
import { useServers, useNodes } from '@/hooks/use-nodes';
import { useBuildGoldenTemplate, useGoldenTemplateStatus } from '@/hooks/use-appstore';
interface Props {
open: boolean;
onOpenChange: (open: boolean) => void;
}
export default function GoldenTemplateDialog({ open, onOpenChange }: Props) {
const { t } = useTranslation();
const { data: servers = [] } = useServers();
const [serverId, setServerId] = useState('');
const [node, setNode] = useState('');
const [templateStorage, setTemplateStorage] = useState('local');
const [rootfsStorage, setRootfsStorage] = useState('local-lvm');
const [force, setForce] = useState(false);
const serverIdNum = serverId ? Number(serverId) : 0;
const { data: nodesData } = useNodes(serverIdNum || 0);
const nodes = nodesData?.nodes ?? [];
const build = useBuildGoldenTemplate();
// Пока операция выполняется — опрашиваем статус каждые 2с для прогресса.
const { data: status } = useGoldenTemplateStatus(open ? 2000 : 0);
const op = status?.last_operation ?? null;
const running = op?.status === 'running';
const lastStep = op?.steps_log?.length ? op.steps_log[op.steps_log.length - 1].step : null;
const configured = status?.configured_template ?? null;
const canSubmit = useMemo(
() => !!serverIdNum && !!templateStorage && !!rootfsStorage && !running && !build.isPending,
[serverIdNum, templateStorage, rootfsStorage, running, build.isPending],
);
const handleBuild = () => {
if (!serverIdNum) {
toast.error(t('appstore.golden.pick_server', 'Выберите сервер Proxmox'));
return;
}
build.mutate(
{
server_id: serverIdNum,
node: node || undefined,
template_storage: templateStorage,
rootfs_storage: rootfsStorage,
force,
},
{
onSuccess: () => toast.success(t('appstore.golden.started', 'Сборка шаблона запущена')),
onError: (e) => toast.error((e as Error).message || t('appstore.golden.failed', 'Не удалось запустить сборку')),
},
);
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-lg">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<HardDriveDownload className="h-5 w-5 text-primary" />
{t('appstore.golden.title', 'Золотой LXC-шаблон')}
</DialogTitle>
</DialogHeader>
<div className="space-y-4">
<p className="text-sm text-muted-foreground">
{t('appstore.golden.desc',
'Автоматическая сборка golden-шаблона (Debian 12 + Docker + Compose) на выбранной ноде. Из него App Store клонирует контейнеры приложений.')}
</p>
{/* Текущий шаблон */}
<div className="rounded-md border bg-muted/40 px-3 py-2 text-xs">
<span className="text-muted-foreground">{t('appstore.golden.current', 'Текущий шаблон')}: </span>
{configured
? <code className="break-all">{configured}</code>
: <span className="text-amber-600">{t('appstore.golden.none', 'не настроен')}</span>}
</div>
{/* Сервер */}
<div className="space-y-1.5">
<Label>{t('appstore.golden.server', 'Сервер Proxmox')}</Label>
<Select value={serverId} onValueChange={(v) => { setServerId(v ?? ''); setNode(''); }}>
<SelectTrigger><SelectValue placeholder={t('appstore.golden.pick_server', 'Выберите сервер')} /></SelectTrigger>
<SelectContent>
{servers.map((s) => (
<SelectItem key={s.id} value={String(s.id)}>{s.name}</SelectItem>
))}
</SelectContent>
</Select>
</div>
{/* Нода / хранилища */}
<div className="grid grid-cols-2 gap-3">
<div className="space-y-1.5">
<Label>{t('appstore.node', 'Нода')}</Label>
<Select value={node || '__auto__'} onValueChange={(v) => setNode(v && v !== '__auto__' ? v : '')} disabled={!serverIdNum}>
<SelectTrigger><SelectValue placeholder={t('wizard.auto_select', 'Авто')} /></SelectTrigger>
<SelectContent>
<SelectItem value="__auto__">{t('wizard.auto_select', 'Авто')}</SelectItem>
{nodes.map((n) => (
<SelectItem key={n.node} value={n.node}>{n.node}</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="space-y-1.5">
<Label>{t('appstore.golden.template_storage', 'Хранилище шаблона')}</Label>
<Input value={templateStorage} onChange={(e) => setTemplateStorage(e.target.value)} placeholder="local" />
</div>
</div>
<div className="grid grid-cols-2 gap-3">
<div className="space-y-1.5">
<Label>{t('appstore.golden.rootfs_storage', 'Хранилище rootfs')}</Label>
<Input value={rootfsStorage} onChange={(e) => setRootfsStorage(e.target.value)} placeholder="local-lvm" />
</div>
<label className="flex items-end gap-2 pb-2 text-sm">
<input type="checkbox" checked={force} onChange={(e) => setForce(e.target.checked)} className="h-4 w-4" />
{t('appstore.golden.force', 'Пересобрать')}
</label>
</div>
{/* Прогресс */}
{op && (
<div className="space-y-1.5">
<div className="flex items-center gap-2 text-sm">
{running && <Loader2 className="h-4 w-4 animate-spin text-primary" />}
{op.status === 'completed' && <CheckCircle2 className="h-4 w-4 text-green-600" />}
{op.status === 'failed' && <XCircle className="h-4 w-4 text-destructive" />}
<span className="truncate text-muted-foreground">
{op.status === 'failed'
? (op.error_text || t('appstore.golden.failed', 'Ошибка сборки'))
: (lastStep || t('appstore.golden.working', 'Выполняется...'))}
</span>
</div>
<div className="h-2 w-full overflow-hidden rounded-full bg-muted">
<div
className={`h-full transition-all ${op.status === 'failed' ? 'bg-destructive' : 'bg-primary'}`}
style={{ width: `${op.progress}%` }}
/>
</div>
</div>
)}
</div>
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)}>
{t('common.close', 'Закрыть')}
</Button>
<Button onClick={handleBuild} disabled={!canSubmit}>
{(build.isPending || running)
? <Loader2 className="mr-2 h-4 w-4 animate-spin" />
: <HardDriveDownload className="mr-2 h-4 w-4" />}
{t('appstore.golden.build', 'Собрать шаблон')}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}

View File

@@ -58,6 +58,41 @@ export function useSyncCatalog() {
});
}
// ── Золотой шаблон (Workstream B) ────────────────────────────────────────────
export interface GoldenTemplateStatus {
configured_template: string | null;
env_template: string | null;
saved_template: string | null;
last_operation: AppOperation | null;
}
export interface GoldenBuildArgs {
server_id: number;
node?: string;
template_storage?: string;
rootfs_storage?: string;
bridge?: string;
force?: boolean;
}
export function useGoldenTemplateStatus(pollMs?: number) {
return useQuery({
queryKey: ['appstore-golden-status'],
queryFn: () => apiClient.get<GoldenTemplateStatus>('/api/appstore/golden-template/status'),
refetchInterval: pollMs && pollMs > 0 ? pollMs : false,
});
}
export function useBuildGoldenTemplate() {
const qc = useQueryClient();
return useMutation({
mutationFn: (data: GoldenBuildArgs) =>
apiClient.post<{ success: boolean; operation_id: number }>('/api/appstore/golden-template', data),
onSuccess: () => qc.invalidateQueries({ queryKey: ['appstore-golden-status'] }),
});
}
// ── Установленные ──────────────────────────────────────────────────────────
export function useInstalledApps() {

View File

@@ -30,6 +30,22 @@
"runtipi": "Runtipi",
"umbrel": "Umbrel"
},
"golden": {
"button": "Golden template",
"title": "Golden LXC template",
"desc": "Automatically build the golden template (Debian 12 + Docker + Compose) on the selected node. App Store clones app containers from it.",
"current": "Current template",
"none": "not configured",
"server": "Proxmox server",
"pick_server": "Select a server",
"template_storage": "Template storage",
"rootfs_storage": "Rootfs storage",
"force": "Rebuild",
"build": "Build template",
"started": "Template build started",
"failed": "Build failed",
"working": "Working..."
},
"refresh_catalog": "Refresh catalog",
"last_synced": "Last synced",
"never": "never",

View File

@@ -30,6 +30,22 @@
"runtipi": "Runtipi",
"umbrel": "Umbrel"
},
"golden": {
"button": "Золотой шаблон",
"title": "Золотой LXC-шаблон",
"desc": "Автоматическая сборка golden-шаблона (Debian 12 + Docker + Compose) на выбранной ноде. Из него App Store клонирует контейнеры приложений.",
"current": "Текущий шаблон",
"none": "не настроен",
"server": "Сервер Proxmox",
"pick_server": "Выберите сервер",
"template_storage": "Хранилище шаблона",
"rootfs_storage": "Хранилище rootfs",
"force": "Пересобрать",
"build": "Собрать шаблон",
"started": "Сборка шаблона запущена",
"failed": "Ошибка сборки",
"working": "Выполняется..."
},
"refresh_catalog": "Обновить каталог",
"last_synced": "Обновлён",
"never": "никогда",