Sfoglia il codice sorgente

feat(beacon): record octet counters from the RTLPlayground beacon v7 (#1536)

The state datagram gains optional per-port ih/il and oh/ol fields: the
high and low 32-bit halves of the accumulated ifInOctets/ifOutOctets
native 64-bit MIB counters. The server assembles them into uint64 and
stores them as rx_bytes/tx_bytes; the port series derive bps alongside
fps, so beacon switches report real bps in the traffic graph while
older beacons keep the frames/s fallback.

Closes #1535
Nacho 1 mese fa
parent
commit
362b6cf700

+ 27 - 16
server-go/internal/httpapi/beacon.go

@@ -34,11 +34,20 @@ import (
 // beaconPort: una boca del beacon. n = número 1..9; l = código de link
 // (0 down · 1 10M · 2 100M · 3 1G · 4 500M · 5 10G · 6 2.5G · 7 5G);
 // tx/rx = contadores acumulados de tramas good (uint32, decimal).
+// ih/il y oh/ol = mitades alta/baja de 32 bits de los octetos acumulados
+// ifInOctets/ifOutOctets (nativos de 64 bits del MIB del RTL837x,
+// gnacho/netpulse#1535, beacon del firmware a partir de v0.1.0-f25dfc6).
+// Ausentes (0) en beacons antiguos: la serie deriva fps de tramas y bps
+// solo cuando hay bytes.
 type beaconPort struct {
 	N  int    `json:"n"`
 	L  int    `json:"l"`
 	Tx uint32 `json:"tx"`
 	Rx uint32 `json:"rx"`
+	Ih uint32 `json:"ih,omitempty"`
+	Il uint32 `json:"il,omitempty"`
+	Oh uint32 `json:"oh,omitempty"`
+	Ol uint32 `json:"ol,omitempty"`
 }
 
 // beaconSFP: diagnóstico digital (DDM/DOM) de una boca óptica del beacon
@@ -58,18 +67,18 @@ type beaconSFP struct {
 // Ev (con Port/Mac) convierte el datagrama en EVENTO inmediato (spec v1.1:
 // loop, port_up, port_down, port_disabled, port_recovered).
 type beaconPacket struct {
-	V     int          `json:"v"` // versión de esquema; solo se acepta 1
-	Seq   uint32       `json:"seq"`
-	Slug  string       `json:"slug"`
-	Token string       `json:"token"`
-	Dev   string       `json:"dev,omitempty"`
-	Fw    string       `json:"fw,omitempty"`
-	Ev    string       `json:"ev,omitempty"`
+	V     int    `json:"v"` // versión de esquema; solo se acepta 1
+	Seq   uint32 `json:"seq"`
+	Slug  string `json:"slug"`
+	Token string `json:"token"`
+	Dev   string `json:"dev,omitempty"`
+	Fw    string `json:"fw,omitempty"`
+	Ev    string `json:"ev,omitempty"`
 	// Spec 2026-09 (gnacho/netpulse#865): el datagrama de estado puede
 	// traer firmware/uptime/MAC al final ("up": segundos desde el boot,
 	// "mac": MAC de gestión sin separadores). Opcionales; un beacon sin
 	// ellos sigue alimentándose del sondeo de consola (#639).
-	Up uint32 `json:"up,omitempty"`
+	Up    uint32       `json:"up,omitempty"`
 	Port  int          `json:"port,omitempty"`
 	Mac   string       `json:"mac,omitempty"`
 	Ports []beaconPort `json:"ports"`
@@ -191,14 +200,14 @@ func (s *server) ingestBeacon(src string, raw []byte) {
 			Kind: "external", Interval: beaconIntervalSec,
 			Data: probe.PayloadData{FDB: &probe.FDBData{MACs: macs, Ports: ports}},
 		}
-	// #865: conservar el System del último payload (del propio beacon, con
-	// fw/up/mac, o del sondeo de consola #639): el ingest FDB reemplaza el
-	// payload entero y sin esto los datos de sistema parpadean cada 5 min.
-	if prev, okPrev := s.agents.StalePayload(p.Slug); okPrev && prev != nil && prev.Data.System != nil {
-		fdbPayload.Data.System = prev.Data.System
-	} else {
-		s.attachRTLConsole(p.Slug, src, fdbPayload)
-	}
+		// #865: conservar el System del último payload (del propio beacon, con
+		// fw/up/mac, o del sondeo de consola #639): el ingest FDB reemplaza el
+		// payload entero y sin esto los datos de sistema parpadean cada 5 min.
+		if prev, okPrev := s.agents.StalePayload(p.Slug); okPrev && prev != nil && prev.Data.System != nil {
+			fdbPayload.Data.System = prev.Data.System
+		} else {
+			s.attachRTLConsole(p.Slug, src, fdbPayload)
+		}
 		s.agents.Ingest(fdbPayload)
 		s.persistAgentState(p.Slug, s.agents.Snapshot(p.Slug))
 		s.beaconSeqNote(p.Slug, p.Seq)
@@ -468,6 +477,8 @@ func (s *server) recordBeaconPortSamples(slug string, bps []beaconPort) {
 			RouterID:  slug,
 			PortID:    fmt.Sprintf("lan%d", bp.N),
 			TS:        now,
+			RxBytes:   uint64(bp.Ih)<<32 | uint64(bp.Il),
+			TxBytes:   uint64(bp.Oh)<<32 | uint64(bp.Ol),
 			RxFrames:  uint64(bp.Rx),
 			TxFrames:  uint64(bp.Tx),
 			SpeedMbps: speedMbps,

+ 40 - 0
server-go/internal/httpapi/beacon_test.go

@@ -137,6 +137,46 @@ func TestBeaconValidIngestOverUDP(t *testing.T) {
 	}
 }
 
+// gnacho/netpulse#1535: el beacon del firmware RTLPlayground (a partir de
+// v0.1.0-f25dfc6) añade por puerto ih/il y oh/ol, las mitades de 32 bits de
+// los octetos acumulados ifInOctets/ifOutOctets. El server los ensambla en
+// uint64 y los graba como bytes de la serie de puertos.
+func TestBeaconOctetsRecordBytes(t *testing.T) {
+	s, token := newBeaconTestServer(t)
+
+	addr, err := s.startBeaconListener("127.0.0.1:0")
+	if err != nil {
+		t.Fatalf("listener: %v", err)
+	}
+	defer s.beaconConn.Close()
+
+	// ih=1, il=500 → in-octets = 2^32+500; oh=0, ol=1000 → 1000.
+	sendUDP(t, addr, fmt.Sprintf(
+		`{"v":1,"seq":1,"slug":"switch16","token":"%s","ports":[{"n":3,"l":3,"tx":10,"rx":20,"ih":1,"il":500,"oh":0,"ol":1000}]}`,
+		token))
+	waitFresh(t, s, "switch16")
+
+	deadline := time.Now().Add(3 * time.Second)
+	var rx, tx uint64
+	for {
+		err := s.db.QueryRow(`SELECT rx_bytes, tx_bytes FROM port_series_raw
+			WHERE router_id = ? AND port_id = ?`, "switch16", "lan3").Scan(&rx, &tx)
+		if err == nil && (rx != 0 || tx != 0) {
+			break
+		}
+		if time.Now().After(deadline) {
+			t.Fatalf("serie de puertos sin bytes (err: %v, rx: %d, tx: %d)", err, rx, tx)
+		}
+		time.Sleep(50 * time.Millisecond)
+	}
+	if want := uint64(1)<<32 | 500; rx != want {
+		t.Fatalf("rx_bytes = %d, esperaba %d", rx, want)
+	}
+	if tx != 1000 {
+		t.Fatalf("tx_bytes = %d, esperaba 1000", tx)
+	}
+}
+
 // Spec 2026-09 (#865): el datagrama de estado puede traer fw/up/mac; el
 // server los convierte en System sin tocar el sondeo de consola (#639).
 func TestBeaconSystemFieldsFromStatusDatagram(t *testing.T) {

+ 23 - 0
server-go/internal/portseries/portseries.go

@@ -202,6 +202,7 @@ func (s *Store) getRaw(routerID, portID string, fromMs, toMs int64) ([]PortPoint
 		return nil, err
 	}
 	deriveFps(out)
+	deriveBps(out)
 	return out, nil
 }
 
@@ -229,6 +230,7 @@ func (s *Store) get5m(routerID, portID string, fromMs, toMs int64) ([]PortPoint,
 		return nil, err
 	}
 	deriveFps(out)
+	deriveBps(out)
 	return out, nil
 }
 
@@ -262,6 +264,7 @@ func (s *Store) getDaily(routerID, portID string, from, to time.Time) ([]PortPoi
 		return nil, err
 	}
 	deriveFps(out)
+	deriveBps(out)
 	return out, nil
 }
 
@@ -284,6 +287,26 @@ func deriveFps(pts []PortPoint) {
 	}
 }
 
+// deriveBps calcula bits/segundo entre puntos consecutivos a partir de los
+// contadores acumulados de bytes (gnacho/netpulse#1535: el beacon del
+// firmware RTLPlayground a partir de v0.1.0-f25dfc6 reporta
+// ifInOctets/ifOutOctets nativos de 64 bits). Mismo criterio que
+// deriveFps: un contador que baja (reset) no produce tasa en ese punto.
+func deriveBps(pts []PortPoint) {
+	for i := 1; i < len(pts); i++ {
+		dt := pts[i].TS.Sub(pts[i-1].TS).Seconds()
+		if dt <= 0 {
+			continue
+		}
+		if pts[i].RxBytes >= pts[i-1].RxBytes {
+			pts[i].RxBps = float64(pts[i].RxBytes-pts[i-1].RxBytes) * 8 / dt
+		}
+		if pts[i].TxBytes >= pts[i-1].TxBytes {
+			pts[i].TxBps = float64(pts[i].TxBytes-pts[i-1].TxBytes) * 8 / dt
+		}
+	}
+}
+
 // 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

+ 32 - 3
server-go/internal/portseries/portseries_test.go

@@ -240,9 +240,9 @@ func TestDeriveFps(t *testing.T) {
 	base := time.Now().Truncate(time.Second)
 	pts := []PortPoint{
 		{TS: base, RxFrames: 0, TxFrames: 0},
-		{TS: base.Add(30 * time.Second), RxFrames: 3000, TxFrames: 1500}, // 100 rx, 50 tx fps
-		{TS: base.Add(60 * time.Second), RxFrames: 6000, TxFrames: 3000}, // 100 rx, 50 tx fps
-		{TS: base.Add(90 * time.Second), RxFrames: 500, TxFrames: 100},   // reset: contador bajó
+		{TS: base.Add(30 * time.Second), RxFrames: 3000, TxFrames: 1500},  // 100 rx, 50 tx fps
+		{TS: base.Add(60 * time.Second), RxFrames: 6000, TxFrames: 3000},  // 100 rx, 50 tx fps
+		{TS: base.Add(90 * time.Second), RxFrames: 500, TxFrames: 100},    // reset: contador bajó
 		{TS: base.Add(120 * time.Second), RxFrames: 3500, TxFrames: 2100}, // 100 rx, 66.6 tx fps
 	}
 	deriveFps(pts)
@@ -265,6 +265,35 @@ func TestDeriveFps(t *testing.T) {
 	}
 }
 
+// #1535: deriveBps calcula bits/s entre muestras consecutivas desde los bytes
+// acumulados y deja a 0 el intervalo que cruza un reset del contador.
+func TestDeriveBps(t *testing.T) {
+	base := time.Now().Truncate(time.Second)
+	pts := []PortPoint{
+		{TS: base, RxBytes: 0, TxBytes: 0},
+		{TS: base.Add(30 * time.Second), RxBytes: 3_750_000, TxBytes: 1_875_000},  // 1 Mbps rx, 0.5 Mbps tx
+		{TS: base.Add(60 * time.Second), RxBytes: 7_500_000, TxBytes: 3_750_000},  // 1 Mbps rx, 0.5 Mbps tx
+		{TS: base.Add(90 * time.Second), RxBytes: 100, TxBytes: 50},               // reset: contador bajó
+		{TS: base.Add(120 * time.Second), RxBytes: 3_750_100, TxBytes: 1_875_050}, // 1 Mbps rx, 0.5 Mbps tx
+	}
+	deriveBps(pts)
+	if pts[0].RxBps != 0 || pts[0].TxBps != 0 {
+		t.Fatalf("primer punto debería tener bps 0: %+v", pts[0])
+	}
+	if pts[1].RxBps != 1_000_000 || pts[1].TxBps != 500_000 {
+		t.Fatalf("punto 1: rx=%.0f tx=%.0f, esperaba 1000000/500000", pts[1].RxBps, pts[1].TxBps)
+	}
+	if pts[2].RxBps != 1_000_000 || pts[2].TxBps != 500_000 {
+		t.Fatalf("punto 2: rx=%.0f tx=%.0f, esperaba 1000000/500000", pts[2].RxBps, pts[2].TxBps)
+	}
+	if pts[3].RxBps != 0 || pts[3].TxBps != 0 {
+		t.Fatalf("punto 3 (reset) debería tener bps 0: %+v", pts[3])
+	}
+	if pts[4].RxBps != 1_000_000 || pts[4].TxBps != 500_000 {
+		t.Fatalf("punto 4: rx=%.0f tx=%.0f, esperaba 1000000/500000", pts[4].RxBps, pts[4].TxBps)
+	}
+}
+
 // 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) {