"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 { Sheet, SheetContent, SheetHeader, SheetTitle, SheetTrigger } from "./ui/sheet" import { Popover, PopoverContent, PopoverTrigger } from "./ui/popover" import { Calendar } from "./ui/calendar" import { FileText, Search, Download, AlertTriangle, Info, CheckCircle, XCircle, Database, Activity, CalendarIcon, RefreshCw, Bell, Mail, Menu, Terminal, CalendarDays, } from "lucide-react" import { useState, useEffect } from "react" import type { DateRange } from "react-day-picker" import { format } from "date-fns" 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 [dateRange, setDateRange] = useState(undefined) const [isDatePickerOpen, setIsDatePickerOpen] = useState(false) 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(() => { if (dateFilter !== "custom") { // Reload logs when non-custom filter changes fetchSystemLogs().then(setLogs) } }, [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") const params = new URLSearchParams() if (dateFilter === "custom" && dateRange?.from && dateRange?.to) { params.append("from_date", format(dateRange.from, "yyyy-MM-dd")) params.append("to_date", format(dateRange.to, "yyyy-MM-dd")) } else if (dateFilter !== "now") { const daysAgo = dateFilter === "custom" ? Number.parseInt(customDays) : Number.parseInt(dateFilter) params.append("since_days", daysAgo.toString()) } if (params.toString()) { apiUrl += `?${params.toString()}` } console.log("[v0] Fetching logs from:", apiUrl) 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 Array.isArray(data) ? data : data.logs || [] } 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 === "custom" && dateRange?.from && dateRange?.to) { const fromDate = format(dateRange.from, "yyyy-MM-dd") const toDate = format(dateRange.to, "yyyy-MM-dd") url += `&from_date=${fromDate}&to_date=${toDate}` } else 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 } } const getMinDate = () => { const twoYearsAgo = new Date() twoYearsAgo.setFullYear(twoYearsAgo.getFullYear() - 2) return twoYearsAgo } const handleApplyDateRange = async () => { if (dateRange?.from && dateRange?.to) { console.log("[v0] Applying date range filter:", dateRange) setIsDatePickerOpen(false) setLoading(true) try { const newLogs = await fetchSystemLogs() setLogs(newLogs) console.log("[v0] Loaded", newLogs.length, "logs for date range") } catch (error) { console.error("[v0] Error loading logs for date range:", error) } finally { setLoading(false) } } } if (loading && logs.length === 0) { return (
) } return (
{/* 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" && (
date > new Date() || date < getMinDate()} />
)}
{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.starttime}
{event.message}
Node: {event.node} • User: {event.user}
))} {events.length === 0 && (

No events found

)}
{/* Backups Tab */}
{backups.map((backup, index) => (
{ setSelectedBackup(backup) setIsBackupModalOpen(true) }} >
{getBackupTypeLabel(backup.volid)}
{backup.storage}
{backup.created}
{backup.volid}
Size: {backup.size_human}
))} {backups.length === 0 && (

No backups found

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

No notifications found

)}
) }