feat(hardware): проброс физических дисков ноды в VM (raw passthrough)
Добавлена возможность пробросить физический диск ноды в VM по стабильному пути /dev/disk/by-id/ (scsiN/virtioN/sataN) в карточке «Проброс устройств». Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
184
frontend/src/features/instances/AddPhysicalDiskDialog.tsx
Normal file
184
frontend/src/features/instances/AddPhysicalDiskDialog.tsx
Normal file
@@ -0,0 +1,184 @@
|
||||
import { useState, useEffect, useMemo } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { HardDrive } from 'lucide-react';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import { useNodeDisks } from '@/hooks/use-disks';
|
||||
import { useAttachPhysicalDisk } from '@/hooks/use-instances';
|
||||
import { formatBytes } from '@/lib/format';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
interface Props {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
serverId: number;
|
||||
vmid: number;
|
||||
node: string;
|
||||
config?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
const BUSES = ['scsi', 'virtio', 'sata'] as const;
|
||||
|
||||
/** Следующее свободное имя устройства для выбранной шины из текущего конфига. */
|
||||
function nextDiskKey(bus: string, config?: Record<string, unknown>): string {
|
||||
const used = new Set(Object.keys(config ?? {}).filter((k) => new RegExp(`^${bus}\\d+$`).test(k)));
|
||||
for (let i = 0; i < 31; i++) {
|
||||
if (!used.has(`${bus}${i}`)) return `${bus}${i}`;
|
||||
}
|
||||
return `${bus}0`;
|
||||
}
|
||||
|
||||
export default function AddPhysicalDiskDialog({ open, onClose, serverId, vmid, node, config }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const { data, isLoading } = useNodeDisks(serverId, node, open);
|
||||
const attach = useAttachPhysicalDisk(serverId, vmid, node);
|
||||
|
||||
const [devpath, setDevpath] = useState('');
|
||||
const [bus, setBus] = useState<string>('scsi');
|
||||
const [ssd, setSsd] = useState(false);
|
||||
const [discard, setDiscard] = useState(false);
|
||||
|
||||
const disks = data?.disks ?? [];
|
||||
const diskKey = useMemo(() => nextDiskKey(bus, config), [bus, config]);
|
||||
const selected = useMemo(() => disks.find((d) => (d.passthrough_path || d.devpath) === devpath), [disks, devpath]);
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setDevpath('');
|
||||
setBus('scsi');
|
||||
setSsd(false);
|
||||
setDiscard(false);
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
const submit = () => {
|
||||
if (!devpath) {
|
||||
toast.error(t('hw.err_disk_required', 'Выберите диск'));
|
||||
return;
|
||||
}
|
||||
attach.mutate(
|
||||
{ disk: diskKey, devpath, ssd, discard },
|
||||
{
|
||||
onSuccess: () => {
|
||||
toast.success(t('hw.disk_added', 'Диск {{key}} проброшен', { key: diskKey }));
|
||||
onClose();
|
||||
},
|
||||
onError: (e) => toast.error((e as Error).message),
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={(o) => !o && onClose()}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<HardDrive className="h-4 w-4" />
|
||||
{t('hw.add_disk_title', 'Проброс физического диска')}
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
{t('hw.add_disk_description', 'Будет добавлено как {{key}}', { key: diskKey })}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-1.5">
|
||||
<Label>{t('hw.disk_device', 'Диск')}</Label>
|
||||
<Select value={devpath} onValueChange={(v) => setDevpath(v ?? '')}>
|
||||
<SelectTrigger className="w-full">
|
||||
<SelectValue
|
||||
placeholder={
|
||||
isLoading
|
||||
? t('common.loading', 'Загрузка…')
|
||||
: t('hw.select_disk', 'Выберите диск')
|
||||
}
|
||||
/>
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{disks.map((d) => {
|
||||
const value = d.passthrough_path || d.devpath;
|
||||
const label = [d.model, d.serial].filter(Boolean).join(' · ');
|
||||
return (
|
||||
<SelectItem key={d.devpath} value={value}>
|
||||
<span className="flex items-center gap-2">
|
||||
<span className="font-mono text-xs">{d.devpath}</span>
|
||||
{typeof d.size === 'number' && (
|
||||
<span className="text-xs text-muted-foreground">{formatBytes(d.size)}</span>
|
||||
)}
|
||||
{label && <span className="text-xs text-muted-foreground">{label}</span>}
|
||||
{d.used && (
|
||||
<span className="text-xs text-warning">({d.used})</span>
|
||||
)}
|
||||
</span>
|
||||
</SelectItem>
|
||||
);
|
||||
})}
|
||||
{!isLoading && disks.length === 0 && (
|
||||
<div className="px-2 py-1.5 text-xs text-muted-foreground">
|
||||
{t('hw.no_disks', 'Диски не найдены')}
|
||||
</div>
|
||||
)}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{selected?.used && (
|
||||
<p className="text-xs text-warning">
|
||||
{t('hw.disk_used_warn', 'Диск занят ({{used}}) — проброс может привести к потере данных.', { used: selected.used })}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<Label>{t('hw.disk_bus', 'Шина')}</Label>
|
||||
<Select value={bus} onValueChange={(v) => v && setBus(v)}>
|
||||
<SelectTrigger className="w-full">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{BUSES.map((b) => (
|
||||
<SelectItem key={b} value={b}>{b}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<label className="flex items-center gap-2 text-sm">
|
||||
<input type="checkbox" checked={ssd} onChange={(e) => setSsd(e.target.checked)} />
|
||||
{t('hw.disk_ssd', 'Эмулировать SSD')}
|
||||
</label>
|
||||
<label className="flex items-center gap-2 text-sm">
|
||||
<input type="checkbox" checked={discard} onChange={(e) => setDiscard(e.target.checked)} />
|
||||
{t('hw.disk_discard', 'Discard / TRIM')}
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('hw.disk_passthrough_hint', 'Диск отдаётся VM монопольно по стабильному пути /dev/disk/by-id/. Привязан к этой ноде — миграция на другую ноду недоступна.')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={onClose}>{t('common.cancel', 'Отмена')}</Button>
|
||||
<Button onClick={submit} disabled={attach.isPending || !devpath}>
|
||||
{t('hw.add_submit', 'Добавить')}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useState, useEffect, useMemo } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Cpu, Usb, Plus, Trash2, MemoryStick, Loader2, AlertTriangle } from 'lucide-react';
|
||||
import { Cpu, Usb, HardDrive, Plus, Trash2, MemoryStick, Loader2, AlertTriangle } from 'lucide-react';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Button } from '@/components/ui/button';
|
||||
@@ -26,6 +26,7 @@ import { useImageStorages } from '@/hooks/use-image-catalog';
|
||||
import { toast } from 'sonner';
|
||||
import AddPciDeviceDialog from '../AddPciDeviceDialog';
|
||||
import AddUsbDeviceDialog from '../AddUsbDeviceDialog';
|
||||
import AddPhysicalDiskDialog from '../AddPhysicalDiskDialog';
|
||||
|
||||
interface Props {
|
||||
serverId: number;
|
||||
@@ -214,21 +215,29 @@ export default function HardwareTab({ serverId, vmid, type, node }: Props) {
|
||||
|
||||
const [showAddPci, setShowAddPci] = useState(false);
|
||||
const [showAddUsb, setShowAddUsb] = useState(false);
|
||||
const [showAddDisk, setShowAddDisk] = useState(false);
|
||||
const [deleteTarget, setDeleteTarget] = useState<string | null>(null);
|
||||
|
||||
const cfg = config as Record<string, unknown> | undefined;
|
||||
// Проброс PCI/USB нельзя менять на работающей VM — устройства не поддерживают hotplug.
|
||||
const isRunning = status?.status === 'running';
|
||||
|
||||
// Проброшенные устройства: hostpciN (PCI) и usbN (USB)
|
||||
// Проброшенные устройства: hostpciN (PCI), usbN (USB) и физдиски (scsiN/virtioN/sataN
|
||||
// со значением-путём /dev/...). Обычные диски (storage:size) сюда не попадают.
|
||||
const passthrough = useMemo(() => {
|
||||
if (!cfg) return [] as Array<{ key: string; value: string; kind: 'pci' | 'usb' }>;
|
||||
if (!cfg) return [] as Array<{ key: string; value: string; kind: 'pci' | 'usb' | 'disk' }>;
|
||||
return Object.entries(cfg)
|
||||
.filter(([k]) => /^(hostpci|usb)\d+$/.test(k))
|
||||
.filter(([k, v]) =>
|
||||
/^(hostpci|usb)\d+$/.test(k) ||
|
||||
(/^(scsi|virtio|sata|ide)\d+$/.test(k) && typeof v === 'string' && v.startsWith('/dev/')))
|
||||
.map(([key, value]) => ({
|
||||
key,
|
||||
value: String(value),
|
||||
kind: key.startsWith('hostpci') ? ('pci' as const) : ('usb' as const),
|
||||
kind: key.startsWith('hostpci')
|
||||
? ('pci' as const)
|
||||
: key.startsWith('usb')
|
||||
? ('usb' as const)
|
||||
: ('disk' as const),
|
||||
}))
|
||||
.sort((a, b) => a.key.localeCompare(b.key));
|
||||
}, [cfg]);
|
||||
@@ -270,6 +279,10 @@ export default function HardwareTab({ serverId, vmid, type, node }: Props) {
|
||||
onClick={() => setShowAddUsb(true)}>
|
||||
<Plus className="mr-1.5 h-3.5 w-3.5" />USB
|
||||
</Button>
|
||||
<Button size="sm" variant="outline"
|
||||
onClick={() => setShowAddDisk(true)}>
|
||||
<Plus className="mr-1.5 h-3.5 w-3.5" />{t('hw.disk', 'Диск')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
@@ -291,7 +304,9 @@ export default function HardwareTab({ serverId, vmid, type, node }: Props) {
|
||||
<div className="flex items-center gap-2">
|
||||
{kind === 'pci'
|
||||
? <Cpu className="h-3.5 w-3.5 text-muted-foreground" />
|
||||
: <Usb className="h-3.5 w-3.5 text-muted-foreground" />}
|
||||
: kind === 'usb'
|
||||
? <Usb className="h-3.5 w-3.5 text-muted-foreground" />
|
||||
: <HardDrive className="h-3.5 w-3.5 text-muted-foreground" />}
|
||||
<Badge variant="outline">{key}</Badge>
|
||||
<span className="font-mono text-xs">{value}</span>
|
||||
</div>
|
||||
@@ -299,9 +314,9 @@ export default function HardwareTab({ serverId, vmid, type, node }: Props) {
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-7 w-7 text-destructive hover:text-destructive"
|
||||
disabled={isRunning}
|
||||
disabled={isRunning && kind !== 'disk'}
|
||||
onClick={() => setDeleteTarget(key)}
|
||||
title={isRunning
|
||||
title={isRunning && kind !== 'disk'
|
||||
? t('hw.stop_first', 'Выключите VM для изменения проброса')
|
||||
: t('hw.remove_device', 'Удалить устройство')}
|
||||
>
|
||||
@@ -332,6 +347,14 @@ export default function HardwareTab({ serverId, vmid, type, node }: Props) {
|
||||
node={node}
|
||||
config={cfg}
|
||||
/>
|
||||
<AddPhysicalDiskDialog
|
||||
open={showAddDisk}
|
||||
onClose={() => setShowAddDisk(false)}
|
||||
serverId={serverId}
|
||||
vmid={vmid}
|
||||
node={node}
|
||||
config={cfg}
|
||||
/>
|
||||
|
||||
{/* Delete confirmation */}
|
||||
<Dialog open={!!deleteTarget} onOpenChange={(o) => !o && setDeleteTarget(null)}>
|
||||
|
||||
@@ -850,7 +850,8 @@ function DiskManagementCard({ serverId, vmid, type, node }: { serverId: number;
|
||||
const re = /^(scsi\d+|sata\d+|virtio\d+|ide\d+)$/;
|
||||
return Object.entries(config)
|
||||
.filter(([k, v]) => re.test(k) && typeof v === 'string'
|
||||
&& !v.includes('media=cdrom') && !v.includes('cloudinit'))
|
||||
&& !v.includes('media=cdrom') && !v.includes('cloudinit')
|
||||
&& !v.startsWith('/dev/')) // проброшенные физдиски — управляются во вкладке «Оборудование»
|
||||
.map(([k]) => k);
|
||||
}, [config]);
|
||||
|
||||
|
||||
@@ -13,6 +13,9 @@ export interface NodeDisk {
|
||||
wearout?: number | string;
|
||||
rpm?: number;
|
||||
gpt?: number;
|
||||
wwn?: string;
|
||||
by_id_link?: string;
|
||||
passthrough_path?: string; // стабильный путь для проброса в VM
|
||||
}
|
||||
|
||||
export interface ZfsPool {
|
||||
|
||||
@@ -608,6 +608,15 @@ export function useAddDisk(serverId: number, vmid: number, node: string) {
|
||||
});
|
||||
}
|
||||
|
||||
export function useAttachPhysicalDisk(serverId: number, vmid: number, node: string) {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: (body: { disk: string; devpath: string; aio?: string; discard?: boolean; ssd?: boolean; serial?: string }) =>
|
||||
apiClient.post(`/proxmox/api/${serverId}/vm/${vmid}/disk/attach-physical?node=${node}`, body),
|
||||
onSuccess: () => qc.invalidateQueries({ queryKey: vmKeys.config(serverId, vmid) }),
|
||||
});
|
||||
}
|
||||
|
||||
export function useDetachDisk(serverId: number, vmid: number, node: string) {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
|
||||
@@ -574,7 +574,20 @@
|
||||
"no_usb": "No devices found",
|
||||
"usb3": "USB 3.0",
|
||||
"err_usb_required": "Select a USB device",
|
||||
"usb_added": "Device {{key}} added"
|
||||
"usb_added": "Device {{key}} added",
|
||||
"disk": "Disk",
|
||||
"add_disk_title": "Physical disk passthrough",
|
||||
"add_disk_description": "Will be added as {{key}}",
|
||||
"disk_device": "Disk",
|
||||
"select_disk": "Select a disk",
|
||||
"no_disks": "No disks found",
|
||||
"disk_bus": "Bus",
|
||||
"disk_ssd": "Emulate SSD",
|
||||
"disk_discard": "Discard / TRIM",
|
||||
"disk_used_warn": "Disk is in use ({{used}}) — passthrough may cause data loss.",
|
||||
"disk_passthrough_hint": "The disk is given to the VM exclusively via a stable /dev/disk/by-id/ path. Bound to this node — migration to another node is not available.",
|
||||
"err_disk_required": "Select a disk",
|
||||
"disk_added": "Disk {{key}} passed through"
|
||||
},
|
||||
"fw": {
|
||||
"title": "Firewall (datacenter)",
|
||||
|
||||
@@ -574,7 +574,20 @@
|
||||
"no_usb": "Устройства не найдены",
|
||||
"usb3": "USB 3.0",
|
||||
"err_usb_required": "Выберите USB-устройство",
|
||||
"usb_added": "Устройство {{key}} добавлено"
|
||||
"usb_added": "Устройство {{key}} добавлено",
|
||||
"disk": "Диск",
|
||||
"add_disk_title": "Проброс физического диска",
|
||||
"add_disk_description": "Будет добавлено как {{key}}",
|
||||
"disk_device": "Диск",
|
||||
"select_disk": "Выберите диск",
|
||||
"no_disks": "Диски не найдены",
|
||||
"disk_bus": "Шина",
|
||||
"disk_ssd": "Эмулировать SSD",
|
||||
"disk_discard": "Discard / TRIM",
|
||||
"disk_used_warn": "Диск занят ({{used}}) — проброс может привести к потере данных.",
|
||||
"disk_passthrough_hint": "Диск отдаётся VM монопольно по стабильному пути /dev/disk/by-id/. Привязан к этой ноде — миграция на другую ноду недоступна.",
|
||||
"err_disk_required": "Выберите диск",
|
||||
"disk_added": "Диск {{key}} проброшен"
|
||||
},
|
||||
"fw": {
|
||||
"title": "Firewall (датацентр)",
|
||||
|
||||
Reference in New Issue
Block a user