Browse Source

feat(server): fleet-card traffic sparkline for sources without bps throughput (from per-port fps) (#649)

Beacon agents (KP-9000 switch) and SNMP switches without aggregated bps
metrics always have an empty metrics-history sparkline, so their fleet
card drew a flat zero traffic line although the device carries real
traffic (per-port frame counters are live).

- portseries: add Store.HourlyFpsTotal(routerID, hours) - per 1h bucket
  take the max cumulative rx_frames/tx_frames per port and compute fps as
  the delta vs the previous hour / 3600 summed over ports; reset-safe (a
  counter that drops contributes 0 that hour); zero-filled output.
- buildOverview: for routers with VitalsAvailable == false and an
  all-zero sparkline, replace it with HourlyFpsTotal when it yields data.
- Tests: HourlyFpsTotal across hour deltas.

Closes #648.

Co-authored-by: gnacho <hnacho@proton.me>
Nacho 2 months ago
parent
commit
c58eeabc33

+ 21 - 0
server-go/internal/adapters/live.go

@@ -1045,6 +1045,16 @@ func countBand(split *demoBandSplit, band string) {
 	}
 }
 
+// allZeroF: ¿todos los valores del slice son 0 (o vacío)?
+func allZeroF(v []float64) bool {
+	for _, x := range v {
+		if x != 0 {
+			return false
+		}
+	}
+	return true
+}
+
 func (l *Live) buildRouter(p *routerPolled, history []histPoint) Router {
 	l.mu.Lock()
 	gw := l.gatewayCfg
@@ -2388,6 +2398,17 @@ func (l *Live) buildOverview(ctx context.Context) (*Overview, error) {
 		routerList[i].Clients = n
 		routerList[i].BandSplit = &split
 	}
+	// Sparkline de la tarjeta para fuentes sin throughput bps (switch beacon/
+	// SNMP sin métricas agregadas): su línea de tráfico 24h sale de los fps de
+	// sus puertos (port_series), no de la tabla metrics (siempre 0 ahí).
+	for i := range routerList {
+		r := &routerList[i]
+		if r.VitalsAvailable != nil && !*r.VitalsAvailable && allZeroF(r.Sparkline) && l.db != nil && l.db.PortSeries != nil {
+			if sp, err := l.db.PortSeries.HourlyFpsTotal(r.ID, len(r.Sparkline)); err == nil && len(sp) > 0 && !allZeroF(sp) {
+				r.Sparkline = sp
+			}
+		}
+	}
 	adguard := l.pollAdGuard(ctx)
 	wireguard := l.pollWireGuard(devices)
 	gwID := ""

+ 79 - 13
server-go/internal/portseries/portseries.go

@@ -10,9 +10,9 @@ import (
 )
 
 const (
-	RawRetentionMS     = 7 * 24 * 60 * 60 * 1000
-	BucketRetentionMS  = 365 * 24 * 60 * 60 * 1000
-	BucketMS           = 5 * 60 * 1000
+	RawRetentionMS    = 7 * 24 * 60 * 60 * 1000
+	BucketRetentionMS = 365 * 24 * 60 * 60 * 1000
+	BucketMS          = 5 * 60 * 1000
 )
 
 // PortSample is a single data point for a port.
@@ -33,19 +33,19 @@ type PortSample struct {
 
 // PortPoint is a time-series point returned by GetSeries.
 type PortPoint struct {
-	TS        time.Time `json:"ts"`
-	RxBytes   uint64    `json:"rxBytes"`
-	TxBytes   uint64    `json:"txBytes"`
-	RxErrors  uint64    `json:"rxErrors"`
-	TxErrors  uint64    `json:"txErrors"`
-	RxBps     float64   `json:"rxBps"`
-	TxBps     float64   `json:"txBps"`
+	TS       time.Time `json:"ts"`
+	RxBytes  uint64    `json:"rxBytes"`
+	TxBytes  uint64    `json:"txBytes"`
+	RxErrors uint64    `json:"rxErrors"`
+	TxErrors uint64    `json:"txErrors"`
+	RxBps    float64   `json:"rxBps"`
+	TxBps    float64   `json:"txBps"`
 	// RxFps/TxFps: frames per second derived from the cumulative frame
 	// counters (issue #641). Devices without byte counters (RTLPlayground
 	// beacon agents) report traffic this way; bps stays 0 for them.
-	RxFps     float64   `json:"rxFps"`
-	TxFps     float64   `json:"txFps"`
-	SpeedMbps int       `json:"speedMbps"`
+	RxFps     float64 `json:"rxFps"`
+	TxFps     float64 `json:"txFps"`
+	SpeedMbps int     `json:"speedMbps"`
 	// RxFrames/TxFrames: cumulative counters used to derive fps; not part of
 	// the JSON contract.
 	RxFrames uint64 `json:"-"`
@@ -278,6 +278,72 @@ func deriveFps(pts []PortPoint) {
 	}
 }
 
+// HourlyFpsTotal devuelve el tráfico agregado del router en frames/s por
+// bucket de una hora (issue #646 follow-up: la tarjeta de la flota de un
+// switch beacon no tiene métricas bps). Por cada hora y puerto se toma el
+// contador acumulado máximo (rx+tx) y el fps de esa hora es el delta respecto
+// a la hora anterior dividido por 3600, sumando todos los puertos. Un
+// contador que baja (reset del dispositivo) no contribuye en esa hora. El
+// slice tiene `hours` entradas (la primera sin anterior = 0); huecos a 0.
+func (s *Store) HourlyFpsTotal(routerID string, hours int) ([]float64, error) {
+	if routerID == "" || hours <= 0 {
+		return nil, nil
+	}
+	const bucketMs = 3600e3
+	// Alinear a hora: el bucket más reciente es la hora en curso (aunque aún
+	// no haya terminado) y hacia atrás `hours` buckets completos.
+	nowMs := time.Now().Truncate(time.Hour).UnixMilli()
+	startMs := nowMs - int64(hours-1)*bucketMs
+	rows, err := s.db.Query(`SELECT (ts / ?) AS h, port_id, MAX(rx_frames), MAX(tx_frames)
+		FROM port_series_raw
+		WHERE router_id = ? AND ts >= ?
+		GROUP BY h, port_id ORDER BY h`, bucketMs, routerID, startMs)
+	if err != nil {
+		return nil, err
+	}
+	defer rows.Close()
+	// rx[h][port] / tx[h][port] con el último acumulado de esa hora.
+	type acc struct{ rx, tx uint64 }
+	buckets := make([]map[string]acc, hours)
+	for rows.Next() {
+		var h int64
+		var port string
+		var rx, tx uint64
+		if err := rows.Scan(&h, &port, &rx, &tx); err != nil {
+			continue
+		}
+		idx := int(h - startMs/bucketMs)
+		if idx < 0 || idx >= hours {
+			continue
+		}
+		if buckets[idx] == nil {
+			buckets[idx] = map[string]acc{}
+		}
+		buckets[idx][port] = acc{rx: rx, tx: tx}
+	}
+	if err := rows.Err(); err != nil {
+		return nil, err
+	}
+	out := make([]float64, hours)
+	for i := 1; i < hours; i++ {
+		var fps float64
+		for port, cur := range buckets[i] {
+			prev, ok := buckets[i-1][port]
+			if !ok {
+				continue
+			}
+			if cur.rx >= prev.rx {
+				fps += float64(cur.rx-prev.rx) / 3600
+			}
+			if cur.tx >= prev.tx {
+				fps += float64(cur.tx-prev.tx) / 3600
+			}
+		}
+		out[i] = fps
+	}
+	return out, nil
+}
+
 // RollupRawTo5m aggregates raw samples into 5-min buckets.
 func (s *Store) RollupRawTo5m(window time.Duration) error {
 	since := time.Now().Add(-window).UnixMilli()

+ 38 - 0
server-go/internal/portseries/portseries_test.go

@@ -264,3 +264,41 @@ func TestDeriveFps(t *testing.T) {
 		t.Fatalf("punto 4: rx=%.1f tx=%.1f, esperaba 100/~66.6", pts[4].RxFps, pts[4].TxFps)
 	}
 }
+
+// HourlyFpsTotal: agrega el tráfico del router en fps por hora sumando los
+// deltas de contadores acumulados (rx+tx) de todos sus puertos.
+func TestHourlyFpsTotal(t *testing.T) {
+	s := openTestDB(t)
+	nowHour := time.Now().Truncate(time.Hour)
+	// Un puerto; acumulados que crecen 1.8M rx + 0.9M tx por hora → 750 fps.
+	acc := []struct {
+		off    time.Duration
+		rx, tx uint64
+	}{
+		{-2 * time.Hour, 1_800_000, 900_000},
+		{-1 * time.Hour, 3_600_000, 1_800_000},
+		{0, 5_400_000, 2_700_000},
+	}
+	for _, a := range acc {
+		if err := s.RecordSample(PortSample{RouterID: "sw1", PortID: "p1",
+			TS: nowHour.Add(a.off), RxFrames: a.rx, TxFrames: a.tx}); err != nil {
+			t.Fatal(err)
+		}
+	}
+	out, err := s.HourlyFpsTotal("sw1", 3)
+	if err != nil {
+		t.Fatal(err)
+	}
+	if len(out) != 3 {
+		t.Fatalf("esperaba 3 buckets, tengo %d", len(out))
+	}
+	// Primer bucket sin anterior → 0; los dos siguientes ~750 fps.
+	if out[0] != 0 {
+		t.Fatalf("hora 0: %.1f fps, esperaba 0", out[0])
+	}
+	for i := 1; i <= 2; i++ {
+		if out[i] < 749 || out[i] > 751 {
+			t.Fatalf("hora %d: %.1f fps, esperaba ~750", i, out[i])
+		}
+	}
+}