mirror of
https://github.com/MacRimi/ProxMenux.git
synced 2025-11-18 03:26:17 +00:00
Update AppImage
This commit is contained in:
244
AppImage/components/metrics-dialog.tsx
Normal file
244
AppImage/components/metrics-dialog.tsx
Normal file
@@ -0,0 +1,244 @@
|
||||
"use client"
|
||||
|
||||
import { useState, useEffect } from "react"
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
|
||||
import { ArrowLeft, Loader2 } from "lucide-react"
|
||||
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Legend } from "recharts"
|
||||
|
||||
interface MetricsDialogProps {
|
||||
open: boolean
|
||||
onClose: () => void
|
||||
vmid: number
|
||||
vmName: string
|
||||
vmType: "qemu" | "lxc"
|
||||
metricType: "cpu" | "memory" | "network" | "disk"
|
||||
}
|
||||
|
||||
const TIMEFRAME_OPTIONS = [
|
||||
{ value: "hour", label: "1 Hora" },
|
||||
{ value: "day", label: "24 Horas" },
|
||||
{ value: "week", label: "7 Días" },
|
||||
{ value: "month", label: "30 Días" },
|
||||
{ value: "year", label: "1 Año" },
|
||||
]
|
||||
|
||||
const METRIC_TITLES = {
|
||||
cpu: "Uso de CPU",
|
||||
memory: "Uso de Memoria",
|
||||
network: "Tráfico de Red",
|
||||
disk: "I/O de Disco",
|
||||
}
|
||||
|
||||
export function MetricsDialog({ open, onClose, vmid, vmName, vmType, metricType }: MetricsDialogProps) {
|
||||
const [timeframe, setTimeframe] = useState("week")
|
||||
const [data, setData] = useState<any[]>([])
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
fetchMetrics()
|
||||
}
|
||||
}, [open, vmid, timeframe])
|
||||
|
||||
const fetchMetrics = async () => {
|
||||
setLoading(true)
|
||||
setError(null)
|
||||
|
||||
try {
|
||||
const response = await fetch(`http://localhost:8008/api/vms/${vmid}/metrics?timeframe=${timeframe}`)
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error("Failed to fetch metrics")
|
||||
}
|
||||
|
||||
const result = await response.json()
|
||||
|
||||
// Transform data for charts
|
||||
const transformedData = result.data.map((item: any) => ({
|
||||
time: new Date(item.time * 1000).toLocaleString("es-ES", {
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
hour: timeframe === "hour" ? "2-digit" : undefined,
|
||||
minute: timeframe === "hour" ? "2-digit" : undefined,
|
||||
}),
|
||||
timestamp: item.time,
|
||||
cpu: item.cpu ? (item.cpu * 100).toFixed(2) : 0,
|
||||
memory: item.mem ? ((item.mem / item.maxmem) * 100).toFixed(2) : 0,
|
||||
memoryMB: item.mem ? (item.mem / 1024 / 1024).toFixed(0) : 0,
|
||||
maxMemoryMB: item.maxmem ? (item.maxmem / 1024 / 1024).toFixed(0) : 0,
|
||||
netin: item.netin ? (item.netin / 1024 / 1024).toFixed(2) : 0,
|
||||
netout: item.netout ? (item.netout / 1024 / 1024).toFixed(2) : 0,
|
||||
diskread: item.diskread ? (item.diskread / 1024 / 1024).toFixed(2) : 0,
|
||||
diskwrite: item.diskwrite ? (item.diskwrite / 1024 / 1024).toFixed(2) : 0,
|
||||
}))
|
||||
|
||||
setData(transformedData)
|
||||
} catch (err) {
|
||||
console.error("[v0] Error fetching metrics:", err)
|
||||
setError("Error al cargar las métricas")
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const renderChart = () => {
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center h-96">
|
||||
<Loader2 className="h-8 w-8 animate-spin text-primary" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="flex items-center justify-center h-96">
|
||||
<p className="text-destructive">{error}</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (data.length === 0) {
|
||||
return (
|
||||
<div className="flex items-center justify-center h-96">
|
||||
<p className="text-muted-foreground">No hay datos disponibles</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
switch (metricType) {
|
||||
case "cpu":
|
||||
return (
|
||||
<ResponsiveContainer width="100%" height={400}>
|
||||
<LineChart data={data}>
|
||||
<CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border))" />
|
||||
<XAxis dataKey="time" stroke="hsl(var(--muted-foreground))" />
|
||||
<YAxis stroke="hsl(var(--muted-foreground))" label={{ value: "%", angle: -90, position: "insideLeft" }} />
|
||||
<Tooltip
|
||||
contentStyle={{ backgroundColor: "hsl(var(--background))", border: "1px solid hsl(var(--border))" }}
|
||||
labelStyle={{ color: "hsl(var(--foreground))" }}
|
||||
/>
|
||||
<Legend />
|
||||
<Line type="monotone" dataKey="cpu" stroke="#3b82f6" name="CPU %" strokeWidth={2} dot={false} />
|
||||
</LineChart>
|
||||
</ResponsiveContainer>
|
||||
)
|
||||
|
||||
case "memory":
|
||||
return (
|
||||
<ResponsiveContainer width="100%" height={400}>
|
||||
<LineChart data={data}>
|
||||
<CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border))" />
|
||||
<XAxis dataKey="time" stroke="hsl(var(--muted-foreground))" />
|
||||
<YAxis stroke="hsl(var(--muted-foreground))" label={{ value: "%", angle: -90, position: "insideLeft" }} />
|
||||
<Tooltip
|
||||
contentStyle={{ backgroundColor: "hsl(var(--background))", border: "1px solid hsl(var(--border))" }}
|
||||
labelStyle={{ color: "hsl(var(--foreground))" }}
|
||||
/>
|
||||
<Legend />
|
||||
<Line type="monotone" dataKey="memory" stroke="#10b981" name="Memoria %" strokeWidth={2} dot={false} />
|
||||
</LineChart>
|
||||
</ResponsiveContainer>
|
||||
)
|
||||
|
||||
case "network":
|
||||
return (
|
||||
<ResponsiveContainer width="100%" height={400}>
|
||||
<LineChart data={data}>
|
||||
<CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border))" />
|
||||
<XAxis dataKey="time" stroke="hsl(var(--muted-foreground))" />
|
||||
<YAxis
|
||||
stroke="hsl(var(--muted-foreground))"
|
||||
label={{ value: "MB", angle: -90, position: "insideLeft" }}
|
||||
/>
|
||||
<Tooltip
|
||||
contentStyle={{ backgroundColor: "hsl(var(--background))", border: "1px solid hsl(var(--border))" }}
|
||||
labelStyle={{ color: "hsl(var(--foreground))" }}
|
||||
/>
|
||||
<Legend />
|
||||
<Line type="monotone" dataKey="netin" stroke="#3b82f6" name="Entrada (MB)" strokeWidth={2} dot={false} />
|
||||
<Line type="monotone" dataKey="netout" stroke="#8b5cf6" name="Salida (MB)" strokeWidth={2} dot={false} />
|
||||
</LineChart>
|
||||
</ResponsiveContainer>
|
||||
)
|
||||
|
||||
case "disk":
|
||||
return (
|
||||
<ResponsiveContainer width="100%" height={400}>
|
||||
<LineChart data={data}>
|
||||
<CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border))" />
|
||||
<XAxis dataKey="time" stroke="hsl(var(--muted-foreground))" />
|
||||
<YAxis
|
||||
stroke="hsl(var(--muted-foreground))"
|
||||
label={{ value: "MB", angle: -90, position: "insideLeft" }}
|
||||
/>
|
||||
<Tooltip
|
||||
contentStyle={{ backgroundColor: "hsl(var(--background))", border: "1px solid hsl(var(--border))" }}
|
||||
labelStyle={{ color: "hsl(var(--foreground))" }}
|
||||
/>
|
||||
<Legend />
|
||||
<Line
|
||||
type="monotone"
|
||||
dataKey="diskread"
|
||||
stroke="#10b981"
|
||||
name="Lectura (MB)"
|
||||
strokeWidth={2}
|
||||
dot={false}
|
||||
/>
|
||||
<Line
|
||||
type="monotone"
|
||||
dataKey="diskwrite"
|
||||
stroke="#f59e0b"
|
||||
name="Escritura (MB)"
|
||||
strokeWidth={2}
|
||||
dot={false}
|
||||
/>
|
||||
</LineChart>
|
||||
</ResponsiveContainer>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onClose}>
|
||||
<DialogContent className="max-w-4xl max-h-[90vh] flex flex-col p-0">
|
||||
{/* Fixed Header */}
|
||||
<DialogHeader className="p-6 pb-4 border-b">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<Button variant="ghost" size="icon" onClick={onClose}>
|
||||
<ArrowLeft className="h-5 w-5" />
|
||||
</Button>
|
||||
<div>
|
||||
<DialogTitle className="text-xl">
|
||||
{METRIC_TITLES[metricType]} - {vmName}
|
||||
</DialogTitle>
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
VMID: {vmid} • Tipo: {vmType.toUpperCase()}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<Select value={timeframe} onValueChange={setTimeframe}>
|
||||
<SelectTrigger className="w-32">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{TIMEFRAME_OPTIONS.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</DialogHeader>
|
||||
|
||||
{/* Scrollable Content */}
|
||||
<div className="flex-1 overflow-y-auto p-6">{renderChart()}</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -678,8 +678,8 @@ export function VirtualMachines() {
|
||||
setVMDetails(null)
|
||||
}}
|
||||
>
|
||||
<DialogContent className="max-w-4xl max-h-[95vh] overflow-y-auto">
|
||||
<DialogHeader className="pb-4 border-b border-border">
|
||||
<DialogContent className="max-w-4xl max-h-[95vh] flex flex-col p-0">
|
||||
<DialogHeader className="pb-4 border-b border-border px-6 pt-6">
|
||||
<DialogTitle className="flex flex-col sm:flex-row sm:items-center gap-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<Server className="h-5 w-5 flex-shrink-0" />
|
||||
@@ -699,7 +699,8 @@ export function VirtualMachines() {
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-6 py-4">
|
||||
<div className="flex-1 overflow-y-auto px-6 py-4">
|
||||
<div className="space-y-6">
|
||||
{selectedVM && (
|
||||
<>
|
||||
<div>
|
||||
@@ -935,53 +936,58 @@ export function VirtualMachines() {
|
||||
</div>
|
||||
</>
|
||||
) : null}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className="border-t border-border bg-background px-6 py-4 mt-auto">
|
||||
<h3 className="text-sm font-semibold text-muted-foreground mb-3 uppercase tracking-wide">
|
||||
Control Actions
|
||||
</h3>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full bg-transparent"
|
||||
disabled={selectedVM.status === "running" || controlLoading}
|
||||
onClick={() => handleVMControl(selectedVM.vmid, "start")}
|
||||
className="w-full bg-green-600 hover:bg-green-700 text-white"
|
||||
disabled={selectedVM?.status === "running" || controlLoading}
|
||||
onClick={() => selectedVM && handleVMControl(selectedVM.vmid, "start")}
|
||||
>
|
||||
<Play className="h-4 w-4 mr-2" />
|
||||
Start
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full bg-transparent"
|
||||
disabled={selectedVM.status !== "running" || controlLoading}
|
||||
onClick={() => handleVMControl(selectedVM.vmid, "shutdown")}
|
||||
className="w-full bg-blue-600 hover:bg-blue-700 text-white"
|
||||
disabled={selectedVM?.status !== "running" || controlLoading}
|
||||
onClick={() => selectedVM && handleVMControl(selectedVM.vmid, "shutdown")}
|
||||
>
|
||||
<Power className="h-4 w-4 mr-2" />
|
||||
Shutdown
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full bg-transparent"
|
||||
disabled={selectedVM.status !== "running" || controlLoading}
|
||||
onClick={() => handleVMControl(selectedVM.vmid, "reboot")}
|
||||
className="w-full bg-blue-600 hover:bg-blue-700 text-white"
|
||||
disabled={selectedVM?.status !== "running" || controlLoading}
|
||||
onClick={() => selectedVM && handleVMControl(selectedVM.vmid, "reboot")}
|
||||
>
|
||||
<RotateCcw className="h-4 w-4 mr-2" />
|
||||
Reboot
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full bg-transparent"
|
||||
disabled={selectedVM.status !== "running" || controlLoading}
|
||||
onClick={() => handleVMControl(selectedVM.vmid, "stop")}
|
||||
className="w-full bg-blue-600 hover:bg-blue-700 text-white"
|
||||
disabled={selectedVM?.status !== "running" || controlLoading}
|
||||
onClick={() => selectedVM && handleVMControl(selectedVM.vmid, "stop")}
|
||||
>
|
||||
<StopCircle className="h-4 w-4 mr-2" />
|
||||
Force Stop
|
||||
</Button>
|
||||
<Button
|
||||
className="w-full col-span-2 bg-purple-600 hover:bg-purple-700 text-white"
|
||||
disabled={controlLoading}
|
||||
onClick={() => selectedVM && handleDownloadLogs(selectedVM.vmid, selectedVM.name)}
|
||||
>
|
||||
<HardDrive className="h-4 w-4 mr-2" />
|
||||
Download Logs
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
|
||||
@@ -3752,6 +3752,54 @@ def api_vms():
|
||||
"""Get virtual machine information"""
|
||||
return jsonify(get_proxmox_vms())
|
||||
|
||||
@app.route('/api/vms/<int:vmid>/metrics', methods=['GET'])
|
||||
def api_vm_metrics(vmid):
|
||||
"""Get historical metrics (RRD data) for a specific VM/LXC"""
|
||||
try:
|
||||
timeframe = request.args.get('timeframe', 'week') # hour, day, week, month, year
|
||||
|
||||
# Validate timeframe
|
||||
valid_timeframes = ['hour', 'day', 'week', 'month', 'year']
|
||||
if timeframe not in valid_timeframes:
|
||||
return jsonify({'error': f'Invalid timeframe. Must be one of: {", ".join(valid_timeframes)}'}), 400
|
||||
|
||||
# Get local node name
|
||||
local_node = socket.gethostname()
|
||||
|
||||
# First, determine if it's a qemu VM or lxc container
|
||||
result = subprocess.run(['pvesh', 'get', f'/nodes/{local_node}/qemu/{vmid}/status/current', '--output-format', 'json'],
|
||||
capture_output=True, text=True, timeout=10)
|
||||
|
||||
vm_type = 'qemu'
|
||||
if result.returncode != 0:
|
||||
# Try LXC
|
||||
result = subprocess.run(['pvesh', 'get', f'/nodes/{local_node}/lxc/{vmid}/status/current', '--output-format', 'json'],
|
||||
capture_output=True, text=True, timeout=10)
|
||||
if result.returncode == 0:
|
||||
vm_type = 'lxc'
|
||||
else:
|
||||
return jsonify({'error': f'VM/LXC {vmid} not found'}), 404
|
||||
|
||||
# Get RRD data
|
||||
rrd_result = subprocess.run(['pvesh', 'get', f'/nodes/{local_node}/{vm_type}/{vmid}/rrddata',
|
||||
'--timeframe', timeframe, '--output-format', 'json'],
|
||||
capture_output=True, text=True, timeout=10)
|
||||
|
||||
if rrd_result.returncode == 0:
|
||||
rrd_data = json.loads(rrd_result.stdout)
|
||||
return jsonify({
|
||||
'vmid': vmid,
|
||||
'type': vm_type,
|
||||
'timeframe': timeframe,
|
||||
'data': rrd_data
|
||||
})
|
||||
else:
|
||||
return jsonify({'error': f'Failed to get RRD data: {rrd_result.stderr}'}), 500
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error getting VM metrics: {e}")
|
||||
return jsonify({'error': str(e)}), 500
|
||||
|
||||
@app.route('/api/logs', methods=['GET'])
|
||||
def api_logs():
|
||||
"""Get system logs"""
|
||||
@@ -4619,6 +4667,7 @@ def api_info():
|
||||
'/api/proxmox-storage',
|
||||
'/api/network',
|
||||
'/api/vms',
|
||||
'/api/vms/<vmid>/metrics', # Added endpoint for RRD data
|
||||
'/api/logs',
|
||||
'/api/health',
|
||||
'/api/hardware',
|
||||
|
||||
Reference in New Issue
Block a user