|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "bufio" |
| 5 | + "context" |
| 6 | + "database/sql" |
| 7 | + "fmt" |
| 8 | + "net/http" |
| 9 | + "os" |
| 10 | + "runtime" |
| 11 | + "strconv" |
| 12 | + "strings" |
| 13 | + "syscall" |
| 14 | + "time" |
| 15 | +) |
| 16 | + |
| 17 | +type hostResources struct { |
| 18 | + CPUPercent *float64 `json:"cpu_percent"` |
| 19 | + MemoryUsedBytes *uint64 `json:"memory_used_bytes"` |
| 20 | + MemoryTotalBytes *uint64 `json:"memory_total_bytes"` |
| 21 | + DiskUsedBytes *uint64 `json:"disk_used_bytes"` |
| 22 | + DiskTotalBytes *uint64 `json:"disk_total_bytes"` |
| 23 | + UptimeSeconds *uint64 `json:"uptime_seconds"` |
| 24 | +} |
| 25 | + |
| 26 | +func (a *app) systemResources(w http.ResponseWriter, r *http.Request) { |
| 27 | + ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second) |
| 28 | + defer cancel() |
| 29 | + writeJSON(w, hostResourceSnapshot(ctx, a.dataDir)) |
| 30 | +} |
| 31 | + |
| 32 | +func (a *app) systemHealth(w http.ResponseWriter, r *http.Request) { |
| 33 | + ctx, cancel := context.WithTimeout(r.Context(), 3*time.Second) |
| 34 | + defer cancel() |
| 35 | + result := map[string]any{"docker_available": false, "runtime_mode": "unknown", "swarm_active": false, "status": "unknown"} |
| 36 | + if mode, err := a.runtimeMode(ctx); err == nil { |
| 37 | + result["runtime_mode"] = mode |
| 38 | + } |
| 39 | + if a.docker != nil { |
| 40 | + snapshot := a.docker.Snapshot(ctx) |
| 41 | + result["docker_available"] = snapshot.Available |
| 42 | + result["docker_message"] = snapshot.Message |
| 43 | + result["engine_version"] = snapshot.EngineVersion |
| 44 | + result["swarm_active"] = snapshot.Swarm.Active |
| 45 | + if snapshot.Available { |
| 46 | + result["status"] = "healthy" |
| 47 | + } else { |
| 48 | + result["status"] = "critical" |
| 49 | + } |
| 50 | + } |
| 51 | + writeJSON(w, result) |
| 52 | +} |
| 53 | + |
| 54 | +func (a *app) dashboard(w http.ResponseWriter, r *http.Request) { |
| 55 | + ctx, cancel := context.WithTimeout(r.Context(), 4*time.Second) |
| 56 | + defer cancel() |
| 57 | + mode, _ := a.runtimeMode(ctx) |
| 58 | + snapshot := map[string]any{"available": false} |
| 59 | + if a.docker != nil { |
| 60 | + info := a.docker.Snapshot(ctx) |
| 61 | + snapshot = map[string]any{"available": info.Available, "engine_version": info.EngineVersion, "runtime_mode": mode, "swarm_active": info.Swarm.Active, "message": info.Message, "swarm": info.Swarm} |
| 62 | + } |
| 63 | + applications := map[string]int{"total": 0, "running": 0, "degraded": 0, "stopped": 0, "failed": 0, "not_deployed": 0} |
| 64 | + rows, _ := a.db.QueryContext(ctx, `SELECT COALESCE(status,'not_deployed'), count(*) FROM applications GROUP BY COALESCE(status,'not_deployed')`) |
| 65 | + if rows != nil { |
| 66 | + for rows.Next() { |
| 67 | + var status string |
| 68 | + var count int |
| 69 | + _ = rows.Scan(&status, &count) |
| 70 | + applications[status] += count |
| 71 | + applications["total"] += count |
| 72 | + } |
| 73 | + rows.Close() |
| 74 | + } |
| 75 | + deployments := map[string]any{"running": scalarInt(ctx, a.db, `SELECT count(*) FROM deployments WHERE status IN ('queued','preparing','deploying','waiting')`), "failed_last_24h": scalarInt(ctx, a.db, `SELECT count(*) FROM deployments WHERE status='failed' AND created_at >= ?`, time.Now().UTC().Add(-24*time.Hour).Format(time.RFC3339)), "recent": recentDeployments(ctx, a.db)} |
| 76 | + domains := map[string]int{"total": 0, "active": 0, "pending": 0, "errors": 0} |
| 77 | + if rows, err := a.db.QueryContext(ctx, `SELECT status, count(*) FROM application_domains GROUP BY status`); err == nil { |
| 78 | + for rows.Next() { |
| 79 | + var status string |
| 80 | + var count int |
| 81 | + _ = rows.Scan(&status, &count) |
| 82 | + domains["total"] += count |
| 83 | + switch status { |
| 84 | + case "active", "ready": |
| 85 | + domains["active"] += count |
| 86 | + case "error", "failed": |
| 87 | + domains["errors"] += count |
| 88 | + default: |
| 89 | + domains["pending"] += count |
| 90 | + } |
| 91 | + } |
| 92 | + rows.Close() |
| 93 | + } |
| 94 | + backup := map[string]any{"last_status": "", "last_created_at": "", "next_scheduled_at": ""} |
| 95 | + var backupStatus, backupCreated string |
| 96 | + if a.db.QueryRowContext(ctx, `SELECT status,created_at FROM backups ORDER BY created_at DESC LIMIT 1`).Scan(&backupStatus, &backupCreated) == nil { |
| 97 | + backup["last_status"] = backupStatus |
| 98 | + backup["last_created_at"] = backupCreated |
| 99 | + } |
| 100 | + alerts := dashboardAlerts(applications, domains, deployments, snapshot) |
| 101 | + resources := hostResourceSnapshot(ctx, a.dataDir) |
| 102 | + writeJSON(w, map[string]any{"docker": snapshot, "host": resources, "applications": applications, "deployments": deployments, "domains": domains, "backups": backup, "alerts": alerts, "activity": recentActivity(ctx, a.db), "projects": scalarInt(ctx, a.db, `SELECT count(*) FROM projects`), "application_count": applications["total"]}) |
| 103 | +} |
| 104 | + |
| 105 | +func (a *app) runtimeMode(ctx context.Context) (string, error) { |
| 106 | + var mode string |
| 107 | + err := a.db.QueryRowContext(ctx, `SELECT runtime_mode FROM environment_settings WHERE id=1`).Scan(&mode) |
| 108 | + return mode, err |
| 109 | +} |
| 110 | +func scalarInt(ctx context.Context, db *sql.DB, query string, args ...any) int { |
| 111 | + var n int |
| 112 | + _ = db.QueryRowContext(ctx, query, args...).Scan(&n) |
| 113 | + return n |
| 114 | +} |
| 115 | + |
| 116 | +func recentDeployments(ctx context.Context, db *sql.DB) []any { |
| 117 | + items := []any{} |
| 118 | + rows, err := db.QueryContext(ctx, `SELECT d.id,d.application_id,d.status,d.source_revision,d.created_at,COALESCE(a.name,'') FROM deployments d LEFT JOIN applications a ON a.id=d.application_id ORDER BY d.created_at DESC LIMIT 8`) |
| 119 | + if err != nil { |
| 120 | + return items |
| 121 | + } |
| 122 | + defer rows.Close() |
| 123 | + for rows.Next() { |
| 124 | + var id, applicationID, revision int64 |
| 125 | + var status, created, name string |
| 126 | + if rows.Scan(&id, &applicationID, &status, &revision, &created, &name) == nil { |
| 127 | + items = append(items, map[string]any{"id": id, "application_id": applicationID, "application": name, "status": status, "revision": revision, "created_at": created}) |
| 128 | + } |
| 129 | + } |
| 130 | + return items |
| 131 | +} |
| 132 | + |
| 133 | +func recentActivity(ctx context.Context, db *sql.DB) []any { |
| 134 | + items := []any{} |
| 135 | + rows, err := db.QueryContext(ctx, `SELECT action,COALESCE(resource_type,''),created_at FROM audit_logs ORDER BY id DESC LIMIT 5`) |
| 136 | + if err != nil { |
| 137 | + return items |
| 138 | + } |
| 139 | + defer rows.Close() |
| 140 | + for rows.Next() { |
| 141 | + var action, resource, created string |
| 142 | + if rows.Scan(&action, &resource, &created) == nil { |
| 143 | + items = append(items, map[string]string{"action": action, "resource_type": resource, "created_at": created, "description": activityDescription(action)}) |
| 144 | + } |
| 145 | + } |
| 146 | + return items |
| 147 | +} |
| 148 | + |
| 149 | +func dashboardAlerts(applications, domains map[string]int, deployments, docker map[string]any) []map[string]any { |
| 150 | + alerts := []map[string]any{} |
| 151 | + if available, _ := docker["available"].(bool); !available { |
| 152 | + alerts = append(alerts, map[string]any{"severity": "critical", "code": "docker_unavailable", "title": "Docker indisponível", "description": "O daemon Docker não respondeu.", "resource_type": "system", "action_url": "/infrastructure"}) |
| 153 | + } |
| 154 | + if n := applications["degraded"]; n > 0 { |
| 155 | + alerts = append(alerts, map[string]any{"severity": "warning", "code": "application_degraded", "title": "Aplicação degradada", "description": strconv.Itoa(n) + " aplicação(ões) precisam de atenção.", "resource_type": "application", "action_url": "/applications"}) |
| 156 | + } |
| 157 | + if n, _ := deployments["failed_last_24h"].(int); n > 0 { |
| 158 | + alerts = append(alerts, map[string]any{"severity": "warning", "code": "deploy_failed", "title": "Deploy falhou recentemente", "description": strconv.Itoa(n) + " deploy(s) falharam nas últimas 24 horas.", "resource_type": "system", "action_url": "/activity"}) |
| 159 | + } |
| 160 | + if n := domains["errors"]; n > 0 { |
| 161 | + alerts = append(alerts, map[string]any{"severity": "warning", "code": "domain_error", "title": "Domínio com erro", "description": strconv.Itoa(n) + " domínio(s) apresentam erro.", "resource_type": "domain", "action_url": "/applications"}) |
| 162 | + } |
| 163 | + return alerts |
| 164 | +} |
| 165 | + |
| 166 | +func hostResourceSnapshot(ctx context.Context, path string) hostResources { |
| 167 | + result := hostResources{} |
| 168 | + if runtime.GOOS == "linux" { |
| 169 | + if file, err := os.Open("/proc/meminfo"); err == nil { |
| 170 | + defer file.Close() |
| 171 | + scanner := bufio.NewScanner(file) |
| 172 | + var total, available uint64 |
| 173 | + for scanner.Scan() { |
| 174 | + fields := strings.Fields(scanner.Text()) |
| 175 | + if len(fields) >= 2 { |
| 176 | + value, _ := strconv.ParseUint(fields[1], 10, 64) |
| 177 | + switch fields[0] { |
| 178 | + case "MemTotal:": |
| 179 | + total = value * 1024 |
| 180 | + case "MemAvailable:": |
| 181 | + available = value * 1024 |
| 182 | + } |
| 183 | + } |
| 184 | + } |
| 185 | + if total > 0 { |
| 186 | + used := total - available |
| 187 | + result.MemoryTotalBytes = &total |
| 188 | + result.MemoryUsedBytes = &used |
| 189 | + } |
| 190 | + } |
| 191 | + if file, err := os.Open("/proc/uptime"); err == nil { |
| 192 | + defer file.Close() |
| 193 | + var seconds float64 |
| 194 | + _, _ = fmt.Fscan(file, &seconds) |
| 195 | + value := uint64(seconds) |
| 196 | + result.UptimeSeconds = &value |
| 197 | + } |
| 198 | + } |
| 199 | + var stat syscall.Statfs_t |
| 200 | + if err := syscall.Statfs(path, &stat); err == nil { |
| 201 | + total := stat.Blocks * uint64(stat.Bsize) |
| 202 | + free := stat.Bavail * uint64(stat.Bsize) |
| 203 | + used := total - free |
| 204 | + result.DiskTotalBytes = &total |
| 205 | + result.DiskUsedBytes = &used |
| 206 | + } |
| 207 | + return result |
| 208 | +} |
0 commit comments