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

feat(topology): colector FDB live — puertos cableados e inferencia de switches/hipervisores

- inferTopology (función pura): puerto 1 MAC = cableado directo (Device.Port);
  puerto multi-MAC = DistributionNode (OUI heterogéneo = inferred, OUI
  hipervisor + host único = hypervisor con VMs anidadas)
- Exclusiones: bridge MAC de routers/APs, clientes de otros routers (uplink),
  wifi; puerto wan ignorado
- 5 tests nuevos (directo, switch inferido, hipervisor, exclusiones, wan)
gnacho 4 месяцев назад
Родитель
Сommit
5f7d72aed2

+ 4 - 1
server-go/internal/adapters/live.go

@@ -951,6 +951,8 @@ func (l *Live) buildOverview(ctx context.Context) (*Overview, error) {
 		routerList = append(routerList, router)
 	}
 	devices := l.buildDevices(polled)
+	// Topología v5: puertos FDB + switches/hipervisores inferidos
+	devices, distNodes := inferTopology(polled, devices)
 	// Aviso de señal débil (< -70 dBm): una alerta por dispositivo y día
 	for _, d := range devices {
 		if d.Online && d.SignalDbm != nil && *d.SignalDbm < -70 {
@@ -1038,7 +1040,8 @@ func (l *Live) buildOverview(ctx context.Context) (*Overview, error) {
 			Total: len(devices), Online: online, KnownOffline: len(devices) - online, NewToday: 0,
 		},
 		TopDevices: top, Alerts: alertsCopy, UnreadAlerts: unread,
-		Ts: time.Now().Unix(),
+		DistributionNodes: distNodes,
+		Ts:                time.Now().Unix(),
 	}, nil
 }
 

+ 153 - 0
server-go/internal/adapters/topology.go

@@ -0,0 +1,153 @@
+package adapters
+
+import (
+	"fmt"
+	"sort"
+	"strings"
+)
+
+// ---------------------------------------------------------------------------
+// Inferencia de topología v5 (FDB): puertos físicos, switches/bridges e
+// hipervisores. Función pura (sin SSH ni BD) para ser testeable.
+//
+// Reglas (plan 2-Ago-2026):
+//   - Un puerto físico (lanN) con UNA MAC aprendida = cableado directo →
+//     Device.Port.
+//   - Un puerto con VARIAS MACs = algo multiplexándolo (switch, hipervisor,
+//     PLC…). El FDB no dice qué: OUI heterogéneo → "inferred" (círculo
+//     dashed, sin afirmar); alguna MAC con OUI de hipervisor y exactamente
+//     un host → "hypervisor" (sus VMs se anidan bajo el host).
+//   - Se excluyen las MACs de los propios routers (su bridge br-lan) y las
+//     de clientes atribuidos a OTROS routers (los clientes wifi de un AP
+//     aparecen en el FDB del gateway por el puerto del uplink).
+// ---------------------------------------------------------------------------
+
+// hypervisorOUI: prefijos de MAC de hipervisores conocidos.
+var hypervisorOUI = []string{
+	"BC:24:11", // Proxmox VE
+	"00:50:56", // VMware (ESXi/Workstation)
+	"00:0C:29", // VMware
+	"00:15:5D", // Hyper-V
+	"52:54:00", // KVM/QEMU
+}
+
+func isHypervisorMAC(mac string) bool {
+	for _, p := range hypervisorOUI {
+		if strings.HasPrefix(mac, p) {
+			return true
+		}
+	}
+	return false
+}
+
+// inferTopology enriquece devices con Port/AttachTo e infiere los
+// DistributionNode del FDB sondeado. `polled` lleva fdb (MAC→puerto, ya
+// filtrado a lanN/wan por parseBridgeFdb) y brMac por router.
+func inferTopology(polled map[string]*routerPolled, devices []Device) ([]Device, []DistributionNode) {
+	byMAC := make(map[string]int, len(devices))
+	for i, d := range devices {
+		byMAC[d.MAC] = i
+	}
+	routerMACs := map[string]bool{}
+	for _, p := range polled {
+		if p.brMac != "" {
+			routerMACs[p.brMac] = true
+		}
+	}
+
+	var dists []DistributionNode
+	// routers en orden determinista (el mapa polled no lo es)
+	routerIDs := make([]string, 0, len(polled))
+	for id := range polled {
+		routerIDs = append(routerIDs, id)
+	}
+	sort.Strings(routerIDs)
+
+	for _, routerID := range routerIDs {
+		p := polled[routerID]
+		// invertir fdb: puerto → MACs (el WAN no es distribución LAN)
+		byPort := map[string][]string{}
+		for mac, port := range p.fdb {
+			if port == "wan" {
+				continue
+			}
+			byPort[port] = append(byPort[port], mac)
+		}
+		ports := make([]string, 0, len(byPort))
+		for port := range byPort {
+			ports = append(ports, port)
+		}
+		sort.Strings(ports)
+
+		for _, port := range ports {
+			var kept []string
+			for _, mac := range byPort[port] {
+				if routerMACs[mac] {
+					continue // el propio router/AP no es un cliente
+				}
+				if idx, ok := byMAC[mac]; ok {
+					d := devices[idx]
+					if d.RouterID != routerID {
+						continue // cliente de otro router (visto por el uplink)
+					}
+					if d.Band != "cable" && d.Band != "—" {
+						continue // wifi no cuelga de un puerto físico
+					}
+				}
+				kept = append(kept, mac)
+			}
+			if len(kept) == 0 {
+				continue
+			}
+			setPort := func() {
+				for _, mac := range kept {
+					if idx, ok := byMAC[mac]; ok && devices[idx].RouterID == routerID {
+						devices[idx].Port = port
+					}
+				}
+			}
+			if len(kept) == 1 {
+				// cableado directo: puerto conocido, sin nodo de distribución
+				setPort()
+				continue
+			}
+
+			// puerto multi-MAC → nodo de distribución
+			setPort()
+			id := fmt.Sprintf("dist-%s-%s", routerID, port)
+			var vmMACs, hostMACs []string
+			for _, mac := range kept {
+				if isHypervisorMAC(mac) {
+					vmMACs = append(vmMACs, mac)
+				} else {
+					hostMACs = append(hostMACs, mac)
+				}
+			}
+			if len(vmMACs) > 0 && len(hostMACs) == 1 {
+				if hidx, ok := byMAC[hostMACs[0]]; ok && devices[hidx].RouterID == routerID {
+					// hipervisor con host identificado: VMs anidadas bajo él
+					dists = append(dists, DistributionNode{
+						ID: id, Kind: "hypervisor", RouterID: routerID, Port: port,
+						MacCount: len(kept), HostDeviceID: devices[hidx].ID, Name: devices[hidx].Name,
+					})
+					for _, mac := range vmMACs {
+						if idx, ok := byMAC[mac]; ok && devices[idx].RouterID == routerID {
+							devices[idx].AttachTo = devices[hidx].ID
+						}
+					}
+					continue
+				}
+			}
+			// OUI heterogéneo (o hipervisor ambiguo sin host claro): inferido
+			dists = append(dists, DistributionNode{
+				ID: id, Kind: "inferred", RouterID: routerID, Port: port, MacCount: len(kept),
+			})
+			for _, mac := range kept {
+				if idx, ok := byMAC[mac]; ok && devices[idx].RouterID == routerID {
+					devices[idx].AttachTo = id
+				}
+			}
+		}
+	}
+	return devices, dists
+}

+ 120 - 0
server-go/internal/adapters/topology_test.go

@@ -0,0 +1,120 @@
+package adapters
+
+import "testing"
+
+// FDB/port helpers para los tests de inferencia.
+func polledWithFDB(routerID, brMac string, fdb map[string]string) map[string]*routerPolled {
+	return map[string]*routerPolled{
+		routerID: {cfg: RouterConfig{ID: routerID}, brMac: brMac, fdb: fdb},
+	}
+}
+
+func dev(mac, routerID, band string) Device {
+	return Device{ID: "d-" + mac, MAC: mac, RouterID: routerID, Band: band, Online: true}
+}
+
+func TestInferTopologyCableadoDirecto(t *testing.T) {
+	polled := polledWithFDB("flint2", "94:83:C4:00:00:01", map[string]string{
+		"00:11:32:9C:51:B7": "lan1",
+	})
+	devices := []Device{dev("00:11:32:9C:51:B7", "flint2", "cable")}
+	devices, dists := inferTopology(polled, devices)
+	if len(dists) != 0 {
+		t.Fatalf("no debería haber distnodes: %+v", dists)
+	}
+	if devices[0].Port != "lan1" {
+		t.Fatalf("port: %q", devices[0].Port)
+	}
+	if devices[0].AttachTo != "" {
+		t.Fatalf("attachTo debería estar vacío: %q", devices[0].AttachTo)
+	}
+}
+
+func TestInferTopologySwitchInferido(t *testing.T) {
+	polled := polledWithFDB("flint2", "94:83:C4:00:00:01", map[string]string{
+		"78:2B:CB:AA:01:01": "lan3",
+		"8C:EA:48:AA:02:02": "lan3",
+		"3C:D9:2B:AA:03:03": "lan3",
+	})
+	devices := []Device{
+		dev("78:2B:CB:AA:01:01", "flint2", "cable"),
+		dev("8C:EA:48:AA:02:02", "flint2", "cable"),
+		// la 3ª MAC es desconocida (sin device): solo cuenta en macCount
+	}
+	devices, dists := inferTopology(polled, devices)
+	if len(dists) != 1 {
+		t.Fatalf("distnodes: %+v", dists)
+	}
+	dn := dists[0]
+	if dn.ID != "dist-flint2-lan3" || dn.Kind != "inferred" || dn.RouterID != "flint2" || dn.Port != "lan3" || dn.MacCount != 3 {
+		t.Fatalf("distnode: %+v", dn)
+	}
+	for _, d := range devices {
+		if d.AttachTo != "dist-flint2-lan3" {
+			t.Fatalf("attachTo de %s: %q", d.MAC, d.AttachTo)
+		}
+		if d.Port != "lan3" {
+			t.Fatalf("port de %s: %q", d.MAC, d.Port)
+		}
+	}
+}
+
+func TestInferTopologyHipervisor(t *testing.T) {
+	polled := polledWithFDB("flint2", "94:83:C4:00:00:01", map[string]string{
+		"3C:52:82:10:20:30": "lan2", // host (OUI normal)
+		"BC:24:11:00:20:10": "lan2", // CT1 (OUI Proxmox)
+		"BC:24:11:00:20:11": "lan2", // CT2
+	})
+	devices := []Device{
+		dev("3C:52:82:10:20:30", "flint2", "cable"),
+		dev("BC:24:11:00:20:10", "flint2", "cable"),
+		dev("BC:24:11:00:20:11", "flint2", "cable"),
+	}
+	devices, dists := inferTopology(polled, devices)
+	if len(dists) != 1 {
+		t.Fatalf("distnodes: %+v", dists)
+	}
+	dn := dists[0]
+	hostID := devices[0].ID
+	if dn.Kind != "hypervisor" || dn.HostDeviceID != hostID || dn.MacCount != 3 {
+		t.Fatalf("distnode hipervisor: %+v", dn)
+	}
+	if devices[0].AttachTo != "" {
+		t.Fatalf("el host cuelga del router, no del distnode: %q", devices[0].AttachTo)
+	}
+	for _, d := range devices[1:] {
+		if d.AttachTo != hostID {
+			t.Fatalf("CT %s attachTo: %q (esperaba host %s)", d.MAC, d.AttachTo, hostID)
+		}
+	}
+}
+
+func TestInferTopologyExclusiones(t *testing.T) {
+	polled := polledWithFDB("flint2", "94:83:C4:00:00:01", map[string]string{
+		"94:83:C4:00:00:02": "lan1", // bridge MAC de un AP (no es cliente)
+		"F2:6D:19:A8:44:C2": "lan1", // cliente wifi del AP (otro routerId)
+	})
+	// El AP también aparece en polled con su propia brMac
+	polled["living"] = &routerPolled{cfg: RouterConfig{ID: "living"}, brMac: "94:83:C4:00:00:02", fdb: map[string]string{}}
+	devices := []Device{
+		dev("F2:6D:19:A8:44:C2", "living", "5 GHz"),
+	}
+	devices, dists := inferTopology(polled, devices)
+	if len(dists) != 0 {
+		t.Fatalf("no debería inferir nada del uplink: %+v", dists)
+	}
+	if devices[0].Port != "" || devices[0].AttachTo != "" {
+		t.Fatalf("cliente wifi del AP tocado: port=%q attachTo=%q", devices[0].Port, devices[0].AttachTo)
+	}
+}
+
+func TestInferTopologyWanIgnorado(t *testing.T) {
+	polled := polledWithFDB("flint2", "94:83:C4:00:00:01", map[string]string{
+		"A0:B1:C2:D3:E4:F5": "wan",
+		"A0:B1:C2:D3:E4:F6": "wan",
+	})
+	devices, dists := inferTopology(polled, nil)
+	if len(dists) != 0 || len(devices) != 0 {
+		t.Fatalf("el puerto WAN no genera distribución: %+v %+v", dists, devices)
+	}
+}