mirror of
https://github.com/MacRimi/ProxMenux.git
synced 2025-10-11 12:26:18 +00:00
Update AppImage
This commit is contained in:
@@ -1,32 +1,47 @@
|
|||||||
"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 { Progress } from "./ui/progress"
|
import { Progress } from "./ui/progress"
|
||||||
import { Server, Play, Square, Monitor, Cpu, MemoryStick, AlertCircle, HardDrive, Network } from "lucide-react"
|
import { Button } from "./ui/button"
|
||||||
|
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "./ui/dialog"
|
||||||
|
import {
|
||||||
|
Server,
|
||||||
|
Play,
|
||||||
|
Square,
|
||||||
|
Monitor,
|
||||||
|
Cpu,
|
||||||
|
MemoryStick,
|
||||||
|
AlertCircle,
|
||||||
|
HardDrive,
|
||||||
|
Network,
|
||||||
|
Power,
|
||||||
|
RotateCcw,
|
||||||
|
Download,
|
||||||
|
StopCircle,
|
||||||
|
} from "lucide-react"
|
||||||
|
import useSWR from "swr"
|
||||||
|
|
||||||
interface VMData {
|
interface VMData {
|
||||||
vmid: number
|
vmid: number
|
||||||
name: string
|
name: string
|
||||||
status: string
|
status: string
|
||||||
type: string // Added type field to distinguish VM from LXC
|
type: string
|
||||||
cpu: number
|
cpu: number
|
||||||
mem: number
|
mem: number
|
||||||
maxmem: number
|
maxmem: number
|
||||||
disk: number
|
disk: number
|
||||||
maxdisk: number
|
maxdisk: number
|
||||||
uptime: number
|
uptime: number
|
||||||
netin?: number // Added network in
|
netin?: number
|
||||||
netout?: number // Added network out
|
netout?: number
|
||||||
diskread?: number // Added disk read
|
diskread?: number
|
||||||
diskwrite?: number // Added disk write
|
diskwrite?: number
|
||||||
}
|
}
|
||||||
|
|
||||||
const fetchVMData = async (): Promise<VMData[]> => {
|
const fetcher = async (url: string) => {
|
||||||
try {
|
const response = await fetch(url, {
|
||||||
console.log("[v0] Fetching VM data from Flask server...")
|
|
||||||
const response = await fetch("/api/vms", {
|
|
||||||
method: "GET",
|
method: "GET",
|
||||||
headers: {
|
headers: {
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
@@ -39,12 +54,7 @@ const fetchVMData = async (): Promise<VMData[]> => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
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 : []
|
return Array.isArray(data) ? data : []
|
||||||
} catch (error) {
|
|
||||||
console.error("[v0] Failed to fetch VM data from Flask server:", error)
|
|
||||||
throw error
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const formatBytes = (bytes: number | undefined): string => {
|
const formatBytes = (bytes: number | undefined): string => {
|
||||||
@@ -56,30 +66,64 @@ const formatBytes = (bytes: number | undefined): string => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function VirtualMachines() {
|
export function VirtualMachines() {
|
||||||
const [vmData, setVmData] = useState<VMData[]>([])
|
const {
|
||||||
const [loading, setLoading] = useState(true)
|
data: vmData,
|
||||||
const [error, setError] = useState<string | null>(null)
|
error,
|
||||||
|
isLoading,
|
||||||
|
mutate,
|
||||||
|
} = useSWR<VMData[]>("/api/vms", fetcher, {
|
||||||
|
refreshInterval: 30000, // Refresh every 30 seconds
|
||||||
|
revalidateOnFocus: false,
|
||||||
|
revalidateOnReconnect: true,
|
||||||
|
})
|
||||||
|
|
||||||
useEffect(() => {
|
const [selectedVM, setSelectedVM] = useState<VMData | null>(null)
|
||||||
const fetchData = async () => {
|
const [controlLoading, setControlLoading] = useState(false)
|
||||||
|
|
||||||
|
const handleVMControl = async (vmid: number, action: string) => {
|
||||||
|
setControlLoading(true)
|
||||||
try {
|
try {
|
||||||
setLoading(true)
|
const response = await fetch(`/api/vms/${vmid}/control`, {
|
||||||
setError(null)
|
method: "POST",
|
||||||
const result = await fetchVMData()
|
headers: {
|
||||||
setVmData(result)
|
"Content-Type": "application/json",
|
||||||
} catch (err) {
|
},
|
||||||
setError("Flask server not available. Please ensure the server is running.")
|
body: JSON.stringify({ action }),
|
||||||
|
})
|
||||||
|
|
||||||
|
if (response.ok) {
|
||||||
|
// Refresh VM data after action
|
||||||
|
mutate()
|
||||||
|
setSelectedVM(null)
|
||||||
|
} else {
|
||||||
|
console.error("Failed to control VM")
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error controlling VM:", error)
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false)
|
setControlLoading(false)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fetchData()
|
const handleDownloadLogs = async (vmid: number) => {
|
||||||
const interval = setInterval(fetchData, 30000)
|
try {
|
||||||
return () => clearInterval(interval)
|
const response = await fetch(`/api/vms/${vmid}/logs`)
|
||||||
}, [])
|
if (response.ok) {
|
||||||
|
const data = await response.json()
|
||||||
|
const blob = new Blob([JSON.stringify(data, null, 2)], { type: "application/json" })
|
||||||
|
const url = URL.createObjectURL(blob)
|
||||||
|
const a = document.createElement("a")
|
||||||
|
a.href = url
|
||||||
|
a.download = `vm-${vmid}-logs.json`
|
||||||
|
a.click()
|
||||||
|
URL.revokeObjectURL(url)
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error downloading logs:", error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (loading) {
|
if (isLoading) {
|
||||||
return (
|
return (
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
<div className="text-center py-8">
|
<div className="text-center py-8">
|
||||||
@@ -89,7 +133,7 @@ export function VirtualMachines() {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
if (error) {
|
if (error || !vmData) {
|
||||||
return (
|
return (
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
<Card className="bg-red-500/10 border-red-500/20">
|
<Card className="bg-red-500/10 border-red-500/20">
|
||||||
@@ -99,7 +143,8 @@ export function VirtualMachines() {
|
|||||||
<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>
|
||||||
@@ -156,7 +201,7 @@ export function VirtualMachines() {
|
|||||||
<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-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">Total VMs</CardTitle>
|
<CardTitle className="text-sm font-medium text-muted-foreground">Total VMs & LXCs</CardTitle>
|
||||||
<Server className="h-4 w-4 text-muted-foreground" />
|
<Server className="h-4 w-4 text-muted-foreground" />
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
@@ -179,7 +224,7 @@ export function VirtualMachines() {
|
|||||||
<Cpu className="h-4 w-4 text-muted-foreground" />
|
<Cpu className="h-4 w-4 text-muted-foreground" />
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
<div className="text-2xl font-bold text-green-500">{(totalCPU * 100).toFixed(0)}%</div>
|
<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>
|
<p className="text-xs text-muted-foreground mt-2">Allocated CPU usage</p>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
@@ -190,7 +235,7 @@ export function VirtualMachines() {
|
|||||||
<MemoryStick className="h-4 w-4 text-muted-foreground" />
|
<MemoryStick className="h-4 w-4 text-muted-foreground" />
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
<div className="text-2xl font-bold text-blue-500">{(totalMemory / 1024 ** 3).toFixed(1)} GB</div>
|
<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>
|
<p className="text-xs text-muted-foreground mt-2">Allocated RAM</p>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
@@ -201,7 +246,7 @@ export function VirtualMachines() {
|
|||||||
<Monitor className="h-4 w-4 text-muted-foreground" />
|
<Monitor className="h-4 w-4 text-muted-foreground" />
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
<div className="text-2xl font-bold text-green-500">
|
<div className="text-2xl font-bold text-foreground">
|
||||||
{runningVMs > 0 ? ((totalCPU / runningVMs) * 100).toFixed(0) : 0}%
|
{runningVMs > 0 ? ((totalCPU / runningVMs) * 100).toFixed(0) : 0}%
|
||||||
</div>
|
</div>
|
||||||
<p className="text-xs text-muted-foreground mt-2">Average resource utilization</p>
|
<p className="text-xs text-muted-foreground mt-2">Average resource utilization</p>
|
||||||
@@ -230,7 +275,11 @@ export function VirtualMachines() {
|
|||||||
const typeBadge = getTypeBadge(vm.type)
|
const typeBadge = getTypeBadge(vm.type)
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div key={vm.vmid} className="p-6 rounded-lg border border-border bg-card/50">
|
<div
|
||||||
|
key={vm.vmid}
|
||||||
|
className="p-6 rounded-lg border border-border bg-card/50 hover:bg-card/80 transition-colors cursor-pointer"
|
||||||
|
onClick={() => setSelectedVM(vm)}
|
||||||
|
>
|
||||||
<div className="flex items-center justify-between mb-4">
|
<div className="flex items-center justify-between mb-4">
|
||||||
<div className="flex items-center space-x-4">
|
<div className="flex items-center space-x-4">
|
||||||
<Server className="h-6 w-6 text-muted-foreground" />
|
<Server className="h-6 w-6 text-muted-foreground" />
|
||||||
@@ -256,13 +305,13 @@ export function VirtualMachines() {
|
|||||||
<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-6">
|
||||||
<div>
|
<div>
|
||||||
<div className="text-sm text-muted-foreground mb-2">CPU Usage</div>
|
<div className="text-sm text-muted-foreground mb-2">CPU Usage</div>
|
||||||
<div className="text-lg font-semibold text-green-500 mb-1">{cpuPercent}%</div>
|
<div className="text-lg font-semibold text-foreground mb-1">{cpuPercent}%</div>
|
||||||
<Progress value={Number.parseFloat(cpuPercent)} className="h-2 [&>div]:bg-green-500" />
|
<Progress value={Number.parseFloat(cpuPercent)} className="h-2 [&>div]:bg-blue-500" />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<div className="text-sm text-muted-foreground mb-2">Memory Usage</div>
|
<div className="text-sm text-muted-foreground mb-2">Memory Usage</div>
|
||||||
<div className="text-lg font-semibold text-blue-500 mb-1">
|
<div className="text-lg font-semibold text-foreground mb-1">
|
||||||
{memGB} / {maxMemGB} GB
|
{memGB} / {maxMemGB} GB
|
||||||
</div>
|
</div>
|
||||||
<Progress value={Number.parseFloat(memPercent)} className="h-2 [&>div]:bg-blue-500" />
|
<Progress value={Number.parseFloat(memPercent)} className="h-2 [&>div]:bg-blue-500" />
|
||||||
@@ -308,6 +357,124 @@ export function VirtualMachines() {
|
|||||||
)}
|
)}
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
|
{/* VM Details Modal */}
|
||||||
|
<Dialog open={!!selectedVM} onOpenChange={() => setSelectedVM(null)}>
|
||||||
|
<DialogContent className="max-w-2xl max-h-[80vh] overflow-y-auto">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle className="flex items-center gap-2">
|
||||||
|
<Server className="h-5 w-5" />
|
||||||
|
{selectedVM?.name} - Details
|
||||||
|
</DialogTitle>
|
||||||
|
</DialogHeader>
|
||||||
|
|
||||||
|
{selectedVM && (
|
||||||
|
<div className="space-y-6">
|
||||||
|
{/* Basic Information */}
|
||||||
|
<div>
|
||||||
|
<h3 className="text-sm font-semibold text-muted-foreground mb-3">Basic Information</h3>
|
||||||
|
<div className="grid grid-cols-2 gap-4">
|
||||||
|
<div>
|
||||||
|
<div className="text-sm text-muted-foreground">Name</div>
|
||||||
|
<div className="font-medium">{selectedVM.name}</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div className="text-sm text-muted-foreground">Type</div>
|
||||||
|
<Badge variant="outline" className={getTypeBadge(selectedVM.type).color}>
|
||||||
|
{getTypeBadge(selectedVM.type).label}
|
||||||
|
</Badge>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div className="text-sm text-muted-foreground">VMID</div>
|
||||||
|
<div className="font-medium">{selectedVM.vmid}</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div className="text-sm text-muted-foreground">Status</div>
|
||||||
|
<Badge variant="outline" className={getStatusColor(selectedVM.status)}>
|
||||||
|
{selectedVM.status.toUpperCase()}
|
||||||
|
</Badge>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div className="text-sm text-muted-foreground">CPU Usage</div>
|
||||||
|
<div className="font-medium">{(selectedVM.cpu * 100).toFixed(1)}%</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div className="text-sm text-muted-foreground">Memory</div>
|
||||||
|
<div className="font-medium">
|
||||||
|
{(selectedVM.mem / 1024 ** 3).toFixed(1)} / {(selectedVM.maxmem / 1024 ** 3).toFixed(1)} GB
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div className="text-sm text-muted-foreground">Disk</div>
|
||||||
|
<div className="font-medium">
|
||||||
|
{(selectedVM.disk / 1024 ** 3).toFixed(1)} / {(selectedVM.maxdisk / 1024 ** 3).toFixed(1)} GB
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div className="text-sm text-muted-foreground">Uptime</div>
|
||||||
|
<div className="font-medium">{formatUptime(selectedVM.uptime)}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Control Actions */}
|
||||||
|
<div>
|
||||||
|
<h3 className="text-sm font-semibold text-muted-foreground mb-3">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")}
|
||||||
|
>
|
||||||
|
<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")}
|
||||||
|
>
|
||||||
|
<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")}
|
||||||
|
>
|
||||||
|
<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")}
|
||||||
|
>
|
||||||
|
<StopCircle className="h-4 w-4 mr-2" />
|
||||||
|
Force Stop
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Download Logs */}
|
||||||
|
<div>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
className="w-full bg-transparent"
|
||||||
|
onClick={() => handleDownloadLogs(selectedVM.vmid)}
|
||||||
|
>
|
||||||
|
<Download className="h-4 w-4 mr-2" />
|
||||||
|
Download Logs
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
@@ -998,7 +998,25 @@ def get_bridge_info(bridge_name):
|
|||||||
bridge_info['members'] = members
|
bridge_info['members'] = members
|
||||||
|
|
||||||
for member in members:
|
for member in members:
|
||||||
if member.startswith(('enp', 'eth', 'eno', 'ens', 'wlan', 'wlp')):
|
# Check if member is a bond first
|
||||||
|
if member.startswith('bond'):
|
||||||
|
bridge_info['physical_interface'] = member
|
||||||
|
print(f"[v0] Bridge {bridge_name} connected to bond: {member}")
|
||||||
|
|
||||||
|
# Get duplex from bond's active slave
|
||||||
|
bond_info = get_bond_info(member)
|
||||||
|
if bond_info['active_slave']:
|
||||||
|
try:
|
||||||
|
net_if_stats = psutil.net_if_stats()
|
||||||
|
if bond_info['active_slave'] in net_if_stats:
|
||||||
|
stats = net_if_stats[bond_info['active_slave']]
|
||||||
|
bridge_info['physical_duplex'] = 'full' if stats.duplex == 2 else 'half' if stats.duplex == 1 else 'unknown'
|
||||||
|
print(f"[v0] Bond {member} active slave {bond_info['active_slave']} duplex: {bridge_info['physical_duplex']}")
|
||||||
|
except Exception as e:
|
||||||
|
print(f"[v0] Error getting duplex for bond slave {bond_info['active_slave']}: {e}")
|
||||||
|
break
|
||||||
|
# Check if member is a physical interface
|
||||||
|
elif member.startswith(('enp', 'eth', 'eno', 'ens', 'wlan', 'wlp')):
|
||||||
bridge_info['physical_interface'] = member
|
bridge_info['physical_interface'] = member
|
||||||
print(f"[v0] Bridge {bridge_name} physical interface: {member}")
|
print(f"[v0] Bridge {bridge_name} physical interface: {member}")
|
||||||
|
|
||||||
@@ -1409,6 +1427,149 @@ def api_info():
|
|||||||
]
|
]
|
||||||
})
|
})
|
||||||
|
|
||||||
|
@app.route('/api/vms/<int:vmid>', methods=['GET'])
|
||||||
|
def api_vm_details(vmid):
|
||||||
|
"""Get detailed information for a specific VM/LXC"""
|
||||||
|
try:
|
||||||
|
result = subprocess.run(['pvesh', 'get', f'/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:
|
||||||
|
if resource.get('vmid') == vmid:
|
||||||
|
vm_type = 'lxc' if resource.get('type') == 'lxc' else 'qemu'
|
||||||
|
node = resource.get('node', 'pve')
|
||||||
|
|
||||||
|
# Get detailed config
|
||||||
|
config_result = subprocess.run(
|
||||||
|
['pvesh', 'get', f'/nodes/{node}/{vm_type}/{vmid}/config', '--output-format', 'json'],
|
||||||
|
capture_output=True, text=True, timeout=10
|
||||||
|
)
|
||||||
|
|
||||||
|
config = {}
|
||||||
|
if config_result.returncode == 0:
|
||||||
|
config = json.loads(config_result.stdout)
|
||||||
|
|
||||||
|
return jsonify({
|
||||||
|
**resource,
|
||||||
|
'config': config,
|
||||||
|
'node': node,
|
||||||
|
'vm_type': vm_type
|
||||||
|
})
|
||||||
|
|
||||||
|
return jsonify({'error': f'VM/LXC {vmid} not found'}), 404
|
||||||
|
else:
|
||||||
|
return jsonify({'error': 'Failed to get VM details'}), 500
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Error getting VM details: {e}")
|
||||||
|
return jsonify({'error': str(e)}), 500
|
||||||
|
|
||||||
|
@app.route('/api/vms/<int:vmid>/logs', methods=['GET'])
|
||||||
|
def api_vm_logs(vmid):
|
||||||
|
"""Download logs for a specific VM/LXC"""
|
||||||
|
try:
|
||||||
|
# Get VM type and node
|
||||||
|
result = subprocess.run(['pvesh', 'get', f'/cluster/resources', '--type', 'vm', '--output-format', 'json'],
|
||||||
|
capture_output=True, text=True, timeout=10)
|
||||||
|
|
||||||
|
if result.returncode == 0:
|
||||||
|
resources = json.loads(result.stdout)
|
||||||
|
vm_info = None
|
||||||
|
for resource in resources:
|
||||||
|
if resource.get('vmid') == vmid:
|
||||||
|
vm_info = resource
|
||||||
|
break
|
||||||
|
|
||||||
|
if not vm_info:
|
||||||
|
return jsonify({'error': f'VM/LXC {vmid} not found'}), 404
|
||||||
|
|
||||||
|
vm_type = 'lxc' if vm_info.get('type') == 'lxc' else 'qemu'
|
||||||
|
node = vm_info.get('node', 'pve')
|
||||||
|
|
||||||
|
# Get task log
|
||||||
|
log_result = subprocess.run(
|
||||||
|
['pvesh', 'get', f'/nodes/{node}/tasks', '--vmid', str(vmid), '--output-format', 'json'],
|
||||||
|
capture_output=True, text=True, timeout=10
|
||||||
|
)
|
||||||
|
|
||||||
|
logs = []
|
||||||
|
if log_result.returncode == 0:
|
||||||
|
tasks = json.loads(log_result.stdout)
|
||||||
|
for task in tasks[:50]: # Last 50 tasks
|
||||||
|
logs.append({
|
||||||
|
'upid': task.get('upid'),
|
||||||
|
'type': task.get('type'),
|
||||||
|
'status': task.get('status'),
|
||||||
|
'starttime': task.get('starttime'),
|
||||||
|
'endtime': task.get('endtime'),
|
||||||
|
'user': task.get('user')
|
||||||
|
})
|
||||||
|
|
||||||
|
return jsonify({
|
||||||
|
'vmid': vmid,
|
||||||
|
'name': vm_info.get('name'),
|
||||||
|
'type': vm_type,
|
||||||
|
'logs': logs
|
||||||
|
})
|
||||||
|
else:
|
||||||
|
return jsonify({'error': 'Failed to get VM logs'}), 500
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Error getting VM logs: {e}")
|
||||||
|
return jsonify({'error': str(e)}), 500
|
||||||
|
|
||||||
|
@app.route('/api/vms/<int:vmid>/control', methods=['POST'])
|
||||||
|
def api_vm_control(vmid):
|
||||||
|
"""Control VM/LXC (start, stop, shutdown, reboot)"""
|
||||||
|
try:
|
||||||
|
data = request.get_json()
|
||||||
|
action = data.get('action') # start, stop, shutdown, reboot
|
||||||
|
|
||||||
|
if action not in ['start', 'stop', 'shutdown', 'reboot']:
|
||||||
|
return jsonify({'error': 'Invalid action'}), 400
|
||||||
|
|
||||||
|
# Get VM type and node
|
||||||
|
result = subprocess.run(['pvesh', 'get', f'/cluster/resources', '--type', 'vm', '--output-format', 'json'],
|
||||||
|
capture_output=True, text=True, timeout=10)
|
||||||
|
|
||||||
|
if result.returncode == 0:
|
||||||
|
resources = json.loads(result.stdout)
|
||||||
|
vm_info = None
|
||||||
|
for resource in resources:
|
||||||
|
if resource.get('vmid') == vmid:
|
||||||
|
vm_info = resource
|
||||||
|
break
|
||||||
|
|
||||||
|
if not vm_info:
|
||||||
|
return jsonify({'error': f'VM/LXC {vmid} not found'}), 404
|
||||||
|
|
||||||
|
vm_type = 'lxc' if vm_info.get('type') == 'lxc' else 'qemu'
|
||||||
|
node = vm_info.get('node', 'pve')
|
||||||
|
|
||||||
|
# Execute action
|
||||||
|
control_result = subprocess.run(
|
||||||
|
['pvesh', 'create', f'/nodes/{node}/{vm_type}/{vmid}/status/{action}'],
|
||||||
|
capture_output=True, text=True, timeout=30
|
||||||
|
)
|
||||||
|
|
||||||
|
if control_result.returncode == 0:
|
||||||
|
return jsonify({
|
||||||
|
'success': True,
|
||||||
|
'vmid': vmid,
|
||||||
|
'action': action,
|
||||||
|
'message': f'Successfully executed {action} on {vm_info.get("name")}'
|
||||||
|
})
|
||||||
|
else:
|
||||||
|
return jsonify({
|
||||||
|
'success': False,
|
||||||
|
'error': control_result.stderr
|
||||||
|
}), 500
|
||||||
|
else:
|
||||||
|
return jsonify({'error': 'Failed to control VM'}), 500
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Error controlling VM: {e}")
|
||||||
|
return jsonify({'error': str(e)}), 500
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
print("Starting ProxMenux Flask Server on port 8008...")
|
print("Starting ProxMenux Flask Server on port 8008...")
|
||||||
print("Server will be accessible on all network interfaces (0.0.0.0:8008)")
|
print("Server will be accessible on all network interfaces (0.0.0.0:8008)")
|
||||||
|
Reference in New Issue
Block a user