فهرست منبع

feat(settings): Backups panel in AdminBar with auto-backup, force, export (#158)

Backend:
- GET/PUT /api/settings/backup — read/update backup config (enabled, frequency_h, retention_days)
- POST /api/backup/run — force manual backup with purge of old files
- GET /api/backup/download — download database as attachment
- Config persisted in kv table

Frontend:
- BackupsPanel component in AdminBar with toggle, frequency/retention selectors,
  force backup button, and export link
- i18n keys for ES and EN

Infra (CT 226):
- systemd timer netpulse-backup.timer (hourly + RandomizedDelaySec 300)
- backup.py script that checks kv config and creates/purges backups
- backup.sh wrapper for systemd ExecStart
gnacho 3 ماه پیش
والد
کامیت
e3119ae904

+ 15 - 0
app/public/locales/en/translation.json

@@ -647,6 +647,21 @@
   "settings": {
     "admin": {
       "title": "Administration",
+      "backup": {
+        "button": "Backups",
+        "autoBackup": "Automatic backup",
+        "runNow": "Backup now",
+        "running": "Backing up…",
+        "export": "Export",
+        "frequency": "Frequency:",
+        "retention": "Retention:",
+        "days": "days",
+        "lastRun": "Last: {{date}}",
+        "noBackups": "No backups yet",
+        "saveError": "Could not save settings",
+        "error": "Could not create backup",
+        "done": "Backup created successfully"
+      },
       "orchestration": "Network orchestration",
       "orchestrationDesc": "Shows the orchestration menu (apply and roll back changes on routers). It is a write surface, so it is off until you enable it."
     },

+ 15 - 0
app/public/locales/es/translation.json

@@ -647,6 +647,21 @@
   "settings": {
     "admin": {
       "title": "Administración",
+      "backup": {
+        "button": "Respaldos",
+        "autoBackup": "Respaldo automático",
+        "runNow": "Respaldar ahora",
+        "running": "Respaldando…",
+        "export": "Exportar",
+        "frequency": "Frecuencia:",
+        "retention": "Retención:",
+        "days": "días",
+        "lastRun": "Último: {{date}}",
+        "noBackups": "Sin respaldos todavía",
+        "saveError": "No se pudieron guardar los ajustes",
+        "error": "No se pudo hacer el respaldo",
+        "done": "Respaldo creado correctamente"
+      },
       "orchestration": "Orquestación de red",
       "orchestrationDesc": "Muestra el menú de orquestación (aplicar y revertir cambios en routers). Es una superficie de escritura; se activa solo si lo quieres."
     },

+ 168 - 3
app/src/pages/Settings.tsx

@@ -9,6 +9,7 @@ import {
   Check,
   ChevronDown,
   Copy,
+  Database,
   Download,
   ExternalLink,
   Eye,
@@ -16,6 +17,7 @@ import {
   FileText,
   FlaskConical,
   Github,
+  HardDrive,
   Heart,
   KeyRound,
   LogOut,
@@ -1364,6 +1366,144 @@ function SystemInfoBlock() {
   )
 }
 
+function BackupsPanel() {
+  const { t, i18n } = useTranslation()
+  const [cfg, setCfg] = useState<{ enabled: boolean; frequency_h: number; retention_days: number; last_run: string } | null>(null)
+  const [busy, setBusy] = useState(false)
+  const [backupBusy, setBackupBusy] = useState(false)
+  const [error, setError] = useState<string | null>(null)
+  const [okMsg, setOkMsg] = useState<string | null>(null)
+
+  const load = useCallback(async () => {
+    try {
+      const res = await fetch('/api/settings/backup')
+      if (res.ok) setCfg(await res.json())
+    } catch { /* ignore */ }
+  }, [])
+
+  useEffect(() => { void load() }, [load])
+
+  const save = async (patch: Record<string, unknown>) => {
+    setBusy(true)
+    setError(null)
+    try {
+      const res = await fetch('/api/settings/backup', {
+        method: 'PUT',
+        headers: { 'Content-Type': 'application/json' },
+        body: JSON.stringify(patch),
+      })
+      if (!res.ok) throw new Error(`HTTP ${res.status}`)
+      setCfg(await res.json())
+    } catch {
+      setError(t('settings.admin.backup.saveError'))
+    } finally {
+      setBusy(false)
+    }
+  }
+
+  const runBackup = async () => {
+    setBackupBusy(true)
+    setError(null)
+    try {
+      const res = await fetch('/api/backup/run', { method: 'POST' })
+      if (!res.ok) throw new Error(`HTTP ${res.status}`)
+      setOkMsg(t('settings.admin.backup.done'))
+      setTimeout(() => setOkMsg(null), 3000)
+      await load()
+    } catch {
+      setError(t('settings.admin.backup.error'))
+    } finally {
+      setBackupBusy(false)
+    }
+  }
+
+  const locale = i18n.language?.startsWith('en') ? 'en' : 'es'
+
+  const fmtDate = (iso: string | null) => {
+    if (!iso) return '—'
+    try {
+      return new Date(iso).toLocaleString(locale === 'en' ? 'en-GB' : 'es-ES', {
+        day: 'numeric', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit',
+      })
+    } catch { return iso }
+  }
+
+  if (!cfg) return <div className="animate-pulse space-y-3"><div className="h-6 w-48 rounded bg-elevated" /><div className="h-6 w-32 rounded bg-elevated" /></div>
+
+  return (
+    <div className="w-full space-y-3">
+      <div className="flex flex-wrap items-center gap-3">
+        <label className="flex items-center gap-2 cursor-pointer">
+          <Switch
+            checked={cfg.enabled}
+            onCheckedChange={() => void save({ enabled: !cfg.enabled })}
+            disabled={busy}
+          />
+          <span className="text-sm text-text-primary">{t('settings.admin.backup.autoBackup')}</span>
+        </label>
+
+        <button
+          type="button"
+          disabled={backupBusy}
+          onClick={() => void runBackup()}
+          className="inline-flex h-8 items-center gap-1.5 rounded-lg border border-border bg-elevated px-3 text-xs font-medium text-text-secondary transition-colors hover:bg-hover hover:text-text-primary disabled:opacity-60"
+        >
+          <HardDrive className="h-3.5 w-3.5" strokeWidth={1.75} />
+          {backupBusy ? t('settings.admin.backup.running') : t('settings.admin.backup.runNow')}
+        </button>
+
+        <a
+          href="/api/backup/download"
+          className="inline-flex h-8 items-center gap-1.5 rounded-lg border border-border bg-elevated px-3 text-xs font-medium text-text-secondary transition-colors hover:bg-hover hover:text-text-primary"
+        >
+          <Download className="h-3.5 w-3.5" strokeWidth={1.75} />
+          {t('settings.admin.backup.export')}
+        </a>
+      </div>
+
+      {cfg.enabled && (
+        <div className="flex flex-wrap items-center gap-3">
+          <label className="flex items-center gap-2 text-caption text-text-muted">
+            <span>{t('settings.admin.backup.frequency')}</span>
+            <select
+              value={cfg.frequency_h}
+              disabled={busy}
+              onChange={(e) => void save({ frequency_h: parseInt(e.target.value, 10) })}
+              className="rounded-lg border border-border bg-elevated px-2 py-1 text-xs text-text-primary"
+            >
+              {[1, 6, 12, 24, 48, 72].map((h) => (
+                <option key={h} value={h}>{h}h</option>
+              ))}
+            </select>
+          </label>
+          <label className="flex items-center gap-2 text-caption text-text-muted">
+            <span>{t('settings.admin.backup.retention')}</span>
+            <select
+              value={cfg.retention_days}
+              disabled={busy}
+              onChange={(e) => void save({ retention_days: parseInt(e.target.value, 10) })}
+              className="rounded-lg border border-border bg-elevated px-2 py-1 text-xs text-text-primary"
+            >
+              {[1, 3, 7, 14, 30].map((d) => (
+                <option key={d} value={d}>{d} {t('settings.admin.backup.days')}</option>
+              ))}
+            </select>
+          </label>
+        </div>
+      )}
+
+      <p className="text-caption text-text-muted">
+        {cfg.last_run
+          ? t('settings.admin.backup.lastRun', { date: fmtDate(cfg.last_run) })
+          : t('settings.admin.backup.noBackups')}
+      </p>
+
+      {error && <p role="alert" className="text-xs text-danger">{error}</p>}
+      {okMsg && <p role="status" className="text-xs text-ok">{okMsg}</p>}
+    </div>
+  )
+}
+
 // ---------------------------------------------------------------------------
 // Página Ajustes `/settings` (settings.md)
 // ---------------------------------------------------------------------------
@@ -2310,7 +2450,7 @@ export default function Settings() {
   const auth = useAuth()
   // SPEC-65 D65-7c: la tarjeta AdGuard entera desaparece si el servicio está oculto
   const [services] = useServicesVisibility()
-  const [adminPanel, setAdminPanel] = useState<'users' | null>(null)
+  const [adminPanel, setAdminPanel] = useState<'users' | 'backups' | null>(null)
 
   // ——— Orquestación (issue #121): toggle opt-in en la AdminBar ———
   const [orchOn, setOrchOn] = useState(false)
@@ -2993,7 +3133,27 @@ export default function Settings() {
                 {/* 1. Comprobar actualizaciones (widget inline) */}
                 <UpdateCheckInline />
 
-                {/* 2. Usuarios (desplegable) */}
+                {/* 2. Respaldos (desplegable) */}
+                <button
+                  type="button"
+                  aria-expanded={adminPanel === 'backups'}
+                  onClick={() => setAdminPanel(adminPanel === 'backups' ? null : 'backups')}
+                  className={[
+                    'inline-flex h-9 shrink-0 items-center gap-1.5 rounded-xl border px-3 text-[13px] font-medium transition-colors',
+                    adminPanel === 'backups'
+                      ? 'border-accent bg-accent-soft text-accent'
+                      : 'border-border bg-elevated text-text-secondary hover:bg-hover hover:text-text-primary',
+                  ].join(' ')}
+                >
+                  <Database className="h-4 w-4 shrink-0" strokeWidth={1.75} aria-hidden="true" />
+                  <span className="hidden sm:inline">{t('settings.admin.backup.button')}</span>
+                  <ChevronDown
+                    className={`h-3.5 w-3.5 shrink-0 transition-transform ${adminPanel === 'backups' ? 'rotate-180' : ''}`}
+                    aria-hidden="true"
+                  />
+                </button>
+
+                {/* 3. Usuarios (desplegable) */}
                 <button
                   type="button"
                   aria-expanded={adminPanel === 'users'}
@@ -3013,12 +3173,17 @@ export default function Settings() {
                   />
                 </button>
 
-                {/* 3. Modo demo a la derecha */}
+                {/* 4. Modo demo a la derecha */}
                 <div className="ml-auto">
                   <DemoCard onSaved={notify} />
                 </div>
               </div>
 
+              {adminPanel === 'backups' && (
+                <div className="mt-4 border-t border-border pt-4">
+                  <BackupsPanel />
+                </div>
+              )}
               {adminPanel === 'users' && (
                 <div className="mt-4 border-t border-border pt-4">
                   <UsersManager reduce={reduce} onSaved={notify} />

+ 196 - 0
server-go/internal/httpapi/backup.go

@@ -0,0 +1,196 @@
+package httpapi
+
+import (
+	"database/sql"
+	"fmt"
+	"net/http"
+	"os"
+	"path/filepath"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/auth"
+	"github.com/gnacho/netpulse/server-go/internal/db"
+)
+
+const (
+	kvBackupEnabled       = "backup.enabled"
+	kvBackupFrequencyH    = "backup.frequency_h"
+	kvBackupRetentionDays = "backup.retention_days"
+	kvBackupLastRun       = "backup.last_run"
+)
+
+type backupConfig struct {
+	Enabled       bool   `json:"enabled"`
+	FrequencyH    int    `json:"frequency_h"`
+	RetentionDays int    `json:"retention_days"`
+	LastRun       string `json:"last_run"`
+}
+
+func kvGetInt(db *sql.DB, key string, defaultVal int) int {
+	v := kvGet(db, key)
+	if v == "" {
+		return defaultVal
+	}
+	var n int
+	if _, err := fmt.Sscanf(v, "%d", &n); err != nil {
+		return defaultVal
+	}
+	return n
+}
+
+func getBackupConfig(d *db.DB) backupConfig {
+	return backupConfig{
+		Enabled:       kvGetBool(d.DB, kvBackupEnabled),
+		FrequencyH:    kvGetInt(d.DB, kvBackupFrequencyH, 24),
+		RetentionDays: kvGetInt(d.DB, kvBackupRetentionDays, 3),
+		LastRun:       kvGet(d.DB, kvBackupLastRun),
+	}
+}
+
+func (s *server) registerBackupRoutes(mux *http.ServeMux) {
+	mux.Handle("GET /api/settings/backup", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		writeJSON(w, http.StatusOK, getBackupConfig(s.db))
+	})))
+
+	mux.Handle("PUT /api/settings/backup", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		var body struct {
+			Enabled       *bool `json:"enabled"`
+			FrequencyH    *int  `json:"frequency_h"`
+			RetentionDays *int  `json:"retention_days"`
+		}
+		if !readJSONBody(r, &body) {
+			writeError(w, http.StatusBadRequest, "invalid_body")
+			return
+		}
+
+		if body.Enabled != nil {
+			if err := kvSetBool(s.db.DB, kvBackupEnabled, *body.Enabled); err != nil {
+				writeError(w, http.StatusInternalServerError, "kv_error")
+				return
+			}
+		}
+		if body.FrequencyH != nil {
+			if *body.FrequencyH < 1 || *body.FrequencyH > 72 {
+				writeError(w, http.StatusBadRequest, "invalid_frequency")
+				return
+			}
+			upsert := "INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value"
+			if _, err := s.db.Exec(upsert, kvBackupFrequencyH, fmt.Sprintf("%d", *body.FrequencyH)); err != nil {
+				writeError(w, http.StatusInternalServerError, "kv_error")
+				return
+			}
+		}
+		if body.RetentionDays != nil {
+			if *body.RetentionDays < 1 || *body.RetentionDays > 30 {
+				writeError(w, http.StatusBadRequest, "invalid_retention")
+				return
+			}
+			upsert := "INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value"
+			if _, err := s.db.Exec(upsert, kvBackupRetentionDays, fmt.Sprintf("%d", *body.RetentionDays)); err != nil {
+				writeError(w, http.StatusInternalServerError, "kv_error")
+				return
+			}
+		}
+
+		writeJSON(w, http.StatusOK, getBackupConfig(s.db))
+	})))
+
+	mux.Handle("POST /api/backup/run", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		cfg := getBackupConfig(s.db)
+		backupDir := filepath.Join(filepath.Dir(s.db.Path), "backups")
+		if err := os.MkdirAll(backupDir, 0755); err != nil {
+			writeError(w, http.StatusInternalServerError, "backup_dir_error")
+			return
+		}
+
+		ts := time.Now().UTC().Format("20060102-150405")
+		dst := filepath.Join(backupDir, "netpulse-"+ts+".db")
+		if err := copyFile(s.db.Path, dst); err != nil {
+			writeError(w, http.StatusInternalServerError, "backup_error")
+			return
+		}
+
+		upsert := "INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value"
+		s.db.Exec(upsert, kvBackupLastRun, time.Now().UTC().Format(time.RFC3339))
+
+		if cfg.RetentionDays > 0 {
+			purgeOldBackups(backupDir, cfg.RetentionDays)
+		}
+
+		writeJSON(w, http.StatusOK, map[string]any{
+			"ok":   true,
+			"file": dst,
+			"size": fileSizeHuman(dst),
+		})
+	})))
+
+	mux.Handle("GET /api/backup/download", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		backupDir := filepath.Join(filepath.Dir(s.db.Path), "backups")
+		os.MkdirAll(backupDir, 0755)
+		tmpFile := filepath.Join(backupDir, "export-temp.db")
+		if err := copyFile(s.db.Path, tmpFile); err != nil {
+			writeError(w, http.StatusInternalServerError, "backup_error")
+			return
+		}
+		defer os.Remove(tmpFile)
+
+		w.Header().Set("Content-Type", "application/octet-stream")
+		w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="netpulse-%s.db"`, time.Now().UTC().Format("20060102-150405")))
+		http.ServeFile(w, r, tmpFile)
+	})))
+}
+
+func copyFile(src, dst string) error {
+	srcFile, err := os.Open(src)
+	if err != nil {
+		return err
+	}
+	defer srcFile.Close()
+
+	dstFile, err := os.Create(dst)
+	if err != nil {
+		return err
+	}
+	defer dstFile.Close()
+
+	_, err = dstFile.ReadFrom(srcFile)
+	return err
+}
+
+func purgeOldBackups(dir string, retentionDays int) {
+	cutoff := time.Now().AddDate(0, 0, -retentionDays)
+	entries, err := os.ReadDir(dir)
+	if err != nil {
+		return
+	}
+	for _, e := range entries {
+		if e.IsDir() || filepath.Ext(e.Name()) != ".db" {
+			continue
+		}
+		info, err := e.Info()
+		if err != nil {
+			continue
+		}
+		if info.ModTime().Before(cutoff) {
+			os.Remove(filepath.Join(dir, e.Name()))
+		}
+	}
+}
+
+func fileSizeHuman(path string) string {
+	info, err := os.Stat(path)
+	if err != nil {
+		return "?"
+	}
+	size := info.Size()
+	switch {
+	case size >= 1<<30:
+		return fmt.Sprintf("%.1f GiB", float64(size)/(1<<30))
+	case size >= 1<<20:
+		return fmt.Sprintf("%.1f MiB", float64(size)/(1<<20))
+	case size >= 1<<10:
+		return fmt.Sprintf("%.1f KiB", float64(size)/(1<<10))
+	default:
+		return fmt.Sprintf("%d B", size)
+	}
+}

+ 3 - 0
server-go/internal/httpapi/server.go

@@ -237,6 +237,9 @@ func NewHandler(d Deps) http.Handler {
 	// --- Ajustes globales en kv (issue #121: orchestration opt-in) ---
 	s.registerSettingsRoutes(mux)
 
+	// --- Copias de seguridad (issue #158) ---
+	s.registerBackupRoutes(mux)
+
 	// --- Overrides manuales de topología (issue #142; solo admin) ---
 	s.registerTopologyOverrideRoutes(mux)