"use client"
import type React from "react"
import { useState, useMemo, useEffect } 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,
Cpu,
MemoryStick,
HardDrive,
Network,
Power,
RotateCcw,
StopCircle,
Container,
ChevronDown,
ChevronUp,
} from "lucide-react"
import useSWR from "swr"
import { MetricsView } from "./metrics-dialog"
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
ip?: 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
os_info?: {
id?: string
version_id?: string
name?: string
pretty_name?: 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 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]}`
}
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`
}
const extractIPFromConfig = (config?: VMConfig): string => {
if (!config) return "DHCP"
// Check net0, net1, net2, etc.
for (let i = 0; i < 10; i++) {
const netKey = `net${i}`
const netConfig = config[netKey]
if (netConfig && typeof netConfig === "string") {
// Look for ip=x.x.x.x/xx or ip=x.x.x.x pattern
const ipMatch = netConfig.match(/ip=([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})/)
if (ipMatch) {
return ipMatch[1] // Return just the IP without CIDR
}
// Check if it's explicitly DHCP
if (netConfig.includes("ip=dhcp")) {
return "DHCP"
}
}
}
return "DHCP"
}
const formatStorage = (sizeInGB: number): string => {
if (sizeInGB < 1) {
// Less than 1 GB, show in MB
return `${(sizeInGB * 1024).toFixed(1)} MB`
} else if (sizeInGB < 1024) {
// Less than 1024 GB, show in GB
return `${sizeInGB.toFixed(1)} GB`
} else {
// 1024 GB or more, show in TB
return `${(sizeInGB / 1024).toFixed(1)} TB`
}
}
const getUsageColor = (percent: number): string => {
if (percent >= 95) return "text-red-500"
if (percent >= 86) return "text-orange-500"
if (percent >= 71) return "text-yellow-500"
return "text-white"
}
const getIconColor = (percent: number): string => {
if (percent >= 95) return "text-red-500"
if (percent >= 86) return "text-orange-500"
if (percent >= 71) return "text-yellow-500"
return "text-green-500"
}
const getProgressColor = (percent: number): string => {
if (percent >= 95) return "[&>div]:bg-red-500"
if (percent >= 86) return "[&>div]:bg-orange-500"
if (percent >= 71) return "[&>div]:bg-yellow-500"
return "[&>div]:bg-blue-500"
}
const getModalProgressColor = (percent: number): string => {
if (percent >= 95) return "[&>div]:bg-red-500"
if (percent >= 86) return "[&>div]:bg-orange-500"
if (percent >= 71) return "[&>div]:bg-yellow-500"
return "[&>div]:bg-blue-500"
}
const getOSIcon = (osInfo: VMDetails["os_info"] | undefined, vmType: string): React.ReactNode => {
// Only show logo for LXCs, VMs show nothing
if (vmType !== "lxc") {
return null
}
const osId = osInfo?.id?.toLowerCase()
// Try to use SVG icons for common distributions
switch (osId) {
case "debian":
return (
{
// fallback to Container icon if SVG doesn't exist
e.currentTarget.style.display = "none"
e.currentTarget.parentElement!.innerHTML =
'
'
}}
/>
)
case "ubuntu":
return (
{
e.currentTarget.style.display = "none"
e.currentTarget.parentElement!.innerHTML =
''
}}
/>
)
case "alpine":
return (
{
e.currentTarget.style.display = "none"
e.currentTarget.parentElement!.innerHTML =
''
}}
/>
)
case "arch":
return (
{
e.currentTarget.style.display = "none"
e.currentTarget.parentElement!.innerHTML =
''
}}
/>
)
default:
// Generic LXC container icon
return
}
}
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 [vmConfigs, setVmConfigs] = useState>({})
const [currentView, setCurrentView] = useState<"main" | "metrics">("main")
const [showAdditionalInfo, setShowAdditionalInfo] = useState(false)
const [selectedMetric, setSelectedMetric] = useState(null) // undeclared variable fix
useEffect(() => {
const fetchLXCIPs = async () => {
if (!vmData) return
const lxcs = vmData.filter((vm) => vm.type === "lxc")
const configs: Record = {}
await Promise.all(
lxcs.map(async (lxc) => {
try {
const response = await fetch(`/api/vms/${lxc.vmid}`)
if (response.ok) {
const details = await response.json()
if (details.config) {
configs[lxc.vmid] = extractIPFromConfig(details.config)
}
}
} catch (error) {
console.error(`Error fetching config for LXC ${lxc.vmid}:`, error)
}
}),
)
setVmConfigs(configs)
}
fetchLXCIPs()
}, [vmData])
const handleVMClick = async (vm: VMData) => {
setSelectedVM(vm)
setCurrentView("main")
setShowAdditionalInfo(false)
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 handleMetricsClick = () => {
setCurrentView("metrics")
}
const handleBackToMain = () => {
setCurrentView("main")
}
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",
icon: ,
}
}
return {
color: "bg-purple-500/10 text-purple-500 border-purple-500/20",
label: "VM",
icon: ,
}
}
const safeVMData = vmData || []
const totalAllocatedMemoryGB = useMemo(() => {
return (safeVMData.reduce((sum, vm) => sum + (vm.maxmem || 0), 0) / 1024 ** 3).toFixed(1)
}, [safeVMData])
const { data: systemData } = useSWR<{ memory_total: number; memory_used: number; memory_usage: number }>(
"/api/system",
fetcher,
{
refreshInterval: 30000,
revalidateOnFocus: false,
},
)
const physicalMemoryGB = systemData?.memory_total ?? null
const usedMemoryGB = systemData?.memory_used ?? null
const memoryUsagePercent = systemData?.memory_usage ?? null
const allocatedMemoryGB = Number.parseFloat(totalAllocatedMemoryGB)
const isMemoryOvercommit = physicalMemoryGB !== null && allocatedMemoryGB > physicalMemoryGB
const getMemoryUsageColor = (percent: number | null) => {
if (percent === null) return "bg-blue-500"
if (percent >= 95) return "bg-red-500"
if (percent >= 86) return "bg-orange-500"
if (percent >= 71) return "bg-yellow-500"
return "bg-blue-500"
}
const getMemoryPercentTextColor = (percent: number | null) => {
if (percent === null) return "text-muted-foreground"
if (percent >= 95) return "text-red-500"
if (percent >= 86) return "text-orange-500"
if (percent >= 71) return "text-yellow-500"
return "text-green-500"
}
if (isLoading) {
return (
Loading virtual machines...
)
}
if (error) {
return (
Error loading virtual machines: {error.message}
)
}
return (
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
{/* Memory Usage (current) */}
{physicalMemoryGB !== null && usedMemoryGB !== null && memoryUsagePercent !== null ? (
{usedMemoryGB.toFixed(1)} GB
{memoryUsagePercent.toFixed(1)}%
{" "}
of {physicalMemoryGB.toFixed(1)} GB
) : (
--
Loading memory usage...
)}
{/* Allocated RAM (configured) */}
{totalAllocatedMemoryGB} GB
Allocated RAM
{physicalMemoryGB !== null && (
{isMemoryOvercommit ? (
Exceeds Physical
) : (
Within Limits
)}
)}
Total Disk
{formatStorage(safeVMData.reduce((sum, vm) => sum + (vm.maxdisk || 0), 0) / 1024 ** 3)}
Allocated disk space
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 diskPercent = vm.maxdisk > 0 ? ((vm.disk / vm.maxdisk) * 100).toFixed(1) : "0"
const diskGB = (vm.disk / 1024 ** 3).toFixed(1)
const maxDiskGB = (vm.maxdisk / 1024 ** 3).toFixed(1)
const typeBadge = getTypeBadge(vm.type)
const lxcIP = vm.type === "lxc" ? vmConfigs[vm.vmid] : null
return (
handleVMClick(vm)}
>
{getStatusIcon(vm.status)}
{vm.status.toUpperCase()}
{typeBadge.icon}
{typeBadge.label}
{lxcIP && (
IP: {lxcIP}
)}
Uptime: {formatUptime(vm.uptime)}
CPU Usage
{
setSelectedMetric("cpu") // undeclared variable fix
}}
>
{cpuPercent}%
Memory
{
setSelectedMetric("memory")
}}
>
{memGB} / {maxMemGB} GB
Disk Usage
{
setSelectedMetric("disk")
}}
>
{diskGB} / {maxDiskGB} GB
Disk I/O
↓ {formatBytes(vm.diskread)}
↑ {formatBytes(vm.diskwrite)}
Network I/O
↓ {formatBytes(vm.netin)}
↑ {formatBytes(vm.netout)}
handleVMClick(vm)}
>
{vm.status === "running" ? (
) : (
)}
{getTypeBadge(vm.type).label}
{/* Name and ID */}
{/* CPU icon with percentage */}
{vm.status === "running" && (
{cpuPercent}%
)}
{/* Memory icon with percentage */}
{vm.status === "running" && (
{memPercent}%
)}
{/* Disk icon with percentage */}
{vm.status === "running" && (
{diskPercent}%
)}
)
})}
)}
)
}