"use client" import { useState, useMemo } from "react" import { Card, CardContent, CardHeader, CardTitle } from "./ui/card" import { Badge } from "./ui/badge" import { Progress } from "./ui/progress" import { Button } from "./ui/button" import { Dialog, DialogContent, DialogHeader, DialogTitle } from "./ui/dialog" import { Server, Play, Square, Monitor, Cpu, MemoryStick, HardDrive, Network, Power, RotateCcw, StopCircle, AlertTriangle, CheckCircle, } from "lucide-react" import useSWR from "swr" interface VMData { vmid: number name: string status: string type: string cpu: number mem: number maxmem: number disk: number maxdisk: number uptime: number netin?: number netout?: number diskread?: number diskwrite?: number ipaddress?: string } interface VMConfig { cores?: number memory?: number swap?: number rootfs?: string net0?: string net1?: string net2?: string nameserver?: string searchdomain?: string onboot?: number unprivileged?: number features?: string ostype?: string arch?: string hostname?: string // VM specific sockets?: number scsi0?: string ide0?: string boot?: string [key: string]: any } interface VMDetails extends VMData { config?: VMConfig node?: string vm_type?: string } const fetcher = async (url: string) => { const response = await fetch(url, { method: "GET", headers: { "Content-Type": "application/json", }, signal: AbortSignal.timeout(5000), }) if (!response.ok) { throw new Error(`Flask server responded with status: ${response.status}`) } const data = await response.json() return Array.isArray(data) ? data : [] } const formatBytes = (bytes: number | undefined): string => { if (!bytes || bytes === 0) return "0 B" const k = 1024 const sizes = ["B", "KB", "MB", "GB", "TB"] const i = Math.floor(Math.log(bytes) / Math.log(k)) return `${(bytes / Math.pow(k, i)).toFixed(2)} ${sizes[i]}` } export function VirtualMachines() { const { data: vmData, error, isLoading, mutate, } = useSWR("/api/vms", fetcher, { refreshInterval: 30000, revalidateOnFocus: false, revalidateOnReconnect: true, }) const [selectedVM, setSelectedVM] = useState(null) const [vmDetails, setVMDetails] = useState(null) const [controlLoading, setControlLoading] = useState(false) const [detailsLoading, setDetailsLoading] = useState(false) const handleVMClick = async (vm: VMData) => { setSelectedVM(vm) setDetailsLoading(true) try { const response = await fetch(`/api/vms/${vm.vmid}`) if (response.ok) { const details = await response.json() setVMDetails(details) } } catch (error) { console.error("Error fetching VM details:", error) } finally { setDetailsLoading(false) } } const handleVMControl = async (vmid: number, action: string) => { setControlLoading(true) try { const response = await fetch(`/api/vms/${vmid}/control`, { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ action }), }) if (response.ok) { mutate() setSelectedVM(null) setVMDetails(null) } else { console.error("Failed to control VM") } } catch (error) { console.error("Error controlling VM:", error) } finally { setControlLoading(false) } } const handleDownloadLogs = async (vmid: number, vmName: string) => { try { const response = await fetch(`/api/vms/${vmid}/logs`) if (response.ok) { const data = await response.json() // Format logs as plain text let logText = `=== Logs for ${vmName} (VMID: ${vmid}) ===\n` logText += `Node: ${data.node}\n` logText += `Type: ${data.type}\n` logText += `Total lines: ${data.log_lines}\n` logText += `Generated: ${new Date().toISOString()}\n` logText += `\n${"=".repeat(80)}\n\n` if (data.logs && Array.isArray(data.logs)) { data.logs.forEach((log: any) => { if (typeof log === "object" && log.t) { logText += `${log.t}\n` } else if (typeof log === "string") { logText += `${log}\n` } }) } const blob = new Blob([logText], { type: "text/plain" }) const url = URL.createObjectURL(blob) const a = document.createElement("a") a.href = url a.download = `${vmName}-${vmid}-logs.txt` a.click() URL.revokeObjectURL(url) } } catch (error) { console.error("Error downloading logs:", error) } } const getStatusColor = (status: string) => { switch (status) { case "running": return "bg-green-500/10 text-green-500 border-green-500/20" case "stopped": return "bg-red-500/10 text-red-500 border-red-500/20" default: return "bg-yellow-500/10 text-yellow-500 border-yellow-500/20" } } const getStatusIcon = (status: string) => { switch (status) { case "running": return case "stopped": return default: return null } } const getTypeBadge = (type: string) => { if (type === "lxc") { return { color: "bg-cyan-500/10 text-cyan-500 border-cyan-500/20", label: "LXC" } } return { color: "bg-purple-500/10 text-purple-500 border-purple-500/20", label: "VM" } } const formatUptime = (seconds: number) => { const days = Math.floor(seconds / 86400) const hours = Math.floor((seconds % 86400) / 3600) const minutes = Math.floor((seconds % 3600) / 60) return `${days}d ${hours}h ${minutes}m` } // Safe data handling with default empty array const safeVMData = vmData || [] const totalAllocatedMemoryGB = useMemo(() => { return (safeVMData.reduce((sum, vm) => sum + (vm.maxmem || 0), 0) / 1024 ** 3).toFixed(1) }, [safeVMData]) const { data: overviewData } = useSWR("/api/overview", fetcher, { refreshInterval: 30000, revalidateOnFocus: false, }) const physicalMemoryGB = useMemo(() => { if (overviewData && overviewData.memory) { return (overviewData.memory.total / 1024 ** 3).toFixed(1) } return null }, [overviewData]) const isMemoryOvercommit = useMemo(() => { if (physicalMemoryGB) { return Number.parseFloat(totalAllocatedMemoryGB) > Number.parseFloat(physicalMemoryGB) } return false }, [totalAllocatedMemoryGB, physicalMemoryGB]) const getMemoryOvercommitBadge = () => { if (!physicalMemoryGB) return null const allocated = Number.parseFloat(totalAllocatedMemoryGB) const physical = Number.parseFloat(physicalMemoryGB) const overcommitPercent = ((allocated / physical) * 100).toFixed(0) if (allocated > physical) { return { color: "bg-yellow-500/10 text-yellow-500 border-yellow-500/20", icon: , label: "Overcommit", message: `${overcommitPercent}% de memoria física`, } } return { color: "bg-green-500/10 text-green-500 border-green-500/20", icon: , label: "Normal", message: `${overcommitPercent}% de memoria física`, } } const memoryBadge = getMemoryOvercommitBadge() if (isLoading) { return (
Loading virtual machines...
) } if (error) { return (
Error loading virtual machines: {error.message}
) } return (
{/* VM Overview Cards */}
Total VMs & LXCs
{safeVMData.length}
{safeVMData.filter((vm) => vm.status === "running").length} Running {safeVMData.filter((vm) => vm.status === "stopped").length} Stopped

Virtual machines configured

Total CPU
{(safeVMData.reduce((sum, vm) => sum + (vm.cpu || 0), 0) * 100).toFixed(0)}%

Allocated CPU usage

Total Memory
{totalAllocatedMemoryGB} GB
{memoryBadge && (
{memoryBadge.icon} {memoryBadge.label}

{memoryBadge.message}

)}
Average Load
{safeVMData.filter((vm) => vm.status === "running").length > 0 ? ( (safeVMData.reduce((sum, vm) => sum + (vm.cpu || 0), 0) / safeVMData.filter((vm) => vm.status === "running").length) * 100 ).toFixed(0) : 0} %

Average resource utilization

{/* Virtual Machines List */} Virtual Machines & Containers {safeVMData.length === 0 ? (
No virtual machines found
) : (
{safeVMData.map((vm) => { const cpuPercent = (vm.cpu * 100).toFixed(1) const memPercent = vm.maxmem > 0 ? ((vm.mem / vm.maxmem) * 100).toFixed(1) : "0" const memGB = (vm.mem / 1024 ** 3).toFixed(1) const maxMemGB = (vm.maxmem / 1024 ** 3).toFixed(1) const typeBadge = getTypeBadge(vm.type) return (
handleVMClick(vm)} >
{vm.name} {typeBadge.label}
ID: {vm.vmid}
{getStatusIcon(vm.status)} {vm.status.toUpperCase()}
{vm.ipaddress && (
IP Address
{vm.ipaddress}
)}
CPU Usage
{cpuPercent}%
Memory Usage
{memGB} / {maxMemGB} GB
Disk I/O
↓ {formatBytes(vm.diskread)}
↑ {formatBytes(vm.diskwrite)}
Network I/O
↓ {formatBytes(vm.netin)}
↑ {formatBytes(vm.netout)}
Uptime
{formatUptime(vm.uptime)}
) })}
)}
{/* VM Details Modal */} { setSelectedVM(null) setVMDetails(null) }} >
{selectedVM?.name}
{selectedVM && (
{getTypeBadge(selectedVM.type).label} {selectedVM.status.toUpperCase()}
)}
{selectedVM && ( <>

Basic Information

Name
{selectedVM.name}
VMID
{selectedVM.vmid}
{selectedVM.ipaddress && (
IP Address
{selectedVM.ipaddress}
)}
CPU Usage
80 ? "text-red-500" : selectedVM.cpu * 100 > 60 ? "text-yellow-500" : "text-green-500" }`} > {(selectedVM.cpu * 100).toFixed(1)}%
Memory
80 ? "text-red-500" : (selectedVM.mem / selectedVM.maxmem) * 100 > 60 ? "text-yellow-500" : "text-blue-500" }`} > {(selectedVM.mem / 1024 ** 3).toFixed(1)} / {(selectedVM.maxmem / 1024 ** 3).toFixed(1)} GB
Disk
{(selectedVM.disk / 1024 ** 3).toFixed(1)} / {(selectedVM.maxdisk / 1024 ** 3).toFixed(1)} GB
Uptime
{formatUptime(selectedVM.uptime)}
Disk I/O
↓ {formatBytes(selectedVM.diskread)}
↑ {formatBytes(selectedVM.diskwrite)}
Network I/O
↓ {formatBytes(selectedVM.netin)}
↑ {formatBytes(selectedVM.netout)}
{/* Resources Configuration */} {detailsLoading ? (
Loading configuration...
) : vmDetails?.config ? ( <>

Resources

{vmDetails.config.cores && (
CPU Cores
{vmDetails.config.cores}
)} {vmDetails.config.sockets && (
CPU Sockets
{vmDetails.config.sockets}
)} {vmDetails.config.memory && (
Memory
{vmDetails.config.memory} MB
)} {vmDetails.config.swap && (
Swap
{vmDetails.config.swap} MB
)} {vmDetails.config.rootfs && (
Root Filesystem
{vmDetails.config.rootfs}
)} {Object.keys(vmDetails.config) .filter((key) => key.match(/^(scsi|sata|ide|virtio)\d+$/)) .map((diskKey) => (
{diskKey.toUpperCase().replace(/(\d+)/, " $1")}
{vmDetails.config[diskKey]}
))}
{/* Network Configuration */}

Network

{Object.keys(vmDetails.config) .filter((key) => key.match(/^net\d+$/)) .map((netKey) => (
Network Interface {netKey.replace("net", "")}
{vmDetails.config[netKey]}
))} {vmDetails.config.nameserver && (
DNS Nameserver
{vmDetails.config.nameserver}
)} {vmDetails.config.searchdomain && (
Search Domain
{vmDetails.config.searchdomain}
)} {vmDetails.config.hostname && (
Hostname
{vmDetails.config.hostname}
)}
{/* Options */}

Options

{vmDetails.config.onboot !== undefined && (
Start on Boot
{vmDetails.config.onboot ? "Yes" : "No"}
)} {vmDetails.config.unprivileged !== undefined && (
Unprivileged
{vmDetails.config.unprivileged ? "Yes" : "No"}
)} {vmDetails.config.ostype && (
OS Type
{vmDetails.config.ostype}
)} {vmDetails.config.arch && (
Architecture
{vmDetails.config.arch}
)} {vmDetails.config.boot && (
Boot Order
{vmDetails.config.boot}
)} {vmDetails.config.features && (
Features
{vmDetails.config.features}
)}
) : null} {/* Control Actions */}

Control Actions

)}
) }