"use client" import { Card, CardContent, CardHeader, CardTitle } from "./ui/card" import { Badge } from "./ui/badge" import { Button } from "./ui/button" import { Input } from "./ui/input" import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select" import { ScrollArea } from "./ui/scroll-area" import { Tabs, TabsContent, TabsList, TabsTrigger } from "./ui/tabs" import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "./ui/dialog" import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetTrigger } from "./ui/sheet" import { FileText, Search, Download, AlertTriangle, Info, CheckCircle, XCircle, Database, Activity, HardDrive, Calendar, RefreshCw, Bell, Mail, Menu, Terminal, CalendarDays, } from "lucide-react" import { useState, useEffect } from "react" interface Log { timestamp: string level: string service: string message: string source: string pid?: string hostname?: string } interface Backup { volid: string storage: string vmid: string | null type: string | null size: number size_human: string created: string timestamp: number } interface Event { upid: string type: string status: string level: string node: string user: string vmid: string starttime: string endtime: string duration: string } interface Notification { timestamp: string type: string service: string message: string source: string } interface SystemLog { timestamp: string level: string service: string message: string source: string pid?: string hostname?: string } export function SystemLogs() { const [logs, setLogs] = useState([]) const [backups, setBackups] = useState([]) const [events, setEvents] = useState([]) const [notifications, setNotifications] = useState([]) const [loading, setLoading] = useState(true) const [error, setError] = useState(null) const [searchTerm, setSearchTerm] = useState("") const [levelFilter, setLevelFilter] = useState("all") const [serviceFilter, setServiceFilter] = useState("all") const [activeTab, setActiveTab] = useState("logs") const [selectedLog, setSelectedLog] = useState(null) const [selectedEvent, setSelectedEvent] = useState(null) const [selectedBackup, setSelectedBackup] = useState(null) const [selectedNotification, setSelectedNotification] = useState(null) // Added const [isLogModalOpen, setIsLogModalOpen] = useState(false) const [isEventModalOpen, setIsEventModalOpen] = useState(false) const [isBackupModalOpen, setIsBackupModalOpen] = useState(false) const [isNotificationModalOpen, setIsNotificationModalOpen] = useState(false) // Added const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false) const [dateFilter, setDateFilter] = useState("now") const [customDays, setCustomDays] = useState("1") const getApiUrl = (endpoint: string) => { if (typeof window !== "undefined") { return `${window.location.protocol}//${window.location.hostname}:8008${endpoint}` } return `http://localhost:8008${endpoint}` } useEffect(() => { fetchAllData() }, []) useEffect(() => { console.log("[v0] Date filter changed:", dateFilter, "Custom days:", customDays) if (dateFilter !== "now") { setLoading(true) fetchSystemLogs() .then((newLogs) => { console.log("[v0] Loaded logs for date filter:", dateFilter, "Count:", newLogs.length) console.log("[v0] First log:", newLogs[0]) setLogs(newLogs) setLoading(false) }) .catch((err) => { console.error("[v0] Error loading logs:", err) setLoading(false) }) } else { fetchAllData() } }, [dateFilter, customDays]) const fetchAllData = async () => { try { setLoading(true) setError(null) const [logsRes, backupsRes, eventsRes, notificationsRes] = await Promise.all([ fetchSystemLogs(), fetch(getApiUrl("/api/backups")), fetch(getApiUrl("/api/events?limit=50")), fetch(getApiUrl("/api/notifications")), ]) setLogs(logsRes) if (backupsRes.ok) { const backupsData = await backupsRes.json() setBackups(backupsData.backups || []) } if (eventsRes.ok) { const eventsData = await eventsRes.json() setEvents(eventsData.events || []) } if (notificationsRes.ok) { const notificationsData = await notificationsRes.json() setNotifications(notificationsData.notifications || []) } } catch (err) { console.error("[v0] Error fetching system logs data:", err) setError("Failed to connect to server") } finally { setLoading(false) } } const fetchSystemLogs = async (): Promise => { try { let apiUrl = getApiUrl("/api/logs") if (dateFilter !== "now") { const daysAgo = dateFilter === "custom" ? Number.parseInt(customDays) : Number.parseInt(dateFilter) apiUrl += `?since_days=${daysAgo}` console.log("[v0] Fetching logs with API URL:", apiUrl, "since_days:", daysAgo) } console.log("[v0] Making fetch request to:", apiUrl) const response = await fetch(apiUrl, { method: "GET", headers: { "Content-Type": "application/json", }, cache: "no-store", }) console.log("[v0] Response status:", response.status, "OK:", response.ok) if (!response.ok) { throw new Error(`Flask server responded with status: ${response.status}`) } const data = await response.json() console.log("[v0] Received logs data, type:", typeof data, "is array:", Array.isArray(data)) console.log("[v0] Data length:", Array.isArray(data) ? data.length : data.logs ? data.logs.length : 0) const logsArray = Array.isArray(data) ? data : data.logs || [] console.log("[v0] Returning logs array with length:", logsArray.length) return logsArray } catch (error) { console.error("[v0] Failed to fetch system logs:", error) return [] } } const handleDownloadLogs = async (type = "system") => { try { let hours = 48 if (filteredLogs.length > 0) { const lastLog = filteredLogs[filteredLogs.length - 1] const lastLogTime = new Date(lastLog.timestamp) const now = new Date() const diffMs = now.getTime() - lastLogTime.getTime() const diffHours = Math.floor(diffMs / (1000 * 60 * 60)) // Download 48 hours from the last visible log hours = 48 } let url = getApiUrl(`/api/logs/download?type=${type}&hours=${hours}`) // Apply filters if any are active if (levelFilter !== "all") { url += `&level=${levelFilter}` } if (serviceFilter !== "all") { url += `&service=${serviceFilter}` } if (dateFilter !== "now") { const daysAgo = dateFilter === "custom" ? Number.parseInt(customDays) : Number.parseInt(dateFilter) url += `&since_days=${daysAgo}` } const response = await fetch(url) if (response.ok) { const blob = await response.blob() const downloadUrl = window.URL.createObjectURL(blob) const a = document.createElement("a") a.href = downloadUrl a.download = `proxmox_${type}_${hours}h.log` document.body.appendChild(a) a.click() window.URL.revokeObjectURL(downloadUrl) document.body.removeChild(a) } } catch (err) { console.error("[v0] Error downloading logs:", err) } } const handleDownloadNotificationLog = async (notification: Notification) => { try { const blob = new Blob( [ `Notification Details\n`, `==================\n\n`, `Timestamp: ${notification.timestamp}\n`, `Type: ${notification.type}\n`, `Service: ${notification.service}\n`, `Source: ${notification.source}\n\n`, `Complete Message:\n`, `${notification.message}\n`, ], { type: "text/plain" }, ) const url = window.URL.createObjectURL(blob) const a = document.createElement("a") a.href = url a.download = `notification_${notification.timestamp.replace(/[:\s]/g, "_")}.txt` document.body.appendChild(a) a.click() window.URL.revokeObjectURL(url) document.body.removeChild(a) } catch (err) { console.error("[v0] Error downloading notification:", err) } } // Filter logs const filteredLogs = logs.filter((log) => { const matchesSearch = log.message.toLowerCase().includes(searchTerm.toLowerCase()) || log.service.toLowerCase().includes(searchTerm.toLowerCase()) const matchesLevel = levelFilter === "all" || log.level === levelFilter const matchesService = serviceFilter === "all" || log.service === serviceFilter return matchesSearch && matchesLevel && matchesService }) const getLevelColor = (level: string) => { switch (level) { case "error": case "critical": case "emergency": case "alert": return "bg-red-500/10 text-red-500 border-red-500/20" case "warning": return "bg-yellow-500/10 text-yellow-500 border-yellow-500/20" case "info": case "notice": return "bg-blue-500/10 text-blue-500 border-blue-500/20" case "success": return "bg-green-500/10 text-green-500 border-green-500/20" default: return "bg-gray-500/10 text-gray-500 border-gray-500/20" } } const getLevelIcon = (level: string) => { switch (level) { case "error": case "critical": case "emergency": case "alert": return case "warning": return case "info": case "notice": return case "success": return default: return } } const getNotificationIcon = (type: string) => { switch (type) { case "email": return case "webhook": return case "alert": return case "error": return case "success": return default: return } } const getNotificationTypeColor = (type: string) => { switch (type.toLowerCase()) { case "error": return "bg-red-500/10 text-red-500 border-red-500/20" case "warning": return "bg-yellow-500/10 text-yellow-500 border-yellow-500/20" case "info": return "bg-blue-500/10 text-blue-500 border-blue-500/20" case "success": return "bg-green-500/10 text-green-500 border-green-500/20" default: return "bg-gray-500/10 text-gray-500 border-gray-500/20" } } const logCounts = { total: logs.length, error: logs.filter((log) => ["error", "critical", "emergency", "alert"].includes(log.level)).length, warning: logs.filter((log) => log.level === "warning").length, info: logs.filter((log) => ["info", "notice", "debug"].includes(log.level)).length, } const uniqueServices = [...new Set(logs.map((log) => log.service))] const getBackupType = (volid: string): "vm" | "lxc" => { if (volid.includes("/vm/") || volid.includes("vzdump-qemu")) { return "vm" } return "lxc" } const getBackupTypeColor = (volid: string) => { const type = getBackupType(volid) return type === "vm" ? "bg-cyan-500/10 text-cyan-500 border-cyan-500/20" : "bg-orange-500/10 text-orange-500 border-orange-500/20" } const getBackupTypeLabel = (volid: string) => { const type = getBackupType(volid) return type === "vm" ? "VM" : "LXC" } const getBackupStorageType = (volid: string): "pbs" | "pve" => { // PBS backups have format: storage:backup/type/vmid/timestamp // PVE backups have format: storage:backup/vzdump-type-vmid-timestamp.vma.zst if (volid.includes(":backup/vm/") || volid.includes(":backup/ct/")) { return "pbs" } return "pve" } const getBackupStorageColor = (volid: string) => { const type = getBackupStorageType(volid) return type === "pbs" ? "bg-purple-500/10 text-purple-500 border-purple-500/20" : "bg-blue-500/10 text-blue-500 border-blue-500/20" } const getBackupStorageLabel = (volid: string) => { const type = getBackupStorageType(volid) return type === "pbs" ? "PBS" : "PVE" } const backupStats = { total: backups.length, totalSize: backups.reduce((sum, b) => sum + b.size, 0), qemu: backups.filter((b) => { // Check if volid contains /vm/ for QEMU or vzdump-qemu for PVE return b.volid.includes("/vm/") || b.volid.includes("vzdump-qemu") }).length, lxc: backups.filter((b) => { // Check if volid contains /ct/ for LXC or vzdump-lxc for PVE return b.volid.includes("/ct/") || b.volid.includes("vzdump-lxc") }).length, } const formatBytes = (bytes: number) => { if (bytes === 0) return "0 B" const k = 1024 const sizes = ["B", "KB", "MB", "GB", "TB"] const i = Math.floor(Math.log(bytes) / Math.log(k)) return `${(bytes / Math.pow(k, i)).toFixed(2)} ${sizes[i]}` } const getSectionIcon = (section: string) => { switch (section) { case "logs": return case "events": return case "backups": return case "notifications": return default: return } } const getSectionLabel = (section: string) => { switch (section) { case "logs": return "System Logs" case "events": return "Recent Events" case "backups": return "Backups" case "notifications": return "Notifications" default: return section } } if (loading && logs.length === 0) { return (
) } return (
{loading && logs.length > 0 && (
Loading logs selected...
Please wait while we fetch the logs
)} {/* Statistics Cards */}
Total Logs
{logCounts.total}

Last 200 entries

Errors
{logCounts.error}

Requires attention

Warnings
{logCounts.warning}

Monitor closely

Backups
{backupStats.total}

{formatBytes(backupStats.totalSize)}

{/* Main Content with Tabs */}
System Logs & Events
System Logs Recent Events Backups Notifications
Sections
{/* System Logs Tab */}
setSearchTerm(e.target.value)} className="pl-10 bg-background border-border" />
{dateFilter === "custom" && ( setCustomDays(e.target.value)} className="w-full sm:w-[120px] bg-background border-border" min="1" /> )}
{filteredLogs.map((log, index) => (
{ setSelectedLog(log) setIsLogModalOpen(true) }} >
{getLevelIcon(log.level)} {log.level.toUpperCase()}
{log.service}
{log.timestamp}
{log.message}
Source: {log.source} {log.pid && ` • PID: ${log.pid}`} {log.hostname && ` • Host: ${log.hostname}`}
))} {filteredLogs.length === 0 && (

No logs found matching your criteria

)}
{/* Recent Events Tab */}
{events.map((event, index) => (
{ setSelectedEvent(event) setIsEventModalOpen(true) }} >
{getLevelIcon(event.level)} {event.status}
{event.type} {event.vmid && ` (VM/CT ${event.vmid})`}
{event.duration}
Node: {event.node} • User: {event.user}
{event.starttime}
))} {events.length === 0 && (

No recent events found

)}
{/* Backups Tab */}
{backupStats.qemu}

QEMU Backups

{backupStats.lxc}

LXC Backups

{formatBytes(backupStats.totalSize)}

Total Size

{backups.map((backup, index) => (
{ setSelectedBackup(backup) setIsBackupModalOpen(true) }} >
{getBackupTypeLabel(backup.volid)} {getBackupStorageLabel(backup.volid)}
{backup.size_human}
Storage: {backup.storage}
{backup.created}
))} {backups.length === 0 && (

No backups found

)}
{/* Notifications Tab */}
{notifications.map((notification, index) => (
{ setSelectedNotification(notification) setIsNotificationModalOpen(true) }} >
{getNotificationIcon(notification.type)} {notification.type.toUpperCase()}
{notification.timestamp}
{notification.message}
Service: {notification.service} • Source: {notification.source}
))} {notifications.length === 0 && (

No notifications found

)}
Log Details Complete information about this log entry {selectedLog && (
Level
{getLevelIcon(selectedLog.level)} {selectedLog.level.toUpperCase()}
Service
{selectedLog.service}
Timestamp
{selectedLog.timestamp}
Source
{selectedLog.source}
{selectedLog.pid && (
Process ID
{selectedLog.pid}
)} {selectedLog.hostname && (
Hostname
{selectedLog.hostname}
)}
Message
{selectedLog.message}
)}
Event Details Complete information about this event {selectedEvent && (
Status
{getLevelIcon(selectedEvent.level)} {selectedEvent.status}
Type
{selectedEvent.type}
Node
{selectedEvent.node}
User
{selectedEvent.user}
{selectedEvent.vmid && (
VM/CT ID
{selectedEvent.vmid}
)}
Duration
{selectedEvent.duration}
Start Time
{selectedEvent.starttime}
End Time
{selectedEvent.endtime}
UPID
                    {selectedEvent.upid}
                  
)}
Backup Details Complete information about this backup {selectedBackup && (
Type
{getBackupTypeLabel(selectedBackup.volid)}
Storage Type
{getBackupStorageLabel(selectedBackup.volid)}
Storage
{selectedBackup.storage}
Size
{selectedBackup.size_human}
{selectedBackup.vmid && (
VM/CT ID
{selectedBackup.vmid}
)}
Created
{selectedBackup.created}
Volume ID
                    {selectedBackup.volid}
                  
)}
Notification Details Complete information about this notification {selectedNotification && (
Type
{selectedNotification.type.toUpperCase()}
Timestamp
{selectedNotification.timestamp}
Service
{selectedNotification.service}
Source
{selectedNotification.source}
Message
                    {selectedNotification.message}
                  
)}
) }