v0.25.0 — Debug page: operator testing & diagnostics dashboard
Debug-mode-only dashboard (/debug) with 8 collapsible sections: system diagnostics, notification testing, backup triggers, storage simulation, hub & connectivity, self-update dry-run, DR/setup wizard, and in-memory log viewer. Migrates debug dump from API router to web server. Adds ring buffer log capture, storage disconnect simulation, event history tracking, and cross-drive/self-update test methods. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,687 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gitea.dooplex.hu/admin/felhom-controller/internal/backup"
|
||||
"gitea.dooplex.hu/admin/felhom-controller/internal/monitor"
|
||||
"gitea.dooplex.hu/admin/felhom-controller/internal/stacks"
|
||||
"gitea.dooplex.hu/admin/felhom-controller/internal/system"
|
||||
)
|
||||
|
||||
// DebugCallbacks holds functions that need main.go wiring (modules not directly on Server).
|
||||
type DebugCallbacks struct {
|
||||
TriggerHubReportPush func() error
|
||||
TriggerHubInfraPush func() error
|
||||
TriggerLocalInfraWrite func() error
|
||||
TriggerSetupMode func() error
|
||||
HubConnectivityTest func() (statusCode int, latencyMs int64, err error)
|
||||
GiteaConnectivityTest func() (statusCode int, latencyMs int64, err error)
|
||||
}
|
||||
|
||||
// debugPageHandler renders the debug dashboard page.
|
||||
func (s *Server) debugPageHandler(w http.ResponseWriter, r *http.Request) {
|
||||
data := s.baseData("debug", "Debug")
|
||||
s.executeTemplate(w, r, "debug", data)
|
||||
}
|
||||
|
||||
// handleDebugAPI dispatches /api/debug/* routes.
|
||||
func (s *Server) handleDebugAPI(w http.ResponseWriter, r *http.Request) {
|
||||
subpath := strings.TrimPrefix(r.URL.Path, "/api/debug/")
|
||||
|
||||
switch {
|
||||
// Section 1: Diagnostic dump
|
||||
case subpath == "dump" && r.Method == http.MethodGet:
|
||||
s.debugDump(w, r)
|
||||
|
||||
// Section 2: Notification & Event testing
|
||||
case subpath == "event/test" && r.Method == http.MethodPost:
|
||||
s.debugTestEvent(w, r)
|
||||
case subpath == "event/history" && r.Method == http.MethodGet:
|
||||
s.debugEventHistory(w, r)
|
||||
|
||||
// Section 3: Backup testing
|
||||
case subpath == "backup/dbdump" && r.Method == http.MethodPost:
|
||||
s.debugTriggerDBDump(w, r)
|
||||
case subpath == "backup/crossdrive" && r.Method == http.MethodPost:
|
||||
s.debugTriggerCrossDrive(w, r)
|
||||
case subpath == "backup/integrity" && r.Method == http.MethodPost:
|
||||
s.debugTriggerIntegrity(w, r)
|
||||
case subpath == "backup/infra" && r.Method == http.MethodPost:
|
||||
s.debugTriggerInfraBackup(w, r)
|
||||
|
||||
// Section 4: Storage simulation
|
||||
case subpath == "storage/simulate-disconnect" && r.Method == http.MethodPost:
|
||||
s.debugSimulateDisconnect(w, r)
|
||||
case subpath == "storage/simulate-reconnect" && r.Method == http.MethodPost:
|
||||
s.debugSimulateReconnect(w, r)
|
||||
case subpath == "storage/watchdog-status" && r.Method == http.MethodGet:
|
||||
s.debugWatchdogStatus(w, r)
|
||||
|
||||
// Section 5: Hub & connectivity
|
||||
case subpath == "hub/push" && r.Method == http.MethodPost:
|
||||
s.debugHubPush(w, r)
|
||||
case subpath == "hub/infra-push" && r.Method == http.MethodPost:
|
||||
s.debugHubInfraPush(w, r)
|
||||
case subpath == "hub/test-connectivity" && r.Method == http.MethodPost:
|
||||
s.debugHubConnectivity(w, r)
|
||||
case subpath == "hub/preferences-sync" && r.Method == http.MethodPost:
|
||||
s.debugPreferencesSync(w, r)
|
||||
case subpath == "gitea/test-connectivity" && r.Method == http.MethodPost:
|
||||
s.debugGiteaConnectivity(w, r)
|
||||
|
||||
// Section 6: Self-update
|
||||
case subpath == "selfupdate/dry-run" && r.Method == http.MethodPost:
|
||||
s.debugSelfUpdateDryRun(w, r)
|
||||
|
||||
// Section 7: DR / Setup
|
||||
case subpath == "dr/trigger-setup" && r.Method == http.MethodPost:
|
||||
s.debugTriggerSetupWizard(w, r)
|
||||
case subpath == "dr/infra-status" && r.Method == http.MethodGet:
|
||||
s.debugInfraBackupStatus(w, r)
|
||||
|
||||
// Section 8: Log viewer
|
||||
case subpath == "logs" && r.Method == http.MethodGet:
|
||||
s.debugLogBuffer(w, r)
|
||||
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}
|
||||
|
||||
// writeDebugJSON writes a standard JSON response for debug endpoints.
|
||||
func writeDebugJSON(w http.ResponseWriter, status int, ok bool, message string, data interface{}) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
resp := map[string]interface{}{
|
||||
"ok": ok,
|
||||
}
|
||||
if message != "" {
|
||||
if ok {
|
||||
resp["message"] = message
|
||||
} else {
|
||||
resp["error"] = message
|
||||
}
|
||||
}
|
||||
if data != nil {
|
||||
resp["data"] = data
|
||||
}
|
||||
json.NewEncoder(w).Encode(resp)
|
||||
}
|
||||
|
||||
// ── Section 1: Diagnostic dump ──────────────────────────────────────
|
||||
|
||||
func (s *Server) debugDump(w http.ResponseWriter, r *http.Request) {
|
||||
dump := make(map[string]interface{})
|
||||
|
||||
// Controller info
|
||||
configHash := ""
|
||||
configPath := s.cfg.Paths.DataDir // approximate; configPath isn't on Server
|
||||
if data, err := os.ReadFile(filepath.Join(filepath.Dir(configPath), "controller.yaml")); err == nil {
|
||||
h := sha256.Sum256(data)
|
||||
configHash = hex.EncodeToString(h[:])
|
||||
}
|
||||
dump["controller"] = map[string]interface{}{
|
||||
"version": s.version,
|
||||
"uptime_seconds": int(time.Since(s.startTime).Seconds()),
|
||||
"config_hash": configHash,
|
||||
"logging_level": s.cfg.Logging.Level,
|
||||
"pid": os.Getpid(),
|
||||
}
|
||||
|
||||
// Storage
|
||||
storagePaths := s.settings.GetStoragePaths()
|
||||
storageEntries := make([]map[string]interface{}, 0, len(storagePaths))
|
||||
for _, sp := range storagePaths {
|
||||
entry := map[string]interface{}{
|
||||
"path": sp.Path,
|
||||
"label": sp.Label,
|
||||
"disconnected": sp.Disconnected,
|
||||
"decommissioned": sp.Decommissioned,
|
||||
}
|
||||
if !sp.Disconnected && !sp.Decommissioned {
|
||||
if di := system.GetDiskUsage(sp.Path); di != nil {
|
||||
entry["total_gb"] = di.TotalGB
|
||||
entry["used_gb"] = di.UsedGB
|
||||
entry["used_percent"] = di.UsedPercent
|
||||
}
|
||||
}
|
||||
storageEntries = append(storageEntries, entry)
|
||||
}
|
||||
dump["storage"] = storageEntries
|
||||
|
||||
// Stacks
|
||||
allStacks := s.stackMgr.GetStacks()
|
||||
deployed := 0
|
||||
running := 0
|
||||
stopped := 0
|
||||
stackList := make([]map[string]interface{}, 0)
|
||||
for _, st := range allStacks {
|
||||
if !st.Deployed {
|
||||
continue
|
||||
}
|
||||
deployed++
|
||||
info := map[string]interface{}{
|
||||
"name": st.Name,
|
||||
"state": string(st.State),
|
||||
}
|
||||
if st.Meta.DisplayName != "" {
|
||||
info["display_name"] = st.Meta.DisplayName
|
||||
}
|
||||
containerNames := make([]string, 0, len(st.Containers))
|
||||
for _, c := range st.Containers {
|
||||
containerNames = append(containerNames, c.Name)
|
||||
switch c.State {
|
||||
case stacks.StateRunning, stacks.StateStarting, stacks.StateUnhealthy:
|
||||
running++
|
||||
default:
|
||||
stopped++
|
||||
}
|
||||
}
|
||||
info["containers"] = containerNames
|
||||
stackList = append(stackList, info)
|
||||
}
|
||||
dump["stacks"] = map[string]interface{}{
|
||||
"deployed": deployed,
|
||||
"running": running,
|
||||
"stopped": stopped,
|
||||
"list": stackList,
|
||||
}
|
||||
|
||||
// Backup
|
||||
if s.backupMgr != nil {
|
||||
backupInfo := map[string]interface{}{
|
||||
"enabled": true,
|
||||
"running": s.backupMgr.IsRunning(),
|
||||
}
|
||||
dbDump, backupSt := s.backupMgr.GetStatus()
|
||||
if dbDump != nil {
|
||||
backupInfo["last_db_dump"] = map[string]interface{}{
|
||||
"time": dbDump.LastRun,
|
||||
"success": dbDump.Success,
|
||||
}
|
||||
}
|
||||
if backupSt != nil {
|
||||
backupInfo["last_backup"] = map[string]interface{}{
|
||||
"time": backupSt.LastRun,
|
||||
"success": backupSt.Success,
|
||||
}
|
||||
if backupSt.RepoStats != nil {
|
||||
backupInfo["repo_size"] = backupSt.RepoStats.TotalSize
|
||||
backupInfo["snapshot_count"] = backupSt.RepoStats.SnapshotCount
|
||||
}
|
||||
}
|
||||
dump["backup"] = backupInfo
|
||||
} else {
|
||||
dump["backup"] = map[string]interface{}{"enabled": false}
|
||||
}
|
||||
|
||||
// Hub
|
||||
hubInfo := map[string]interface{}{
|
||||
"url": s.cfg.Hub.URL,
|
||||
"enabled": s.cfg.Hub.Enabled,
|
||||
}
|
||||
if s.hubPushStatusFn != nil {
|
||||
st := s.hubPushStatusFn()
|
||||
hubInfo["last_attempt"] = st.LastAttempt
|
||||
hubInfo["last_success"] = st.LastSuccess
|
||||
hubInfo["last_error"] = st.LastError
|
||||
hubInfo["consecutive_failures"] = st.Consecutive
|
||||
}
|
||||
dump["hub"] = hubInfo
|
||||
|
||||
// Scheduler
|
||||
if s.scheduler != nil {
|
||||
jobs := s.scheduler.GetJobs()
|
||||
jobList := make([]map[string]interface{}, 0, len(jobs))
|
||||
for _, j := range jobs {
|
||||
entry := map[string]interface{}{
|
||||
"name": j.Name,
|
||||
"running": j.Running,
|
||||
}
|
||||
if j.Interval > 0 {
|
||||
entry["type"] = "every"
|
||||
entry["interval"] = j.Interval.String()
|
||||
} else if j.Schedule != "" {
|
||||
entry["type"] = "daily"
|
||||
entry["schedule"] = j.Schedule
|
||||
}
|
||||
if !j.LastRun.IsZero() {
|
||||
entry["last_run"] = j.LastRun
|
||||
}
|
||||
if j.LastErr != nil {
|
||||
entry["last_error"] = j.LastErr.Error()
|
||||
}
|
||||
jobList = append(jobList, entry)
|
||||
}
|
||||
dump["scheduler"] = jobList
|
||||
}
|
||||
|
||||
// Health
|
||||
healthReport := monitor.RunHealthCheck(s.cfg, s.cpuCollector, storagePaths, s.logger)
|
||||
dump["health"] = map[string]interface{}{
|
||||
"status": healthReport.Status,
|
||||
"issues": healthReport.Issues,
|
||||
"warnings": healthReport.Warnings,
|
||||
}
|
||||
|
||||
// Notifications
|
||||
prefs := s.settings.GetNotificationPrefs()
|
||||
dump["notifications"] = map[string]interface{}{
|
||||
"email": prefs.Email,
|
||||
"enabled_events": prefs.EnabledEvents,
|
||||
"cooldown_hours": prefs.CooldownHours,
|
||||
}
|
||||
|
||||
// Self-update
|
||||
if s.updater != nil {
|
||||
status := s.updater.GetStatus()
|
||||
dump["self_update"] = map[string]interface{}{
|
||||
"enabled": true,
|
||||
"auto": s.cfg.SelfUpdate.AutoUpdate,
|
||||
"last_check": status.LastCheck,
|
||||
}
|
||||
} else {
|
||||
dump["self_update"] = map[string]interface{}{"enabled": false}
|
||||
}
|
||||
|
||||
// Alerts
|
||||
if s.alertManager != nil {
|
||||
dump["alerts"] = s.alertManager.GetAlerts()
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(dump)
|
||||
}
|
||||
|
||||
// ── Section 2: Notification & Event testing ─────────────────────────
|
||||
|
||||
func (s *Server) debugTestEvent(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
EventType string `json:"event_type"`
|
||||
Severity string `json:"severity"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeDebugJSON(w, http.StatusBadRequest, false, "Érvénytelen kérés", nil)
|
||||
return
|
||||
}
|
||||
if req.EventType == "" {
|
||||
req.EventType = "test"
|
||||
}
|
||||
if req.Severity == "" {
|
||||
req.Severity = "info"
|
||||
}
|
||||
|
||||
if s.notifier == nil {
|
||||
writeDebugJSON(w, http.StatusBadRequest, false, "Notifier nincs konfigurálva", nil)
|
||||
return
|
||||
}
|
||||
|
||||
statusCode, err := s.notifier.PushTestEventSync(req.EventType, req.Severity,
|
||||
fmt.Sprintf("Teszt esemény: %s (%s)", req.EventType, req.Severity))
|
||||
if err != nil {
|
||||
writeDebugJSON(w, http.StatusOK, false, err.Error(), map[string]interface{}{
|
||||
"hub_status": statusCode,
|
||||
})
|
||||
return
|
||||
}
|
||||
writeDebugJSON(w, http.StatusOK, true, fmt.Sprintf("Esemény elküldve (HTTP %d)", statusCode),
|
||||
map[string]interface{}{"hub_status": statusCode})
|
||||
}
|
||||
|
||||
func (s *Server) debugEventHistory(w http.ResponseWriter, r *http.Request) {
|
||||
if s.notifier == nil {
|
||||
writeDebugJSON(w, http.StatusOK, true, "", []interface{}{})
|
||||
return
|
||||
}
|
||||
history := s.notifier.GetEventHistory(20)
|
||||
writeDebugJSON(w, http.StatusOK, true, "", history)
|
||||
}
|
||||
|
||||
// ── Section 3: Backup testing ───────────────────────────────────────
|
||||
|
||||
func (s *Server) debugTriggerDBDump(w http.ResponseWriter, r *http.Request) {
|
||||
if s.backupMgr == nil {
|
||||
writeDebugJSON(w, http.StatusBadRequest, false, "Backup manager nincs konfigurálva", nil)
|
||||
return
|
||||
}
|
||||
go func() {
|
||||
if err := s.backupMgr.RunDBDumps(context.Background()); err != nil {
|
||||
s.logger.Printf("[WARN] Debug DB dump failed: %v", err)
|
||||
}
|
||||
}()
|
||||
writeDebugJSON(w, http.StatusOK, true, "DB dump elindítva", nil)
|
||||
}
|
||||
|
||||
func (s *Server) debugTriggerCrossDrive(w http.ResponseWriter, r *http.Request) {
|
||||
if s.crossDriveRunner == nil {
|
||||
writeDebugJSON(w, http.StatusBadRequest, false, "Cross-drive runner nincs konfigurálva", nil)
|
||||
return
|
||||
}
|
||||
go func() {
|
||||
if err := s.crossDriveRunner.RunAllConfigured(context.Background()); err != nil {
|
||||
s.logger.Printf("[WARN] Debug cross-drive failed: %v", err)
|
||||
}
|
||||
}()
|
||||
writeDebugJSON(w, http.StatusOK, true, "Cross-drive mentés elindítva", nil)
|
||||
}
|
||||
|
||||
func (s *Server) debugTriggerIntegrity(w http.ResponseWriter, r *http.Request) {
|
||||
if s.backupMgr == nil {
|
||||
writeDebugJSON(w, http.StatusBadRequest, false, "Backup manager nincs konfigurálva", nil)
|
||||
return
|
||||
}
|
||||
go func() {
|
||||
if err := s.backupMgr.RunIntegrityCheck(context.Background()); err != nil {
|
||||
s.logger.Printf("[WARN] Debug integrity check failed: %v", err)
|
||||
}
|
||||
}()
|
||||
writeDebugJSON(w, http.StatusOK, true, "Integritás ellenőrzés elindítva", nil)
|
||||
}
|
||||
|
||||
func (s *Server) debugTriggerInfraBackup(w http.ResponseWriter, r *http.Request) {
|
||||
if s.debugCallbacks == nil || s.debugCallbacks.TriggerLocalInfraWrite == nil {
|
||||
writeDebugJSON(w, http.StatusNotImplemented, false, "Nem bekötött", nil)
|
||||
return
|
||||
}
|
||||
go func() {
|
||||
if err := s.debugCallbacks.TriggerLocalInfraWrite(); err != nil {
|
||||
s.logger.Printf("[WARN] Debug infra backup failed: %v", err)
|
||||
}
|
||||
}()
|
||||
writeDebugJSON(w, http.StatusOK, true, "Infra mentés elindítva", nil)
|
||||
}
|
||||
|
||||
// ── Section 4: Storage simulation ───────────────────────────────────
|
||||
|
||||
func (s *Server) debugSimulateDisconnect(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
Path string `json:"path"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.Path == "" {
|
||||
writeDebugJSON(w, http.StatusBadRequest, false, "Érvénytelen kérés: path szükséges", nil)
|
||||
return
|
||||
}
|
||||
if s.storageWatchdog == nil {
|
||||
writeDebugJSON(w, http.StatusBadRequest, false, "Storage watchdog nincs konfigurálva", nil)
|
||||
return
|
||||
}
|
||||
stopped, err := s.storageWatchdog.SimulateDisconnect(r.Context(), req.Path)
|
||||
if err != nil {
|
||||
writeDebugJSON(w, http.StatusBadRequest, false, err.Error(), nil)
|
||||
return
|
||||
}
|
||||
writeDebugJSON(w, http.StatusOK, true,
|
||||
fmt.Sprintf("Leválasztás szimulálva: %s (%d app leállítva)", req.Path, len(stopped)),
|
||||
map[string]interface{}{"stopped_stacks": stopped})
|
||||
}
|
||||
|
||||
func (s *Server) debugSimulateReconnect(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
Path string `json:"path"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.Path == "" {
|
||||
writeDebugJSON(w, http.StatusBadRequest, false, "Érvénytelen kérés: path szükséges", nil)
|
||||
return
|
||||
}
|
||||
if s.storageWatchdog == nil {
|
||||
writeDebugJSON(w, http.StatusBadRequest, false, "Storage watchdog nincs konfigurálva", nil)
|
||||
return
|
||||
}
|
||||
if err := s.storageWatchdog.SimulateReconnect(r.Context(), req.Path); err != nil {
|
||||
writeDebugJSON(w, http.StatusBadRequest, false, err.Error(), nil)
|
||||
return
|
||||
}
|
||||
writeDebugJSON(w, http.StatusOK, true,
|
||||
fmt.Sprintf("Visszacsatlakozás szimulálva: %s", req.Path), nil)
|
||||
}
|
||||
|
||||
func (s *Server) debugWatchdogStatus(w http.ResponseWriter, r *http.Request) {
|
||||
if s.storageWatchdog == nil {
|
||||
writeDebugJSON(w, http.StatusOK, true, "", []interface{}{})
|
||||
return
|
||||
}
|
||||
status := s.storageWatchdog.GetDebugStatus()
|
||||
writeDebugJSON(w, http.StatusOK, true, "", status)
|
||||
}
|
||||
|
||||
// ── Section 5: Hub & connectivity ───────────────────────────────────
|
||||
|
||||
func (s *Server) debugHubPush(w http.ResponseWriter, r *http.Request) {
|
||||
if s.debugCallbacks == nil || s.debugCallbacks.TriggerHubReportPush == nil {
|
||||
writeDebugJSON(w, http.StatusNotImplemented, false, "Nem bekötött", nil)
|
||||
return
|
||||
}
|
||||
start := time.Now()
|
||||
err := s.debugCallbacks.TriggerHubReportPush()
|
||||
latency := time.Since(start).Milliseconds()
|
||||
if err != nil {
|
||||
writeDebugJSON(w, http.StatusOK, false, err.Error(), map[string]interface{}{"latency_ms": latency})
|
||||
return
|
||||
}
|
||||
writeDebugJSON(w, http.StatusOK, true, "Hub jelentés elküldve",
|
||||
map[string]interface{}{"latency_ms": latency})
|
||||
}
|
||||
|
||||
func (s *Server) debugHubInfraPush(w http.ResponseWriter, r *http.Request) {
|
||||
if s.debugCallbacks == nil || s.debugCallbacks.TriggerHubInfraPush == nil {
|
||||
writeDebugJSON(w, http.StatusNotImplemented, false, "Nem bekötött", nil)
|
||||
return
|
||||
}
|
||||
start := time.Now()
|
||||
err := s.debugCallbacks.TriggerHubInfraPush()
|
||||
latency := time.Since(start).Milliseconds()
|
||||
if err != nil {
|
||||
writeDebugJSON(w, http.StatusOK, false, err.Error(), map[string]interface{}{"latency_ms": latency})
|
||||
return
|
||||
}
|
||||
writeDebugJSON(w, http.StatusOK, true, "Infra backup elküldve a Hubra",
|
||||
map[string]interface{}{"latency_ms": latency})
|
||||
}
|
||||
|
||||
func (s *Server) debugHubConnectivity(w http.ResponseWriter, r *http.Request) {
|
||||
if s.debugCallbacks == nil || s.debugCallbacks.HubConnectivityTest == nil {
|
||||
writeDebugJSON(w, http.StatusNotImplemented, false, "Nem bekötött", nil)
|
||||
return
|
||||
}
|
||||
statusCode, latency, err := s.debugCallbacks.HubConnectivityTest()
|
||||
data := map[string]interface{}{
|
||||
"status_code": statusCode,
|
||||
"latency_ms": latency,
|
||||
}
|
||||
if err != nil {
|
||||
writeDebugJSON(w, http.StatusOK, false, err.Error(), data)
|
||||
return
|
||||
}
|
||||
writeDebugJSON(w, http.StatusOK, true,
|
||||
fmt.Sprintf("Hub elérhető (HTTP %d, %dms)", statusCode, latency), data)
|
||||
}
|
||||
|
||||
func (s *Server) debugPreferencesSync(w http.ResponseWriter, r *http.Request) {
|
||||
if s.notifier == nil {
|
||||
writeDebugJSON(w, http.StatusBadRequest, false, "Notifier nincs konfigurálva", nil)
|
||||
return
|
||||
}
|
||||
prefs := s.settings.GetNotificationPrefs()
|
||||
if err := s.notifier.SyncPreferences(prefs.Email, prefs.EnabledEvents, prefs.CooldownHours); err != nil {
|
||||
writeDebugJSON(w, http.StatusOK, false, err.Error(), nil)
|
||||
return
|
||||
}
|
||||
writeDebugJSON(w, http.StatusOK, true, "Preferenciák szinkronizálva", nil)
|
||||
}
|
||||
|
||||
func (s *Server) debugGiteaConnectivity(w http.ResponseWriter, r *http.Request) {
|
||||
if s.debugCallbacks == nil || s.debugCallbacks.GiteaConnectivityTest == nil {
|
||||
writeDebugJSON(w, http.StatusNotImplemented, false, "Nem bekötött", nil)
|
||||
return
|
||||
}
|
||||
statusCode, latency, err := s.debugCallbacks.GiteaConnectivityTest()
|
||||
data := map[string]interface{}{
|
||||
"status_code": statusCode,
|
||||
"latency_ms": latency,
|
||||
}
|
||||
if err != nil {
|
||||
writeDebugJSON(w, http.StatusOK, false, err.Error(), data)
|
||||
return
|
||||
}
|
||||
writeDebugJSON(w, http.StatusOK, true,
|
||||
fmt.Sprintf("Gitea elérhető (HTTP %d, %dms)", statusCode, latency), data)
|
||||
}
|
||||
|
||||
// ── Section 6: Self-update ──────────────────────────────────────────
|
||||
|
||||
func (s *Server) debugSelfUpdateDryRun(w http.ResponseWriter, r *http.Request) {
|
||||
if s.updater == nil {
|
||||
writeDebugJSON(w, http.StatusBadRequest, false, "Self-update nincs konfigurálva", nil)
|
||||
return
|
||||
}
|
||||
result := s.updater.DryRun()
|
||||
writeDebugJSON(w, http.StatusOK, true, "", result)
|
||||
}
|
||||
|
||||
// ── Section 7: DR / Setup ───────────────────────────────────────────
|
||||
|
||||
func (s *Server) debugTriggerSetupWizard(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
Confirm string `json:"confirm"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeDebugJSON(w, http.StatusBadRequest, false, "Érvénytelen kérés", nil)
|
||||
return
|
||||
}
|
||||
if req.Confirm != "RESET" {
|
||||
writeDebugJSON(w, http.StatusBadRequest, false, "Érvénytelen megerősítés — írja be: RESET", nil)
|
||||
return
|
||||
}
|
||||
|
||||
// Pre-check: verify infra backup exists on at least one drive
|
||||
if !s.hasInfraBackupOnDrive() {
|
||||
writeDebugJSON(w, http.StatusBadRequest, false,
|
||||
"Nincs infra backup egyetlen meghajtón sem! Először készítsen infra backupot.", nil)
|
||||
return
|
||||
}
|
||||
|
||||
// Write marker file
|
||||
markerPath := filepath.Join(s.cfg.Paths.DataDir, ".needs-setup")
|
||||
if err := os.WriteFile(markerPath, []byte("debug-triggered\n"), 0644); err != nil {
|
||||
writeDebugJSON(w, http.StatusInternalServerError, false,
|
||||
fmt.Sprintf("Marker fájl írási hiba: %v", err), nil)
|
||||
return
|
||||
}
|
||||
|
||||
writeDebugJSON(w, http.StatusOK, true, "Controller újraindítása setup módba...", nil)
|
||||
|
||||
// Exit after response is sent so the container restarts into setup mode
|
||||
go func() {
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
os.Exit(0)
|
||||
}()
|
||||
}
|
||||
|
||||
func (s *Server) debugInfraBackupStatus(w http.ResponseWriter, r *http.Request) {
|
||||
storagePaths := s.settings.GetStoragePaths()
|
||||
drives := make([]map[string]interface{}, 0, len(storagePaths))
|
||||
|
||||
for _, sp := range storagePaths {
|
||||
if sp.Decommissioned || sp.Disconnected {
|
||||
continue
|
||||
}
|
||||
driveInfo := map[string]interface{}{
|
||||
"path": sp.Path,
|
||||
"label": sp.Label,
|
||||
"has_backup": false,
|
||||
}
|
||||
|
||||
infraDir := backup.InfraBackupDir(sp.Path)
|
||||
info, err := os.Stat(infraDir)
|
||||
if err == nil && info.IsDir() {
|
||||
driveInfo["has_backup"] = true
|
||||
driveInfo["last_modified"] = info.ModTime()
|
||||
|
||||
// List files
|
||||
entries, _ := os.ReadDir(infraDir)
|
||||
files := make([]string, 0, len(entries))
|
||||
for _, e := range entries {
|
||||
files = append(files, e.Name())
|
||||
}
|
||||
driveInfo["files"] = files
|
||||
}
|
||||
|
||||
drives = append(drives, driveInfo)
|
||||
}
|
||||
|
||||
data := map[string]interface{}{
|
||||
"drives": drives,
|
||||
}
|
||||
if s.hubPushStatusFn != nil {
|
||||
st := s.hubPushStatusFn()
|
||||
data["hub_infra_push"] = map[string]interface{}{
|
||||
"last_attempt": st.LastAttempt,
|
||||
"last_success": st.LastSuccess,
|
||||
"last_error": st.LastError,
|
||||
}
|
||||
}
|
||||
|
||||
writeDebugJSON(w, http.StatusOK, true, "", data)
|
||||
}
|
||||
|
||||
// hasInfraBackupOnDrive checks if any connected storage drive has an infra backup.
|
||||
func (s *Server) hasInfraBackupOnDrive() bool {
|
||||
for _, sp := range s.settings.GetStoragePaths() {
|
||||
if sp.Decommissioned || sp.Disconnected {
|
||||
continue
|
||||
}
|
||||
infraDir := backup.InfraBackupDir(sp.Path)
|
||||
if info, err := os.Stat(infraDir); err == nil && info.IsDir() {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// ── Section 8: Log viewer ───────────────────────────────────────────
|
||||
|
||||
func (s *Server) debugLogBuffer(w http.ResponseWriter, r *http.Request) {
|
||||
if s.logBuffer == nil {
|
||||
writeDebugJSON(w, http.StatusOK, true, "", map[string]interface{}{
|
||||
"entries": []interface{}{},
|
||||
"total": 0,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
level := r.URL.Query().Get("level")
|
||||
if level == "" {
|
||||
level = "DEBUG"
|
||||
}
|
||||
|
||||
limit := 200
|
||||
if v := r.URL.Query().Get("limit"); v != "" {
|
||||
if n, err := strconv.Atoi(v); err == nil && n > 0 && n <= 1000 {
|
||||
limit = n
|
||||
}
|
||||
}
|
||||
|
||||
var after time.Time
|
||||
if v := r.URL.Query().Get("after"); v != "" {
|
||||
if t, err := time.Parse(time.RFC3339Nano, v); err == nil {
|
||||
after = t
|
||||
}
|
||||
}
|
||||
|
||||
entries, total := s.logBuffer.Entries(level, limit, after)
|
||||
writeDebugJSON(w, http.StatusOK, true, "", map[string]interface{}{
|
||||
"entries": entries,
|
||||
"total": total,
|
||||
})
|
||||
}
|
||||
@@ -97,6 +97,7 @@ func (s *Server) baseData(page, title string) map[string]interface{} {
|
||||
"Domain": s.cfg.Customer.Domain,
|
||||
"Version": s.version,
|
||||
"AuthEnabled": s.authEnabled(),
|
||||
"DebugMode": s.isDebug(),
|
||||
}
|
||||
if s.alertManager != nil {
|
||||
data["Alerts"] = s.alertManager.GetAlerts()
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// LogEntry represents a single parsed log line.
|
||||
type LogEntry struct {
|
||||
Timestamp time.Time `json:"timestamp"`
|
||||
Level string `json:"level"` // "DEBUG", "INFO", "WARN", "ERROR"
|
||||
Message string `json:"message"`
|
||||
Source string `json:"source"` // "file.go:123" if Lshortfile enabled
|
||||
}
|
||||
|
||||
// LogBuffer is a thread-safe ring buffer that captures log output.
|
||||
// It implements io.Writer so it can be used with log.New(io.MultiWriter(...)).
|
||||
type LogBuffer struct {
|
||||
mu sync.RWMutex
|
||||
entries []LogEntry
|
||||
size int
|
||||
pos int
|
||||
full bool
|
||||
}
|
||||
|
||||
// NewLogBuffer creates a ring buffer that keeps the last `size` log entries.
|
||||
func NewLogBuffer(size int) *LogBuffer {
|
||||
return &LogBuffer{
|
||||
entries: make([]LogEntry, size),
|
||||
size: size,
|
||||
}
|
||||
}
|
||||
|
||||
// Write implements io.Writer. It parses Go's standard log output format.
|
||||
// Handles two formats:
|
||||
// - With Lshortfile: "2026/02/21 18:33:35 file.go:123: [LEVEL] message"
|
||||
// - Without: "2026/02/21 18:33:35 [LEVEL] message"
|
||||
func (lb *LogBuffer) Write(p []byte) (n int, err error) {
|
||||
line := strings.TrimRight(string(p), "\n\r")
|
||||
if line == "" {
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
entry := parseLine(line)
|
||||
|
||||
lb.mu.Lock()
|
||||
lb.entries[lb.pos] = entry
|
||||
lb.pos = (lb.pos + 1) % lb.size
|
||||
if lb.pos == 0 && !lb.full {
|
||||
lb.full = true
|
||||
}
|
||||
lb.mu.Unlock()
|
||||
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
// Entries returns log entries filtered by minimum level, limited by count,
|
||||
// and optionally filtered to entries after a given timestamp.
|
||||
// Returns the matching entries and the total count in the buffer.
|
||||
func (lb *LogBuffer) Entries(minLevel string, limit int, after time.Time) ([]LogEntry, int) {
|
||||
lb.mu.RLock()
|
||||
defer lb.mu.RUnlock()
|
||||
|
||||
// Collect all entries in chronological order
|
||||
total := lb.size
|
||||
if !lb.full {
|
||||
total = lb.pos
|
||||
}
|
||||
|
||||
if limit <= 0 || limit > 1000 {
|
||||
limit = 200
|
||||
}
|
||||
|
||||
levelOrder := levelPriority(minLevel)
|
||||
|
||||
var result []LogEntry
|
||||
start := 0
|
||||
if lb.full {
|
||||
start = lb.pos
|
||||
}
|
||||
|
||||
for i := 0; i < total; i++ {
|
||||
idx := (start + i) % lb.size
|
||||
e := lb.entries[idx]
|
||||
|
||||
// Filter by level
|
||||
if levelPriority(e.Level) < levelOrder {
|
||||
continue
|
||||
}
|
||||
// Filter by timestamp
|
||||
if !after.IsZero() && !e.Timestamp.After(after) {
|
||||
continue
|
||||
}
|
||||
result = append(result, e)
|
||||
}
|
||||
|
||||
// Apply limit (keep the most recent entries)
|
||||
if len(result) > limit {
|
||||
result = result[len(result)-limit:]
|
||||
}
|
||||
|
||||
return result, total
|
||||
}
|
||||
|
||||
// parseLine parses a single log line into a LogEntry.
|
||||
func parseLine(line string) LogEntry {
|
||||
entry := LogEntry{
|
||||
Level: "INFO",
|
||||
Message: line,
|
||||
}
|
||||
|
||||
// Try to parse timestamp: "2006/01/02 15:04:05"
|
||||
if len(line) >= 19 {
|
||||
if t, err := time.Parse("2006/01/02 15:04:05", line[:19]); err == nil {
|
||||
entry.Timestamp = t
|
||||
rest := line[19:]
|
||||
if len(rest) > 0 && rest[0] == ' ' {
|
||||
rest = rest[1:]
|
||||
}
|
||||
// Check for source file (Lshortfile): "file.go:123: [LEVEL] ..."
|
||||
if colonIdx := strings.Index(rest, ": "); colonIdx > 0 && colonIdx < 40 {
|
||||
candidate := rest[:colonIdx]
|
||||
// Source file pattern: contains ".go:" or ".go" before the colon
|
||||
if strings.Contains(candidate, ".go:") || strings.HasSuffix(candidate, ".go") {
|
||||
entry.Source = candidate
|
||||
rest = rest[colonIdx+2:]
|
||||
}
|
||||
}
|
||||
// Extract level tag: [DEBUG], [INFO], [WARN], [ERROR], [SYNC], [SCHED], etc.
|
||||
entry.Level, entry.Message = extractLevel(rest)
|
||||
}
|
||||
}
|
||||
|
||||
if entry.Timestamp.IsZero() {
|
||||
entry.Timestamp = time.Now()
|
||||
}
|
||||
|
||||
return entry
|
||||
}
|
||||
|
||||
// extractLevel finds and removes a [LEVEL] tag from the beginning of a string.
|
||||
func extractLevel(s string) (string, string) {
|
||||
s = strings.TrimSpace(s)
|
||||
if len(s) < 3 || s[0] != '[' {
|
||||
return "INFO", s
|
||||
}
|
||||
end := strings.Index(s, "]")
|
||||
if end < 0 || end > 20 {
|
||||
return "INFO", s
|
||||
}
|
||||
tag := s[1:end]
|
||||
msg := strings.TrimSpace(s[end+1:])
|
||||
|
||||
switch tag {
|
||||
case "DEBUG":
|
||||
return "DEBUG", msg
|
||||
case "INFO":
|
||||
return "INFO", msg
|
||||
case "WARN":
|
||||
return "WARN", msg
|
||||
case "ERROR":
|
||||
return "ERROR", msg
|
||||
case "FATAL":
|
||||
return "ERROR", msg
|
||||
default:
|
||||
// Tags like [SYNC], [SCHED], [STORAGE] etc. — treat as INFO, keep tag in message
|
||||
return "INFO", s
|
||||
}
|
||||
}
|
||||
|
||||
// levelPriority returns numeric priority for log levels.
|
||||
func levelPriority(level string) int {
|
||||
switch strings.ToUpper(level) {
|
||||
case "DEBUG":
|
||||
return 0
|
||||
case "INFO":
|
||||
return 1
|
||||
case "WARN":
|
||||
return 2
|
||||
case "ERROR":
|
||||
return 3
|
||||
default:
|
||||
return 0
|
||||
}
|
||||
}
|
||||
@@ -65,6 +65,11 @@ type Server struct {
|
||||
|
||||
// Asset syncer for Hub-managed assets (optional)
|
||||
assetsSyncer *assets.Syncer
|
||||
|
||||
// Debug mode support
|
||||
logBuffer *LogBuffer
|
||||
debugCallbacks *DebugCallbacks
|
||||
startTime time.Time
|
||||
}
|
||||
|
||||
func NewServer(cfg *config.Config, stackMgr *stacks.Manager, cpuCollector *system.CPUCollector, backupMgr *backup.Manager, crossDrive *backup.CrossDriveRunner, sched *scheduler.Scheduler, sett *settings.Settings, alertMgr *AlertManager, notif *notify.Notifier, updater *selfupdate.Updater, logger *log.Logger, version string) *Server {
|
||||
@@ -143,6 +148,36 @@ func (s *Server) SetAssetsSyncer(as *assets.Syncer) {
|
||||
s.assetsSyncer = as
|
||||
}
|
||||
|
||||
// SetLogBuffer sets the in-memory log ring buffer for the debug log viewer.
|
||||
func (s *Server) SetLogBuffer(lb *LogBuffer) {
|
||||
s.logBuffer = lb
|
||||
}
|
||||
|
||||
// SetDebugCallbacks sets the callbacks for debug endpoints that need main.go wiring.
|
||||
func (s *Server) SetDebugCallbacks(dc *DebugCallbacks) {
|
||||
s.debugCallbacks = dc
|
||||
}
|
||||
|
||||
// SetStartTime records the controller start time for uptime calculation.
|
||||
func (s *Server) SetStartTime(t time.Time) {
|
||||
s.startTime = t
|
||||
}
|
||||
|
||||
// isDebug returns true if the controller is running in debug mode.
|
||||
func (s *Server) isDebug() bool {
|
||||
return s.cfg.Logging.Level == "debug"
|
||||
}
|
||||
|
||||
// ServeDebugAPI handles /api/debug/* routes (JSON API for debug operations).
|
||||
// Called from the mux carve-out; debug mode check is done here.
|
||||
func (s *Server) ServeDebugAPI(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.isDebug() {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
s.handleDebugAPI(w, r)
|
||||
}
|
||||
|
||||
// InRestoreMode returns true if the server is in DR restore mode.
|
||||
func (s *Server) InRestoreMode() bool {
|
||||
s.restoreMu.RLock()
|
||||
@@ -239,6 +274,12 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
case strings.HasPrefix(path, "/apps/"):
|
||||
slug := strings.TrimPrefix(path, "/apps/")
|
||||
s.appDetailHandler(w, r, slug)
|
||||
case path == "/debug":
|
||||
if !s.isDebug() {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
s.debugPageHandler(w, r)
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,620 @@
|
||||
{{define "debug"}}
|
||||
{{template "layout_start" .}}
|
||||
|
||||
<div class="page-header">
|
||||
<h2>Debug</h2>
|
||||
</div>
|
||||
|
||||
<div class="debug-banner">
|
||||
⚠ Debug mód aktív — ez az oldal csak fejlesztéshez és hibaelhárításhoz
|
||||
</div>
|
||||
|
||||
<!-- Section 1: System Diagnostic -->
|
||||
<div class="card debug-section" id="section-diagnostic">
|
||||
<div class="card-header debug-section-header" onclick="toggleSection('diagnostic')">
|
||||
<h3>Rendszer diagnosztika</h3>
|
||||
<span class="section-toggle">▶</span>
|
||||
</div>
|
||||
<div class="card-body debug-section-body" style="display:none">
|
||||
<div id="diagnostic-content"><span class="text-muted">Betöltés...</span></div>
|
||||
<div class="debug-actions">
|
||||
<button class="btn btn-secondary btn-sm" id="btn-download-dump" data-label="Nyers JSON letöltése" onclick="downloadDump()">Nyers JSON letöltése</button>
|
||||
<button class="btn btn-secondary btn-sm" id="btn-refresh-diag" data-label="Frissítés" onclick="loadSectionData('diagnostic')">Frissítés</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Section 2: Notification & Event Testing -->
|
||||
<div class="card debug-section" id="section-events">
|
||||
<div class="card-header debug-section-header" onclick="toggleSection('events')">
|
||||
<h3>Értesítés teszt</h3>
|
||||
<span class="section-toggle">▶</span>
|
||||
</div>
|
||||
<div class="card-body debug-section-body" style="display:none">
|
||||
<div class="debug-form-row">
|
||||
<label>Esemény típus:</label>
|
||||
<select id="event-type">
|
||||
<option value="test">test (info)</option>
|
||||
<option value="backup_failed">backup_failed (error)</option>
|
||||
<option value="db_dump_failed">db_dump_failed (error)</option>
|
||||
<option value="backup_integrity_failed">backup_integrity_failed (error)</option>
|
||||
<option value="crossdrive_failed">crossdrive_failed (error)</option>
|
||||
<option value="disk_warning">disk_warning (warning)</option>
|
||||
<option value="disk_critical">disk_critical (error)</option>
|
||||
<option value="storage_disconnected">storage_disconnected (error)</option>
|
||||
<option value="storage_reconnected">storage_reconnected (info)</option>
|
||||
<option value="health_critical">health_critical (error)</option>
|
||||
<option value="health_recovered">health_recovered (info)</option>
|
||||
<option value="update_available">update_available (info)</option>
|
||||
<option value="controller_started">controller_started (info)</option>
|
||||
</select>
|
||||
<label>Súlyosság:</label>
|
||||
<select id="event-severity">
|
||||
<option value="error">error</option>
|
||||
<option value="warning">warning</option>
|
||||
<option value="info">info</option>
|
||||
</select>
|
||||
<button class="btn btn-primary btn-sm" id="btn-test-event" data-label="Teszt esemény küldése" onclick="sendTestEvent()">Teszt esemény küldése</button>
|
||||
<span class="debug-result" id="btn-test-event-result"></span>
|
||||
</div>
|
||||
<h4>Utolsó események</h4>
|
||||
<div id="event-history"><span class="text-muted">Betöltés...</span></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Section 3: Backup Testing -->
|
||||
<div class="card debug-section" id="section-backup">
|
||||
<div class="card-header debug-section-header" onclick="toggleSection('backup')">
|
||||
<h3>Mentés teszt</h3>
|
||||
<span class="section-toggle">▶</span>
|
||||
</div>
|
||||
<div class="card-body debug-section-body" style="display:none">
|
||||
<div id="backup-status"><span class="text-muted">Betöltés...</span></div>
|
||||
<div class="debug-actions">
|
||||
<button class="btn btn-primary btn-sm" id="btn-full-backup" data-label="Teljes mentés" onclick="triggerAction('btn-full-backup','/api/backup/run','POST')">Teljes mentés</button>
|
||||
<span class="debug-result" id="btn-full-backup-result"></span>
|
||||
|
||||
<button class="btn btn-secondary btn-sm" id="btn-dbdump" data-label="Csak DB dump" onclick="triggerAction('btn-dbdump','/api/debug/backup/dbdump','POST')">Csak DB dump</button>
|
||||
<span class="debug-result" id="btn-dbdump-result"></span>
|
||||
|
||||
<button class="btn btn-secondary btn-sm" id="btn-crossdrive" data-label="Csak cross-drive" onclick="triggerAction('btn-crossdrive','/api/debug/backup/crossdrive','POST')">Csak cross-drive</button>
|
||||
<span class="debug-result" id="btn-crossdrive-result"></span>
|
||||
|
||||
<button class="btn btn-secondary btn-sm" id="btn-integrity" data-label="Restic integritás" onclick="triggerAction('btn-integrity','/api/debug/backup/integrity','POST')">Restic integritás</button>
|
||||
<span class="debug-result" id="btn-integrity-result"></span>
|
||||
|
||||
<button class="btn btn-secondary btn-sm" id="btn-infra-backup" data-label="Infra mentés" onclick="triggerAction('btn-infra-backup','/api/debug/backup/infra','POST')">Infra mentés</button>
|
||||
<span class="debug-result" id="btn-infra-backup-result"></span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Section 4: Storage Testing -->
|
||||
<div class="card debug-section" id="section-storage">
|
||||
<div class="card-header debug-section-header" onclick="toggleSection('storage')">
|
||||
<h3>Tárhely teszt</h3>
|
||||
<span class="section-toggle">▶</span>
|
||||
</div>
|
||||
<div class="card-body debug-section-body" style="display:none">
|
||||
<div id="watchdog-status"><span class="text-muted">Betöltés...</span></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Section 5: Hub & Connectivity -->
|
||||
<div class="card debug-section" id="section-hub">
|
||||
<div class="card-header debug-section-header" onclick="toggleSection('hub')">
|
||||
<h3>Hub & Kapcsolatok</h3>
|
||||
<span class="section-toggle">▶</span>
|
||||
</div>
|
||||
<div class="card-body debug-section-body" style="display:none">
|
||||
<div id="hub-status"><span class="text-muted">Betöltés...</span></div>
|
||||
<div class="debug-actions">
|
||||
<button class="btn btn-primary btn-sm" id="btn-hub-push" data-label="Hub jelentés küldése" onclick="triggerAction('btn-hub-push','/api/debug/hub/push','POST')">Hub jelentés küldése</button>
|
||||
<span class="debug-result" id="btn-hub-push-result"></span>
|
||||
|
||||
<button class="btn btn-secondary btn-sm" id="btn-hub-infra" data-label="Infra backup küldése" onclick="triggerAction('btn-hub-infra','/api/debug/hub/infra-push','POST')">Infra backup küldése</button>
|
||||
<span class="debug-result" id="btn-hub-infra-result"></span>
|
||||
|
||||
<button class="btn btn-secondary btn-sm" id="btn-hub-conn" data-label="Hub elérhetőség" onclick="triggerAction('btn-hub-conn','/api/debug/hub/test-connectivity','POST')">Hub elérhetőség</button>
|
||||
<span class="debug-result" id="btn-hub-conn-result"></span>
|
||||
|
||||
<button class="btn btn-secondary btn-sm" id="btn-pref-sync" data-label="Preferencia szinkron" onclick="triggerAction('btn-pref-sync','/api/debug/hub/preferences-sync','POST')">Preferencia szinkron</button>
|
||||
<span class="debug-result" id="btn-pref-sync-result"></span>
|
||||
|
||||
<button class="btn btn-secondary btn-sm" id="btn-gitea-conn" data-label="Gitea elérhetőség" onclick="triggerAction('btn-gitea-conn','/api/debug/gitea/test-connectivity','POST')">Gitea elérhetőség</button>
|
||||
<span class="debug-result" id="btn-gitea-conn-result"></span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Section 6: Self-Update Testing -->
|
||||
<div class="card debug-section" id="section-selfupdate">
|
||||
<div class="card-header debug-section-header" onclick="toggleSection('selfupdate')">
|
||||
<h3>Önfrissítés teszt</h3>
|
||||
<span class="section-toggle">▶</span>
|
||||
</div>
|
||||
<div class="card-body debug-section-body" style="display:none">
|
||||
<div id="selfupdate-status"><span class="text-muted">Betöltés...</span></div>
|
||||
<div class="debug-actions">
|
||||
<button class="btn btn-primary btn-sm" id="btn-check-update" data-label="Frissítés keresése" onclick="triggerAction('btn-check-update','/api/selfupdate/check','POST')">Frissítés keresése</button>
|
||||
<span class="debug-result" id="btn-check-update-result"></span>
|
||||
|
||||
<button class="btn btn-secondary btn-sm" id="btn-dryrun" data-label="Dry-run frissítés" onclick="triggerAction('btn-dryrun','/api/debug/selfupdate/dry-run','POST')">Dry-run frissítés</button>
|
||||
<span class="debug-result" id="btn-dryrun-result"></span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Section 7: DR / Setup Wizard -->
|
||||
<div class="card debug-section" id="section-dr">
|
||||
<div class="card-header debug-section-header" onclick="toggleSection('dr')">
|
||||
<h3>DR / Telepítő varázsló</h3>
|
||||
<span class="section-toggle">▶</span>
|
||||
</div>
|
||||
<div class="card-body debug-section-body" style="display:none">
|
||||
<div id="dr-status"><span class="text-muted">Betöltés...</span></div>
|
||||
<div class="debug-actions" style="margin-top:1rem">
|
||||
<div class="debug-dr-danger">
|
||||
<p style="color:var(--red);font-weight:600">Vészhelyzet szimuláció</p>
|
||||
<p class="text-muted" style="font-size:.85rem;margin-bottom:.5rem">Ez törli az ügyfél azonosítót és újraindítja a controllert setup módba. A konfigurációs fájlok megmaradnak a meghajtókon.</p>
|
||||
<div class="debug-form-row">
|
||||
<label>Írja be "RESET" a megerősítéshez:</label>
|
||||
<input type="text" id="dr-confirm-input" class="form-control debug-confirm-input" placeholder="RESET" autocomplete="off">
|
||||
<button class="btn btn-danger btn-sm" id="btn-dr-trigger" data-label="Újraindítás setup módban" onclick="triggerDR()">Újraindítás setup módban</button>
|
||||
<span class="debug-result" id="btn-dr-trigger-result"></span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Section 8: Log Viewer -->
|
||||
<div class="card debug-section" id="section-logs">
|
||||
<div class="card-header debug-section-header" onclick="toggleSection('logs')">
|
||||
<h3>Naplóviewer</h3>
|
||||
<span class="section-toggle">▶</span>
|
||||
</div>
|
||||
<div class="card-body debug-section-body" style="display:none">
|
||||
<div class="debug-log-controls">
|
||||
<div class="debug-log-filters">
|
||||
<button class="btn btn-xs debug-log-filter active" data-level="DEBUG" onclick="setLogLevel('DEBUG',this)">DEBUG</button>
|
||||
<button class="btn btn-xs debug-log-filter" data-level="INFO" onclick="setLogLevel('INFO',this)">INFO</button>
|
||||
<button class="btn btn-xs debug-log-filter" data-level="WARN" onclick="setLogLevel('WARN',this)">WARN</button>
|
||||
<button class="btn btn-xs debug-log-filter" data-level="ERROR" onclick="setLogLevel('ERROR',this)">ERROR</button>
|
||||
</div>
|
||||
<div>
|
||||
<label style="font-size:.85rem;cursor:pointer">
|
||||
<input type="checkbox" id="log-auto-refresh" checked onchange="toggleLogAutoRefresh()"> Automatikus frissítés
|
||||
</label>
|
||||
<button class="btn btn-xs btn-secondary" onclick="clearLogDisplay()">Törlés</button>
|
||||
<span class="text-muted" id="log-count" style="font-size:.85rem;margin-left:.5rem"></span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="debug-log-viewer" id="log-viewer"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
// ── Section toggle ──
|
||||
var pollingIntervals = {};
|
||||
function toggleSection(id) {
|
||||
var body = document.querySelector('#section-' + id + ' .debug-section-body');
|
||||
var toggle = document.querySelector('#section-' + id + ' .section-toggle');
|
||||
var visible = body.style.display !== 'none';
|
||||
body.style.display = visible ? 'none' : 'block';
|
||||
toggle.textContent = visible ? '▶' : '▼';
|
||||
if (!visible && !body.dataset.loaded) {
|
||||
body.dataset.loaded = 'true';
|
||||
loadSectionData(id);
|
||||
}
|
||||
// Stop polling when section is collapsed
|
||||
if (visible) {
|
||||
stopPolling(id);
|
||||
}
|
||||
}
|
||||
|
||||
function startPolling(id, interval, fn) {
|
||||
stopPolling(id);
|
||||
fn();
|
||||
pollingIntervals[id] = setInterval(fn, interval);
|
||||
}
|
||||
function stopPolling(id) {
|
||||
if (pollingIntervals[id]) {
|
||||
clearInterval(pollingIntervals[id]);
|
||||
delete pollingIntervals[id];
|
||||
}
|
||||
}
|
||||
window.addEventListener('beforeunload', function() {
|
||||
for (var k in pollingIntervals) { clearInterval(pollingIntervals[k]); }
|
||||
});
|
||||
|
||||
// ── Standard action button pattern ──
|
||||
function triggerAction(buttonId, url, method, body) {
|
||||
var btn = document.getElementById(buttonId);
|
||||
var result = document.getElementById(buttonId + '-result');
|
||||
btn.disabled = true;
|
||||
btn.textContent = 'Folyamatban...';
|
||||
result.className = 'debug-result';
|
||||
result.textContent = '';
|
||||
fetch(url, {
|
||||
method: method || 'POST',
|
||||
headers: Object.assign({'Content-Type':'application/json'}, csrfHeaders()),
|
||||
body: body ? JSON.stringify(body) : undefined
|
||||
}).then(function(r) { return r.json(); }).then(function(data) {
|
||||
if (data.ok) {
|
||||
result.className = 'debug-result debug-result-ok';
|
||||
result.textContent = data.message || 'OK';
|
||||
if (data.data && data.data.latency_ms) result.textContent += ' (' + data.data.latency_ms + 'ms)';
|
||||
} else {
|
||||
result.className = 'debug-result debug-result-error';
|
||||
result.textContent = data.error || 'Hiba';
|
||||
}
|
||||
}).catch(function(e) {
|
||||
result.className = 'debug-result debug-result-error';
|
||||
result.textContent = 'Hálózati hiba: ' + e.message;
|
||||
}).finally(function() {
|
||||
btn.disabled = false;
|
||||
btn.textContent = btn.dataset.label;
|
||||
});
|
||||
}
|
||||
|
||||
// ── Section data loaders (stubs — filled in later phases) ──
|
||||
function loadSectionData(id) {
|
||||
switch (id) {
|
||||
case 'diagnostic': loadDiagnostic(); break;
|
||||
case 'events': loadEventHistory(); break;
|
||||
case 'backup': loadBackupStatus(); break;
|
||||
case 'storage': loadWatchdogStatus(); break;
|
||||
case 'hub': loadHubStatus(); break;
|
||||
case 'selfupdate': loadSelfUpdateStatus(); break;
|
||||
case 'dr': loadDRStatus(); break;
|
||||
case 'logs': initLogViewer(); break;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Section 1: Diagnostic ──
|
||||
function loadDiagnostic() {
|
||||
document.getElementById('diagnostic-content').innerHTML = '<span class="text-muted">Betöltés...</span>';
|
||||
fetch('/api/debug/dump', {headers: csrfHeaders()}).then(function(r){return r.json()}).then(function(data) {
|
||||
renderDiagnostic(data);
|
||||
}).catch(function(e) {
|
||||
document.getElementById('diagnostic-content').innerHTML = '<span class="debug-result-error">Hiba: ' + e.message + '</span>';
|
||||
});
|
||||
}
|
||||
function renderDiagnostic(d) {
|
||||
var html = '';
|
||||
// Controller info
|
||||
if (d.controller) {
|
||||
var c = d.controller;
|
||||
var uptime = c.uptime_seconds;
|
||||
var uptimeStr = uptime < 60 ? uptime + 'mp' : uptime < 3600 ? Math.floor(uptime/60) + 'p' : Math.floor(uptime/3600) + 'ó ' + Math.floor((uptime%3600)/60) + 'p';
|
||||
html += '<div class="debug-kv-grid"><dt>Verzió</dt><dd class="mono">' + c.version + '</dd>';
|
||||
html += '<dt>Uptime</dt><dd>' + uptimeStr + '</dd>';
|
||||
html += '<dt>PID</dt><dd>' + c.pid + '</dd>';
|
||||
html += '<dt>Log szint</dt><dd>' + c.logging_level + '</dd>';
|
||||
if (c.config_hash) html += '<dt>Config hash</dt><dd class="mono" style="font-size:.75rem">' + c.config_hash.substring(0,12) + '…</dd>';
|
||||
html += '</div>';
|
||||
}
|
||||
// Storage
|
||||
if (d.storage && d.storage.length > 0) {
|
||||
html += '<h4 style="margin-top:.75rem">Tárhely</h4><table class="info-table debug-table"><tr><th>Útvonal</th><th>Cimke</th><th>Állapot</th><th>Használat</th></tr>';
|
||||
d.storage.forEach(function(s) {
|
||||
var status = s.disconnected ? '<span class="status-dot red"></span> Leválasztva' : s.decommissioned ? '<span class="status-dot gray"></span> Leszerelve' : '<span class="status-dot green"></span> OK';
|
||||
var usage = s.used_percent !== undefined ? s.used_gb.toFixed(1) + ' / ' + s.total_gb.toFixed(1) + ' GB (' + s.used_percent.toFixed(0) + '%)' : '-';
|
||||
html += '<tr><td class="mono">' + s.path + '</td><td>' + (s.label||'-') + '</td><td>' + status + '</td><td>' + usage + '</td></tr>';
|
||||
});
|
||||
html += '</table>';
|
||||
}
|
||||
// Stacks
|
||||
if (d.stacks) {
|
||||
html += '<h4 style="margin-top:.75rem">Stack-ek</h4>';
|
||||
html += '<div class="debug-kv-grid"><dt>Telepítve</dt><dd>' + d.stacks.deployed + '</dd><dt>Futó konténerek</dt><dd>' + d.stacks.running + '</dd><dt>Leállt</dt><dd>' + d.stacks.stopped + '</dd></div>';
|
||||
if (d.stacks.list && d.stacks.list.length > 0) {
|
||||
html += '<table class="info-table debug-table"><tr><th>Név</th><th>Állapot</th><th>Konténerek</th></tr>';
|
||||
d.stacks.list.forEach(function(st) {
|
||||
var stateDot = st.state === 'running' ? '<span class="status-dot green"></span>' : st.state === 'stopped' ? '<span class="status-dot red"></span>' : '<span class="status-dot yellow"></span>';
|
||||
html += '<tr><td>' + (st.display_name || st.name) + '</td><td>' + stateDot + ' ' + st.state + '</td><td class="mono" style="font-size:.75rem">' + (st.containers||[]).join(', ') + '</td></tr>';
|
||||
});
|
||||
html += '</table>';
|
||||
}
|
||||
}
|
||||
// Scheduler
|
||||
if (d.scheduler && d.scheduler.length > 0) {
|
||||
html += '<h4 style="margin-top:.75rem">Ütemező</h4><table class="info-table debug-table"><tr><th>Név</th><th>Típus</th><th>Utolsó futás</th><th>Fut</th></tr>';
|
||||
d.scheduler.forEach(function(j) {
|
||||
var type = j.type === 'daily' ? j.schedule : (j.interval || '-');
|
||||
html += '<tr><td>' + j.name + '</td><td>' + type + '</td><td>' + (j.last_run ? fmtTime(j.last_run) : '-') + '</td><td>' + (j.running ? '🔄' : '-') + '</td></tr>';
|
||||
});
|
||||
html += '</table>';
|
||||
}
|
||||
// Alerts
|
||||
if (d.alerts && d.alerts.length > 0) {
|
||||
html += '<h4 style="margin-top:.75rem">Figyelmeztetések</h4>';
|
||||
d.alerts.forEach(function(a) {
|
||||
var cls = a.level === 'error' ? 'debug-result-error' : a.level === 'warning' ? 'debug-result debug-result-pending' : '';
|
||||
html += '<div class="' + cls + '" style="padding:.3rem .5rem;margin-bottom:.25rem;border-radius:4px;font-size:.85rem">' + a.message + '</div>';
|
||||
});
|
||||
}
|
||||
document.getElementById('diagnostic-content').innerHTML = html;
|
||||
}
|
||||
function downloadDump() {
|
||||
fetch('/api/debug/dump', {headers: csrfHeaders()}).then(function(r){return r.json()}).then(function(data) {
|
||||
var blob = new Blob([JSON.stringify(data, null, 2)], {type:'application/json'});
|
||||
var a = document.createElement('a');
|
||||
a.href = URL.createObjectURL(blob);
|
||||
a.download = 'debug-dump-' + new Date().toISOString().replace(/[:.]/g,'-') + '.json';
|
||||
a.click();
|
||||
});
|
||||
}
|
||||
|
||||
// ── Section 2: Events ──
|
||||
function sendTestEvent() {
|
||||
var eventType = document.getElementById('event-type').value;
|
||||
var severity = document.getElementById('event-severity').value;
|
||||
triggerAction('btn-test-event', '/api/debug/event/test', 'POST', {event_type: eventType, severity: severity});
|
||||
setTimeout(loadEventHistory, 1500);
|
||||
}
|
||||
function loadEventHistory() {
|
||||
fetch('/api/debug/event/history', {headers: csrfHeaders()}).then(function(r){return r.json()}).then(function(data) {
|
||||
if (!data.ok || !data.data || data.data.length === 0) {
|
||||
document.getElementById('event-history').innerHTML = '<span class="text-muted">Nincs esemény</span>';
|
||||
return;
|
||||
}
|
||||
var html = '<table class="info-table debug-table"><tr><th>Idő</th><th>Típus</th><th>Súlyosság</th><th>Hub</th></tr>';
|
||||
data.data.forEach(function(e) {
|
||||
var statusCls = e.hub_status >= 200 && e.hub_status < 300 ? 'debug-result-ok' : 'debug-result-error';
|
||||
html += '<tr><td>' + fmtTime(e.timestamp) + '</td><td>' + e.event_type + '</td><td>' + e.severity + '</td><td class="' + statusCls + '">' + (e.hub_status || e.hub_error || '-') + '</td></tr>';
|
||||
});
|
||||
html += '</table>';
|
||||
document.getElementById('event-history').innerHTML = html;
|
||||
}).catch(function() {
|
||||
document.getElementById('event-history').innerHTML = '<span class="text-muted">Hiba</span>';
|
||||
});
|
||||
}
|
||||
|
||||
// ── Section 3: Backup ──
|
||||
function loadBackupStatus() {
|
||||
fetch('/api/backup/status', {headers: csrfHeaders()}).then(function(r){return r.json()}).then(function(data) {
|
||||
if (!data.ok) { document.getElementById('backup-status').innerHTML = '<span class="text-muted">Nem elérhető</span>'; return; }
|
||||
var d = data.data || {};
|
||||
var html = '<div class="debug-kv-grid">';
|
||||
html += '<span>Állapot:</span><span>' + (d.running ? '🔄 Fut' : '✅ Kész') + '</span>';
|
||||
if (d.last_db_dump) html += '<span>Utolsó DB dump:</span><span>' + fmtTime(d.last_db_dump) + '</span>';
|
||||
if (d.last_backup) html += '<span>Utolsó restic:</span><span>' + fmtTime(d.last_backup) + '</span>';
|
||||
if (d.snapshot_count !== undefined) html += '<span>Snapshotok:</span><span>' + d.snapshot_count + '</span>';
|
||||
html += '</div>';
|
||||
document.getElementById('backup-status').innerHTML = html;
|
||||
}).catch(function() {
|
||||
document.getElementById('backup-status').innerHTML = '<span class="text-muted">Nem elérhető</span>';
|
||||
});
|
||||
}
|
||||
|
||||
// ── Section 4: Storage ──
|
||||
function loadWatchdogStatus() {
|
||||
fetch('/api/debug/storage/watchdog-status', {headers: csrfHeaders()}).then(function(r){return r.json()}).then(function(data) {
|
||||
if (!data.ok) { document.getElementById('watchdog-status').innerHTML = '<span class="text-muted">Nem elérhető</span>'; return; }
|
||||
renderWatchdogStatus(data.data);
|
||||
}).catch(function() {
|
||||
document.getElementById('watchdog-status').innerHTML = '<span class="text-muted">Nem elérhető</span>';
|
||||
});
|
||||
startPolling('storage', 5000, function() {
|
||||
fetch('/api/debug/storage/watchdog-status', {headers: csrfHeaders()}).then(function(r){return r.json()}).then(function(data) {
|
||||
if (data.ok) renderWatchdogStatus(data.data);
|
||||
}).catch(function(){});
|
||||
});
|
||||
}
|
||||
function renderWatchdogStatus(paths) {
|
||||
if (!paths || paths.length === 0) {
|
||||
document.getElementById('watchdog-status').innerHTML = '<span class="text-muted">Nincs tárhely</span>';
|
||||
return;
|
||||
}
|
||||
var html = '<table class="info-table debug-table"><tr><th>Útvonal</th><th>Cimke</th><th>Állapot</th><th>Probe</th><th>Debounce</th><th>Latency</th><th>Művelet</th></tr>';
|
||||
paths.forEach(function(p) {
|
||||
var dot = p.status === 'connected' ? '<span class="status-dot green"></span>' : '<span class="status-dot red"></span>';
|
||||
var simBadge = p.simulated ? ' <span class="badge-warn">SIM</span>' : '';
|
||||
var action = '';
|
||||
if (p.status === 'connected' && !p.simulated) {
|
||||
action = '<button class="btn btn-xs btn-secondary" onclick="simulateDisconnect(\'' + p.path + '\')">Leválasztás</button>';
|
||||
} else if (p.simulated) {
|
||||
action = '<button class="btn btn-xs btn-primary" onclick="simulateReconnect(\'' + p.path + '\')">Visszacsatl.</button>';
|
||||
}
|
||||
html += '<tr><td class="mono">' + p.path + '</td><td>' + (p.label||'-') + '</td><td>' + dot + ' ' + p.status + simBadge + '</td>';
|
||||
html += '<td>' + (p.probe_ok_count||0) + '/' + (p.probe_count||0) + '</td><td>' + (p.debounce_count||0) + '/' + (p.debounce_max||3) + '</td>';
|
||||
html += '<td>' + (p.avg_latency_ms ? p.avg_latency_ms.toFixed(1) + 'ms' : '-') + '</td><td>' + action + '</td></tr>';
|
||||
});
|
||||
html += '</table>';
|
||||
document.getElementById('watchdog-status').innerHTML = html;
|
||||
}
|
||||
function simulateDisconnect(path) {
|
||||
if (!confirm('Biztosan szimulálja a leválasztást?\n\nEz leállítja az érintett alkalmazásokat.')) return;
|
||||
fetch('/api/debug/storage/simulate-disconnect', {
|
||||
method: 'POST',
|
||||
headers: Object.assign({'Content-Type':'application/json'}, csrfHeaders()),
|
||||
body: JSON.stringify({path: path})
|
||||
}).then(function(r){return r.json()}).then(function(data) {
|
||||
if (!data.ok) alert('Hiba: ' + (data.error || 'ismeretlen'));
|
||||
loadWatchdogStatus();
|
||||
}).catch(function(e) { alert('Hiba: ' + e.message); });
|
||||
}
|
||||
function simulateReconnect(path) {
|
||||
fetch('/api/debug/storage/simulate-reconnect', {
|
||||
method: 'POST',
|
||||
headers: Object.assign({'Content-Type':'application/json'}, csrfHeaders()),
|
||||
body: JSON.stringify({path: path})
|
||||
}).then(function(r){return r.json()}).then(function(data) {
|
||||
if (!data.ok) alert('Hiba: ' + (data.error || 'ismeretlen'));
|
||||
loadWatchdogStatus();
|
||||
}).catch(function(e) { alert('Hiba: ' + e.message); });
|
||||
}
|
||||
|
||||
// ── Section 5: Hub ──
|
||||
function loadHubStatus() {
|
||||
fetch('/api/debug/dump', {headers: csrfHeaders()}).then(function(r){return r.json()}).then(function(data) {
|
||||
var h = data.hub || {};
|
||||
var html = '<div class="debug-kv-grid">';
|
||||
html += '<span>URL:</span><span class="mono">' + (h.url||'-') + '</span>';
|
||||
html += '<span>Utolsó push:</span><span>' + (h.last_success ? fmtTime(h.last_success) : '-') + '</span>';
|
||||
html += '<span>Hibák egymás után:</span><span>' + (h.consecutive_failures||0) + '</span>';
|
||||
if (h.last_error) html += '<span>Utolsó hiba:</span><span class="debug-result-error">' + h.last_error + '</span>';
|
||||
html += '</div>';
|
||||
document.getElementById('hub-status').innerHTML = html;
|
||||
}).catch(function() {
|
||||
document.getElementById('hub-status').innerHTML = '<span class="text-muted">Nem elérhető</span>';
|
||||
});
|
||||
}
|
||||
|
||||
// ── Section 6: Self-update ──
|
||||
function loadSelfUpdateStatus() {
|
||||
fetch('/api/debug/dump', {headers: csrfHeaders()}).then(function(r){return r.json()}).then(function(data) {
|
||||
var u = data.self_update || {};
|
||||
var html = '<div class="debug-kv-grid">';
|
||||
html += '<span>Engedélyezve:</span><span>' + (u.enabled ? 'Igen' : 'Nem') + '</span>';
|
||||
html += '<span>Automatikus:</span><span>' + (u.auto ? 'Igen' : 'Nem') + '</span>';
|
||||
if (u.last_check) {
|
||||
html += '<span>Jelenlegi:</span><span class="mono">' + u.last_check.current_version + '</span>';
|
||||
html += '<span>Legújabb:</span><span class="mono">' + u.last_check.latest_version + '</span>';
|
||||
html += '<span>Frissítés:</span><span>' + (u.last_check.update_available ? '<span class="state-text-green">Elérhető</span>' : 'Naprakész') + '</span>';
|
||||
}
|
||||
html += '</div>';
|
||||
document.getElementById('selfupdate-status').innerHTML = html;
|
||||
}).catch(function() {
|
||||
document.getElementById('selfupdate-status').innerHTML = '<span class="text-muted">Nem elérhető</span>';
|
||||
});
|
||||
}
|
||||
|
||||
// ── Section 7: DR ──
|
||||
function loadDRStatus() {
|
||||
fetch('/api/debug/dr/infra-status', {headers: csrfHeaders()}).then(function(r){return r.json()}).then(function(data) {
|
||||
if (!data.ok) { document.getElementById('dr-status').innerHTML = '<span class="text-muted">Nem elérhető</span>'; return; }
|
||||
var d = data.data || {};
|
||||
var html = '<h4>Helyi infra backup</h4>';
|
||||
if (d.drives && d.drives.length > 0) {
|
||||
html += '<table class="info-table debug-table"><tr><th>Meghajtó</th><th>Cimke</th><th>Állapot</th><th>Utolsó módosítás</th><th>Fájlok</th></tr>';
|
||||
d.drives.forEach(function(dr) {
|
||||
var files = (dr.files || []).join(', ') || '-';
|
||||
html += '<tr><td class="mono">' + dr.path + '</td><td>' + (dr.label||'-') + '</td><td>' + (dr.has_backup ? '✅ Van' : '❌ Nincs') + '</td><td>' + (dr.last_modified ? fmtTime(dr.last_modified) : '-') + '</td><td class="text-muted" style="font-size:.75rem">' + files + '</td></tr>';
|
||||
});
|
||||
html += '</table>';
|
||||
} else {
|
||||
html += '<span class="text-muted">Nincs csatlakoztatott meghajtó</span>';
|
||||
}
|
||||
if (d.hub_infra_push) {
|
||||
html += '<h4>Hub infra backup</h4><div class="debug-kv-grid">';
|
||||
html += '<span>Utolsó push:</span><span>' + (d.hub_infra_push.last_success ? fmtTime(d.hub_infra_push.last_success) : '-') + '</span>';
|
||||
if (d.hub_infra_push.last_error) html += '<span>Utolsó hiba:</span><span class="debug-result-error">' + d.hub_infra_push.last_error + '</span>';
|
||||
html += '</div>';
|
||||
}
|
||||
document.getElementById('dr-status').innerHTML = html;
|
||||
}).catch(function() {
|
||||
document.getElementById('dr-status').innerHTML = '<span class="text-muted">Nem elérhető</span>';
|
||||
});
|
||||
}
|
||||
function triggerDR() {
|
||||
var input = document.getElementById('dr-confirm-input');
|
||||
if (input.value !== 'RESET') {
|
||||
var result = document.getElementById('btn-dr-trigger-result');
|
||||
result.className = 'debug-result debug-result-error';
|
||||
result.textContent = 'Írja be: RESET';
|
||||
return;
|
||||
}
|
||||
if (!confirm('FIGYELEM! Ez újraindítja a controllert setup módba.\n\nBiztosan folytatja?')) return;
|
||||
var btn = document.getElementById('btn-dr-trigger');
|
||||
var result = document.getElementById('btn-dr-trigger-result');
|
||||
btn.disabled = true;
|
||||
btn.textContent = 'Folyamatban...';
|
||||
fetch('/api/debug/dr/trigger-setup', {
|
||||
method: 'POST',
|
||||
headers: Object.assign({'Content-Type':'application/json'}, csrfHeaders()),
|
||||
body: JSON.stringify({confirm: 'RESET'})
|
||||
}).then(function(r){return r.json()}).then(function(data) {
|
||||
if (data.ok) {
|
||||
result.className = 'debug-result debug-result-ok';
|
||||
result.textContent = 'Controller újraindulása...';
|
||||
} else {
|
||||
result.className = 'debug-result debug-result-error';
|
||||
result.textContent = data.error || 'Hiba';
|
||||
btn.disabled = false;
|
||||
btn.textContent = btn.dataset.label;
|
||||
}
|
||||
}).catch(function(e) {
|
||||
result.className = 'debug-result debug-result-error';
|
||||
result.textContent = 'Hiba: ' + e.message;
|
||||
btn.disabled = false;
|
||||
btn.textContent = btn.dataset.label;
|
||||
});
|
||||
}
|
||||
|
||||
// ── Section 8: Log viewer ──
|
||||
var currentLogLevel = 'DEBUG';
|
||||
var lastLogTimestamp = '';
|
||||
function setLogLevel(level, btn) {
|
||||
currentLogLevel = level;
|
||||
document.querySelectorAll('.debug-log-filter').forEach(function(b) { b.classList.remove('active'); });
|
||||
btn.classList.add('active');
|
||||
refreshLogs();
|
||||
}
|
||||
function initLogViewer() {
|
||||
refreshLogs();
|
||||
if (document.getElementById('log-auto-refresh').checked) {
|
||||
startPolling('logs', 2000, function() { refreshLogs(true); });
|
||||
}
|
||||
}
|
||||
function toggleLogAutoRefresh() {
|
||||
if (document.getElementById('log-auto-refresh').checked) {
|
||||
startPolling('logs', 2000, function() { refreshLogs(true); });
|
||||
} else {
|
||||
stopPolling('logs');
|
||||
}
|
||||
}
|
||||
function refreshLogs(append) {
|
||||
var url = '/api/debug/logs?level=' + currentLogLevel + '&limit=500';
|
||||
if (append && lastLogTimestamp) url += '&after=' + encodeURIComponent(lastLogTimestamp);
|
||||
fetch(url, {headers: csrfHeaders()}).then(function(r){return r.json()}).then(function(data) {
|
||||
if (!data.ok) return;
|
||||
var entries = (data.data && data.data.entries) || [];
|
||||
var total = (data.data && data.data.total) || 0;
|
||||
var viewer = document.getElementById('log-viewer');
|
||||
if (!append) viewer.innerHTML = '';
|
||||
entries.forEach(function(e) {
|
||||
var cls = 'debug-log-entry debug-log-' + e.level.toLowerCase();
|
||||
var ts = e.timestamp ? fmtTime(e.timestamp) : '';
|
||||
var src = e.source ? ' <span class="text-muted">' + e.source + '</span>' : '';
|
||||
var div = document.createElement('div');
|
||||
div.className = cls;
|
||||
div.innerHTML = '<span class="text-muted">' + ts + '</span> <span class="debug-log-level">[' + e.level + ']</span>' + src + ' ' + escapeHtml(e.message);
|
||||
viewer.appendChild(div);
|
||||
if (e.timestamp) lastLogTimestamp = e.timestamp;
|
||||
});
|
||||
if (!append || entries.length > 0) {
|
||||
viewer.scrollTop = viewer.scrollHeight;
|
||||
}
|
||||
document.getElementById('log-count').textContent = viewer.children.length + ' / ' + total + ' bejegyzés';
|
||||
}).catch(function(){});
|
||||
}
|
||||
function clearLogDisplay() {
|
||||
document.getElementById('log-viewer').innerHTML = '';
|
||||
document.getElementById('log-count').textContent = '';
|
||||
lastLogTimestamp = '';
|
||||
}
|
||||
|
||||
// ── Helpers ──
|
||||
function fmtTime(ts) {
|
||||
if (!ts) return '-';
|
||||
var d = new Date(ts);
|
||||
if (isNaN(d.getTime())) return ts;
|
||||
var now = new Date();
|
||||
var diff = Math.floor((now - d) / 1000);
|
||||
if (diff < 60) return diff + 'mp';
|
||||
if (diff < 3600) return Math.floor(diff/60) + 'p';
|
||||
if (diff < 86400) return Math.floor(diff/3600) + 'ó ' + Math.floor((diff%3600)/60) + 'p';
|
||||
return d.toLocaleString('hu-HU');
|
||||
}
|
||||
function escapeHtml(s) {
|
||||
var d = document.createElement('div');
|
||||
d.textContent = s;
|
||||
return d.innerHTML;
|
||||
}
|
||||
</script>
|
||||
|
||||
{{template "layout_end" .}}
|
||||
{{end}}
|
||||
@@ -20,6 +20,7 @@
|
||||
<li><a href="/stacks" class="{{if eq .Page "stacks"}}active{{end}}">Alkalmazások</a></li>
|
||||
<li><a href="/backups" class="{{if eq .Page "backups"}}active{{end}}">Biztonsági mentés</a></li>
|
||||
<li><a href="/monitoring" class="{{if eq .Page "monitoring"}}active{{end}}">Rendszermonitor</a></li>
|
||||
{{if .DebugMode}}<li><a href="/debug" class="{{if eq .Page "debug"}}active{{end}}">🔧 Debug</a></li>{{end}}
|
||||
</ul>
|
||||
<div class="sidebar-bottom">
|
||||
<a href="/settings" class="sidebar-settings-link {{if eq .Page "settings"}}active{{end}}">⚙ Beállítások</a>
|
||||
|
||||
@@ -2787,3 +2787,199 @@ a.stat-card:hover {
|
||||
margin-left: .15rem;
|
||||
cursor: help;
|
||||
}
|
||||
|
||||
/* ── Debug page ────────────────────────────────────────── */
|
||||
.debug-banner {
|
||||
background: rgba(255, 152, 0, 0.12);
|
||||
border: 1px solid rgba(255, 152, 0, 0.35);
|
||||
border-radius: var(--radius);
|
||||
padding: 0.75rem 1rem;
|
||||
margin-bottom: 1.5rem;
|
||||
color: var(--yellow);
|
||||
font-size: 0.85rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
.debug-banner strong { color: var(--orange); }
|
||||
|
||||
.debug-section {
|
||||
background: var(--bg-card);
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: var(--radius);
|
||||
margin-bottom: 0.75rem;
|
||||
overflow: hidden;
|
||||
}
|
||||
.debug-section-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 0.75rem 1rem;
|
||||
cursor: pointer;
|
||||
user-select: none;
|
||||
transition: background .15s;
|
||||
}
|
||||
.debug-section-header:hover { background: rgba(255,255,255,0.03); }
|
||||
.debug-section-header h3 {
|
||||
font-size: 0.95rem;
|
||||
font-weight: 600;
|
||||
color: var(--text-primary);
|
||||
margin: 0;
|
||||
}
|
||||
.debug-section-toggle {
|
||||
color: var(--text-muted);
|
||||
font-size: 0.8rem;
|
||||
transition: transform .2s;
|
||||
}
|
||||
.debug-section.open .debug-section-toggle { transform: rotate(180deg); }
|
||||
.debug-section-body {
|
||||
display: none;
|
||||
padding: 0 1rem 1rem;
|
||||
border-top: 1px solid var(--border-color);
|
||||
}
|
||||
.debug-section.open .debug-section-body { display: block; }
|
||||
|
||||
.debug-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.5rem;
|
||||
margin-bottom: 0.75rem;
|
||||
}
|
||||
.debug-actions .btn { font-size: 0.8rem; padding: 0.35rem 0.75rem; }
|
||||
|
||||
.debug-result {
|
||||
font-size: 0.8rem;
|
||||
padding: 0.5rem 0.75rem;
|
||||
border-radius: 6px;
|
||||
margin-top: 0.5rem;
|
||||
font-family: 'JetBrains Mono', monospace;
|
||||
}
|
||||
.debug-result-ok {
|
||||
color: var(--green);
|
||||
background: var(--green-bg);
|
||||
border: 1px solid rgba(35, 134, 54, 0.3);
|
||||
}
|
||||
.debug-result-error {
|
||||
color: var(--red);
|
||||
background: var(--red-bg);
|
||||
border: 1px solid rgba(218, 54, 51, 0.3);
|
||||
}
|
||||
.debug-result-pending {
|
||||
color: var(--yellow);
|
||||
background: var(--yellow-bg);
|
||||
border: 1px solid rgba(210, 153, 34, 0.3);
|
||||
}
|
||||
|
||||
.debug-kv-grid {
|
||||
display: grid;
|
||||
grid-template-columns: auto 1fr;
|
||||
gap: 0.25rem 1rem;
|
||||
font-size: 0.85rem;
|
||||
margin-bottom: 0.75rem;
|
||||
}
|
||||
.debug-kv-grid dt { color: var(--text-muted); font-weight: 500; white-space: nowrap; }
|
||||
.debug-kv-grid dd { color: var(--text-primary); margin: 0; }
|
||||
|
||||
.debug-table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
font-size: 0.8rem;
|
||||
margin-bottom: 0.75rem;
|
||||
}
|
||||
.debug-table th {
|
||||
text-align: left;
|
||||
color: var(--text-muted);
|
||||
font-weight: 600;
|
||||
font-size: 0.75rem;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.5px;
|
||||
padding: 0.35rem 0.5rem;
|
||||
border-bottom: 1px solid var(--border-color);
|
||||
}
|
||||
.debug-table td {
|
||||
padding: 0.35rem 0.5rem;
|
||||
color: var(--text-primary);
|
||||
border-bottom: 1px solid rgba(48, 54, 61, 0.4);
|
||||
}
|
||||
.debug-table tr:last-child td { border-bottom: none; }
|
||||
|
||||
.debug-log-viewer {
|
||||
background: var(--bg-primary);
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: 6px;
|
||||
padding: 0.5rem;
|
||||
max-height: 400px;
|
||||
overflow-y: auto;
|
||||
font-family: 'JetBrains Mono', monospace;
|
||||
font-size: 0.75rem;
|
||||
line-height: 1.5;
|
||||
}
|
||||
.debug-log-entry { white-space: pre-wrap; word-break: break-all; }
|
||||
.debug-log-debug { color: var(--text-muted); }
|
||||
.debug-log-info { color: var(--text-primary); }
|
||||
.debug-log-warn { color: var(--yellow); }
|
||||
.debug-log-error { color: var(--red); }
|
||||
|
||||
.debug-log-controls {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
margin-bottom: 0.5rem;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.debug-log-controls .btn {
|
||||
font-size: 0.75rem;
|
||||
padding: 0.25rem 0.5rem;
|
||||
}
|
||||
.debug-log-controls .btn.active {
|
||||
background: var(--accent-blue);
|
||||
color: #fff;
|
||||
}
|
||||
.debug-log-count {
|
||||
font-size: 0.75rem;
|
||||
color: var(--text-muted);
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
.debug-confirm-input {
|
||||
background: var(--bg-primary);
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: 6px;
|
||||
padding: 0.4rem 0.75rem;
|
||||
color: var(--text-primary);
|
||||
font-family: 'JetBrains Mono', monospace;
|
||||
font-size: 0.85rem;
|
||||
width: 120px;
|
||||
}
|
||||
.debug-confirm-input:focus {
|
||||
outline: none;
|
||||
border-color: var(--red);
|
||||
box-shadow: 0 0 0 2px rgba(218, 54, 51, 0.2);
|
||||
}
|
||||
|
||||
.btn-danger {
|
||||
background: var(--red);
|
||||
color: #fff;
|
||||
border: none;
|
||||
border-radius: 6px;
|
||||
padding: 0.4rem 0.85rem;
|
||||
cursor: pointer;
|
||||
font-size: 0.85rem;
|
||||
font-weight: 600;
|
||||
transition: background .15s, opacity .15s;
|
||||
}
|
||||
.btn-danger:hover { background: #e5534b; }
|
||||
.btn-danger:disabled { opacity: 0.5; cursor: not-allowed; }
|
||||
|
||||
.debug-spinner {
|
||||
display: inline-block;
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
border: 2px solid var(--text-muted);
|
||||
border-top-color: var(--accent-blue);
|
||||
border-radius: 50%;
|
||||
animation: debug-spin 0.6s linear infinite;
|
||||
vertical-align: middle;
|
||||
margin-right: 0.3rem;
|
||||
}
|
||||
@keyframes debug-spin { to { transform: rotate(360deg); } }
|
||||
|
||||
Reference in New Issue
Block a user