"use client" import { useState } 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, AlertCircle, HardDrive, Network, Power, RotateCcw, Download, StopCircle, } 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 } 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, // Refresh every 30 seconds revalidateOnFocus: false, revalidateOnReconnect: true, }) const [selectedVM, setSelectedVM] = useState(null) const [controlLoading, setControlLoading] = useState(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) { // Refresh VM data after action mutate() setSelectedVM(null) } else { console.error("Failed to control VM") } } catch (error) { console.error("Error controlling VM:", error) } finally { setControlLoading(false) } } const handleDownloadLogs = async (vmid: number) => { try { const response = await fetch(`/api/vms/${vmid}/logs`) if (response.ok) { const data = await response.json() const blob = new Blob([JSON.stringify(data, null, 2)], { type: "application/json" }) const url = URL.createObjectURL(blob) const a = document.createElement("a") a.href = url a.download = `vm-${vmid}-logs.json` a.click() URL.revokeObjectURL(url) } } catch (error) { console.error("Error downloading logs:", error) } } if (isLoading) { return (
Loading VM data...
) } if (error || !vmData) { return (
Flask Server Not Available
{error?.message || "Unable to connect to the Flask server. Please ensure the server is running and try again."}
) } const runningVMs = vmData.filter((vm) => vm.status === "running").length const stoppedVMs = vmData.filter((vm) => vm.status === "stopped").length const totalCPU = vmData.reduce((sum, vm) => sum + (vm.cpu || 0), 0) const totalMemory = vmData.reduce((sum, vm) => sum + (vm.maxmem || 0), 0) 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` } return (
{/* VM Overview Cards */}
Total VMs & LXCs
{vmData.length}
{runningVMs} Running {stoppedVMs} Stopped

Virtual machines configured

Total CPU
{(totalCPU * 100).toFixed(0)}%

Allocated CPU usage

Total Memory
{(totalMemory / 1024 ** 3).toFixed(1)} GB

Allocated RAM

Average Load
{runningVMs > 0 ? ((totalCPU / runningVMs) * 100).toFixed(0) : 0}%

Average resource utilization

{/* Virtual Machines List */} Virtual Machines & Containers {vmData.length === 0 ? (
No virtual machines found
) : (
{vmData.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 (
setSelectedVM(vm)} >
{vm.name} {typeBadge.label}
ID: {vm.vmid}
{getStatusIcon(vm.status)} {vm.status.toUpperCase()}
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)}> {selectedVM?.name} - Details {selectedVM && (
{/* Basic Information */}

Basic Information

Name
{selectedVM.name}
Type
{getTypeBadge(selectedVM.type).label}
VMID
{selectedVM.vmid}
Status
{selectedVM.status.toUpperCase()}
CPU Usage
{(selectedVM.cpu * 100).toFixed(1)}%
Memory
{(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)}
{/* Control Actions */}

Control Actions

{/* Download Logs */}
)}
) }