Files
2026-10-30 16:35:46 +02:00

388 lines
10 KiB
Go

package api
import (
"database/sql"
"encoding/json"
"fmt"
"log"
"net/http"
"strconv"
"strings"
"time"
"github.com/mahmoud/db-monitor/storage"
_ "github.com/lib/pq"
)
// SettingsHandler manages settings API endpoints
type SettingsHandler struct {
store *storage.Store
onDBAdded func(id int64, name, dsn string) error
onDBRemoved func(id int64, name string) error
}
// NewSettingsHandler creates a new settings handler
func NewSettingsHandler(store *storage.Store) *SettingsHandler {
return &SettingsHandler{store: store}
}
// SetDBCallbacks sets callbacks for when databases are added/removed
func (h *SettingsHandler) SetDBCallbacks(onAdd func(int64, string, string) error, onRemove func(int64, string) error) {
h.onDBAdded = onAdd
h.onDBRemoved = onRemove
}
// RegisterRoutes sets up settings API routes
func (h *SettingsHandler) RegisterRoutes(mux *http.ServeMux) {
mux.HandleFunc("/api/settings/databases", h.handleDatabases)
mux.HandleFunc("/api/settings/databases/", h.handleDatabaseByID)
mux.HandleFunc("/api/settings/databases/test", h.handleTestConnection)
mux.HandleFunc("/api/settings/alerts", h.handleAlerts)
mux.HandleFunc("/api/settings/alerts/", h.handleAlertByID)
mux.HandleFunc("/api/settings/notifications", h.handleNotifications)
mux.HandleFunc("/api/settings/notifications/test", h.handleTestNotification)
}
// ---- Databases ----
func (h *SettingsHandler) handleDatabases(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
dbs, err := h.store.ListTrackedDatabases()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if dbs == nil {
dbs = []storage.TrackedDatabase{}
}
writeSettingsJSON(w, dbs)
case http.MethodPost:
var req struct {
Name string `json:"name"`
DSN string `json:"dsn"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "Invalid JSON", http.StatusBadRequest)
return
}
if req.DSN == "" {
http.Error(w, "DSN is required", http.StatusBadRequest)
return
}
// Auto-detect name from DSN if not provided
if req.Name == "" {
req.Name = extractDBNameFromDSN(req.DSN)
}
id, err := h.store.AddTrackedDatabase(req.Name, req.DSN)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Notify main to add collector
if h.onDBAdded != nil {
if err := h.onDBAdded(id, req.Name, req.DSN); err != nil {
log.Printf("⚠️ Failed to start collector for %s: %v", req.Name, err)
}
}
writeSettingsJSON(w, map[string]interface{}{
"id": id,
"name": req.Name,
"dsn": req.DSN,
})
default:
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
}
}
func (h *SettingsHandler) handleDatabaseByID(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodDelete {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
// Extract ID from path: /api/settings/databases/123
path := strings.TrimPrefix(r.URL.Path, "/api/settings/databases/")
id, err := strconv.ParseInt(path, 10, 64)
if err != nil {
http.Error(w, "Invalid ID", http.StatusBadRequest)
return
}
// Get the database info before deleting
db, err := h.store.GetTrackedDatabase(id)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if db == nil {
http.Error(w, "Database not found", http.StatusNotFound)
return
}
if err := h.store.RemoveTrackedDatabase(id); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Notify main to remove collector
if h.onDBRemoved != nil {
if err := h.onDBRemoved(id, db.Name); err != nil {
log.Printf("⚠️ Failed to remove collector for %s: %v", db.Name, err)
}
}
writeSettingsJSON(w, map[string]string{"status": "deleted"})
}
func (h *SettingsHandler) handleTestConnection(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
var req struct {
DSN string `json:"dsn"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "Invalid JSON", http.StatusBadRequest)
return
}
// Try to connect
db, err := sql.Open("postgres", req.DSN)
if err != nil {
writeSettingsJSON(w, map[string]interface{}{
"success": false,
"error": err.Error(),
})
return
}
defer db.Close()
db.SetConnMaxLifetime(5 * time.Second)
start := time.Now()
err = db.Ping()
latency := time.Since(start).Milliseconds()
if err != nil {
writeSettingsJSON(w, map[string]interface{}{
"success": false,
"error": err.Error(),
})
return
}
var version string
db.QueryRow("SELECT version()").Scan(&version)
writeSettingsJSON(w, map[string]interface{}{
"success": true,
"latency_ms": latency,
"version": version,
"name": extractDBNameFromDSN(req.DSN),
})
}
// ---- Alert Rules ----
func (h *SettingsHandler) handleAlerts(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
rules, err := h.store.ListAlertRules()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if rules == nil {
rules = []storage.AlertRule{}
}
writeSettingsJSON(w, rules)
case http.MethodPost:
var req struct {
ID int64 `json:"id,omitempty"`
DBName string `json:"db_name"`
Metric string `json:"metric"`
Operator string `json:"operator"`
Threshold float64 `json:"threshold"`
Enabled bool `json:"enabled"`
CooldownMin int `json:"cooldown_min"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "Invalid JSON", http.StatusBadRequest)
return
}
if req.CooldownMin <= 0 {
req.CooldownMin = 5
}
if req.ID > 0 {
// Update existing
err := h.store.UpdateAlertRule(req.ID, req.DBName, req.Metric, req.Operator, req.Threshold, req.Enabled, req.CooldownMin)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
writeSettingsJSON(w, map[string]string{"status": "updated"})
} else {
// Create new
id, err := h.store.AddAlertRule(req.DBName, req.Metric, req.Operator, req.Threshold, req.CooldownMin)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
writeSettingsJSON(w, map[string]interface{}{"id": id, "status": "created"})
}
default:
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
}
}
func (h *SettingsHandler) handleAlertByID(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodDelete {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
path := strings.TrimPrefix(r.URL.Path, "/api/settings/alerts/")
id, err := strconv.ParseInt(path, 10, 64)
if err != nil {
http.Error(w, "Invalid ID", http.StatusBadRequest)
return
}
if err := h.store.DeleteAlertRule(id); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
writeSettingsJSON(w, map[string]string{"status": "deleted"})
}
// ---- Notification Channels ----
func (h *SettingsHandler) handleNotifications(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
channels, err := h.store.ListNotificationChannels()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if channels == nil {
channels = []storage.NotificationChannel{}
}
writeSettingsJSON(w, channels)
case http.MethodPost:
var req struct {
ChannelType string `json:"channel_type"`
Config json.RawMessage `json:"config"`
Enabled bool `json:"enabled"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "Invalid JSON", http.StatusBadRequest)
return
}
if err := h.store.SaveNotificationChannel(req.ChannelType, req.Config, req.Enabled); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
writeSettingsJSON(w, map[string]string{"status": "saved"})
default:
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
}
}
func (h *SettingsHandler) handleTestNotification(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
var req struct {
ChannelType string `json:"channel_type"`
Config json.RawMessage `json:"config"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "Invalid JSON", http.StatusBadRequest)
return
}
switch req.ChannelType {
case "telegram":
var cfg storage.TelegramConfig
if err := json.Unmarshal(req.Config, &cfg); err != nil {
http.Error(w, "Invalid Telegram config", http.StatusBadRequest)
return
}
err := sendTestTelegram(cfg.BotToken, cfg.ChatID)
if err != nil {
writeSettingsJSON(w, map[string]interface{}{
"success": false,
"error": err.Error(),
})
return
}
writeSettingsJSON(w, map[string]interface{}{"success": true})
default:
http.Error(w, "Unsupported channel type", http.StatusBadRequest)
}
}
// ---- Helpers ----
func sendTestTelegram(botToken, chatID string) error {
apiURL := fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage", botToken)
resp, err := http.PostForm(apiURL, map[string][]string{
"chat_id": {chatID},
"text": {"✅ *DB Monitor Test*\nThis is a test notification from DB Monitor. Your Telegram integration is working!"},
"parse_mode": {"Markdown"},
})
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("telegram returned status %d", resp.StatusCode)
}
return nil
}
func extractDBNameFromDSN(dsn string) string {
for i := len(dsn) - 1; i >= 0; i-- {
if dsn[i] == '/' {
name := dsn[i+1:]
for j, c := range name {
if c == '?' {
name = name[:j]
break
}
}
if name != "" {
return name
}
}
}
return "postgres"
}
func writeSettingsJSON(w http.ResponseWriter, data interface{}) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
json.NewEncoder(w).Encode(data)
}