feat(scripts): каталог bash-скриптов для нод и гостей (VM/LXC)
Добавлена библиотека скриптов по образцу VMmanager: свои скрипты (CRUD в UI) и синхронизация из git-репозитория, параметризация через env-переменные (без конкатенации в shell), выполнение на нодах Proxmox (SSH), в LXC (pct exec) и в VM (QEMU guest agent, переиспользует существующий execute_script). Журнал запусков встроен в общий список задач /api/all-tasks. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
62
frontend/src/features/scripts/ExecutionDetailDialog.tsx
Normal file
62
frontend/src/features/scripts/ExecutionDetailDialog.tsx
Normal file
@@ -0,0 +1,62 @@
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { CheckCircle2, XCircle, Loader2 } from 'lucide-react';
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { useScriptExecution } from '@/hooks/use-scripts';
|
||||
|
||||
interface Props {
|
||||
executionId: number | null;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
}
|
||||
|
||||
export default function ExecutionDetailDialog({ executionId, onOpenChange }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const open = !!executionId;
|
||||
const { data: execution, isLoading } = useScriptExecution(executionId || 0);
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={(v) => !v && onOpenChange(false)}>
|
||||
<DialogContent className="max-w-2xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t('scripts.execution_title', 'Запуск: {{name}}', { name: execution?.script_name || execution?.script_id })}</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
{isLoading || !execution ? (
|
||||
<div className="py-10 text-center"><Loader2 className="mx-auto h-6 w-6 animate-spin text-muted-foreground" /></div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center gap-2 text-sm">
|
||||
{execution.status === 'success' && <CheckCircle2 className="h-4 w-4 text-green-600" />}
|
||||
{execution.status === 'failed' && <XCircle className="h-4 w-4 text-destructive" />}
|
||||
{execution.status === 'running' && <Loader2 className="h-4 w-4 animate-spin text-primary" />}
|
||||
<span>{t('scripts.exit_code', 'Exit code')}: {execution.exit_code ?? '—'}</span>
|
||||
<span className="text-muted-foreground">
|
||||
{execution.target_type === 'node' ? execution.node : `${execution.node} / vmid ${execution.vmid}`}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{Object.keys(execution.params_used || {}).length > 0 && (
|
||||
<div className="rounded-md border p-2 text-xs">
|
||||
{Object.entries(execution.params_used).map(([k, v]) => (
|
||||
<div key={k}><span className="text-muted-foreground">{k}</span> = {v}</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{execution.error_text && (
|
||||
<p className="text-sm text-destructive">{execution.error_text}</p>
|
||||
)}
|
||||
|
||||
<pre className="max-h-96 overflow-auto rounded bg-muted/40 p-2 text-xs whitespace-pre-wrap">
|
||||
{execution.output || t('scripts.no_output', '(нет вывода)')}
|
||||
</pre>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)}>{t('common.close', 'Закрыть')}</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
188
frontend/src/features/scripts/ScriptEditDialog.tsx
Normal file
188
frontend/src/features/scripts/ScriptEditDialog.tsx
Normal file
@@ -0,0 +1,188 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { toast } from 'sonner';
|
||||
import { Loader2, Plus, Trash2 } 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 { useCreateScript, useUpdateScript } from '@/hooks/use-scripts';
|
||||
import type { ScriptCatalogItem, ScriptParamField } from '@/types/scripts';
|
||||
|
||||
interface Props {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
script: ScriptCatalogItem | null;
|
||||
}
|
||||
|
||||
const emptyParam = (): ScriptParamField => ({ name: '', label: '', type: 'string', required: false, default: '' });
|
||||
|
||||
export default function ScriptEditDialog({ open, onOpenChange, script }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const isEdit = !!script;
|
||||
|
||||
const [name, setName] = useState('');
|
||||
const [slug, setSlug] = useState('');
|
||||
const [description, setDescription] = useState('');
|
||||
const [category, setCategory] = useState('');
|
||||
const [targetType, setTargetType] = useState<'node' | 'guest'>('guest');
|
||||
const [interpreter, setInterpreter] = useState('/bin/bash');
|
||||
const [content, setContent] = useState('#!/bin/bash\n');
|
||||
const [params, setParams] = useState<ScriptParamField[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
if (script) {
|
||||
setName(script.name);
|
||||
setSlug(script.slug);
|
||||
setDescription(script.description || '');
|
||||
setCategory(script.category || '');
|
||||
setTargetType(script.target_type);
|
||||
setInterpreter(script.interpreter);
|
||||
setContent(script.content || '');
|
||||
setParams(script.params_schema || []);
|
||||
} else {
|
||||
setName(''); setSlug(''); setDescription(''); setCategory('');
|
||||
setTargetType('guest'); setInterpreter('/bin/bash'); setContent('#!/bin/bash\n'); setParams([]);
|
||||
}
|
||||
}, [open, script]);
|
||||
|
||||
const create = useCreateScript();
|
||||
const update = useUpdateScript(script?.id || 0);
|
||||
const pending = create.isPending || update.isPending;
|
||||
|
||||
const handleNameChange = (v: string) => {
|
||||
setName(v);
|
||||
if (!isEdit) {
|
||||
setSlug(v.toLowerCase().trim().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, ''));
|
||||
}
|
||||
};
|
||||
|
||||
const handleSave = () => {
|
||||
if (!name.trim() || !slug.trim() || !content.trim()) {
|
||||
toast.error(t('scripts.validation_required', 'Заполните имя, slug и содержимое скрипта'));
|
||||
return;
|
||||
}
|
||||
const payload = {
|
||||
name, slug, description: description || undefined, category: category || undefined,
|
||||
target_type: targetType, interpreter, content,
|
||||
params_schema: params.filter((p) => p.name.trim()),
|
||||
};
|
||||
const onDone = {
|
||||
onSuccess: () => { toast.success(t('scripts.saved', 'Скрипт сохранён')); onOpenChange(false); },
|
||||
onError: (e: unknown) => toast.error((e as Error).message),
|
||||
};
|
||||
if (isEdit) update.mutate(payload, onDone);
|
||||
else create.mutate(payload, onDone);
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-2xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{isEdit ? t('scripts.edit_title', 'Редактировать скрипт') : t('scripts.new_title', 'Новый скрипт')}</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="max-h-[65vh] space-y-4 overflow-y-auto pr-1">
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div className="space-y-1.5">
|
||||
<Label>{t('scripts.name', 'Имя')}</Label>
|
||||
<Input value={name} onChange={(e) => handleNameChange(e.target.value)} placeholder="Очистка логов" />
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label>{t('scripts.slug', 'Slug')}</Label>
|
||||
<Input value={slug} onChange={(e) => setSlug(e.target.value)} disabled={isEdit} placeholder="clean-logs" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<Label>{t('scripts.description', 'Описание')}</Label>
|
||||
<Input value={description} onChange={(e) => setDescription(e.target.value)} />
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-3 gap-3">
|
||||
<div className="space-y-1.5">
|
||||
<Label>{t('scripts.category', 'Категория')}</Label>
|
||||
<Input value={category} onChange={(e) => setCategory(e.target.value)} placeholder="maintenance" />
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label>{t('scripts.target_type', 'Цель выполнения')}</Label>
|
||||
<Select value={targetType} onValueChange={(v) => setTargetType((v as 'node' | 'guest') ?? 'guest')}>
|
||||
<SelectTrigger><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="guest">{t('scripts.target_guest', 'VM/LXC')}</SelectItem>
|
||||
<SelectItem value="node">{t('scripts.target_node', 'Нода Proxmox')}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label>{t('scripts.interpreter', 'Интерпретатор')}</Label>
|
||||
<Input value={interpreter} onChange={(e) => setInterpreter(e.target.value)} placeholder="/bin/bash" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<Label>{t('scripts.content', 'Содержимое скрипта')}</Label>
|
||||
<textarea
|
||||
className="min-h-[220px] w-full rounded-lg border border-input bg-transparent p-2.5 font-mono text-xs outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 dark:bg-input/30"
|
||||
value={content}
|
||||
onChange={(e) => setContent(e.target.value)}
|
||||
spellCheck={false}
|
||||
/>
|
||||
<p className="text-2xs text-muted-foreground">
|
||||
{t('scripts.params_hint', 'Параметры доступны как переменные окружения ($NAME).')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<Label>{t('scripts.params', 'Параметры')}</Label>
|
||||
<Button size="sm" variant="outline" onClick={() => setParams([...params, emptyParam()])}>
|
||||
<Plus className="mr-1.5 h-3.5 w-3.5" />{t('scripts.add_param', 'Добавить параметр')}
|
||||
</Button>
|
||||
</div>
|
||||
{params.map((p, i) => (
|
||||
<div key={i} className="grid grid-cols-[1fr_1fr_100px_80px_auto] items-center gap-2">
|
||||
<Input
|
||||
placeholder="NAME" value={p.name}
|
||||
onChange={(e) => setParams(params.map((x, j) => j === i ? { ...x, name: e.target.value.toUpperCase() } : x))}
|
||||
/>
|
||||
<Input
|
||||
placeholder={t('scripts.param_label', 'Подпись')} value={p.label}
|
||||
onChange={(e) => setParams(params.map((x, j) => j === i ? { ...x, label: e.target.value } : x))}
|
||||
/>
|
||||
<Select value={p.type} onValueChange={(v) => setParams(params.map((x, j) => j === i ? { ...x, type: (v as ScriptParamField['type']) ?? 'string' } : x))}>
|
||||
<SelectTrigger><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="string">string</SelectItem>
|
||||
<SelectItem value="number">number</SelectItem>
|
||||
<SelectItem value="bool">bool</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<label className="flex items-center justify-center gap-1 text-xs">
|
||||
<input
|
||||
type="checkbox" checked={p.required}
|
||||
onChange={(e) => setParams(params.map((x, j) => j === i ? { ...x, required: e.target.checked } : x))}
|
||||
/>
|
||||
{t('scripts.required', 'обяз.')}
|
||||
</label>
|
||||
<Button size="sm" variant="outline" onClick={() => setParams(params.filter((_, j) => j !== i))}>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)}>{t('common.cancel', 'Отмена')}</Button>
|
||||
<Button onClick={handleSave} disabled={pending}>
|
||||
{pending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||
{t('common.save', 'Сохранить')}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
177
frontend/src/features/scripts/ScriptExecuteDialog.tsx
Normal file
177
frontend/src/features/scripts/ScriptExecuteDialog.tsx
Normal file
@@ -0,0 +1,177 @@
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { toast } from 'sonner';
|
||||
import { Loader2, Play, 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 { useVirtualMachines } from '@/hooks/use-instances';
|
||||
import { useExecuteScript } from '@/hooks/use-scripts';
|
||||
import type { ScriptCatalogItem } from '@/types/scripts';
|
||||
import type { ScriptExecution } from '@/types/scripts';
|
||||
|
||||
interface Props {
|
||||
script: ScriptCatalogItem | null;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
}
|
||||
|
||||
export default function ScriptExecuteDialog({ script, onOpenChange }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const open = !!script;
|
||||
|
||||
const { data: servers = [] } = useServers();
|
||||
const { data: vms = [] } = useVirtualMachines();
|
||||
|
||||
const [serverId, setServerId] = useState('');
|
||||
const [node, setNode] = useState('');
|
||||
const [guestKey, setGuestKey] = useState(''); // `${server_id}:${vmid}:${type}`
|
||||
const [paramValues, setParamValues] = useState<Record<string, string>>({});
|
||||
const [result, setResult] = useState<ScriptExecution | null>(null);
|
||||
|
||||
const serverIdNum = serverId ? Number(serverId) : 0;
|
||||
const { data: nodesData } = useNodes(serverIdNum || 0);
|
||||
const nodes = nodesData?.nodes ?? [];
|
||||
|
||||
const guestOptions = useMemo(
|
||||
() => vms.filter((v) => !v.template && (!serverIdNum || v.server_id === serverIdNum)),
|
||||
[vms, serverIdNum],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
setServerId(''); setNode(''); setGuestKey(''); setResult(null);
|
||||
const defaults: Record<string, string> = {};
|
||||
for (const p of script?.params_schema || []) {
|
||||
defaults[p.name] = p.default != null ? String(p.default) : '';
|
||||
}
|
||||
setParamValues(defaults);
|
||||
}, [open, script]);
|
||||
|
||||
const execute = useExecuteScript(script?.id || 0);
|
||||
|
||||
const selectedGuest = useMemo(() => {
|
||||
if (!guestKey) return null;
|
||||
const [sid, vmid] = guestKey.split(':');
|
||||
return guestOptions.find((v) => String(v.server_id) === sid && String(v.vmid) === vmid) || null;
|
||||
}, [guestKey, guestOptions]);
|
||||
|
||||
const canRun = useMemo(() => {
|
||||
if (!script || !serverIdNum) return false;
|
||||
if (script.target_type === 'node') return !!node;
|
||||
return !!selectedGuest;
|
||||
}, [script, serverIdNum, node, selectedGuest]);
|
||||
|
||||
const handleRun = () => {
|
||||
if (!script) return;
|
||||
for (const p of script.params_schema) {
|
||||
if (p.required && !paramValues[p.name]?.trim()) {
|
||||
toast.error(t('scripts.param_required', 'Параметр "{{label}}" обязателен', { label: p.label }));
|
||||
return;
|
||||
}
|
||||
}
|
||||
execute.mutate(
|
||||
{
|
||||
server_id: serverIdNum,
|
||||
node: script.target_type === 'node' ? node : selectedGuest?.node,
|
||||
vmid: script.target_type === 'guest' ? selectedGuest?.vmid : undefined,
|
||||
vm_type: script.target_type === 'guest' ? selectedGuest?.type : undefined,
|
||||
params: paramValues,
|
||||
},
|
||||
{
|
||||
onSuccess: (r) => setResult(r),
|
||||
onError: (e) => toast.error((e as Error).message),
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
if (!script) return null;
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={(v) => !v && onOpenChange(false)}>
|
||||
<DialogContent className="max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t('scripts.run_title', 'Запустить: {{name}}', { name: script.name })}</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-1.5">
|
||||
<Label>{t('scripts.server', 'Сервер Proxmox')}</Label>
|
||||
<Select value={serverId} onValueChange={(v) => { setServerId(v ?? ''); setNode(''); setGuestKey(''); }}>
|
||||
<SelectTrigger><SelectValue placeholder={t('scripts.pick_server', 'Выберите сервер')} /></SelectTrigger>
|
||||
<SelectContent>
|
||||
{servers.map((s) => <SelectItem key={s.id} value={String(s.id)}>{s.name}</SelectItem>)}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{script.target_type === 'node' ? (
|
||||
<div className="space-y-1.5">
|
||||
<Label>{t('scripts.node', 'Нода')}</Label>
|
||||
<Select value={node} onValueChange={(v) => setNode(v ?? '')} disabled={!serverIdNum}>
|
||||
<SelectTrigger><SelectValue placeholder={t('scripts.pick_node', 'Выберите ноду')} /></SelectTrigger>
|
||||
<SelectContent>
|
||||
{nodes.map((n) => <SelectItem key={n.node} value={n.node}>{n.node}</SelectItem>)}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-1.5">
|
||||
<Label>{t('scripts.guest', 'VM / LXC')}</Label>
|
||||
<Select value={guestKey} onValueChange={(v) => setGuestKey(v ?? '')} disabled={!serverIdNum}>
|
||||
<SelectTrigger><SelectValue placeholder={t('scripts.pick_guest', 'Выберите ВМ/контейнер')} /></SelectTrigger>
|
||||
<SelectContent>
|
||||
{guestOptions.map((v) => (
|
||||
<SelectItem key={`${v.server_id}:${v.vmid}`} value={`${v.server_id}:${v.vmid}:${v.type}`}>
|
||||
{v.vmid} — {v.name} ({v.type})
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{script.params_schema.length > 0 && (
|
||||
<div className="space-y-3 rounded-md border p-3">
|
||||
{script.params_schema.map((p) => (
|
||||
<div key={p.name} className="space-y-1.5">
|
||||
<Label>{p.label}{p.required && ' *'}</Label>
|
||||
<Input
|
||||
value={paramValues[p.name] ?? ''}
|
||||
onChange={(e) => setParamValues({ ...paramValues, [p.name]: e.target.value })}
|
||||
type={p.type === 'number' ? 'number' : 'text'}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{result && (
|
||||
<div className="space-y-1.5 rounded-md border bg-muted/40 p-3">
|
||||
<div className="flex items-center gap-2 text-sm">
|
||||
{result.status === 'success'
|
||||
? <CheckCircle2 className="h-4 w-4 text-green-600" />
|
||||
: <XCircle className="h-4 w-4 text-destructive" />}
|
||||
<span>{t('scripts.exit_code', 'Exit code')}: {result.exit_code ?? '—'}</span>
|
||||
</div>
|
||||
{result.error_text && <p className="text-xs text-destructive">{result.error_text}</p>}
|
||||
{result.output && (
|
||||
<pre className="max-h-64 overflow-auto rounded bg-background p-2 text-xs whitespace-pre-wrap">{result.output}</pre>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)}>{t('common.close', 'Закрыть')}</Button>
|
||||
<Button onClick={handleRun} disabled={!canRun || execute.isPending}>
|
||||
{execute.isPending ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : <Play className="mr-2 h-4 w-4" />}
|
||||
{t('scripts.run', 'Запустить')}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
245
frontend/src/features/scripts/ScriptsPage.tsx
Normal file
245
frontend/src/features/scripts/ScriptsPage.tsx
Normal file
@@ -0,0 +1,245 @@
|
||||
import { useMemo, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { toast } from 'sonner';
|
||||
import { Terminal, Plus, RefreshCw, Loader2, Play, Pencil, Trash2, GitBranch } from 'lucide-react';
|
||||
import { Card } from '@/components/ui/card';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
||||
import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from '@/components/ui/table';
|
||||
import {
|
||||
useScripts, useDeleteScript,
|
||||
useScriptRepos, useCreateScriptRepo, useSyncScriptRepo, useDeleteScriptRepo,
|
||||
useScriptExecutions,
|
||||
} from '@/hooks/use-scripts';
|
||||
import type { ScriptCatalogItem } from '@/types/scripts';
|
||||
import ScriptEditDialog from './ScriptEditDialog';
|
||||
import ScriptExecuteDialog from './ScriptExecuteDialog';
|
||||
import ExecutionDetailDialog from './ExecutionDetailDialog';
|
||||
|
||||
export default function ScriptsPage() {
|
||||
const { t } = useTranslation();
|
||||
const [tab, setTab] = useState('catalog');
|
||||
|
||||
const { data: scripts = [], isLoading } = useScripts();
|
||||
const deleteScript = useDeleteScript();
|
||||
|
||||
const [editOpen, setEditOpen] = useState(false);
|
||||
const [editing, setEditing] = useState<ScriptCatalogItem | null>(null);
|
||||
const [execScript, setExecScript] = useState<ScriptCatalogItem | null>(null);
|
||||
|
||||
const { data: repos = [] } = useScriptRepos();
|
||||
const createRepo = useCreateScriptRepo();
|
||||
const syncRepo = useSyncScriptRepo();
|
||||
const deleteRepo = useDeleteScriptRepo();
|
||||
const [repoUrl, setRepoUrl] = useState('');
|
||||
|
||||
const { data: executions = [] } = useScriptExecutions();
|
||||
const [execDetailId, setExecDetailId] = useState<number | null>(null);
|
||||
|
||||
const manualScripts = useMemo(() => scripts.filter((s) => s.source === 'manual'), [scripts]);
|
||||
const gitScripts = useMemo(() => scripts.filter((s) => s.source === 'git'), [scripts]);
|
||||
|
||||
const handleDelete = (script: ScriptCatalogItem) => {
|
||||
if (!confirm(t('scripts.confirm_delete', 'Удалить скрипт "{{name}}"?', { name: script.name }))) return;
|
||||
deleteScript.mutate(script.id, {
|
||||
onSuccess: () => toast.success(t('scripts.deleted', 'Скрипт удалён')),
|
||||
onError: (e) => toast.error((e as Error).message),
|
||||
});
|
||||
};
|
||||
|
||||
const handleAddRepo = () => {
|
||||
if (!repoUrl.trim()) return;
|
||||
createRepo.mutate({ url: repoUrl.trim() }, {
|
||||
onSuccess: () => { setRepoUrl(''); toast.success(t('scripts.repo_added', 'Источник добавлен')); },
|
||||
onError: (e) => toast.error((e as Error).message),
|
||||
});
|
||||
};
|
||||
|
||||
const renderScriptCard = (script: ScriptCatalogItem) => (
|
||||
<Card key={script.id} className="flex flex-col gap-2 p-3">
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<div className="min-w-0">
|
||||
<p className="truncate text-sm font-medium">{script.name}</p>
|
||||
<p className="line-clamp-2 text-xs text-muted-foreground">{script.description}</p>
|
||||
</div>
|
||||
<Badge variant="outline" className="shrink-0 text-2xs">
|
||||
{script.target_type === 'node' ? t('scripts.target_node', 'Нода') : t('scripts.target_guest', 'VM/LXC')}
|
||||
</Badge>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-1">
|
||||
{script.category && <Badge variant="secondary" className="text-2xs">{script.category}</Badge>}
|
||||
{script.source === 'git' && (
|
||||
<Badge variant="outline" className="gap-1 text-2xs"><GitBranch className="h-3 w-3" />{script.git_path}</Badge>
|
||||
)}
|
||||
</div>
|
||||
<div className="mt-auto flex items-center gap-2 pt-1">
|
||||
<Button size="sm" onClick={() => setExecScript(script)}>
|
||||
<Play className="mr-1.5 h-3.5 w-3.5" />{t('scripts.run', 'Запустить')}
|
||||
</Button>
|
||||
{script.source === 'manual' && (
|
||||
<>
|
||||
<Button size="sm" variant="outline" onClick={() => { setEditing(script); setEditOpen(true); }}>
|
||||
<Pencil className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
<Button size="sm" variant="outline" onClick={() => handleDelete(script)}>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<Terminal className="h-6 w-6 text-primary" />
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold">{t('scripts.title', 'Каталог скриптов')}</h1>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t('scripts.subtitle', 'Bash-скрипты для выполнения на нодах Proxmox и гостях (VM/LXC)')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<Button size="sm" onClick={() => { setEditing(null); setEditOpen(true); }}>
|
||||
<Plus className="mr-2 h-4 w-4" />{t('scripts.new_script', 'Новый скрипт')}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<Tabs value={tab} onValueChange={setTab}>
|
||||
<TabsList>
|
||||
<TabsTrigger value="catalog">{t('scripts.tab_catalog', 'Каталог')}</TabsTrigger>
|
||||
<TabsTrigger value="repos">{t('scripts.tab_repos', 'Git-источники')}</TabsTrigger>
|
||||
<TabsTrigger value="executions">{t('scripts.tab_executions', 'История запусков')}</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="catalog" className="mt-4 space-y-4">
|
||||
{isLoading ? (
|
||||
<div className="py-20 text-center text-sm text-muted-foreground">{t('common.loading', 'Загрузка...')}</div>
|
||||
) : scripts.length === 0 ? (
|
||||
<div className="py-20 text-center text-muted-foreground">
|
||||
<Terminal className="mx-auto mb-3 h-12 w-12 opacity-40" />
|
||||
<p>{t('scripts.no_scripts', 'Пока нет ни одного скрипта')}</p>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{manualScripts.length > 0 && (
|
||||
<div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-3">
|
||||
{manualScripts.map(renderScriptCard)}
|
||||
</div>
|
||||
)}
|
||||
{gitScripts.length > 0 && (
|
||||
<div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-3">
|
||||
{gitScripts.map(renderScriptCard)}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="repos" className="mt-4 space-y-4">
|
||||
<Card className="flex flex-wrap items-center gap-2 p-3">
|
||||
<input
|
||||
className="h-8 min-w-[280px] flex-1 rounded-lg border border-input bg-transparent px-2.5 text-sm outline-none focus-visible:ring-3 focus-visible:ring-ring/50"
|
||||
placeholder={t('scripts.repo_url_placeholder', 'https://github.com/user/scripts.git')}
|
||||
value={repoUrl}
|
||||
onChange={(e) => setRepoUrl(e.target.value)}
|
||||
/>
|
||||
<Button size="sm" onClick={handleAddRepo} disabled={createRepo.isPending}>
|
||||
<Plus className="mr-1.5 h-4 w-4" />{t('scripts.add_repo', 'Добавить источник')}
|
||||
</Button>
|
||||
</Card>
|
||||
|
||||
{repos.length === 0 ? (
|
||||
<div className="py-10 text-center text-sm text-muted-foreground">
|
||||
{t('scripts.no_repos', 'Git-источники не настроены')}
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{repos.map((repo) => (
|
||||
<Card key={repo.id} className="flex flex-wrap items-center justify-between gap-2 p-3">
|
||||
<div className="min-w-0">
|
||||
<p className="truncate text-sm font-medium">{repo.url}</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{repo.branch} · {repo.path_glob}
|
||||
{repo.last_synced_at && ` · ${t('scripts.last_synced', 'синк')}: ${new Date(repo.last_synced_at).toLocaleString()}`}
|
||||
</p>
|
||||
{repo.last_sync_error && (
|
||||
<p className="text-xs text-destructive">{repo.last_sync_error}</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
size="sm" variant="outline"
|
||||
onClick={() => syncRepo.mutate(repo.id, {
|
||||
onSuccess: (r) => r.success
|
||||
? toast.success(t('scripts.sync_done', 'Синхронизировано: +{{created}} / изм. {{updated}}', { created: r.created, updated: r.updated }))
|
||||
: toast.error(r.error || t('scripts.sync_failed', 'Ошибка синхронизации')),
|
||||
onError: (e) => toast.error((e as Error).message),
|
||||
})}
|
||||
disabled={syncRepo.isPending}
|
||||
>
|
||||
{syncRepo.isPending ? <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" /> : <RefreshCw className="mr-1.5 h-3.5 w-3.5" />}
|
||||
{t('scripts.sync', 'Синхронизировать')}
|
||||
</Button>
|
||||
<Button size="sm" variant="outline" onClick={() => deleteRepo.mutate(repo.id)}>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="executions" className="mt-4">
|
||||
{executions.length === 0 ? (
|
||||
<div className="py-20 text-center text-sm text-muted-foreground">
|
||||
{t('scripts.no_executions', 'Пока нет запусков')}
|
||||
</div>
|
||||
) : (
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>{t('scripts.col_script', 'Скрипт')}</TableHead>
|
||||
<TableHead>{t('scripts.col_target', 'Цель')}</TableHead>
|
||||
<TableHead>{t('scripts.col_status', 'Статус')}</TableHead>
|
||||
<TableHead>{t('scripts.col_exit_code', 'Exit code')}</TableHead>
|
||||
<TableHead>{t('scripts.col_started', 'Запущен')}</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{executions.map((e) => (
|
||||
<TableRow key={e.id} className="cursor-pointer" onClick={() => setExecDetailId(e.id)}>
|
||||
<TableCell>{e.script_name || e.script_id}</TableCell>
|
||||
<TableCell className="text-xs text-muted-foreground">
|
||||
{e.target_type === 'node' ? e.node : `${e.node} / vmid ${e.vmid}`}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Badge variant={e.status === 'success' ? 'secondary' : e.status === 'failed' ? 'destructive' : 'outline'}>
|
||||
{e.status}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell>{e.exit_code ?? '—'}</TableCell>
|
||||
<TableCell className="text-xs text-muted-foreground">
|
||||
{e.started_at ? new Date(e.started_at).toLocaleString() : '—'}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
)}
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
|
||||
<ScriptEditDialog open={editOpen} onOpenChange={setEditOpen} script={editing} />
|
||||
<ScriptExecuteDialog script={execScript} onOpenChange={(open) => !open && setExecScript(null)} />
|
||||
<ExecutionDetailDialog
|
||||
executionId={execDetailId}
|
||||
onOpenChange={(open) => !open && setExecDetailId(null)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user