Update system-overview.tsx

This commit is contained in:
MacRimi
2025-10-02 19:34:53 +02:00
parent 15f3af2020
commit f7fb9034ef

View File

@@ -4,8 +4,7 @@ import { useState, useEffect } from "react"
import { Card, CardContent, CardHeader, CardTitle } from "./ui/card" import { Card, CardContent, CardHeader, CardTitle } from "./ui/card"
import { Progress } from "./ui/progress" import { Progress } from "./ui/progress"
import { Badge } from "./ui/badge" import { Badge } from "./ui/badge"
import { XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, AreaChart, Area, Legend } from "recharts" import { Cpu, MemoryStick, Thermometer, Server, Zap, AlertCircle, HardDrive, Network } from "lucide-react"
import { Cpu, MemoryStick, Thermometer, Activity, Server, Zap, AlertCircle } from "lucide-react"
interface SystemData { interface SystemData {
cpu_usage: number cpu_usage: number
@@ -37,23 +36,38 @@ interface VMData {
type?: string type?: string
} }
interface HistoricalData { interface StorageData {
timestamp: string total: number
cpu_usage: number used: number
memory_used: number available: number
memory_total: number disks: Array<{
name: string
mountpoint: string
total: number
used: number
available: number
usage_percent: number
}>
} }
const historicalDataStore: HistoricalData[] = [] interface NetworkData {
const MAX_HISTORICAL_POINTS = 144 // Store 144 data points for 24h view interfaces: Array<{
name: string
status: string
addresses: Array<{ ip: string; netmask: string }>
}>
traffic: {
bytes_sent: number
bytes_recv: number
packets_sent: number
packets_recv: number
}
}
const fetchSystemData = async (): Promise<SystemData | null> => { const fetchSystemData = async (): Promise<SystemData | null> => {
try { try {
console.log("[v0] Fetching system data from Flask server...")
const baseUrl = typeof window !== "undefined" ? `${window.location.protocol}//${window.location.hostname}:8008` : "" const baseUrl = typeof window !== "undefined" ? `${window.location.protocol}//${window.location.hostname}:8008` : ""
const apiUrl = `${baseUrl}/api/system` const apiUrl = `${baseUrl}/api/system`
console.log("[v0] Fetching from URL:", apiUrl)
const response = await fetch(apiUrl, { const response = await fetch(apiUrl, {
method: "GET", method: "GET",
@@ -63,62 +77,22 @@ const fetchSystemData = async (): Promise<SystemData | null> => {
cache: "no-store", cache: "no-store",
}) })
console.log("[v0] Response status:", response.status)
console.log("[v0] Response ok:", response.ok)
console.log("[v0] Response headers:", Object.fromEntries(response.headers.entries()))
if (!response.ok) { if (!response.ok) {
const errorText = await response.text()
console.error("[v0] Flask server error response:", errorText)
throw new Error(`Flask server responded with status: ${response.status}`) throw new Error(`Flask server responded with status: ${response.status}`)
} }
const responseText = await response.text() const data = await response.json()
console.log("[v0] Raw response text:", responseText)
console.log("[v0] Response text length:", responseText.length)
console.log("[v0] First 100 chars:", responseText.substring(0, 100))
// Try to parse the JSON
let data
try {
data = JSON.parse(responseText)
console.log("[v0] Successfully parsed JSON:", data)
} catch (parseError) {
console.error("[v0] JSON parse error:", parseError)
console.error("[v0] Failed to parse response as JSON")
throw new Error("Invalid JSON response from server")
}
// 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 return data
} catch (error) { } catch (error) {
console.error("[v0] Failed to fetch system data from Flask server:", error) console.error("[v0] Failed to fetch system data:", error)
console.error("[v0] Error type:", error instanceof Error ? error.constructor.name : typeof error)
console.error("[v0] Error message:", error instanceof Error ? error.message : String(error))
console.error("[v0] Error stack:", error instanceof Error ? error.stack : "No stack trace")
return null return null
} }
} }
const fetchVMData = async (): Promise<VMData[]> => { const fetchVMData = async (): Promise<VMData[]> => {
try { try {
console.log("[v0] Fetching VM data from Flask server...")
const baseUrl = typeof window !== "undefined" ? `${window.location.protocol}//${window.location.hostname}:8008` : "" const baseUrl = typeof window !== "undefined" ? `${window.location.protocol}//${window.location.hostname}:8008` : ""
const apiUrl = `${baseUrl}/api/vms` const apiUrl = `${baseUrl}/api/vms`
console.log("[v0] Fetching from URL:", apiUrl)
const response = await fetch(apiUrl, { const response = await fetch(apiUrl, {
method: "GET", method: "GET",
@@ -128,48 +102,73 @@ const fetchVMData = async (): Promise<VMData[]> => {
cache: "no-store", cache: "no-store",
}) })
console.log("[v0] VM Response status:", response.status)
if (!response.ok) { if (!response.ok) {
const errorText = await response.text()
console.error("[v0] Flask server error response:", errorText)
throw new Error(`Flask server responded with status: ${response.status}`) throw new Error(`Flask server responded with status: ${response.status}`)
} }
const data = await response.json() const data = await response.json()
console.log("[v0] Successfully fetched VM data from Flask:", data)
return Array.isArray(data) ? data : data.vms || [] return Array.isArray(data) ? data : data.vms || []
} catch (error) { } catch (error) {
console.error("[v0] Failed to fetch VM data from Flask server:", error) console.error("[v0] Failed to fetch VM data:", error)
console.error("[v0] Error type:", error instanceof Error ? error.constructor.name : typeof error)
console.error("[v0] Error message:", error instanceof Error ? error.message : String(error))
return [] return []
} }
} }
const generateChartData = () => { const fetchStorageData = async (): Promise<StorageData | null> => {
if (historicalDataStore.length === 0) { try {
return { cpuData: [], memoryData: [] } const baseUrl = typeof window !== "undefined" ? `${window.location.protocol}//${window.location.hostname}:8008` : ""
const apiUrl = `${baseUrl}/api/storage`
const response = await fetch(apiUrl, {
method: "GET",
headers: {
"Content-Type": "application/json",
},
cache: "no-store",
})
if (!response.ok) {
throw new Error(`Flask server responded with status: ${response.status}`)
}
const data = await response.json()
return data
} catch (error) {
console.error("[v0] Failed to fetch storage data:", error)
return null
} }
}
const cpuData = historicalDataStore.map((point) => ({ const fetchNetworkData = async (): Promise<NetworkData | null> => {
time: new Date(point.timestamp).toLocaleTimeString("en-US", { hour: "2-digit", minute: "2-digit" }), try {
value: point.cpu_usage, const baseUrl = typeof window !== "undefined" ? `${window.location.protocol}//${window.location.hostname}:8008` : ""
})) const apiUrl = `${baseUrl}/api/network`
const memoryData = historicalDataStore.map((point) => ({ const response = await fetch(apiUrl, {
time: new Date(point.timestamp).toLocaleTimeString("en-US", { hour: "2-digit", minute: "2-digit" }), method: "GET",
used: point.memory_used, headers: {
available: point.memory_total - point.memory_used, "Content-Type": "application/json",
})) },
cache: "no-store",
})
return { cpuData, memoryData } if (!response.ok) {
throw new Error(`Flask server responded with status: ${response.status}`)
}
const data = await response.json()
return data
} catch (error) {
console.error("[v0] Failed to fetch network data:", error)
return null
}
} }
export function SystemOverview() { export function SystemOverview() {
const [systemData, setSystemData] = useState<SystemData | null>(null) const [systemData, setSystemData] = useState<SystemData | null>(null)
const [vmData, setVmData] = useState<VMData[]>([]) const [vmData, setVmData] = useState<VMData[]>([])
const [chartData, setChartData] = useState(generateChartData()) const [storageData, setStorageData] = useState<StorageData | null>(null)
const [networkData, setNetworkData] = useState<NetworkData | null>(null)
const [loading, setLoading] = useState(true) const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null) const [error, setError] = useState<string | null>(null)
@@ -179,7 +178,12 @@ export function SystemOverview() {
setLoading(true) setLoading(true)
setError(null) setError(null)
const [systemResult, vmResult] = await Promise.all([fetchSystemData(), fetchVMData()]) const [systemResult, vmResult, storageResult, networkResult] = await Promise.all([
fetchSystemData(),
fetchVMData(),
fetchStorageData(),
fetchNetworkData(),
])
if (!systemResult) { if (!systemResult) {
setError("Flask server not available. Please ensure the server is running.") setError("Flask server not available. Please ensure the server is running.")
@@ -189,7 +193,8 @@ export function SystemOverview() {
setSystemData(systemResult) setSystemData(systemResult)
setVmData(vmResult) setVmData(vmResult)
setChartData(generateChartData()) setStorageData(storageResult)
setNetworkData(networkResult)
} catch (err) { } catch (err) {
console.error("[v0] Error fetching data:", err) console.error("[v0] Error fetching data:", err)
setError("Failed to connect to Flask server. Please check your connection.") setError("Failed to connect to Flask server. Please check your connection.")
@@ -202,7 +207,7 @@ export function SystemOverview() {
const interval = setInterval(() => { const interval = setInterval(() => {
fetchData() fetchData()
}, 30000) // Update every 30 seconds }, 60000) // Update every 60 seconds instead of 30
return () => { return () => {
clearInterval(interval) clearInterval(interval)
@@ -244,14 +249,6 @@ export function SystemOverview() {
<div className="text-sm"> <div className="text-sm">
{error || "Unable to connect to the Flask server. Please ensure the server is running and try again."} {error || "Unable to connect to the Flask server. Please ensure the server is running and try again."}
</div> </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>
</div> </div>
</CardContent> </CardContent>
@@ -351,100 +348,92 @@ export function SystemOverview() {
</Card> </Card>
</div> </div>
{/* Charts Section */}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6"> <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
{/* Storage Summary */}
<Card className="bg-card border-border"> <Card className="bg-card border-border">
<CardHeader> <CardHeader>
<CardTitle className="text-foreground flex items-center"> <CardTitle className="text-foreground flex items-center">
<Activity className="h-5 w-5 mr-2" /> <HardDrive className="h-5 w-5 mr-2" />
CPU Usage (Last 24h) Storage Overview
</CardTitle> </CardTitle>
</CardHeader> </CardHeader>
<CardContent> <CardContent>
{chartData.cpuData.length > 0 ? ( {storageData ? (
<ResponsiveContainer width="100%" height={300}> <div className="space-y-4">
<AreaChart data={chartData.cpuData}> <div className="flex justify-between items-center">
<CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border))" opacity={0.3} /> <span className="text-sm text-muted-foreground">Total Storage:</span>
<XAxis dataKey="time" stroke="hsl(var(--foreground))" fontSize={12} opacity={0.7} /> <span className="text-lg font-semibold text-foreground">{storageData.total} GB</span>
<YAxis stroke="hsl(var(--foreground))" fontSize={12} opacity={0.7} /> </div>
<Tooltip <div className="flex justify-between items-center">
contentStyle={{ <span className="text-sm text-muted-foreground">Used:</span>
backgroundColor: "hsl(var(--card))", <span className="text-lg font-semibold text-foreground">{storageData.used} GB</span>
border: "1px solid hsl(var(--border))", </div>
borderRadius: "8px", <div className="flex justify-between items-center">
color: "hsl(var(--foreground))", <span className="text-sm text-muted-foreground">Available:</span>
}} <span className="text-lg font-semibold text-green-500">{storageData.available} GB</span>
labelStyle={{ color: "hsl(var(--foreground))" }} </div>
/> <Progress value={(storageData.used / storageData.total) * 100} className="mt-2" />
<Area <div className="pt-2 border-t border-border">
type="monotone" <p className="text-xs text-muted-foreground">
dataKey="value" {storageData.disks.length} disk{storageData.disks.length !== 1 ? "s" : ""} configured
stroke="#3b82f6" </p>
fill="#3b82f6" </div>
fillOpacity={0.4}
name="CPU %"
strokeWidth={2}
/>
</AreaChart>
</ResponsiveContainer>
) : (
<div className="h-[300px] flex items-center justify-center text-muted-foreground">
Collecting data... Check back in a few minutes
</div> </div>
) : (
<div className="text-center py-8 text-muted-foreground">Storage data not available</div>
)} )}
</CardContent> </CardContent>
</Card> </Card>
{/* Network Summary */}
<Card className="bg-card border-border"> <Card className="bg-card border-border">
<CardHeader> <CardHeader>
<CardTitle className="text-foreground flex items-center"> <CardTitle className="text-foreground flex items-center">
<MemoryStick className="h-5 w-5 mr-2" /> <Network className="h-5 w-5 mr-2" />
Memory Usage (Last 24h) Network Overview
</CardTitle> </CardTitle>
</CardHeader> </CardHeader>
<CardContent> <CardContent>
{chartData.memoryData.length > 0 ? ( {networkData ? (
<ResponsiveContainer width="100%" height={300}> <div className="space-y-4">
<AreaChart data={chartData.memoryData}> <div className="flex justify-between items-center">
<CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border))" opacity={0.3} /> <span className="text-sm text-muted-foreground">Active Interfaces:</span>
<XAxis dataKey="time" stroke="hsl(var(--foreground))" fontSize={12} opacity={0.7} /> <span className="text-lg font-semibold text-foreground">
<YAxis stroke="hsl(var(--foreground))" fontSize={12} opacity={0.7} /> {networkData.interfaces.filter((i) => i.status === "up").length}
<Tooltip </span>
contentStyle={{ </div>
backgroundColor: "hsl(var(--card))", <div className="flex justify-between items-center">
border: "1px solid hsl(var(--border))", <span className="text-sm text-muted-foreground">Data Sent:</span>
borderRadius: "8px", <span className="text-lg font-semibold text-foreground">
color: "hsl(var(--foreground))", {(networkData.traffic.bytes_sent / 1024 ** 3).toFixed(2)} GB
}} </span>
labelStyle={{ color: "hsl(var(--foreground))" }} </div>
/> <div className="flex justify-between items-center">
<Legend wrapperStyle={{ color: "hsl(var(--foreground))" }} iconType="square" /> <span className="text-sm text-muted-foreground">Data Received:</span>
<Area <span className="text-lg font-semibold text-foreground">
type="monotone" {(networkData.traffic.bytes_recv / 1024 ** 3).toFixed(2)} GB
dataKey="used" </span>
stackId="1" </div>
stroke="#3b82f6" <div className="pt-2 border-t border-border space-y-1">
fill="#3b82f6" {networkData.interfaces.slice(0, 3).map((iface) => (
fillOpacity={0.6} <div key={iface.name} className="flex justify-between items-center">
name="Used Memory (GB)" <span className="text-xs text-muted-foreground">{iface.name}:</span>
strokeWidth={2} <Badge
/> variant="outline"
<Area className={
type="monotone" iface.status === "up"
dataKey="available" ? "bg-green-500/10 text-green-500 border-green-500/20"
stackId="1" : "bg-gray-500/10 text-gray-500 border-gray-500/20"
stroke="#10b981" }
fill="#10b981" >
fillOpacity={0.6} {iface.status}
name="Available Memory (GB)" </Badge>
strokeWidth={2} </div>
/> ))}
</AreaChart> </div>
</ResponsiveContainer>
) : (
<div className="h-[300px] flex items-center justify-center text-muted-foreground">
Collecting data... Check back in a few minutes
</div> </div>
) : (
<div className="text-center py-8 text-muted-foreground">Network data not available</div>
)} )}
</CardContent> </CardContent>
</Card> </Card>