Просмотр исходного кода

fix(retention): keep 90 days of 5m buckets and compress update backups (#1862) (#1863)

Nacho 1 месяц назад
Родитель
Сommit
3e1f0c410b

+ 1 - 0
CHANGELOG.md

@@ -22,6 +22,7 @@ y este proyecto se adhiere a [Versionado Semántico](https://semver.org/lang/es/
 
 ### Changed
 
+- Five-minute buckets are kept for 90 days instead of a year, and the copy the updater takes before an update is compressed. On a live install the database had reached 419 MB, 182 MB of it in five-minute buckets that were only 64 days old, and the three copies the updater keeps were full uncompressed dumps: at a year of history that is about 1.3 GB of database and 3.8 GB of copies on a container with a couple of gigabytes free. Ninety days keeps the quarter view, and the copies shrink to a third (419 MB to 130 MB measured on the nightly backups). A rollback restores from the compressed copy, dropping the stale `-wal` and `-shm` first so no writes from the previous version land on the restored file (#1862).
 - Every page now shares the same width and the same header gap (#1823). Alerts and Settings capped their content at their own width while the rest used the shell, so Alerts looked narrower than the menu it sits in. The breadcrumb also sat outside the block that holds the explanation, which is why the gap under it differed from page to page. Both now come from the same shell width and the same header block.
 - The in-app help covers integrations and certificates (#1823). Two flows are new: one walks through the add-ons group in Settings, the vendor catalog and what a pusher is, including the units that already push without a record; the other covers the HTTPS card, from the certificate or private CA source to the agent pin and the extra options for connection strings and plain HTTP. Both cite the real UI labels as chips, like the rest of the page.
 - The Channels page no longer repeats its name (#1823). The top bar said Canales and the page said Analisis de canales right below it, because it was the one page that kept its own title and had no breadcrumb. It now follows the same header as the rest. The extra margin that pushed the explanation away from the breadcrumb on Routers, Devices, Reports and Roaming is gone too, so the gap is the same everywhere.

+ 22 - 2
deploy/update.sh

@@ -58,7 +58,14 @@ PYEOF
   else
     cp -a "$DB_FILE" "$BACKUP_DIR/netpulse.db"
   fi
-  echo "copia de seguridad de BD en $BACKUP_DIR/netpulse.db"
+  # La BD con las series comprime a un tercio y con KEEP=3 son cientos de MB
+  # en un disco pequeño (#1862). Sin gzip se queda sin comprimir.
+  if command -v gzip >/dev/null 2>&1 && gzip -9 "$BACKUP_DIR/netpulse.db" 2>/dev/null; then
+    echo "copia de seguridad de BD comprimida en $BACKUP_DIR/netpulse.db.gz"
+  else
+    rm -f "$BACKUP_DIR/netpulse.db.gz"
+    echo "copia de seguridad de BD en $BACKUP_DIR/netpulse.db"
+  fi
 fi
 
 echo "STEP:fetch"
@@ -204,7 +211,20 @@ if [ -f "$SERVER_BIN" ]; then
       chmod 600 "$SSH_DIR/id_ed25519" 2>/dev/null || true
       chmod 644 "$SSH_DIR/id_ed25519.pub" "$SSH_DIR/known_hosts" 2>/dev/null || true
     fi
-    if [ -f "$BACKUP_DIR/netpulse.db" ]; then
+    if [ -f "$BACKUP_DIR/netpulse.db.gz" ]; then
+      # Se descomprime a un temporal y se renombra, para no dejar la BD a
+      # medias si el disco se llena. Los -wal/-shm viejos se tiran: aplicarían
+      # escrituras de la versión anterior sobre la BD restaurada (#1862).
+      if gunzip -c "$BACKUP_DIR/netpulse.db.gz" > "$DB_FILE.restore" 2>/dev/null; then
+        rm -f "$DB_FILE-wal" "$DB_FILE-shm"
+        mv -f "$DB_FILE.restore" "$DB_FILE"
+        echo "BD restaurada desde $BACKUP_DIR/netpulse.db.gz"
+      else
+        rm -f "$DB_FILE.restore"
+        echo "ERROR: no pude restaurar la BD desde $BACKUP_DIR/netpulse.db.gz" >&2
+      fi
+    elif [ -f "$BACKUP_DIR/netpulse.db" ]; then
+      rm -f "$DB_FILE-wal" "$DB_FILE-shm"
       cp -a "$BACKUP_DIR/netpulse.db" "$DB_FILE"
     fi
     # Forzamos un nuevo reinicio para levantar con la versión anterior.

+ 68 - 0
server-go/internal/clientbw/retention_1862_test.go

@@ -0,0 +1,68 @@
+package clientbw
+
+import (
+	"testing"
+	"time"
+)
+
+// #1862: los buckets de 5m se guardan 90 días, no un año. Con un año la BD
+// llegaba a ~1,3 GB en un contenedor de 8 GB. Este test fija la frontera: un
+// bucket de hace 100 días se poda, uno de hace 89 sobrevive.
+func TestPurgeKeepsNinetyDaysOfBuckets(t *testing.T) {
+	s := openTestStore(t)
+	now := time.Now()
+
+	oldBucket := now.Add(-100 * 24 * time.Hour).UnixMilli()
+	recentBucket := now.Add(-89 * 24 * time.Hour).UnixMilli()
+	for _, ts := range []int64{oldBucket, recentBucket} {
+		_, err := s.db.Exec(`INSERT INTO client_bw_5m
+			(mac, router_id, bucket_ts, n, rx_bytes, tx_bytes)
+			VALUES ('aa:bb:cc:dd:ee:ff', 'rt1', ?, 1, 10, 20)`, ts)
+		if err != nil {
+			t.Fatal(err)
+		}
+	}
+
+	oldRaw := now.Add(-8 * 24 * time.Hour).UnixMilli()
+	recentRaw := now.Add(-6 * 24 * time.Hour).UnixMilli()
+	for _, ts := range []int64{oldRaw, recentRaw} {
+		_, err := s.db.Exec(`INSERT INTO client_bw_raw
+			(mac, router_id, ts, rx_bytes, tx_bytes)
+			VALUES ('aa:bb:cc:dd:ee:ff', 'rt1', ?, 10, 20)`, ts)
+		if err != nil {
+			t.Fatal(err)
+		}
+	}
+
+	if err := s.Purge(); err != nil {
+		t.Fatal(err)
+	}
+
+	var buckets int
+	if err := s.db.QueryRow("SELECT COUNT(*) FROM client_bw_5m WHERE bucket_ts = ?", oldBucket).Scan(&buckets); err != nil {
+		t.Fatal(err)
+	}
+	if buckets != 0 {
+		t.Error("un bucket de 100 días debería podarse")
+	}
+	if err := s.db.QueryRow("SELECT COUNT(*) FROM client_bw_5m WHERE bucket_ts = ?", recentBucket).Scan(&buckets); err != nil {
+		t.Fatal(err)
+	}
+	if buckets != 1 {
+		t.Error("un bucket de 89 días debería sobrevivir")
+	}
+
+	var raws int
+	if err := s.db.QueryRow("SELECT COUNT(*) FROM client_bw_raw WHERE ts = ?", oldRaw).Scan(&raws); err != nil {
+		t.Fatal(err)
+	}
+	if raws != 0 {
+		t.Error("una muestra raw de 8 días debería podarse")
+	}
+	if err := s.db.QueryRow("SELECT COUNT(*) FROM client_bw_raw WHERE ts = ?", recentRaw).Scan(&raws); err != nil {
+		t.Fatal(err)
+	}
+	if raws != 1 {
+		t.Error("una muestra raw de 6 días debería sobrevivir")
+	}
+}

+ 7 - 2
server-go/internal/clientbw/store.go

@@ -7,8 +7,13 @@ import (
 )
 
 const (
-	RawRetentionMS    = 7 * 24 * 60 * 60 * 1000
-	BucketRetentionMS = 365 * 24 * 60 * 60 * 1000
+	RawRetentionMS = 7 * 24 * 60 * 60 * 1000
+	// BucketRetentionMS (#1862): un trimestre de buckets de 5m. Con un año la
+	// BD llegaba a ~1,3 GB en este despliegue (los 5m ya ocupaban 182 MB con
+	// 64 días), demasiado para el disco del contenedor junto con las copias
+	// del updater. Noventa días cubren las vistas de trimestre y dejan el
+	// histórico largo a los buckets de más granularidad.
+	BucketRetentionMS = 90 * 24 * 60 * 60 * 1000
 	BucketMS          = 5 * 60 * 1000
 )
 

+ 6 - 3
server-go/internal/portseries/portseries.go

@@ -1,5 +1,5 @@
 // Package portseries: per-port time series with tiered retention (issue #302).
-// raw (7d) -> buckets 5m (1 year) -> daily (forever).
+// raw (7d) -> buckets 5m (90d, #1862) -> daily (forever).
 package portseries
 
 import (
@@ -10,8 +10,11 @@ import (
 )
 
 const (
-	RawRetentionMS    = 7 * 24 * 60 * 60 * 1000
-	BucketRetentionMS = 365 * 24 * 60 * 60 * 1000
+	RawRetentionMS = 7 * 24 * 60 * 60 * 1000
+	// BucketRetentionMS (#1862): un trimestre, igual que en clientbw. Los 5m
+	// de puerto crecían al mismo ritmo y con un año llenaban el disco del
+	// contenedor.
+	BucketRetentionMS = 90 * 24 * 60 * 60 * 1000
 	BucketMS          = 5 * 60 * 1000
 )