Update AppImage

This commit is contained in:
MacRimi
2025-09-30 00:09:11 +02:00
parent 00db93e03f
commit acc0362180
4 changed files with 622 additions and 748 deletions

View File

@@ -1,31 +1,111 @@
"use client"
import { useState, useEffect } from "react"
import { Card, CardContent, CardHeader, CardTitle } from "./ui/card"
import { Badge } from "./ui/badge"
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, AreaChart, Area } from "recharts"
import { Wifi, Globe, Shield, Activity, Network, Router } from "lucide-react"
import { Wifi, Globe, Shield, Activity, Network, Router, AlertCircle } from "lucide-react"
const networkTraffic = [
{ time: "00:00", incoming: 45, outgoing: 32 },
{ time: "04:00", incoming: 52, outgoing: 28 },
{ time: "08:00", incoming: 78, outgoing: 65 },
{ time: "12:00", incoming: 65, outgoing: 45 },
{ time: "16:00", incoming: 82, outgoing: 58 },
{ time: "20:00", incoming: 58, outgoing: 42 },
{ time: "24:00", incoming: 43, outgoing: 35 },
]
interface NetworkData {
interfaces: NetworkInterface[]
traffic: {
bytes_sent: number
bytes_recv: number
packets_sent?: number
packets_recv?: number
}
}
const connectionData = [
{ time: "00:00", connections: 1250 },
{ time: "04:00", connections: 980 },
{ time: "08:00", connections: 1850 },
{ time: "12:00", connections: 1650 },
{ time: "16:00", connections: 2100 },
{ time: "20:00", connections: 1580 },
{ time: "24:00", connections: 1320 },
]
interface NetworkInterface {
name: string
status: string
addresses: Array<{
ip: string
netmask: string
}>
}
const fetchNetworkData = async (): Promise<NetworkData | null> => {
try {
console.log("[v0] Fetching network data from Flask server...")
const response = await fetch("/api/network", {
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()
console.log("[v0] Successfully fetched network data from Flask:", data)
return data
} catch (error) {
console.error("[v0] Failed to fetch network data from Flask server:", error)
return null
}
}
export function NetworkMetrics() {
const [networkData, setNetworkData] = useState<NetworkData | null>(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
useEffect(() => {
const fetchData = async () => {
setLoading(true)
setError(null)
const result = await fetchNetworkData()
if (!result) {
setError("Flask server not available. Please ensure the server is running.")
} else {
setNetworkData(result)
}
setLoading(false)
}
fetchData()
const interval = setInterval(fetchData, 30000)
return () => clearInterval(interval)
}, [])
if (loading) {
return (
<div className="space-y-6">
<div className="text-center py-8">
<div className="text-lg font-medium text-foreground mb-2">Loading network data...</div>
</div>
</div>
)
}
if (error || !networkData) {
return (
<div className="space-y-6">
<Card className="bg-red-500/10 border-red-500/20">
<CardContent className="p-6">
<div className="flex items-center gap-3 text-red-600">
<AlertCircle className="h-6 w-6" />
<div>
<div className="font-semibold text-lg mb-1">Flask Server Not Available</div>
<div className="text-sm">
{error || "Unable to connect to the Flask server. Please ensure the server is running and try again."}
</div>
</div>
</div>
</CardContent>
</Card>
</div>
)
}
const trafficInMB = (networkData.traffic.bytes_recv / (1024 * 1024)).toFixed(1)
const trafficOutMB = (networkData.traffic.bytes_sent / (1024 * 1024)).toFixed(1)
return (
<div className="space-y-6">
{/* Network Overview Cards */}
@@ -36,30 +116,30 @@ export function NetworkMetrics() {
<Activity className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold text-foreground">156 MB/s</div>
<div className="text-2xl font-bold text-foreground">{trafficInMB} MB</div>
<div className="flex items-center space-x-2 mt-2">
<span className="text-xs text-green-500"> 89 MB/s</span>
<span className="text-xs text-blue-500"> 67 MB/s</span>
<span className="text-xs text-green-500"> {trafficInMB} MB</span>
<span className="text-xs text-blue-500"> {trafficOutMB} MB</span>
</div>
<p className="text-xs text-muted-foreground mt-2">Peak: 245 MB/s at 16:30</p>
<p className="text-xs text-muted-foreground mt-2">Total data transferred</p>
</CardContent>
</Card>
<Card className="bg-card border-border">
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium text-muted-foreground">Active Connections</CardTitle>
<CardTitle className="text-sm font-medium text-muted-foreground">Active Interfaces</CardTitle>
<Network className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold text-foreground">1,847</div>
<div className="text-2xl font-bold text-foreground">
{networkData.interfaces.filter((i) => i.status === "up").length}
</div>
<div className="flex items-center mt-2">
<Badge variant="outline" className="bg-green-500/10 text-green-500 border-green-500/20">
Normal
Online
</Badge>
</div>
<p className="text-xs text-muted-foreground mt-2">
<span className="text-green-500"> 12%</span> from last hour
</p>
<p className="text-xs text-muted-foreground mt-2">{networkData.interfaces.length} total interfaces</p>
</CardContent>
</Card>
@@ -75,7 +155,7 @@ export function NetworkMetrics() {
Protected
</Badge>
</div>
<p className="text-xs text-muted-foreground mt-2">247 blocked attempts today</p>
<p className="text-xs text-muted-foreground mt-2">System protected</p>
</CardContent>
</Card>
@@ -83,97 +163,19 @@ export function NetworkMetrics() {
<CardHeader>
<CardTitle className="text-foreground flex items-center">
<Globe className="h-5 w-5 mr-2" />
Latency
Packets
</CardTitle>
</CardHeader>
<CardContent>
<div className="text-2xl font-bold text-foreground">12ms</div>
<div className="text-2xl font-bold text-foreground">
{networkData.traffic.packets_recv ? (networkData.traffic.packets_recv / 1000).toFixed(0) : "N/A"}K
</div>
<div className="flex items-center mt-2">
<Badge variant="outline" className="bg-green-500/10 text-green-500 border-green-500/20">
Excellent
Received
</Badge>
</div>
<p className="text-xs text-muted-foreground mt-2">Avg response time</p>
</CardContent>
</Card>
</div>
{/* Network Charts */}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
<Card className="bg-card border-border">
<CardHeader>
<CardTitle className="text-foreground flex items-center">
<Activity className="h-5 w-5 mr-2" />
Network Traffic (24h)
</CardTitle>
</CardHeader>
<CardContent>
<ResponsiveContainer width="100%" height={300}>
<AreaChart data={networkTraffic}>
<CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border))" />
<XAxis dataKey="time" stroke="hsl(var(--muted-foreground))" fontSize={12} />
<YAxis stroke="hsl(var(--muted-foreground))" fontSize={12} />
<Tooltip
contentStyle={{
backgroundColor: "hsl(var(--card))",
border: "1px solid hsl(var(--border))",
borderRadius: "8px",
color: "hsl(var(--foreground))",
}}
formatter={(value, name) => [`${value} MB/s`, name === "incoming" ? "Incoming" : "Outgoing"]}
/>
<Area
type="monotone"
dataKey="incoming"
stackId="1"
stroke="#10b981"
fill="#10b981"
fillOpacity={0.6}
/>
<Area
type="monotone"
dataKey="outgoing"
stackId="1"
stroke="#3b82f6"
fill="#3b82f6"
fillOpacity={0.6}
/>
</AreaChart>
</ResponsiveContainer>
</CardContent>
</Card>
<Card className="bg-card border-border">
<CardHeader>
<CardTitle className="text-foreground flex items-center">
<Network className="h-5 w-5 mr-2" />
Active Connections (24h)
</CardTitle>
</CardHeader>
<CardContent>
<ResponsiveContainer width="100%" height={300}>
<LineChart data={connectionData}>
<CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border))" />
<XAxis dataKey="time" stroke="hsl(var(--muted-foreground))" fontSize={12} />
<YAxis stroke="hsl(var(--muted-foreground))" fontSize={12} />
<Tooltip
contentStyle={{
backgroundColor: "hsl(var(--card))",
border: "1px solid hsl(var(--border))",
borderRadius: "8px",
color: "hsl(var(--foreground))",
}}
formatter={(value) => [`${value}`, "Connections"]}
/>
<Line
type="monotone"
dataKey="connections"
stroke="#8b5cf6"
strokeWidth={3}
dot={{ fill: "#8b5cf6", strokeWidth: 2, r: 5 }}
/>
</LineChart>
</ResponsiveContainer>
<p className="text-xs text-muted-foreground mt-2">Total packets received</p>
</CardContent>
</Card>
</div>
@@ -188,44 +190,7 @@ export function NetworkMetrics() {
</CardHeader>
<CardContent>
<div className="space-y-4">
{[
{
name: "vmbr0",
type: "Bridge",
status: "up",
ip: "192.168.1.100/24",
speed: "1000 Mbps",
rx: "2.3 GB",
tx: "1.8 GB",
},
{
name: "enp1s0",
type: "Physical",
status: "up",
ip: "192.168.1.101/24",
speed: "1000 Mbps",
rx: "1.2 GB",
tx: "890 MB",
},
{
name: "vmbr1",
type: "Bridge",
status: "up",
ip: "10.0.0.1/24",
speed: "1000 Mbps",
rx: "456 MB",
tx: "234 MB",
},
{
name: "tap101i0",
type: "TAP",
status: "up",
ip: "10.0.0.101/24",
speed: "1000 Mbps",
rx: "123 MB",
tx: "89 MB",
},
].map((interface_, index) => (
{networkData.interfaces.map((interface_, index) => (
<div
key={index}
className="flex items-center justify-between p-4 rounded-lg border border-border bg-card/50"
@@ -234,26 +199,33 @@ export function NetworkMetrics() {
<Wifi className="h-5 w-5 text-muted-foreground" />
<div>
<div className="font-medium text-foreground">{interface_.name}</div>
<div className="text-sm text-muted-foreground">
{interface_.type} {interface_.speed}
</div>
<div className="text-sm text-muted-foreground">Network Interface</div>
</div>
</div>
<div className="flex items-center space-x-6">
<div className="text-center">
<div className="text-sm text-muted-foreground">IP Address</div>
<div className="text-sm font-medium text-foreground font-mono">{interface_.ip}</div>
</div>
<div className="text-center">
<div className="text-sm text-muted-foreground">RX / TX</div>
<div className="text-sm font-medium text-foreground">
{interface_.rx} / {interface_.tx}
<div className="text-sm font-medium text-foreground font-mono">
{interface_.addresses.length > 0 ? interface_.addresses[0].ip : "N/A"}
</div>
</div>
<Badge variant="outline" className="bg-green-500/10 text-green-500 border-green-500/20">
<div className="text-center">
<div className="text-sm text-muted-foreground">Netmask</div>
<div className="text-sm font-medium text-foreground">
{interface_.addresses.length > 0 ? interface_.addresses[0].netmask : "N/A"}
</div>
</div>
<Badge
variant="outline"
className={
interface_.status === "up"
? "bg-green-500/10 text-green-500 border-green-500/20"
: "bg-red-500/10 text-red-500 border-red-500/20"
}
>
{interface_.status.toUpperCase()}
</Badge>
</div>

View File

@@ -1,24 +1,111 @@
"use client"
import { useState, useEffect } from "react"
import { Card, CardContent, CardHeader, CardTitle } from "./ui/card"
import { Progress } from "./ui/progress"
import { Badge } from "./ui/badge"
import { ResponsiveContainer, BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip } from "recharts"
import { HardDrive, Database, Archive, AlertTriangle, CheckCircle, Activity } from "lucide-react"
import { HardDrive, Database, Archive, AlertTriangle, CheckCircle, Activity, AlertCircle } from "lucide-react"
const storageData = [
{ name: "Used", value: 1250, color: "#3b82f6" }, // Blue
{ name: "Available", value: 750, color: "#10b981" }, // Green
]
interface StorageData {
total: number
used: number
available: number
disks: DiskInfo[]
}
const diskPerformance = [
{ disk: "sda", read: 45, write: 32, iops: 1250 },
{ disk: "sdb", read: 67, write: 28, iops: 980 },
{ disk: "sdc", read: 23, write: 45, iops: 1100 },
{ disk: "nvme0n1", read: 156, write: 89, iops: 3400 },
]
interface DiskInfo {
name: string
mountpoint: string
fstype: string
total: number
used: number
available: number
usage_percent: number
health: string
temperature: number
}
const fetchStorageData = async (): Promise<StorageData | null> => {
try {
console.log("[v0] Fetching storage data from Flask server...")
const response = await fetch("/api/storage", {
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()
console.log("[v0] Successfully fetched storage data from Flask:", data)
return data
} catch (error) {
console.error("[v0] Failed to fetch storage data from Flask server:", error)
return null
}
}
export function StorageMetrics() {
const [storageData, setStorageData] = useState<StorageData | null>(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
useEffect(() => {
const fetchData = async () => {
setLoading(true)
setError(null)
const result = await fetchStorageData()
if (!result) {
setError("Flask server not available. Please ensure the server is running.")
} else {
setStorageData(result)
}
setLoading(false)
}
fetchData()
const interval = setInterval(fetchData, 30000)
return () => clearInterval(interval)
}, [])
if (loading) {
return (
<div className="space-y-6">
<div className="text-center py-8">
<div className="text-lg font-medium text-foreground mb-2">Loading storage data...</div>
</div>
</div>
)
}
if (error || !storageData) {
return (
<div className="space-y-6">
<Card className="bg-red-500/10 border-red-500/20">
<CardContent className="p-6">
<div className="flex items-center gap-3 text-red-600">
<AlertCircle className="h-6 w-6" />
<div>
<div className="font-semibold text-lg mb-1">Flask Server Not Available</div>
<div className="text-sm">
{error || "Unable to connect to the Flask server. Please ensure the server is running and try again."}
</div>
</div>
</div>
</CardContent>
</Card>
</div>
)
}
const usagePercent = storageData.total > 0 ? (storageData.used / storageData.total) * 100 : 0
return (
<div className="space-y-6">
{/* Storage Overview Cards */}
@@ -29,21 +116,23 @@ export function StorageMetrics() {
<HardDrive className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold text-foreground">2.0 TB</div>
<Progress value={62.5} className="mt-2" />
<p className="text-xs text-muted-foreground mt-2">1.25 TB used 750 GB available</p>
<div className="text-2xl font-bold text-foreground">{storageData.total.toFixed(1)} GB</div>
<Progress value={usagePercent} className="mt-2" />
<p className="text-xs text-muted-foreground mt-2">
{storageData.used.toFixed(1)} GB used {storageData.available.toFixed(1)} GB available
</p>
</CardContent>
</Card>
<Card className="bg-card border-border">
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium text-muted-foreground">VM & LXC Storage</CardTitle>
<CardTitle className="text-sm font-medium text-muted-foreground">Used Storage</CardTitle>
<Database className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold text-foreground">890 GB</div>
<Progress value={71.2} className="mt-2" />
<p className="text-xs text-muted-foreground mt-2">71.2% of allocated space</p>
<div className="text-2xl font-bold text-foreground">{storageData.used.toFixed(1)} GB</div>
<Progress value={usagePercent} className="mt-2" />
<p className="text-xs text-muted-foreground mt-2">{usagePercent.toFixed(1)}% of total space</p>
</CardContent>
</Card>
@@ -51,17 +140,17 @@ export function StorageMetrics() {
<CardHeader>
<CardTitle className="text-foreground flex items-center">
<Archive className="h-5 w-5 mr-2" />
Backups
Available
</CardTitle>
</CardHeader>
<CardContent>
<div className="text-2xl font-bold text-foreground">245 GB</div>
<div className="text-2xl font-bold text-foreground">{storageData.available.toFixed(1)} GB</div>
<div className="flex items-center mt-2">
<Badge variant="outline" className="bg-green-500/10 text-green-500 border-green-500/20">
12 Backups
{((storageData.available / storageData.total) * 100).toFixed(1)}% Free
</Badge>
</div>
<p className="text-xs text-muted-foreground mt-2">Last backup: 2h ago</p>
<p className="text-xs text-muted-foreground mt-2">Available space</p>
</CardContent>
</Card>
@@ -69,104 +158,17 @@ export function StorageMetrics() {
<CardHeader>
<CardTitle className="text-foreground flex items-center">
<Activity className="h-5 w-5 mr-2" />
IOPS
Disks
</CardTitle>
</CardHeader>
<CardContent>
<div className="text-2xl font-bold text-foreground">6.7K</div>
<div className="text-2xl font-bold text-foreground">{storageData.disks.length}</div>
<div className="flex items-center space-x-2 mt-2">
<span className="text-xs text-green-500">Read: 4.2K</span>
<span className="text-xs text-blue-500">Write: 2.5K</span>
<Badge variant="outline" className="bg-green-500/10 text-green-500 border-green-500/20">
{storageData.disks.filter((d) => d.health === "healthy").length} Healthy
</Badge>
</div>
<p className="text-xs text-muted-foreground mt-2">Average operations/sec</p>
</CardContent>
</Card>
</div>
{/* Storage Distribution and Performance */}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
<Card className="bg-card border-border">
<CardHeader>
<CardTitle className="text-foreground flex items-center">
<HardDrive className="h-5 w-5 mr-2" />
Storage Distribution
</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-4">
<div className="space-y-2">
<div className="flex justify-between text-sm">
<span className="text-foreground font-medium">Used Storage</span>
<span className="text-muted-foreground">1.25 TB (62.5%)</span>
</div>
<div className="w-full bg-muted rounded-full h-3">
<div
className="bg-blue-500 h-3 rounded-full transition-all duration-300"
style={{ width: "62.5%" }}
></div>
</div>
</div>
<div className="space-y-2">
<div className="flex justify-between text-sm">
<span className="text-foreground font-medium">Available Storage</span>
<span className="text-muted-foreground">750 GB (37.5%)</span>
</div>
<div className="w-full bg-muted rounded-full h-3">
<div
className="bg-green-500 h-3 rounded-full transition-all duration-300"
style={{ width: "37.5%" }}
></div>
</div>
</div>
<div className="pt-4 border-t border-border">
<div className="grid grid-cols-2 gap-4 text-center">
<div className="space-y-1">
<div className="flex items-center justify-center">
<div className="w-3 h-3 bg-blue-500 rounded-full mr-2"></div>
<span className="text-sm font-medium text-foreground">Used</span>
</div>
<div className="text-lg font-bold text-foreground">1.25 TB</div>
</div>
<div className="space-y-1">
<div className="flex items-center justify-center">
<div className="w-3 h-3 bg-green-500 rounded-full mr-2"></div>
<span className="text-sm font-medium text-foreground">Available</span>
</div>
<div className="text-lg font-bold text-foreground">750 GB</div>
</div>
</div>
</div>
</div>
</CardContent>
</Card>
<Card className="bg-card border-border">
<CardHeader>
<CardTitle className="text-foreground flex items-center">
<Activity className="h-5 w-5 mr-2" />
Disk Performance
</CardTitle>
</CardHeader>
<CardContent>
<ResponsiveContainer width="100%" height={300}>
<BarChart data={diskPerformance}>
<CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border))" />
<XAxis dataKey="disk" stroke="hsl(var(--muted-foreground))" fontSize={12} />
<YAxis stroke="hsl(var(--muted-foreground))" fontSize={12} />
<Tooltip
contentStyle={{
backgroundColor: "hsl(var(--card))",
border: "1px solid hsl(var(--border))",
borderRadius: "8px",
color: "hsl(var(--foreground))",
}}
/>
<Bar dataKey="read" fill="#3b82f6" name="Read MB/s" />
<Bar dataKey="write" fill="#10b981" name="Write MB/s" />
</BarChart>
</ResponsiveContainer>
<p className="text-xs text-muted-foreground mt-2">Storage devices</p>
</CardContent>
</Card>
</div>
@@ -181,12 +183,7 @@ export function StorageMetrics() {
</CardHeader>
<CardContent>
<div className="space-y-4">
{[
{ name: "/dev/sda", type: "HDD", size: "1TB", used: "650GB", health: "healthy", temp: "42°C" },
{ name: "/dev/sdb", type: "HDD", size: "1TB", used: "480GB", health: "healthy", temp: "38°C" },
{ name: "/dev/sdc", type: "SSD", size: "500GB", used: "120GB", health: "healthy", temp: "35°C" },
{ name: "/dev/nvme0n1", type: "NVMe", size: "1TB", used: "340GB", health: "warning", temp: "55°C" },
].map((disk, index) => (
{storageData.disks.map((disk, index) => (
<div
key={index}
className="flex items-center justify-between p-4 rounded-lg border border-border bg-card/50"
@@ -196,7 +193,7 @@ export function StorageMetrics() {
<div>
<div className="font-medium text-foreground">{disk.name}</div>
<div className="text-sm text-muted-foreground">
{disk.type} {disk.size}
{disk.fstype} {disk.mountpoint}
</div>
</div>
</div>
@@ -204,17 +201,14 @@ export function StorageMetrics() {
<div className="flex items-center space-x-6">
<div className="text-right">
<div className="text-sm font-medium text-foreground">
{disk.used} / {disk.size}
{disk.used.toFixed(1)} GB / {disk.total.toFixed(1)} GB
</div>
<Progress
value={(Number.parseInt(disk.used) / Number.parseInt(disk.size)) * 100}
className="w-24 mt-1"
/>
<Progress value={disk.usage_percent} className="w-24 mt-1" />
</div>
<div className="text-center">
<div className="text-sm text-muted-foreground">Temp</div>
<div className="text-sm font-medium text-foreground">{disk.temp}</div>
<div className="text-sm font-medium text-foreground">{disk.temperature}°C</div>
</div>
<Badge

View File

@@ -5,7 +5,7 @@ import { Card, CardContent, CardHeader, CardTitle } from "./ui/card"
import { Progress } from "./ui/progress"
import { Badge } from "./ui/badge"
import { XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, AreaChart, Area } from "recharts"
import { Cpu, MemoryStick, Thermometer, Users, Activity, Server, Zap, AlertCircle } from "lucide-react"
import { Cpu, MemoryStick, Thermometer, Activity, Server, Zap, AlertCircle } from "lucide-react"
interface SystemData {
cpu_usage: number
@@ -32,64 +32,25 @@ interface VMData {
uptime: number
}
const generateDemoSystemData = (): SystemData => ({
cpu_usage: Math.floor(Math.random() * 20) + 60, // 60-80%
memory_usage: Math.floor(Math.random() * 10) + 45, // 45-55%
memory_total: 32.0,
memory_used: 15.8 + Math.random() * 2, // 15.8-17.8 GB
temperature: Math.floor(Math.random() * 8) + 48, // 48-56°C
uptime: "15d 7h 23m",
load_average: [1.23, 1.45, 1.67],
hostname: "proxmox-demo",
node_id: "pve-demo-node",
timestamp: new Date().toISOString(),
})
interface HistoricalData {
timestamp: string
cpu_usage: number
memory_used: number
memory_total: number
}
const demVMData: VMData[] = [
{
vmid: 100,
name: "web-server-01",
status: "running",
cpu: 0.45,
mem: 8589934592,
maxmem: 17179869184,
disk: 53687091200,
maxdisk: 107374182400,
uptime: 1324800,
},
{
vmid: 101,
name: "database-server",
status: "running",
cpu: 0.23,
mem: 4294967296,
maxmem: 8589934592,
disk: 26843545600,
maxdisk: 53687091200,
uptime: 864000,
},
{
vmid: 102,
name: "backup-server",
status: "stopped",
cpu: 0,
mem: 0,
maxmem: 4294967296,
disk: 10737418240,
maxdisk: 21474836480,
uptime: 0,
},
]
const historicalDataStore: HistoricalData[] = []
const MAX_HISTORICAL_POINTS = 24 // Store 24 data points for 24h view
const fetchSystemData = async (): Promise<{ data: SystemData | null; isDemo: boolean }> => {
const fetchSystemData = async (): Promise<SystemData | null> => {
try {
console.log("[v0] Attempting to fetch system data from Flask server...")
console.log("[v0] Fetching system data from Flask server...")
const response = await fetch("/api/system", {
method: "GET",
headers: {
"Content-Type": "application/json",
},
signal: AbortSignal.timeout(3000), // Reduced timeout for faster fallback
signal: AbortSignal.timeout(5000),
})
if (!response.ok) {
@@ -98,22 +59,36 @@ const fetchSystemData = async (): Promise<{ data: SystemData | null; isDemo: boo
const data = await response.json()
console.log("[v0] Successfully fetched real system data from Flask:", data)
return { data, isDemo: false }
// Store historical data
historicalDataStore.push({
timestamp: data.timestamp,
cpu_usage: data.cpu_usage,
memory_used: data.memory_used,
memory_total: data.memory_total,
})
// Keep only last MAX_HISTORICAL_POINTS
if (historicalDataStore.length > MAX_HISTORICAL_POINTS) {
historicalDataStore.shift()
}
return data
} catch (error) {
console.log("[v0] Flask server not available, using demo data for development")
return { data: generateDemoSystemData(), isDemo: true }
console.error("[v0] Failed to fetch system data from Flask server:", error)
return null
}
}
const fetchVMData = async (): Promise<{ data: VMData[]; isDemo: boolean }> => {
const fetchVMData = async (): Promise<VMData[]> => {
try {
console.log("[v0] Attempting to fetch VM data from Flask server...")
console.log("[v0] Fetching VM data from Flask server...")
const response = await fetch("/api/vms", {
method: "GET",
headers: {
"Content-Type": "application/json",
},
signal: AbortSignal.timeout(3000), // Reduced timeout for faster fallback
signal: AbortSignal.timeout(5000),
})
if (!response.ok) {
@@ -122,36 +97,29 @@ const fetchVMData = async (): Promise<{ data: VMData[]; isDemo: boolean }> => {
const data = await response.json()
console.log("[v0] Successfully fetched VM data from Flask:", data)
return { data: data.vms || [], isDemo: false }
return Array.isArray(data) ? data : data.vms || []
} catch (error) {
console.log("[v0] Flask server not available, using demo VM data")
return { data: demVMData, isDemo: true }
console.error("[v0] Failed to fetch VM data from Flask server:", error)
return []
}
}
const generateChartData = (systemData?: SystemData) => {
const cpuData = []
const memoryData = []
for (let i = 0; i < 24; i += 4) {
const time = `${i.toString().padStart(2, "0")}:00`
// Use real CPU data as base if available, otherwise use random data
const baseCpu = systemData?.cpu_usage || 60
cpuData.push({
time,
value: Math.max(0, Math.min(100, baseCpu + (Math.random() - 0.5) * 20)),
})
// Use real memory data as base if available
const baseMemory = systemData?.memory_used || 15.8
const totalMemory = systemData?.memory_total || 32
memoryData.push({
time,
used: Math.max(0, baseMemory + (Math.random() - 0.5) * 4),
available: Math.max(0, totalMemory - (baseMemory + (Math.random() - 0.5) * 4)),
})
const generateChartData = () => {
if (historicalDataStore.length === 0) {
return { cpuData: [], memoryData: [] }
}
const cpuData = historicalDataStore.map((point) => ({
time: new Date(point.timestamp).toLocaleTimeString("en-US", { hour: "2-digit", minute: "2-digit" }),
value: point.cpu_usage,
}))
const memoryData = historicalDataStore.map((point) => ({
time: new Date(point.timestamp).toLocaleTimeString("en-US", { hour: "2-digit", minute: "2-digit" }),
used: point.memory_used,
available: point.memory_total - point.memory_used,
}))
return { cpuData, memoryData }
}
@@ -160,29 +128,28 @@ export function SystemOverview() {
const [vmData, setVmData] = useState<VMData[]>([])
const [chartData, setChartData] = useState(generateChartData())
const [loading, setLoading] = useState(true)
const [isDemo, setIsDemo] = useState(false) // Added demo mode state
const [error, setError] = useState<string | null>(null)
useEffect(() => {
const fetchData = async () => {
try {
setLoading(true)
setError(null)
const [systemResult, vmResult] = await Promise.all([fetchSystemData(), fetchVMData()])
setSystemData(systemResult.data)
setVmData(vmResult.data)
setIsDemo(systemResult.isDemo || vmResult.isDemo) // Set demo mode if either fetch is demo
if (systemResult.data) {
setChartData(generateChartData(systemResult.data))
if (!systemResult) {
setError("Flask server not available. Please ensure the server is running.")
setLoading(false)
return
}
setSystemData(systemResult)
setVmData(vmResult)
setChartData(generateChartData())
} catch (err) {
console.error("[v0] Error fetching data:", err)
const fallbackData = generateDemoSystemData()
setSystemData(fallbackData)
setVmData(demVMData)
setChartData(generateChartData(fallbackData))
setIsDemo(true)
setError("Failed to connect to Flask server. Please check your connection.")
} finally {
setLoading(false)
}
@@ -191,20 +158,13 @@ export function SystemOverview() {
fetchData()
const interval = setInterval(() => {
if (!isDemo) {
fetchData()
} else {
// In demo mode, just update with new random data
const newDemoData = generateDemoSystemData()
setSystemData(newDemoData)
setChartData(generateChartData(newDemoData))
}
}, 30000) // Update every 30 seconds instead of 5
fetchData()
}, 30000) // Update every 30 seconds
return () => {
clearInterval(interval)
}
}, [isDemo])
}, [])
if (loading) {
return (
@@ -229,7 +189,33 @@ export function SystemOverview() {
)
}
if (!systemData) return null
if (error || !systemData) {
return (
<div className="space-y-6">
<Card className="bg-red-500/10 border-red-500/20">
<CardContent className="p-6">
<div className="flex items-center gap-3 text-red-600">
<AlertCircle className="h-6 w-6" />
<div>
<div className="font-semibold text-lg mb-1">Flask Server Not Available</div>
<div className="text-sm">
{error || "Unable to connect to the Flask server. Please ensure the server is running and try again."}
</div>
<div className="text-sm mt-2">
<strong>Troubleshooting:</strong>
<ul className="list-disc list-inside mt-1 space-y-1">
<li>Check if the Flask server is running on the correct port</li>
<li>Verify network connectivity</li>
<li>Check server logs for errors</li>
</ul>
</div>
</div>
</div>
</CardContent>
</Card>
</div>
)
}
const vmStats = {
total: vmData.length,
@@ -239,6 +225,7 @@ export function SystemOverview() {
}
const getTemperatureStatus = (temp: number) => {
if (temp === 0) return { status: "N/A", color: "bg-gray-500/10 text-gray-500 border-gray-500/20" }
if (temp < 60) return { status: "Normal", color: "bg-green-500/10 text-green-500 border-green-500/20" }
if (temp < 75) return { status: "Warm", color: "bg-yellow-500/10 text-yellow-500 border-yellow-500/20" }
return { status: "Hot", color: "bg-red-500/10 text-red-500 border-red-500/20" }
@@ -248,160 +235,156 @@ export function SystemOverview() {
return (
<div className="space-y-6">
{isDemo && (
<Card className="bg-blue-500/10 border-blue-500/20">
<CardContent className="p-4">
<div className="flex items-center gap-2 text-sm text-blue-600">
<AlertCircle className="h-4 w-4" />
<span>
<strong>Demo Mode:</strong> Flask server not available. Showing simulated data for development. In the
AppImage, this will connect to the real Flask server.
</span>
</div>
</CardContent>
</Card>
)}
{/* Key Metrics Cards */}
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
<Card className="bg-card border-border metric-card">
<Card className="bg-card border-border">
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium text-muted-foreground">CPU Usage</CardTitle>
<Cpu className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold text-foreground metric-value">{systemData.cpu_usage}%</div>
<div className="text-2xl font-bold text-foreground">{systemData.cpu_usage}%</div>
<Progress value={systemData.cpu_usage} className="mt-2" />
<p className="text-xs text-muted-foreground mt-2 metric-label">
{isDemo ? "Simulated data" : "Real-time data from Flask server"}
</p>
<p className="text-xs text-muted-foreground mt-2">Real-time data from Flask server</p>
</CardContent>
</Card>
<Card className="bg-card border-border metric-card">
<Card className="bg-card border-border">
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium text-muted-foreground">Memory Usage</CardTitle>
<MemoryStick className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold text-foreground metric-value">
{systemData.memory_used.toFixed(1)} GB
</div>
<div className="text-2xl font-bold text-foreground">{systemData.memory_used.toFixed(1)} GB</div>
<Progress value={systemData.memory_usage} className="mt-2" />
<p className="text-xs text-muted-foreground mt-2 metric-label">
<p className="text-xs text-muted-foreground mt-2">
{systemData.memory_usage.toFixed(1)}% of {systemData.memory_total} GB
</p>
</CardContent>
</Card>
<Card className="bg-card border-border metric-card">
<Card className="bg-card border-border">
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium text-muted-foreground">Temperature</CardTitle>
<Thermometer className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold text-foreground metric-value">{systemData.temperature}°C</div>
<div className="text-2xl font-bold text-foreground">
{systemData.temperature === 0 ? "N/A" : `${systemData.temperature}°C`}
</div>
<div className="flex items-center mt-2">
<Badge variant="outline" className={tempStatus.color}>
{tempStatus.status}
</Badge>
</div>
<p className="text-xs text-muted-foreground mt-2 metric-label">
{isDemo ? "Simulated temperature" : "Live temperature reading"}
<p className="text-xs text-muted-foreground mt-2">
{systemData.temperature === 0 ? "No sensor available" : "Live temperature reading"}
</p>
</CardContent>
</Card>
<Card className="bg-card border-border metric-card">
<Card className="bg-card border-border">
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium text-muted-foreground">Active VMs</CardTitle>
<Server className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold text-foreground metric-value">{vmStats.running}</div>
<div className="vm-badges mt-2 flex flex-wrap gap-1">
<Badge variant="outline" className="vm-badge bg-green-500/10 text-green-500 border-green-500/20">
<div className="text-2xl font-bold text-foreground">{vmStats.running}</div>
<div className="mt-2 flex flex-wrap gap-1">
<Badge variant="outline" className="bg-green-500/10 text-green-500 border-green-500/20">
{vmStats.running} Running
</Badge>
{vmStats.stopped > 0 && (
<Badge variant="outline" className="vm-badge bg-yellow-500/10 text-yellow-500 border-yellow-500/20">
<Badge variant="outline" className="bg-yellow-500/10 text-yellow-500 border-yellow-500/20">
{vmStats.stopped} Stopped
</Badge>
)}
</div>
<p className="text-xs text-muted-foreground mt-2 metric-label">Total: {vmStats.total} VMs configured</p>
<p className="text-xs text-muted-foreground mt-2">Total: {vmStats.total} VMs configured</p>
</CardContent>
</Card>
</div>
{/* Charts Section */}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
<Card className="bg-card border-border metric-card">
<Card className="bg-card border-border">
<CardHeader>
<CardTitle className="text-foreground flex items-center">
<Activity className="h-5 w-5 mr-2" />
CPU Usage (24h)
CPU Usage (Last {historicalDataStore.length} readings)
</CardTitle>
</CardHeader>
<CardContent>
<ResponsiveContainer width="100%" height={300}>
<AreaChart data={chartData.cpuData}>
<CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border))" />
<XAxis dataKey="time" stroke="hsl(var(--muted-foreground))" fontSize={12} />
<YAxis stroke="hsl(var(--muted-foreground))" fontSize={12} />
<Tooltip
contentStyle={{
backgroundColor: "hsl(var(--card))",
border: "1px solid hsl(var(--border))",
borderRadius: "8px",
color: "hsl(var(--foreground))",
}}
/>
<Area type="monotone" dataKey="value" stroke="#3b82f6" fill="#3b82f6" fillOpacity={0.2} />
</AreaChart>
</ResponsiveContainer>
{chartData.cpuData.length > 0 ? (
<ResponsiveContainer width="100%" height={300}>
<AreaChart data={chartData.cpuData}>
<CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border))" />
<XAxis dataKey="time" stroke="hsl(var(--muted-foreground))" fontSize={12} />
<YAxis stroke="hsl(var(--muted-foreground))" fontSize={12} />
<Tooltip
contentStyle={{
backgroundColor: "hsl(var(--card))",
border: "1px solid hsl(var(--border))",
borderRadius: "8px",
color: "hsl(var(--foreground))",
}}
/>
<Area type="monotone" dataKey="value" stroke="#3b82f6" fill="#3b82f6" fillOpacity={0.2} />
</AreaChart>
</ResponsiveContainer>
) : (
<div className="h-[300px] flex items-center justify-center text-muted-foreground">
Collecting data... Check back in a few minutes
</div>
)}
</CardContent>
</Card>
<Card className="bg-card border-border metric-card">
<Card className="bg-card border-border">
<CardHeader>
<CardTitle className="text-foreground flex items-center">
<MemoryStick className="h-5 w-5 mr-2" />
Memory Usage (24h)
Memory Usage (Last {historicalDataStore.length} readings)
</CardTitle>
</CardHeader>
<CardContent>
<ResponsiveContainer width="100%" height={300}>
<AreaChart data={chartData.memoryData}>
<CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border))" />
<XAxis dataKey="time" stroke="hsl(var(--muted-foreground))" fontSize={12} />
<YAxis stroke="hsl(var(--muted-foreground))" fontSize={12} />
<Tooltip
contentStyle={{
backgroundColor: "hsl(var(--card))",
border: "1px solid hsl(var(--border))",
borderRadius: "8px",
color: "hsl(var(--foreground))",
}}
/>
<Area type="monotone" dataKey="used" stackId="1" stroke="#3b82f6" fill="#3b82f6" fillOpacity={0.6} />
<Area
type="monotone"
dataKey="available"
stackId="1"
stroke="#10b981"
fill="#10b981"
fillOpacity={0.6}
/>
</AreaChart>
</ResponsiveContainer>
{chartData.memoryData.length > 0 ? (
<ResponsiveContainer width="100%" height={300}>
<AreaChart data={chartData.memoryData}>
<CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border))" />
<XAxis dataKey="time" stroke="hsl(var(--muted-foreground))" fontSize={12} />
<YAxis stroke="hsl(var(--muted-foreground))" fontSize={12} />
<Tooltip
contentStyle={{
backgroundColor: "hsl(var(--card))",
border: "1px solid hsl(var(--border))",
borderRadius: "8px",
color: "hsl(var(--foreground))",
}}
/>
<Area type="monotone" dataKey="used" stackId="1" stroke="#3b82f6" fill="#3b82f6" fillOpacity={0.6} />
<Area
type="monotone"
dataKey="available"
stackId="1"
stroke="#10b981"
fill="#10b981"
fillOpacity={0.6}
/>
</AreaChart>
</ResponsiveContainer>
) : (
<div className="h-[300px] flex items-center justify-center text-muted-foreground">
Collecting data... Check back in a few minutes
</div>
)}
</CardContent>
</Card>
</div>
{/* System Information */}
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
<Card className="bg-card border-border metric-card">
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
<Card className="bg-card border-border">
<CardHeader>
<CardTitle className="text-foreground flex items-center">
<Server className="h-5 w-5 mr-2" />
@@ -410,76 +393,51 @@ export function SystemOverview() {
</CardHeader>
<CardContent className="space-y-3">
<div className="flex justify-between">
<span className="text-muted-foreground metric-label">Hostname:</span>
<span className="text-foreground font-mono metric-value">{systemData.hostname}</span>
<span className="text-muted-foreground">Hostname:</span>
<span className="text-foreground font-mono">{systemData.hostname}</span>
</div>
<div className="flex justify-between">
<span className="text-muted-foreground metric-label">Uptime:</span>
<span className="text-foreground metric-value">{systemData.uptime}</span>
<span className="text-muted-foreground">Uptime:</span>
<span className="text-foreground">{systemData.uptime}</span>
</div>
<div className="flex justify-between">
<span className="text-muted-foreground metric-label">Node ID:</span>
<span className="text-foreground font-mono metric-value">{systemData.node_id}</span>
<span className="text-muted-foreground">Node ID:</span>
<span className="text-foreground font-mono">{systemData.node_id}</span>
</div>
<div className="flex justify-between">
<span className="text-muted-foreground metric-label">Last Update:</span>
<span className="text-foreground metric-value">
{new Date(systemData.timestamp).toLocaleTimeString()}
</span>
<span className="text-muted-foreground">Last Update:</span>
<span className="text-foreground">{new Date(systemData.timestamp).toLocaleTimeString()}</span>
</div>
</CardContent>
</Card>
<Card className="bg-card border-border metric-card">
<CardHeader>
<CardTitle className="text-foreground flex items-center">
<Users className="h-5 w-5 mr-2" />
Active Sessions
</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
<div className="flex justify-between items-center">
<span className="text-muted-foreground metric-label">Web Console:</span>
<Badge variant="outline" className="bg-green-500/10 text-green-500 border-green-500/20">
3 active
</Badge>
</div>
<div className="flex justify-between items-center">
<span className="text-muted-foreground metric-label">SSH Sessions:</span>
<Badge variant="outline" className="bg-blue-500/10 text-blue-500 border-blue-500/20">
1 active
</Badge>
</div>
<div className="flex justify-between">
<span className="text-muted-foreground metric-label">API Calls:</span>
<span className="text-foreground metric-value">247/hour</span>
</div>
</CardContent>
</Card>
<Card className="bg-card border-border metric-card">
<Card className="bg-card border-border">
<CardHeader>
<CardTitle className="text-foreground flex items-center">
<Zap className="h-5 w-5 mr-2" />
Power & Performance
Performance Metrics
</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
<div className="flex justify-between">
<span className="text-muted-foreground metric-label">Power State:</span>
<Badge variant="outline" className="bg-green-500/10 text-green-500 border-green-500/20">
Running
</Badge>
</div>
<div className="flex justify-between">
<span className="text-muted-foreground metric-label">Load Average:</span>
<span className="text-foreground font-mono metric-value">
<span className="text-muted-foreground">Load Average:</span>
<span className="text-foreground font-mono">
{systemData.load_average.map((avg) => avg.toFixed(2)).join(", ")}
</span>
</div>
<div className="flex justify-between">
<span className="text-muted-foreground metric-label">Boot Time:</span>
<span className="text-foreground metric-value">2.3s</span>
<span className="text-muted-foreground">Total Memory:</span>
<span className="text-foreground">{systemData.memory_total} GB</span>
</div>
<div className="flex justify-between">
<span className="text-muted-foreground">Available Memory:</span>
<span className="text-foreground">
{(systemData.memory_total - systemData.memory_used).toFixed(1)} GB
</span>
</div>
<div className="flex justify-between">
<span className="text-muted-foreground">CPU Cores:</span>
<span className="text-foreground">{navigator.hardwareConcurrency || "N/A"}</span>
</div>
</CardContent>
</Card>

View File

@@ -1,147 +1,105 @@
"use client"
import { useState, useEffect } from "react"
import { Card, CardContent, CardHeader, CardTitle } from "./ui/card"
import { Badge } from "./ui/badge"
import { Progress } from "./ui/progress"
import { Server, Play, Square, RotateCcw, Monitor, Cpu, MemoryStick } from "lucide-react"
import { Server, Play, Square, Monitor, Cpu, MemoryStick, AlertCircle } from "lucide-react"
const virtualMachines = [
{
id: 100,
name: "web-server-01",
type: "vm",
status: "running",
os: "Ubuntu 22.04",
cpu: 4,
memory: 8192,
disk: 50,
uptime: "15d 7h 23m",
cpuUsage: 45,
memoryUsage: 62,
diskUsage: 78,
},
{
id: 101,
name: "database-01",
type: "vm",
status: "running",
os: "CentOS 8",
cpu: 8,
memory: 16384,
disk: 100,
uptime: "12d 3h 45m",
cpuUsage: 78,
memoryUsage: 85,
diskUsage: 45,
},
{
id: 102,
name: "backup-server",
type: "vm",
status: "stopped",
os: "Debian 11",
cpu: 2,
memory: 4096,
disk: 200,
uptime: "0d 0h 0m",
cpuUsage: 0,
memoryUsage: 0,
diskUsage: 23,
},
{
id: 103,
name: "dev-environment",
type: "vm",
status: "running",
os: "Ubuntu 20.04",
cpu: 6,
memory: 12288,
disk: 75,
uptime: "3d 12h 18m",
cpuUsage: 32,
memoryUsage: 58,
diskUsage: 67,
},
{
id: 104,
name: "monitoring-01",
type: "vm",
status: "running",
os: "Alpine Linux",
cpu: 2,
memory: 2048,
disk: 25,
uptime: "8d 15h 32m",
cpuUsage: 15,
memoryUsage: 34,
diskUsage: 42,
},
{
id: 105,
name: "mail-server",
type: "vm",
status: "stopped",
os: "Ubuntu 22.04",
cpu: 4,
memory: 8192,
disk: 60,
uptime: "0d 0h 0m",
cpuUsage: 0,
memoryUsage: 0,
diskUsage: 56,
},
{
id: 200,
name: "nginx-proxy",
type: "lxc",
status: "running",
os: "Ubuntu 22.04 LXC",
cpu: 1,
memory: 512,
disk: 8,
uptime: "25d 14h 12m",
cpuUsage: 8,
memoryUsage: 45,
diskUsage: 32,
},
{
id: 201,
name: "redis-cache",
type: "lxc",
status: "running",
os: "Alpine Linux LXC",
cpu: 1,
memory: 1024,
disk: 4,
uptime: "18d 6h 45m",
cpuUsage: 12,
memoryUsage: 38,
diskUsage: 28,
},
{
id: 202,
name: "log-collector",
type: "lxc",
status: "stopped",
os: "Debian 11 LXC",
cpu: 1,
memory: 256,
disk: 2,
uptime: "0d 0h 0m",
cpuUsage: 0,
memoryUsage: 0,
diskUsage: 15,
},
]
interface VMData {
vmid: number
name: string
status: string
cpu: number
mem: number
maxmem: number
disk: number
maxdisk: number
uptime: number
}
const fetchVMData = async (): Promise<VMData[]> => {
try {
console.log("[v0] Fetching VM data from Flask server...")
const response = await fetch("/api/vms", {
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()
console.log("[v0] Successfully fetched VM data from Flask:", data)
return Array.isArray(data) ? data : []
} catch (error) {
console.error("[v0] Failed to fetch VM data from Flask server:", error)
throw error
}
}
export function VirtualMachines() {
const runningVMs = virtualMachines.filter((vm) => vm.status === "running").length
const stoppedVMs = virtualMachines.filter((vm) => vm.status === "stopped").length
const runningLXC = virtualMachines.filter((vm) => vm.type === "lxc" && vm.status === "running").length
const totalVMs = virtualMachines.filter((vm) => vm.type === "vm").length
const totalLXC = virtualMachines.filter((vm) => vm.type === "lxc").length
const totalCPU = virtualMachines.reduce((sum, vm) => sum + vm.cpu, 0)
const totalMemory = virtualMachines.reduce((sum, vm) => sum + vm.memory, 0)
const [vmData, setVmData] = useState<VMData[]>([])
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
useEffect(() => {
const fetchData = async () => {
try {
setLoading(true)
setError(null)
const result = await fetchVMData()
setVmData(result)
} catch (err) {
setError("Flask server not available. Please ensure the server is running.")
} finally {
setLoading(false)
}
}
fetchData()
const interval = setInterval(fetchData, 30000)
return () => clearInterval(interval)
}, [])
if (loading) {
return (
<div className="space-y-6">
<div className="text-center py-8">
<div className="text-lg font-medium text-foreground mb-2">Loading VM data...</div>
</div>
</div>
)
}
if (error) {
return (
<div className="space-y-6">
<Card className="bg-red-500/10 border-red-500/20">
<CardContent className="p-6">
<div className="flex items-center gap-3 text-red-600">
<AlertCircle className="h-6 w-6" />
<div>
<div className="font-semibold text-lg mb-1">Flask Server Not Available</div>
<div className="text-sm">
{error || "Unable to connect to the Flask server. Please ensure the server is running and try again."}
</div>
</div>
</div>
</CardContent>
</Card>
</div>
)
}
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) {
@@ -161,46 +119,48 @@ export function VirtualMachines() {
case "stopped":
return <Square className="h-3 w-3 mr-1" />
default:
return <RotateCcw className="h-3 w-3 mr-1" />
return null
}
}
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 (
<div className="space-y-6">
{/* VM Overview Cards */}
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
<Card className="bg-card border-border">
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium text-muted-foreground">Total VMs & LXC</CardTitle>
<CardTitle className="text-sm font-medium text-muted-foreground">Total VMs</CardTitle>
<Server className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold text-foreground">{virtualMachines.length}</div>
<div className="text-2xl font-bold text-foreground">{vmData.length}</div>
<div className="vm-badges mt-2">
<Badge variant="outline" className="vm-badge bg-green-500/10 text-green-500 border-green-500/20">
{runningVMs} VMs
</Badge>
<Badge variant="outline" className="vm-badge bg-blue-500/10 text-blue-500 border-blue-500/20">
{runningLXC} LXC
{runningVMs} Running
</Badge>
<Badge variant="outline" className="vm-badge bg-red-500/10 text-red-500 border-red-500/20">
{stoppedVMs} Stopped
</Badge>
</div>
<p className="text-xs text-muted-foreground mt-2">
{totalVMs} VMs {totalLXC} LXC
</p>
<p className="text-xs text-muted-foreground mt-2">Virtual machines configured</p>
</CardContent>
</Card>
<Card className="bg-card border-border">
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium text-muted-foreground">Total CPU Cores</CardTitle>
<CardTitle className="text-sm font-medium text-muted-foreground">Total CPU</CardTitle>
<Cpu className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold text-foreground">{totalCPU}</div>
<p className="text-xs text-muted-foreground mt-2">Allocated across all VMs and LXC containers</p>
<div className="text-2xl font-bold text-foreground">{(totalCPU * 100).toFixed(0)}%</div>
<p className="text-xs text-muted-foreground mt-2">Allocated CPU usage</p>
</CardContent>
</Card>
@@ -210,8 +170,8 @@ export function VirtualMachines() {
<MemoryStick className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold text-foreground">{(totalMemory / 1024).toFixed(1)} GB</div>
<p className="text-xs text-muted-foreground mt-2">Allocated RAM across all VMs and LXC containers</p>
<div className="text-2xl font-bold text-foreground">{(totalMemory / 1024 ** 3).toFixed(1)} GB</div>
<p className="text-xs text-muted-foreground mt-2">Allocated RAM</p>
</CardContent>
</Card>
@@ -221,7 +181,9 @@ export function VirtualMachines() {
<Monitor className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold text-foreground">42%</div>
<div className="text-2xl font-bold text-foreground">
{runningVMs > 0 ? ((totalCPU / runningVMs) * 100).toFixed(0) : 0}%
</div>
<p className="text-xs text-muted-foreground mt-2">Average resource utilization</p>
</CardContent>
</Card>
@@ -232,84 +194,72 @@ export function VirtualMachines() {
<CardHeader>
<CardTitle className="text-foreground flex items-center">
<Server className="h-5 w-5 mr-2" />
Virtual Machines & LXC Containers
Virtual Machines
</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-4">
{virtualMachines.map((vm) => (
<div key={vm.id} className="p-6 rounded-lg border border-border bg-card/50">
<div className="flex items-center justify-between mb-4">
<div className="flex items-center space-x-4">
<Server className="h-6 w-6 text-muted-foreground" />
<div>
<div className="font-semibold text-foreground text-lg flex items-center">
{vm.name}
<Badge
variant="outline"
className={`ml-2 text-xs ${
vm.type === "lxc"
? "bg-blue-500/10 text-blue-500 border-blue-500/20"
: "bg-purple-500/10 text-purple-500 border-purple-500/20"
}`}
>
{vm.type.toUpperCase()}
{vmData.length === 0 ? (
<div className="text-center py-8 text-muted-foreground">No virtual machines found</div>
) : (
<div className="space-y-4">
{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)
return (
<div key={vm.vmid} className="p-6 rounded-lg border border-border bg-card/50">
<div className="flex items-center justify-between mb-4">
<div className="flex items-center space-x-4">
<Server className="h-6 w-6 text-muted-foreground" />
<div>
<div className="font-semibold text-foreground text-lg flex items-center">
{vm.name}
<Badge
variant="outline"
className="ml-2 text-xs bg-purple-500/10 text-purple-500 border-purple-500/20"
>
VM
</Badge>
</div>
<div className="text-sm text-muted-foreground">ID: {vm.vmid}</div>
</div>
</div>
<div className="flex items-center space-x-3">
<Badge variant="outline" className={getStatusColor(vm.status)}>
{getStatusIcon(vm.status)}
{vm.status.toUpperCase()}
</Badge>
</div>
<div className="text-sm text-muted-foreground">
ID: {vm.id} {vm.os}
</div>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
<div>
<div className="text-sm text-muted-foreground mb-2">CPU Usage</div>
<div className="text-lg font-semibold text-foreground mb-1">{cpuPercent}%</div>
<Progress value={Number.parseFloat(cpuPercent)} className="h-2" />
</div>
<div>
<div className="text-sm text-muted-foreground mb-2">Memory Usage</div>
<div className="text-lg font-semibold text-foreground mb-1">
{memGB} GB / {maxMemGB} GB
</div>
<Progress value={Number.parseFloat(memPercent)} className="h-2" />
</div>
<div>
<div className="text-sm text-muted-foreground mb-2">Uptime</div>
<div className="text-lg font-semibold text-foreground">{formatUptime(vm.uptime)}</div>
</div>
</div>
</div>
<div className="flex items-center space-x-3">
<Badge variant="outline" className={getStatusColor(vm.status)}>
{getStatusIcon(vm.status)}
{vm.status.toUpperCase()}
</Badge>
</div>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
<div>
<div className="text-sm text-muted-foreground mb-2">Resources</div>
<div className="space-y-1 text-sm">
<div className="flex justify-between">
<span>CPU:</span>
<span className="font-medium">{vm.cpu} cores</span>
</div>
<div className="flex justify-between">
<span>Memory:</span>
<span className="font-medium">{(vm.memory / 1024).toFixed(1)} GB</span>
</div>
<div className="flex justify-between">
<span>Disk:</span>
<span className="font-medium">{vm.disk} GB</span>
</div>
</div>
</div>
<div>
<div className="text-sm text-muted-foreground mb-2">CPU Usage</div>
<div className="text-lg font-semibold text-foreground mb-1">{vm.cpuUsage}%</div>
<Progress value={vm.cpuUsage} className="h-2" />
</div>
<div>
<div className="text-sm text-muted-foreground mb-2">Memory Usage</div>
<div className="text-lg font-semibold text-foreground mb-1">{vm.memoryUsage}%</div>
<Progress value={vm.memoryUsage} className="h-2" />
</div>
<div>
<div className="text-sm text-muted-foreground mb-2">Uptime</div>
<div className="text-lg font-semibold text-foreground">{vm.uptime}</div>
<div className="text-xs text-muted-foreground mt-1">Disk: {vm.diskUsage}% used</div>
</div>
</div>
</div>
))}
</div>
)
})}
</div>
)}
</CardContent>
</Card>
</div>