فهرست منبع

fix(backup): run automatic backups on a scheduler and add a daily time option (#741) (#745)

Co-authored-by: gnacho <hnacho@proton.me>
Nacho 2 ماه پیش
والد
کامیت
b2c78b6ca1

+ 10 - 0
CHANGELOG.md

@@ -5,6 +5,16 @@ Todos los cambios notables de NetPulse se documentan en este fichero.
 El formato se basa en [Keep a Changelog](https://keepachangelog.com/es/1.1.0/),
 y este proyecto se adhiere a [Versionado Semántico](https://semver.org/lang/es/).
 
+## [Unreleased]
+
+### Fixed
+
+- **Los respaldos automáticos ahora se ejecutan de verdad (#741)**: la configuración (activado, frecuencia, retención) existía y se mostraba en la UI, pero nada en el servidor la leía para disparar el respaldo; el único camino que copiaba la base de datos era el botón manual, así que un respaldo inicial y nada más era el comportamiento esperado del código. Ahora un bucle periódico (patrón del scheduler de speedtest) decide en cada pasada si toca, con el vencimiento derivado SIEMPRE del `last_run` persistido: los reinicios y el auto-updater no resetean el reloj. El run manual y el programado comparten el mismo código con exclusión mutua.
+
+### Added
+
+- **Hora fija para el respaldo diario (#741)**: campo opcional `Hora` (HH:MM, hora local) en la tarjeta de Respaldos; vacío mantiene el comportamiento "cada N horas" y con hora fija el respaldo dispara una vez al día a esa hora (ventana de mantenimiento). Validación `HH:MM` en el servidor.
+
 ## [2.28.22] - 2026-09-11
 
 ### Changed

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

@@ -1070,6 +1070,8 @@
         "days": "days",
         "lastRun": "Last: {{date}}",
         "noBackups": "No backups yet",
+        "time": "Time:",
+        "timeHint": "Empty = every N hours; with a time, daily at that time",
         "saveError": "Could not save settings",
         "error": "Could not create backup",
         "done": "Backup created successfully"

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

@@ -1070,6 +1070,8 @@
         "days": "días",
         "lastRun": "Último: {{date}}",
         "noBackups": "Sin respaldos todavía",
+        "time": "Hora:",
+        "timeHint": "Vacío = cada N horas; con hora, diario a esa hora",
         "saveError": "No se pudieron guardar los ajustes",
         "error": "No se pudo hacer el respaldo",
         "done": "Respaldo creado correctamente"

+ 12 - 1
app/src/pages/Settings.tsx

@@ -1941,7 +1941,7 @@ function SystemInfoBlock({ bare = false }: { bare?: boolean }) {
 
 function BackupsPanel() {
   const { t, i18n } = useTranslation()
-  const [cfg, setCfg] = useState<{ enabled: boolean; frequency_h: number; retention_days: number; last_run: string } | null>(null)
+  const [cfg, setCfg] = useState<{ enabled: boolean; frequency_h: number; retention_days: number; last_run: string; time: string } | null>(null)
   const [busy, setBusy] = useState(false)
   const [backupBusy, setBackupBusy] = useState(false)
   const [error, setError] = useState<string | null>(null)
@@ -2062,6 +2062,17 @@ function BackupsPanel() {
               ))}
             </select>
           </label>
+          <label className="flex items-center gap-2 text-caption text-text-muted">
+            <span>{t('settings.admin.backup.time')}</span>
+            <input
+              type="time"
+              value={cfg.time || ''}
+              disabled={busy}
+              onChange={(e) => void save({ time: e.target.value })}
+              className="rounded-lg border border-border bg-elevated px-2 py-1 text-xs text-text-primary"
+            />
+            <span className="hidden text-[11px] text-text-muted sm:inline">{t('settings.admin.backup.timeHint')}</span>
+          </label>
         </div>
       )}
 

+ 139 - 24
server-go/internal/httpapi/backup.go

@@ -1,6 +1,13 @@
+// backup.go — backups automáticos de la BD (#741): config persistida en kv,
+// run manual (POST /api/backup/run), descarga completa (#218) y, desde el fix
+// del scheduler, un bucle periódico que ejecuta el backup cuando vence el
+// intervalo (o a la hora fija configurada). El vencimiento se deriva SIEMPRE
+// del last_run persistido, así los reinicios y el auto-updater no resetean
+// el reloj (el bug original: la config existía pero nada la ejecutaba).
 package httpapi
 
 import (
+	"context"
 	"database/sql"
 	"fmt"
 	"log"
@@ -18,13 +25,23 @@ const (
 	kvBackupFrequencyH    = "backup.frequency_h"
 	kvBackupRetentionDays = "backup.retention_days"
 	kvBackupLastRun       = "backup.last_run"
+	kvBackupTime          = "backup.time"
+
+	// backupTickEvery: cadencia del bucle. Corta a propósito: un cambio de
+	// ajustes aplica en menos de un minuto sin canales ni reinicios (mismo
+	// patrón que el scheduler de speedtest #511).
+	backupTickEvery = 1 * time.Minute
 )
 
-type backupConfig struct {
+// BackupConfig es la configuración de backups automáticos (kv backup.*).
+// Time es opcional ("HH:MM", hora local): con valor, el backup es diario a
+// esa hora (ventana de mantenimiento); vacío, cada FrequencyH horas.
+type BackupConfig struct {
 	Enabled       bool   `json:"enabled"`
 	FrequencyH    int    `json:"frequency_h"`
 	RetentionDays int    `json:"retention_days"`
 	LastRun       string `json:"last_run"`
+	Time          string `json:"time"`
 }
 
 func kvGetInt(db *sql.DB, key string, defaultVal int) int {
@@ -39,13 +56,108 @@ func kvGetInt(db *sql.DB, key string, defaultVal int) int {
 	return n
 }
 
-func getBackupConfig(d *db.DB) backupConfig {
-	return backupConfig{
+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),
+		Time:          kvGet(d.DB, kvBackupTime),
+	}
+}
+
+// BackupDue decide si toca backup. Con Time vacío: intervalo FrequencyH desde
+// lastRun (lastRun zero = ya). Con Time "HH:MM": diario a esa hora local;
+// toca si ya pasó la hora de hoy y el último backup es anterior a la de hoy.
+func BackupDue(cfg BackupConfig, lastRun time.Time, now time.Time) bool {
+	if !cfg.Enabled {
+		return false
+	}
+	if t, err := time.Parse("15:04", cfg.Time); err == nil && cfg.Time != "" {
+		today := time.Date(now.Year(), now.Month(), now.Day(), t.Hour(), t.Minute(), 0, 0, now.Location())
+		return !now.Before(today) && lastRun.Before(today)
+	}
+	if lastRun.IsZero() {
+		return true
+	}
+	return now.Sub(lastRun) >= time.Duration(cfg.FrequencyH)*time.Hour
+}
+
+// backupLastRun lee el último run persistido (RFC3339 UTC; zero si nunca).
+func (s *server) backupLastRun() time.Time {
+	v := kvGet(s.db.DB, kvBackupLastRun)
+	if v == "" {
+		return time.Time{}
+	}
+	t, err := time.Parse(time.RFC3339, v)
+	if err != nil {
+		return time.Time{}
+	}
+	return t
+}
+
+// runBackup copia la BD, marca last_run y aplica la retención. Single-flight
+// con mutex: el run manual y el programado nunca se pisan.
+func (s *server) runBackup() (string, error) {
+	s.backupMu.Lock()
+	defer s.backupMu.Unlock()
+
+	cfg := getBackupConfig(s.db)
+	backupDir := filepath.Join(filepath.Dir(s.db.Path), "backups")
+	if err := os.MkdirAll(backupDir, 0755); err != nil {
+		return "", err
+	}
+
+	ts := time.Now().UTC().Format("20060102-150405")
+	dst := filepath.Join(backupDir, "netpulse-"+ts+".db")
+	if err := copyFile(s.db.Path, dst); err != nil {
+		return "", err
+	}
+
+	upsert := "INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value"
+	if _, err := s.db.Exec(upsert, kvBackupLastRun, time.Now().UTC().Format(time.RFC3339)); err != nil {
+		return dst, err
 	}
+
+	if cfg.RetentionDays > 0 {
+		purgeOldBackups(backupDir, cfg.RetentionDays)
+	}
+	return dst, nil
+}
+
+// backupLoop es el bucle periódico de backups automáticos (#741).
+func (s *server) backupLoop(ctx context.Context, tickEvery time.Duration) {
+	ticker := time.NewTicker(tickEvery)
+	defer ticker.Stop()
+	for {
+		select {
+		case <-ctx.Done():
+			return
+		case <-ticker.C:
+			s.backupTick()
+		}
+	}
+}
+
+func (s *server) backupTick() {
+	cfg := getBackupConfig(s.db)
+	if !BackupDue(cfg, s.backupLastRun(), time.Now()) {
+		return
+	}
+	dst, err := s.runBackup()
+	if err != nil {
+		log.Printf("[netpulse] backup automático falló: %v", err)
+		return
+	}
+	log.Printf("[netpulse] backup automático completado: %s", dst)
+}
+
+func validBackupTime(v string) bool {
+	if v == "" {
+		return true
+	}
+	_, err := time.Parse("15:04", v)
+	return err == nil
 }
 
 func (s *server) registerBackupRoutes(mux *http.ServeMux) {
@@ -55,9 +167,10 @@ func (s *server) registerBackupRoutes(mux *http.ServeMux) {
 
 	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"`
+			Enabled       *bool   `json:"enabled"`
+			FrequencyH    *int    `json:"frequency_h"`
+			RetentionDays *int    `json:"retention_days"`
+			Time          *string `json:"time"`
 		}
 		if st := readJSONBody(w, r, &body); st != 0 {
 			writeBodyError(w, st, "invalid_body", "")
@@ -92,32 +205,34 @@ func (s *server) registerBackupRoutes(mux *http.ServeMux) {
 				return
 			}
 		}
+		if body.Time != nil && !validBackupTime(*body.Time) {
+			writeError(w, http.StatusBadRequest, "invalid_time")
+			return
+		}
+		if body.Time != nil {
+			if *body.Time == "" {
+				if _, err := s.db.Exec("DELETE FROM kv WHERE key = ?", kvBackupTime); err != nil {
+					writeError(w, http.StatusInternalServerError, "kv_error")
+					return
+				}
+			} else {
+				upsert := "INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value"
+				if _, err := s.db.Exec(upsert, kvBackupTime, *body.Time); 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 {
+		dst, err := s.runBackup()
+		if 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,

+ 85 - 0
server-go/internal/httpapi/backup_sched_internal_test.go

@@ -0,0 +1,85 @@
+// backup_sched_internal_test.go — #741: el bucle de backups automáticos
+// dispara cuando el last_run persistido está vencido. Test interno del
+// paquete para poder construir el server con BD temporal y un tick corto.
+package httpapi
+
+import (
+	"context"
+	"os"
+	"path/filepath"
+	"testing"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/db"
+)
+
+func TestBackupLoopRunsWhenDue(t *testing.T) {
+	dataDir := t.TempDir()
+	d, err := db.Open(dataDir)
+	if err != nil {
+		t.Fatalf("db: %v", err)
+	}
+	defer d.Close()
+	s := &server{db: d}
+
+	upsert := "INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value"
+	if _, err := d.Exec(upsert, kvBackupEnabled, "1"); err != nil {
+		t.Fatalf("kv enabled: %v", err)
+	}
+	if _, err := d.Exec(upsert, kvBackupFrequencyH, "24"); err != nil {
+		t.Fatalf("kv frequency: %v", err)
+	}
+	oldLastRun := time.Now().Add(-25 * time.Hour).UTC().Format(time.RFC3339)
+	if _, err := d.Exec(upsert, kvBackupLastRun, oldLastRun); err != nil {
+		t.Fatalf("kv last_run: %v", err)
+	}
+
+	ctx, cancel := context.WithCancel(context.Background())
+	defer cancel()
+	go s.backupLoop(ctx, 20*time.Millisecond)
+
+	backupDir := filepath.Join(dataDir, "backups")
+	deadline := time.Now().Add(5 * time.Second)
+	for {
+		entries, err := os.ReadDir(backupDir)
+		if err == nil && len(entries) >= 1 {
+			var last string
+			_ = d.QueryRow("SELECT value FROM kv WHERE key = ?", kvBackupLastRun).Scan(&last)
+			if last == oldLastRun {
+				t.Fatal("el backup se creó pero last_run no se actualizó")
+			}
+			return
+		}
+		if time.Now().After(deadline) {
+			t.Fatal("el scheduler no disparó un backup vencido (25h con frecuencia 24h)")
+		}
+		time.Sleep(20 * time.Millisecond)
+	}
+}
+
+func TestBackupLoopSkipsWhenFresh(t *testing.T) {
+	dataDir := t.TempDir()
+	d, err := db.Open(dataDir)
+	if err != nil {
+		t.Fatalf("db: %v", err)
+	}
+	defer d.Close()
+	s := &server{db: d}
+
+	upsert := "INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value"
+	d.Exec(upsert, kvBackupEnabled, "1")
+	d.Exec(upsert, kvBackupFrequencyH, "24")
+	// Último run hace 1h: no vence (24h) y nunca ha habido backup antes.
+	d.Exec(upsert, kvBackupLastRun, time.Now().Add(-time.Hour).UTC().Format(time.RFC3339))
+
+	ctx, cancel := context.WithCancel(context.Background())
+	defer cancel()
+	go s.backupLoop(ctx, 20*time.Millisecond)
+
+	backupDir := filepath.Join(dataDir, "backups")
+	time.Sleep(300 * time.Millisecond)
+	cancel()
+	if entries, err := os.ReadDir(backupDir); err == nil && len(entries) > 0 {
+		t.Fatalf("no debía disparar un backup fresco, pero hay %d ficheros", len(entries))
+	}
+}

+ 92 - 0
server-go/internal/httpapi/backup_test.go

@@ -1,10 +1,16 @@
 // backup_test.go — issue #218: el download de la BD completa queda
 // restringido a admin y avisa explícitamente de que contiene secrets kv.
+// Issue #741: BackupDue (frecuencia y hora fija) y validación del time.
 package httpapi_test
 
 import (
+	"bytes"
+	"encoding/json"
 	"net/http"
 	"testing"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/httpapi"
 )
 
 func TestBackupDownloadAdminHeaderYGate(t *testing.T) {
@@ -36,3 +42,89 @@ func TestBackupDownloadAdminHeaderYGate(t *testing.T) {
 		t.Fatal("el download sin sesión debe rechazarse")
 	}
 }
+
+func TestBackupDueFrequency(t *testing.T) {
+	now := time.Date(2026, 9, 11, 12, 0, 0, 0, time.UTC)
+	cases := []struct {
+		name    string
+		cfg     httpapi.BackupConfig
+		lastRun time.Time
+		want    bool
+	}{
+		{"disabled never", httpapi.BackupConfig{Enabled: false, FrequencyH: 24}, now.Add(-48 * time.Hour), false},
+		{"never ran and enabled", httpapi.BackupConfig{Enabled: true, FrequencyH: 24}, time.Time{}, true},
+		{"fresh run", httpapi.BackupConfig{Enabled: true, FrequencyH: 24}, now.Add(-1 * time.Hour), false},
+		{"expired run", httpapi.BackupConfig{Enabled: true, FrequencyH: 24}, now.Add(-25 * time.Hour), true},
+		{"exact boundary", httpapi.BackupConfig{Enabled: true, FrequencyH: 1}, now.Add(-1 * time.Hour), true},
+	}
+	for _, tc := range cases {
+		t.Run(tc.name, func(t *testing.T) {
+			if got := httpapi.BackupDue(tc.cfg, tc.lastRun, now); got != tc.want {
+				t.Fatalf("BackupDue = %v, want %v", got, tc.want)
+			}
+		})
+	}
+}
+
+func TestBackupDueDailyTime(t *testing.T) {
+	cfg := httpapi.BackupConfig{Enabled: true, FrequencyH: 24, Time: "04:30"}
+	at := func(h, m int) time.Time { return time.Date(2026, 9, 11, h, m, 0, 0, time.UTC) }
+	yesterday := time.Date(2026, 9, 10, 20, 0, 0, 0, time.UTC)
+
+	cases := []struct {
+		name    string
+		now     time.Time
+		lastRun time.Time
+		want    bool
+	}{
+		{"before window", at(3, 0), yesterday, false},
+		{"after window, not run today", at(5, 0), yesterday, true},
+		{"after window, already run today", at(5, 0), at(4, 35), false},
+		{"exactly at window", at(4, 30), yesterday, true},
+		{"invalid time falls back to frequency", at(5, 0), yesterday, false}, // freq 24h, ayer 20:00
+	}
+	for _, tc := range cases {
+		t.Run(tc.name, func(t *testing.T) {
+			c := cfg
+			if tc.name == "invalid time falls back to frequency" {
+				c.Time = "9x:99"
+			}
+			if got := httpapi.BackupDue(c, tc.lastRun, tc.now); got != tc.want {
+				t.Fatalf("BackupDue = %v, want %v", got, tc.want)
+			}
+		})
+	}
+}
+
+func TestBackupTimeSettingValidation(t *testing.T) {
+	srv := makeTestServer(t)
+	_, adminCookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
+
+	put := func(body string) (int, httpapi.BackupConfig) {
+		req, _ := http.NewRequest("PUT", srv.URL+"/api/settings/backup", bytes.NewBufferString(body))
+		req.Header.Set("Content-Type", "application/json")
+		req.AddCookie(&http.Cookie{Name: "session", Value: adminCookie})
+		res, err := http.DefaultClient.Do(req)
+		if err != nil {
+			t.Fatalf("put: %v", err)
+		}
+		defer res.Body.Close()
+		var cfg httpapi.BackupConfig
+		if res.StatusCode == http.StatusOK {
+			if err := json.NewDecoder(res.Body).Decode(&cfg); err != nil {
+				t.Fatalf("decode: %v", err)
+			}
+		}
+		return res.StatusCode, cfg
+	}
+
+	if st, cfg := put(`{"time":"04:30"}`); st != http.StatusOK || cfg.Time != "04:30" {
+		t.Fatalf("time válido: status %d cfg %+v", st, cfg)
+	}
+	if st, _ := put(`{"time":"25:99"}`); st != http.StatusBadRequest {
+		t.Fatalf("time inválido: got %d want 400", st)
+	}
+	if st, cfg := put(`{"time":""}`); st != http.StatusOK || cfg.Time != "" {
+		t.Fatalf("time vacío debe limpiar: status %d cfg %+v", st, cfg)
+	}
+}

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

@@ -11,6 +11,7 @@ package httpapi
 
 import (
 	"bytes"
+	"context"
 	"crypto/rand"
 	"database/sql"
 	"encoding/hex"
@@ -155,6 +156,10 @@ type server struct {
 	beaconCandMu sync.Mutex
 	beaconCand   map[string]beaconCandidate
 
+	// Backups automáticos (#741): mutex single-flight entre el run manual
+	// (POST /api/backup/run) y el scheduler periódico.
+	backupMu sync.Mutex
+
 	// rtlConsole (#639): sondeo HTTP de la consola de switches RTLPlayground
 	// (firmware + uptime) para agentes external/beacon. nil si desactivado.
 	rtlConsole *rtlConsoleCache
@@ -447,6 +452,13 @@ func NewHandler(d Deps) http.Handler {
 	// --- Copias de seguridad (issue #158) ---
 	s.registerBackupRoutes(mux)
 
+	// Backups automáticos (#741): el scheduler vive con el handler; el
+	// vencimiento se deriva del last_run persistido, así que reinicios y
+	// auto-updates no resetean el reloj. Solo en live (en demo no hay datos).
+	if s.cfg == nil || !s.cfg.DemoMode {
+		go s.backupLoop(context.Background(), backupTickEvery)
+	}
+
 	// --- Overrides manuales de topología (issue #142; solo admin) ---
 	s.registerTopologyOverrideRoutes(mux)