Update AppImage

This commit is contained in:
MacRimi
2025-10-04 19:25:28 +02:00
parent dc03144773
commit 441cc35e5a
2 changed files with 368 additions and 133 deletions

View File

@@ -1,19 +1,29 @@
"use client" "use client"
import { useState, useEffect } from "react" import { useState } from "react"
import { Card, CardContent, CardHeader, CardTitle } from "./ui/card" import { Card, CardContent, CardHeader, CardTitle } from "./ui/card"
import { Badge } from "./ui/badge" import { Badge } from "./ui/badge"
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "./ui/dialog" import { Dialog, DialogContent, DialogHeader, DialogTitle } from "./ui/dialog"
import { Wifi, Globe, Shield, Activity, Network, Router, AlertCircle, Zap } from "lucide-react" import { Wifi, Globe, Shield, Activity, Network, Router, AlertCircle, Zap } from "lucide-react"
import useSWR from "swr"
interface NetworkData { interface NetworkData {
interfaces: NetworkInterface[] interfaces: NetworkInterface[]
vm_lxc_interfaces?: NetworkInterface[]
traffic: { traffic: {
bytes_sent: number bytes_sent: number
bytes_recv: number bytes_recv: number
packets_sent?: number packets_sent?: number
packets_recv?: number packets_recv?: number
packet_loss_in?: number
packet_loss_out?: number
dropin?: number
dropout?: number
} }
active_count?: number
total_count?: number
vm_lxc_active_count?: number
vm_lxc_total_count?: number
} }
interface NetworkInterface { interface NetworkInterface {
@@ -40,6 +50,12 @@ interface NetworkInterface {
bond_slaves?: string[] bond_slaves?: string[]
bond_active_slave?: string | null bond_active_slave?: string | null
bridge_members?: string[] bridge_members?: string[]
packet_loss_in?: number
packet_loss_out?: number
vmid?: number
vm_name?: string
vm_type?: string
vm_status?: string
} }
const getInterfaceTypeBadge = (type: string) => { const getInterfaceTypeBadge = (type: string) => {
@@ -52,6 +68,8 @@ const getInterfaceTypeBadge = (type: string) => {
return { color: "bg-purple-500/10 text-purple-500 border-purple-500/20", label: "Bond" } return { color: "bg-purple-500/10 text-purple-500 border-purple-500/20", label: "Bond" }
case "vlan": case "vlan":
return { color: "bg-cyan-500/10 text-cyan-500 border-cyan-500/20", label: "VLAN" } return { color: "bg-cyan-500/10 text-cyan-500 border-cyan-500/20", label: "VLAN" }
case "vm_lxc":
return { color: "bg-orange-500/10 text-orange-500 border-orange-500/20", label: "Virtual" }
case "virtual": case "virtual":
return { color: "bg-orange-500/10 text-orange-500 border-orange-500/20", label: "Virtual" } return { color: "bg-orange-500/10 text-orange-500 border-orange-500/20", label: "Virtual" }
default: default:
@@ -59,6 +77,15 @@ const getInterfaceTypeBadge = (type: string) => {
} }
} }
const getVMTypeBadge = (vmType: string | undefined) => {
if (vmType === "lxc") {
return { color: "bg-cyan-500/10 text-cyan-500 border-cyan-500/20", label: "LXC" }
} else if (vmType === "vm") {
return { color: "bg-purple-500/10 text-purple-500 border-purple-500/20", label: "VM" }
}
return { color: "bg-gray-500/10 text-gray-500 border-gray-500/20", label: "Unknown" }
}
const formatBytes = (bytes: number | undefined): string => { const formatBytes = (bytes: number | undefined): string => {
if (!bytes || bytes === 0) return "0 B" if (!bytes || bytes === 0) return "0 B"
const k = 1024 const k = 1024
@@ -73,57 +100,36 @@ const formatSpeed = (speed: number): string => {
return `${speed} Mbps` return `${speed} Mbps`
} }
const fetchNetworkData = async (): Promise<NetworkData | null> => { const fetcher = async (url: string): Promise<NetworkData> => {
try { const response = await fetch(url, {
console.log("[v0] Fetching network data from Flask server...") method: "GET",
const response = await fetch("/api/network", { headers: {
method: "GET", "Content-Type": "application/json",
headers: { },
"Content-Type": "application/json", signal: AbortSignal.timeout(5000),
}, })
signal: AbortSignal.timeout(5000),
})
if (!response.ok) { if (!response.ok) {
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()
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
} }
return response.json()
} }
export function NetworkMetrics() { export function NetworkMetrics() {
const [networkData, setNetworkData] = useState<NetworkData | null>(null) const {
const [loading, setLoading] = useState(true) data: networkData,
const [error, setError] = useState<string | null>(null) error,
isLoading,
} = useSWR<NetworkData>("/api/network", fetcher, {
refreshInterval: 30000, // Refresh every 30 seconds
revalidateOnFocus: false,
revalidateOnReconnect: true,
})
const [selectedInterface, setSelectedInterface] = useState<NetworkInterface | null>(null) const [selectedInterface, setSelectedInterface] = useState<NetworkInterface | null>(null)
useEffect(() => { if (isLoading) {
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 ( return (
<div className="space-y-6"> <div className="space-y-6">
<div className="text-center py-8"> <div className="text-center py-8">
@@ -143,7 +149,8 @@ export function NetworkMetrics() {
<div> <div>
<div className="font-semibold text-lg mb-1">Flask Server Not Available</div> <div className="font-semibold text-lg mb-1">Flask Server Not Available</div>
<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?.message ||
"Unable to connect to the Flask server. Please ensure the server is running and try again."}
</div> </div>
</div> </div>
</div> </div>
@@ -153,23 +160,24 @@ export function NetworkMetrics() {
) )
} }
const trafficInMB = (networkData.traffic.bytes_recv / (1024 * 1024)).toFixed(1) const trafficInGB = (networkData.traffic.bytes_recv / 1024 ** 3).toFixed(2)
const trafficOutMB = (networkData.traffic.bytes_sent / (1024 * 1024)).toFixed(1) const trafficOutGB = (networkData.traffic.bytes_sent / 1024 ** 3).toFixed(2)
const packetsRecvK = networkData.traffic.packets_recv ? (networkData.traffic.packets_recv / 1000).toFixed(0) : "0"
return ( return (
<div className="space-y-6"> <div className="space-y-6">
{/* Network Overview Cards */} {/* Network Overview Cards */}
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6"> <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 md:gap-6">
<Card className="bg-card border-border"> <Card className="bg-card border-border">
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2"> <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium text-muted-foreground">Network Traffic</CardTitle> <CardTitle className="text-sm font-medium text-muted-foreground">Network Traffic</CardTitle>
<Activity className="h-4 w-4 text-muted-foreground" /> <Activity className="h-4 w-4 text-muted-foreground" />
</CardHeader> </CardHeader>
<CardContent> <CardContent>
<div className="text-2xl font-bold text-foreground">{trafficInMB} MB</div> <div className="text-2xl font-bold text-foreground">{trafficInGB} GB</div>
<div className="flex items-center space-x-2 mt-2"> <div className="flex flex-wrap items-center gap-2 mt-2">
<span className="text-xs text-green-500"> {trafficInMB} MB</span> <span className="text-xs text-green-500"> {trafficInGB} GB</span>
<span className="text-xs text-blue-500"> {trafficOutMB} MB</span> <span className="text-xs text-blue-500"> {trafficOutGB} GB</span>
</div> </div>
<p className="text-xs text-muted-foreground mt-2">Total data transferred</p> <p className="text-xs text-muted-foreground mt-2">Total data transferred</p>
</CardContent> </CardContent>
@@ -181,15 +189,13 @@ export function NetworkMetrics() {
<Network className="h-4 w-4 text-muted-foreground" /> <Network className="h-4 w-4 text-muted-foreground" />
</CardHeader> </CardHeader>
<CardContent> <CardContent>
<div className="text-2xl font-bold text-foreground"> <div className="text-2xl font-bold text-foreground">{networkData.active_count ?? 0}</div>
{networkData.interfaces.filter((i) => i.status === "up").length}
</div>
<div className="flex items-center mt-2"> <div className="flex items-center mt-2">
<Badge variant="outline" className="bg-green-500/10 text-green-500 border-green-500/20"> <Badge variant="outline" className="bg-green-500/10 text-green-500 border-green-500/20">
Online Online
</Badge> </Badge>
</div> </div>
<p className="text-xs text-muted-foreground mt-2">{networkData.interfaces.length} total interfaces</p> <p className="text-xs text-muted-foreground mt-2">{networkData.total_count ?? 0} total interfaces</p>
</CardContent> </CardContent>
</Card> </Card>
@@ -210,22 +216,23 @@ export function NetworkMetrics() {
</Card> </Card>
<Card className="bg-card border-border"> <Card className="bg-card border-border">
<CardHeader> <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-foreground flex items-center"> <CardTitle className="text-sm font-medium text-muted-foreground">Packets</CardTitle>
<Globe className="h-5 w-5 mr-2" /> <Globe className="h-4 w-4 text-muted-foreground" />
Packets
</CardTitle>
</CardHeader> </CardHeader>
<CardContent> <CardContent>
<div className="text-2xl font-bold text-foreground"> <div className="text-2xl font-bold text-foreground">{packetsRecvK}K</div>
{networkData.traffic.packets_recv ? (networkData.traffic.packets_recv / 1000).toFixed(0) : "N/A"}K
</div>
<div className="flex items-center mt-2"> <div className="flex items-center mt-2">
<Badge variant="outline" className="bg-green-500/10 text-green-500 border-green-500/20"> <Badge variant="outline" className="bg-green-500/10 text-green-500 border-green-500/20">
Received Received
</Badge> </Badge>
</div> </div>
<p className="text-xs text-muted-foreground mt-2">Total packets received</p> {networkData.traffic.packet_loss_in !== undefined && networkData.traffic.packet_loss_in > 0 && (
<p className="text-xs text-yellow-500 mt-2">Loss: {networkData.traffic.packet_loss_in}%</p>
)}
{(!networkData.traffic.packet_loss_in || networkData.traffic.packet_loss_in === 0) && (
<p className="text-xs text-muted-foreground mt-2">No packet loss</p>
)}
</CardContent> </CardContent>
</Card> </Card>
</div> </div>
@@ -249,10 +256,10 @@ export function NetworkMetrics() {
className="flex flex-col gap-3 p-4 rounded-lg border border-border bg-card/50 hover:bg-card/80 transition-colors cursor-pointer" className="flex flex-col gap-3 p-4 rounded-lg border border-border bg-card/50 hover:bg-card/80 transition-colors cursor-pointer"
onClick={() => setSelectedInterface(interface_)} onClick={() => setSelectedInterface(interface_)}
> >
{/* First row: Icon, Name, Type Badge */} {/* First row: Icon, Name, Type Badge, Status */}
<div className="flex items-center gap-3"> <div className="flex items-center gap-3 flex-wrap">
<Wifi className="h-5 w-5 text-muted-foreground flex-shrink-0" /> <Wifi className="h-5 w-5 text-muted-foreground flex-shrink-0" />
<div className="flex items-center gap-2 min-w-0 flex-1"> <div className="flex items-center gap-2 min-w-0">
<div className="font-medium text-foreground">{interface_.name}</div> <div className="font-medium text-foreground">{interface_.name}</div>
<Badge variant="outline" className={typeBadge.color}> <Badge variant="outline" className={typeBadge.color}>
{typeBadge.label} {typeBadge.label}
@@ -262,48 +269,48 @@ export function NetworkMetrics() {
variant="outline" variant="outline"
className={ className={
interface_.status === "up" interface_.status === "up"
? "bg-green-500/10 text-green-500 border-green-500/20" ? "bg-green-500/10 text-green-500 border-green-500/20 ml-auto"
: "bg-red-500/10 text-red-500 border-red-500/20" : "bg-red-500/10 text-red-500 border-red-500/20 ml-auto"
} }
> >
{interface_.status.toUpperCase()} {interface_.status.toUpperCase()}
</Badge> </Badge>
</div> </div>
{/* Second row: Details */} {/* Second row: Details - Responsive layout */}
<div className="flex items-center justify-between gap-6 text-sm"> <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
<div className="flex items-center gap-6"> <div>
<div> <div className="text-muted-foreground text-xs">IP Address</div>
<div className="text-muted-foreground">IP Address</div> <div className="font-medium text-foreground font-mono text-sm truncate">
<div className="font-medium text-foreground font-mono"> {interface_.addresses.length > 0 ? interface_.addresses[0].ip : "N/A"}
{interface_.addresses.length > 0 ? interface_.addresses[0].ip : "N/A"}
</div>
</div> </div>
<div>
<div className="text-muted-foreground">Speed</div>
<div className="font-medium text-foreground flex items-center gap-1">
<Zap className="h-3 w-3" />
{formatSpeed(interface_.speed)}
</div>
</div>
<div>
<div className="text-muted-foreground">Traffic</div>
<div className="font-medium text-foreground">
<span className="text-green-500"> {formatBytes(interface_.bytes_recv)}</span>
{" / "}
<span className="text-blue-500"> {formatBytes(interface_.bytes_sent)}</span>
</div>
</div>
{interface_.mac_address && (
<div>
<div className="text-muted-foreground">MAC</div>
<div className="font-medium text-foreground font-mono text-xs">{interface_.mac_address}</div>
</div>
)}
</div> </div>
<div>
<div className="text-muted-foreground text-xs">Speed</div>
<div className="font-medium text-foreground flex items-center gap-1">
<Zap className="h-3 w-3" />
{formatSpeed(interface_.speed)}
</div>
</div>
<div className="col-span-2 md:col-span-1">
<div className="text-muted-foreground text-xs">Traffic</div>
<div className="font-medium text-foreground text-xs">
<span className="text-green-500"> {formatBytes(interface_.bytes_recv)}</span>
{" / "}
<span className="text-blue-500"> {formatBytes(interface_.bytes_sent)}</span>
</div>
</div>
{interface_.mac_address && (
<div className="col-span-2 md:col-span-1">
<div className="text-muted-foreground text-xs">MAC</div>
<div className="font-medium text-foreground font-mono text-xs truncate">
{interface_.mac_address}
</div>
</div>
)}
</div> </div>
</div> </div>
) )
@@ -312,6 +319,93 @@ export function NetworkMetrics() {
</CardContent> </CardContent>
</Card> </Card>
{networkData.vm_lxc_interfaces && networkData.vm_lxc_interfaces.length > 0 && (
<Card className="bg-card border-border">
<CardHeader>
<CardTitle className="text-foreground flex items-center">
<Network className="h-5 w-5 mr-2" />
VM & LXC Network Interfaces
<Badge variant="outline" className="ml-3 bg-orange-500/10 text-orange-500 border-orange-500/20">
{networkData.vm_lxc_active_count ?? 0} / {networkData.vm_lxc_total_count ?? 0} Active
</Badge>
</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-4">
{networkData.vm_lxc_interfaces.map((interface_, index) => {
const vmTypeBadge = getVMTypeBadge(interface_.vm_type)
return (
<div
key={index}
className="flex flex-col gap-3 p-4 rounded-lg border border-border bg-card/50 hover:bg-card/80 transition-colors cursor-pointer"
onClick={() => setSelectedInterface(interface_)}
>
{/* First row: Icon, Name, VM/LXC Badge, VM Name, Status */}
<div className="flex items-center gap-3 flex-wrap">
<Wifi className="h-5 w-5 text-muted-foreground flex-shrink-0" />
<div className="flex items-center gap-2 min-w-0 flex-1">
<div className="font-medium text-foreground">{interface_.name}</div>
<Badge variant="outline" className={vmTypeBadge.color}>
{vmTypeBadge.label}
</Badge>
{interface_.vm_name && (
<div className="text-sm text-muted-foreground truncate"> {interface_.vm_name}</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>
{/* Second row: Details - Responsive layout */}
<div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
<div>
<div className="text-muted-foreground text-xs">VMID</div>
<div className="font-medium text-foreground">{interface_.vmid ?? "N/A"}</div>
</div>
<div>
<div className="text-muted-foreground text-xs">Speed</div>
<div className="font-medium text-foreground flex items-center gap-1">
<Zap className="h-3 w-3" />
{formatSpeed(interface_.speed)}
</div>
</div>
<div className="col-span-2 md:col-span-1">
<div className="text-muted-foreground text-xs">Traffic</div>
<div className="font-medium text-foreground text-xs">
<span className="text-green-500"> {formatBytes(interface_.bytes_recv)}</span>
{" / "}
<span className="text-blue-500"> {formatBytes(interface_.bytes_sent)}</span>
</div>
</div>
{interface_.mac_address && (
<div className="col-span-2 md:col-span-1">
<div className="text-muted-foreground text-xs">MAC</div>
<div className="font-medium text-foreground font-mono text-xs truncate">
{interface_.mac_address}
</div>
</div>
)}
</div>
</div>
)
})}
</div>
</CardContent>
</Card>
)}
{/* Interface Details Modal */} {/* Interface Details Modal */}
<Dialog open={!!selectedInterface} onOpenChange={() => setSelectedInterface(null)}> <Dialog open={!!selectedInterface} onOpenChange={() => setSelectedInterface(null)}>
<DialogContent className="max-w-2xl max-h-[80vh] overflow-y-auto"> <DialogContent className="max-w-2xl max-h-[80vh] overflow-y-auto">
@@ -425,6 +519,26 @@ export function NetworkMetrics() {
<div className="text-sm text-muted-foreground">Drops Out</div> <div className="text-sm text-muted-foreground">Drops Out</div>
<div className="font-medium text-yellow-500">{selectedInterface.drops_out || 0}</div> <div className="font-medium text-yellow-500">{selectedInterface.drops_out || 0}</div>
</div> </div>
{selectedInterface.packet_loss_in !== undefined && (
<div>
<div className="text-sm text-muted-foreground">Packet Loss In</div>
<div
className={`font-medium ${selectedInterface.packet_loss_in > 1 ? "text-red-500" : "text-green-500"}`}
>
{selectedInterface.packet_loss_in}%
</div>
</div>
)}
{selectedInterface.packet_loss_out !== undefined && (
<div>
<div className="text-sm text-muted-foreground">Packet Loss Out</div>
<div
className={`font-medium ${selectedInterface.packet_loss_out > 1 ? "text-red-500" : "text-green-500"}`}
>
{selectedInterface.packet_loss_out}%
</div>
</div>
)}
</div> </div>
</div> </div>

View File

@@ -15,10 +15,56 @@ import os
import time import time
import socket import socket
from datetime import datetime, timedelta from datetime import datetime, timedelta
import re # Added for regex matching
app = Flask(__name__) app = Flask(__name__)
CORS(app) # Enable CORS for Next.js frontend CORS(app) # Enable CORS for Next.js frontend
def extract_vmid_from_interface(interface_name):
"""Extract VMID from virtual interface name (veth100i0 -> 100, tap105i0 -> 105)"""
try:
match = re.match(r'(veth|tap)(\d+)i\d+', interface_name)
if match:
vmid = int(match.group(2))
interface_type = 'lxc' if match.group(1) == 'veth' else 'vm'
return vmid, interface_type
return None, None
except Exception as e:
print(f"[v0] Error extracting VMID from {interface_name}: {e}")
return None, None
def get_vm_lxc_names():
"""Get VM and LXC names from Proxmox API"""
vm_lxc_map = {}
try:
result = subprocess.run(['pvesh', 'get', '/cluster/resources', '--type', 'vm', '--output-format', 'json'],
capture_output=True, text=True, timeout=10)
if result.returncode == 0:
resources = json.loads(result.stdout)
for resource in resources:
vmid = resource.get('vmid')
name = resource.get('name', f'VM-{vmid}')
vm_type = resource.get('type', 'unknown') # 'qemu' or 'lxc'
status = resource.get('status', 'unknown')
if vmid:
vm_lxc_map[vmid] = {
'name': name,
'type': 'lxc' if vm_type == 'lxc' else 'vm',
'status': status
}
print(f"[v0] Found {vm_type} {vmid}: {name} ({status})")
else:
print(f"[v0] pvesh command failed: {result.stderr}")
except FileNotFoundError:
print("[v0] pvesh command not found - Proxmox not installed")
except Exception as e:
print(f"[v0] Error getting VM/LXC names: {e}")
return vm_lxc_map
@app.route('/') @app.route('/')
def serve_dashboard(): def serve_dashboard():
"""Serve the main dashboard page from Next.js build""" """Serve the main dashboard page from Next.js build"""
@@ -873,35 +919,38 @@ def get_proxmox_storage():
def get_interface_type(interface_name): def get_interface_type(interface_name):
"""Detect the type of network interface""" """Detect the type of network interface"""
try: try:
# Skip loopback
if interface_name == 'lo':
return 'skip'
if interface_name.startswith(('veth', 'tap')):
return 'vm_lxc'
# Skip other virtual interfaces
if interface_name.startswith(('tun', 'vnet', 'docker', 'virbr')):
return 'skip'
# Check if it's a bond # Check if it's a bond
if interface_name.startswith('bond'): if interface_name.startswith('bond'):
return 'bond' return 'bond'
# Check if it's a bridge # Check if it's a bridge (but not virbr which we skip above)
if interface_name.startswith(('vmbr', 'br', 'virbr')): if interface_name.startswith(('vmbr', 'br')):
return 'bridge' return 'bridge'
# Check if it's a VLAN (contains a dot) # Check if it's a VLAN (contains a dot)
if '.' in interface_name: if '.' in interface_name:
return 'vlan' return 'vlan'
# Check if it's NVMe (virtual)
if interface_name.startswith('nvme'):
return 'virtual'
# Check if it's a physical interface # Check if it's a physical interface
if interface_name.startswith(('enp', 'eth', 'wlan', 'wlp')): if interface_name.startswith(('enp', 'eth', 'wlan', 'wlp', 'eno', 'ens')):
return 'physical' return 'physical'
# Check if it's virtual (veth, tap, tun, etc.) # Default to skip for unknown types
if interface_name.startswith(('veth', 'tap', 'tun', 'vnet')): return 'skip'
return 'virtual'
# Default to unknown
return 'unknown'
except Exception as e: except Exception as e:
print(f"[v0] Error detecting interface type for {interface_name}: {e}") print(f"[v0] Error detecting interface type for {interface_name}: {e}")
return 'unknown' return 'skip'
def get_bond_info(bond_name): def get_bond_info(bond_name):
"""Get detailed information about a bonding interface""" """Get detailed information about a bonding interface"""
@@ -952,13 +1001,16 @@ def get_bridge_info(bridge_name):
return bridge_info return bridge_info
def get_network_info(): def get_network_info():
"""Get network interface information - Enhanced with type detection, speed, MAC, bonds, bridges""" """Get network interface information - Enhanced with VM/LXC interface separation"""
try: try:
network_data = { network_data = {
'interfaces': [], 'interfaces': [],
'traffic': {'bytes_sent': 0, 'bytes_recv': 0} 'vm_lxc_interfaces': [], # Added separate list for VM/LXC interfaces
'traffic': {'bytes_sent': 0, 'bytes_recv': 0, 'packets_sent': 0, 'packets_recv': 0}
} }
vm_lxc_map = get_vm_lxc_names()
# Get network interfaces # Get network interfaces
net_if_addrs = psutil.net_if_addrs() net_if_addrs = psutil.net_if_addrs()
net_if_stats = psutil.net_if_stats() net_if_stats = psutil.net_if_stats()
@@ -969,32 +1021,55 @@ def get_network_info():
print(f"[v0] Error getting per-NIC stats: {e}") print(f"[v0] Error getting per-NIC stats: {e}")
net_io_per_nic = {} net_io_per_nic = {}
for interface_name, interface_addresses in net_if_addrs.items(): active_count = 0
# Skip loopback total_count = 0
if interface_name == 'lo': vm_lxc_active_count = 0
continue vm_lxc_total_count = 0
for interface_name, interface_addresses in net_if_addrs.items():
interface_type = get_interface_type(interface_name) interface_type = get_interface_type(interface_name)
# Skip unknown virtual interfaces if interface_type == 'skip':
if interface_type == 'unknown' and not interface_name.startswith(('enp', 'eth', 'wlan', 'vmbr', 'br', 'bond')): print(f"[v0] Skipping interface: {interface_name} (type: {interface_type})")
continue continue
stats = net_if_stats.get(interface_name) stats = net_if_stats.get(interface_name)
if not stats: if not stats:
continue continue
if interface_type == 'vm_lxc':
vm_lxc_total_count += 1
if stats.isup:
vm_lxc_active_count += 1
else:
total_count += 1
if stats.isup:
active_count += 1
interface_info = { interface_info = {
'name': interface_name, 'name': interface_name,
'type': interface_type, # Added type 'type': interface_type,
'status': 'up' if stats.isup else 'down', 'status': 'up' if stats.isup else 'down',
'speed': stats.speed if stats.speed > 0 else 0, # Added speed in Mbps 'speed': stats.speed if stats.speed > 0 else 0,
'duplex': 'full' if stats.duplex == 2 else 'half' if stats.duplex == 1 else 'unknown', # Added duplex 'duplex': 'full' if stats.duplex == 2 else 'half' if stats.duplex == 1 else 'unknown',
'mtu': stats.mtu, # Added MTU 'mtu': stats.mtu,
'addresses': [], 'addresses': [],
'mac_address': None, # Added MAC address 'mac_address': None,
} }
if interface_type == 'vm_lxc':
vmid, vm_type = extract_vmid_from_interface(interface_name)
if vmid and vmid in vm_lxc_map:
interface_info['vmid'] = vmid
interface_info['vm_name'] = vm_lxc_map[vmid]['name']
interface_info['vm_type'] = vm_lxc_map[vmid]['type']
interface_info['vm_status'] = vm_lxc_map[vmid]['status']
elif vmid:
interface_info['vmid'] = vmid
interface_info['vm_name'] = f'{"LXC" if vm_type == "lxc" else "VM"} {vmid}'
interface_info['vm_type'] = vm_type
interface_info['vm_status'] = 'unknown'
for address in interface_addresses: for address in interface_addresses:
if address.family == 2: # IPv4 if address.family == 2: # IPv4
interface_info['addresses'].append({ interface_info['addresses'].append({
@@ -1015,6 +1090,19 @@ def get_network_info():
interface_info['drops_in'] = io_stats.dropin interface_info['drops_in'] = io_stats.dropin
interface_info['drops_out'] = io_stats.dropout interface_info['drops_out'] = io_stats.dropout
total_packets_in = io_stats.packets_recv + io_stats.dropin
total_packets_out = io_stats.packets_sent + io_stats.dropout
if total_packets_in > 0:
interface_info['packet_loss_in'] = round((io_stats.dropin / total_packets_in) * 100, 2)
else:
interface_info['packet_loss_in'] = 0
if total_packets_out > 0:
interface_info['packet_loss_out'] = round((io_stats.dropout / total_packets_out) * 100, 2)
else:
interface_info['packet_loss_out'] = 0
if interface_type == 'bond': if interface_type == 'bond':
bond_info = get_bond_info(interface_name) bond_info = get_bond_info(interface_name)
interface_info['bond_mode'] = bond_info['mode'] interface_info['bond_mode'] = bond_info['mode']
@@ -1025,7 +1113,18 @@ def get_network_info():
bridge_info = get_bridge_info(interface_name) bridge_info = get_bridge_info(interface_name)
interface_info['bridge_members'] = bridge_info['members'] interface_info['bridge_members'] = bridge_info['members']
network_data['interfaces'].append(interface_info) if interface_type == 'vm_lxc':
network_data['vm_lxc_interfaces'].append(interface_info)
else:
network_data['interfaces'].append(interface_info)
network_data['active_count'] = active_count
network_data['total_count'] = total_count
network_data['vm_lxc_active_count'] = vm_lxc_active_count
network_data['vm_lxc_total_count'] = vm_lxc_total_count
print(f"[v0] Physical interfaces: {active_count} active out of {total_count} total")
print(f"[v0] VM/LXC interfaces: {vm_lxc_active_count} active out of {vm_lxc_total_count} total")
# Get network I/O statistics (global) # Get network I/O statistics (global)
net_io = psutil.net_io_counters() net_io = psutil.net_io_counters()
@@ -1033,9 +1132,26 @@ def get_network_info():
'bytes_sent': net_io.bytes_sent, 'bytes_sent': net_io.bytes_sent,
'bytes_recv': net_io.bytes_recv, 'bytes_recv': net_io.bytes_recv,
'packets_sent': net_io.packets_sent, 'packets_sent': net_io.packets_sent,
'packets_recv': net_io.packets_recv 'packets_recv': net_io.packets_recv,
'errin': net_io.errin,
'errout': net_io.errout,
'dropin': net_io.dropin,
'dropout': net_io.dropout
} }
total_packets_in = net_io.packets_recv + net_io.dropin
total_packets_out = net_io.packets_sent + net_io.dropout
if total_packets_in > 0:
network_data['traffic']['packet_loss_in'] = round((net_io.dropin / total_packets_in) * 100, 2)
else:
network_data['traffic']['packet_loss_in'] = 0
if total_packets_out > 0:
network_data['traffic']['packet_loss_out'] = round((net_io.dropout / total_packets_out) * 100, 2)
else:
network_data['traffic']['packet_loss_out'] = 0
return network_data return network_data
except Exception as e: except Exception as e:
print(f"Error getting network info: {e}") print(f"Error getting network info: {e}")
@@ -1044,7 +1160,12 @@ def get_network_info():
return { return {
'error': f'Unable to access network information: {str(e)}', 'error': f'Unable to access network information: {str(e)}',
'interfaces': [], 'interfaces': [],
'traffic': {'bytes_sent': 0, 'bytes_recv': 0, 'packets_sent': 0, 'packets_recv': 0} 'vm_lxc_interfaces': [],
'traffic': {'bytes_sent': 0, 'bytes_recv': 0, 'packets_sent': 0, 'packets_recv': 0},
'active_count': 0,
'total_count': 0,
'vm_lxc_active_count': 0,
'vm_lxc_total_count': 0
} }
def get_proxmox_vms(): def get_proxmox_vms():