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

feat(topology): real uplink evidence, inferred leaf switches, hover card dedupe (#1325)

Refs #1325. TopoLink.Evidence (device/fdb/lldp/override) drives the uplink label; managed switches infer leaf nodes behind non-uplink ports with 2+ wired clients; switch hover cards dedupe the same-peer line. Items 1-2 of the issue stay open pending the fleet retest.
Nacho 1 месяц назад
Родитель
Сommit
b6ea1f858d

+ 10 - 2
app/src/components/topology/TopologyMap.tsx

@@ -291,7 +291,10 @@ function TooltipCard({
             <span className="font-display text-sm font-semibold text-text-primary">
               {tip.node.name ?? t('topology.dist.managed')}
             </span>
-            <StatusPill tone="accent" label="LLDP" />
+            {/* #1325: la procedencia se alinea con la evidencia real del nodo
+                (LLDP si el router lo vio anunciarse; si no, el integrador).
+                Antes era "LLDP" en todas las cajas gestionadas. */}
+            <StatusPill tone="accent" label={distBadge(tip.node) || t('topology.dist.managed')} />
           </div>
           <div className="mt-0.5 text-caption text-text-muted">
             {[tip.node.ip, portName(tip.node.port, tip.node.portLabel)].filter(Boolean).join(' · ')}
@@ -300,7 +303,12 @@ function TooltipCard({
             <MiniStat label={t('topology.dist.port', { owner: portOwnerName(tip.node) })} value={portName(tip.node.port, tip.node.portLabel)} />
             <MiniStat label={t('topology.dist.macs')} value={String(tip.node.macCount)} />
           </div>
-          {tip.node.lldp && (
+          {/* #1325 (item 1): work-around defensivo. La label del distnode
+              (name/ip) y la del puerto (lldp.chassis/mgmt) resuelven al MISMO
+              vecino por vías distintas; si el chasis LLDP repite el nombre del
+              nodo, se pinta UNA sola línea (el nombre ya identifica al peer).
+              Mientras el server no unifique las dos vías. */}
+          {tip.node.lldp && tip.node.lldp.chassis !== tip.node.name && (
             <div className="mt-2 text-caption font-semibold text-accent">
               {t('topology.lldpIdentified', {
                 chassis: tip.node.lldp.chassis ?? '—',

+ 22 - 1
app/src/components/topology/model.ts

@@ -679,6 +679,27 @@ function flowFor(mbps: number, alive = false): { packets: number; packetDur: num
   return { packets, packetDur: Math.max(1.6, 5 - mbps / 12) }
 }
 
+/**
+ * Tag de evidencia real del uplink (#1325). El server manda `evidence` por
+ * enlace; el front ya no decide el "· LLDP" por node.router.lldp (heurístico
+ * del router), que podía etiquetar "LLDP" un enlace resuelto por FDB/device.
+ * Vacía = fallback al gateway (sin evidencia, sin tag).
+ */
+function evidenceTag(evidence?: string): string {
+  switch (evidence) {
+    case 'lldp':
+      return ' · LLDP'
+    case 'fdb':
+      return ' · FDB'
+    case 'device':
+      return ' · device'
+    case 'override':
+      return ' · manual'
+    default:
+      return ''
+  }
+}
+
 // ---------------------------------------------------------------------------
 // Builder
 // ---------------------------------------------------------------------------
@@ -1436,7 +1457,7 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
               : `${sl.speedMbps} Mbps`)
             : '1G'
           const portSuffix = sl.port ? ` · ${sl.port}` : ''
-          const label = isWifi ? 'WiFi uplink' : `Cable ${speedText}${node.router.lldp ? ' · LLDP' : ''}${portSuffix}`
+          const label = isWifi ? 'WiFi uplink' : `Cable ${speedText}${evidenceTag(sl.evidence)}${portSuffix}`
           // #1047: el padre lo decide la semántica (FDB del switch cuando no
           // hay LLDP); solo se cae al gateway si el server no lo resolvió.
           // #1060: el padre puede ser un distnode (círculo inferido/gestionado):

+ 6 - 0
app/src/data/types.ts

@@ -433,6 +433,12 @@ export interface TopoSemLink {
   port?: string
   /** velocidad negociada en la boca del padre (Mbps), 0/ausente = sin dato (#1321) */
   speedMbps?: number
+  /**
+   * Evidencia real que resolvió el uplink del hijo (#1325): "override" |
+   * "lldp" | "device" | "fdb". Ausente/vacía = fallback al gateway (sin
+   * evidencia: el front no pinta tag). Solo en enlaces kind='uplink'.
+   */
+  evidence?: string
 }
 
 /**

+ 10 - 1
server-go/internal/adapters/topo_semantics.go

@@ -383,12 +383,18 @@ func BuildTopoSemantics(routers []Router, devices []Device, wg WireGuardStats, d
 		}
 	}
 	uplinkEvidence := map[string]topoParent{}
+	// uplinkSource (#1325): qué capa fijó el padre de cada unidad de flota,
+	// para exponer la evidencia real por enlace (el front ya no decide el tag
+	// "LLDP" por node.router.lldp). Valores canónicos: "device"/"fdb"/"lldp"/
+	// "override". Vacío = fallback al gateway (sin evidencia, sin tag).
+	uplinkSource := map[string]string{}
 	filtered := online[:0]
 	for _, d := range online {
 		if rid, ok := routerMacs[strings.ToUpper(d.MAC)]; ok {
 			if rid != d.RouterID {
 				if _, seen := uplinkEvidence[rid]; !seen {
 					uplinkEvidence[rid] = topoParent{parent: d.RouterID, port: d.Port}
+					uplinkSource[rid] = "device"
 				}
 			}
 			continue
@@ -402,6 +408,7 @@ func BuildTopoSemantics(routers []Router, devices []Device, wg WireGuardStats, d
 	for rid, ev := range fdbEvidence {
 		if _, ok := uplinkEvidence[rid]; !ok {
 			uplinkEvidence[rid] = ev
+			uplinkSource[rid] = "fdb"
 		}
 	}
 	// #1279: el LLDP es ground truth (dos equipos que se anuncian por el
@@ -411,6 +418,7 @@ func BuildTopoSemantics(routers []Router, devices []Device, wg WireGuardStats, d
 	for rid, ev := range lldpEvidence {
 		if ev.parent != rid {
 			uplinkEvidence[rid] = ev
+			uplinkSource[rid] = "lldp"
 		}
 	}
 	// #1321: el attach manual (#142) sobre la MAC bridge de una unidad de
@@ -426,6 +434,7 @@ func BuildTopoSemantics(routers []Router, devices []Device, wg WireGuardStats, d
 			}
 		}
 		uplinkEvidence[rid] = ev
+		uplinkSource[rid] = "override"
 	}
 	// #1042: el equipo aguas arriba del gateway (módem/ONT del ISP) se
 	// descubre por ARP como un cliente más, pero vive en el lado WAN: si su
@@ -538,7 +547,7 @@ func BuildTopoSemantics(routers []Router, devices []Device, wg WireGuardStats, d
 				}
 			}
 		}
-		sem.Links = append(sem.Links, TopoLink{From: from, To: ap.ID, Kind: "uplink", Port: port})
+		sem.Links = append(sem.Links, TopoLink{From: from, To: ap.ID, Kind: "uplink", Port: port, Evidence: uplinkSource[ap.ID]})
 	}
 	// router → distnode (solo inferred|managed son hubs propios en el mapa).
 	// En una cadena LLDP switch→switch (issue #300) el distnode cuelga de su

+ 30 - 11
server-go/internal/adapters/topo_semantics_test.go

@@ -251,11 +251,11 @@ func TestTopoSemanticsFdbUplinkParent(t *testing.T) {
 			links[l.To] = l
 		}
 	}
-	if got := links["sw1"]; got.From != "gw" || got.Port != "1" {
-		t.Fatalf("uplink sw1: %+v, want from gw puerto 1", got)
+	if got := links["sw1"]; got.From != "gw" || got.Port != "1" || got.Evidence != "device" {
+		t.Fatalf("uplink sw1: %+v, want from gw puerto 1 evidencia device", got)
 	}
-	if got := links["ap1"]; got.From != "sw1" || got.Port != "5" {
-		t.Fatalf("uplink ap1: %+v, want from sw1 puerto 5", got)
+	if got := links["ap1"]; got.From != "sw1" || got.Port != "5" || got.Evidence != "device" {
+		t.Fatalf("uplink ap1: %+v, want from sw1 puerto 5 evidencia device", got)
 	}
 	// Las unidades de flota no duplican como chips de cliente.
 	for _, ring := range sem.Rings {
@@ -289,11 +289,11 @@ func TestTopoSemanticsFdbEvidenceSinDevices(t *testing.T) {
 			links[l.To] = l
 		}
 	}
-	if got := links["ap1"]; got.From != "sw1" || got.Port != "5" {
-		t.Fatalf("uplink ap1: %+v, want from sw1 puerto 5", got)
+	if got := links["ap1"]; got.From != "sw1" || got.Port != "5" || got.Evidence != "fdb" {
+		t.Fatalf("uplink ap1: %+v, want from sw1 puerto 5 evidencia fdb", got)
 	}
-	if got := links["sw1"]; got.From != "gw" || got.Port != "1" {
-		t.Fatalf("uplink sw1: %+v, want from gw puerto 1", got)
+	if got := links["sw1"]; got.From != "gw" || got.Port != "1" || got.Evidence != "fdb" {
+		t.Fatalf("uplink sw1: %+v, want from gw puerto 1 evidencia fdb", got)
 	}
 }
 
@@ -311,7 +311,7 @@ func TestTopoSemanticsDeviceEvidenceManda(t *testing.T) {
 	sem := BuildTopoSemantics(routers, devices, WireGuardStats{}, nil, "", ev, nil, nil)
 	for _, l := range sem.Links {
 		if l.Kind == "uplink" && l.To == "ap1" {
-			if l.From != "gw" || l.Port != "4" {
+			if l.From != "gw" || l.Port != "4" || l.Evidence != "device" {
 				t.Fatalf("la evidencia de device debe mandar: %+v", l)
 			}
 			return
@@ -562,7 +562,7 @@ func TestTopoSemanticsLldpEvidenceWins(t *testing.T) {
 	sem := BuildTopoSemantics(routers, nil, WireGuardStats{}, nil, "", fdb, lldp, nil)
 	for _, l := range sem.Links {
 		if l.Kind == "uplink" && l.To == "ap1" {
-			if l.From != "sw1" || l.Port != "two-gigabitEthernet 1/0/21" {
+			if l.From != "sw1" || l.Port != "two-gigabitEthernet 1/0/21" || l.Evidence != "lldp" {
 				t.Fatalf("LLDP debe mandar sobre la FDB: %+v", l)
 			}
 			return
@@ -584,7 +584,7 @@ func TestTopoSemanticsOverrideEvidenceWins(t *testing.T) {
 	sem := BuildTopoSemantics(routers, nil, WireGuardStats{}, nil, "", nil, lldp, ovr)
 	for _, l := range sem.Links {
 		if l.Kind == "uplink" && l.To == "ap1" {
-			if l.From != "sw1" || l.Port != "lan4" {
+			if l.From != "sw1" || l.Port != "lan4" || l.Evidence != "override" {
 				t.Fatalf("el override debe mandar conservando el puerto inferido: %+v", l)
 			}
 			return
@@ -592,3 +592,22 @@ func TestTopoSemanticsOverrideEvidenceWins(t *testing.T) {
 	}
 	t.Fatal("falta el uplink de ap1")
 }
+
+// #1325: sin evidencia de ninguna capa el uplink cae al gateway y no lleva
+// tag de evidencia (Evidence vacía). El fallback al gateway no es evidencia.
+func TestTopoSemanticsFallbackSinEvidencia(t *testing.T) {
+	routers := []Router{
+		{ID: "gw", Name: "gateway", RoleBadge: "Principal", MAC: "AA:BB:CC:00:00:01"},
+		{ID: "ap1", Name: "ap1", MAC: "AA:BB:CC:00:00:03"},
+	}
+	sem := BuildTopoSemantics(routers, nil, WireGuardStats{}, nil, "", nil, nil, nil)
+	for _, l := range sem.Links {
+		if l.Kind == "uplink" && l.To == "ap1" {
+			if l.From != "gw" || l.Evidence != "" {
+				t.Fatalf("uplink ap1 sin evidencia: %+v, want from gw y Evidence vacía", l)
+			}
+			return
+		}
+	}
+	t.Fatal("falta el uplink de ap1")
+}

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

@@ -93,6 +93,28 @@ func keptMacsForPort(portMACs []string, routerID string, byMAC map[string]int, d
 	return kept
 }
 
+// leafSwitchClients (#1325): MACs de un puerto del FDB de un SWITCH gestionado
+// que cuentan como clientes para el umbral de switch hoja (>= 2). Excluye las
+// bridge-MACs de la flota y los clientes wifi conocidos (los de un AP que
+// transitan por el switch). A diferencia de keptMacsForPort, NO filtra por
+// RouterID: los clientes cableados de un switch se atribuyen al DHCP server
+// (casi siempre el gateway), no al switch, y aquí importa el enlace físico.
+func leafSwitchClients(portMACs []string, byMAC map[string]int, devices []Device, routerMACs map[string]bool) []string {
+	kept := make([]string, 0, len(portMACs))
+	for _, mac := range portMACs {
+		if routerMACs[mac] {
+			continue
+		}
+		if idx, ok := byMAC[mac]; ok {
+			if devices[idx].Band != "cable" && devices[idx].Band != "—" {
+				continue
+			}
+		}
+		kept = append(kept, mac)
+	}
+	return kept
+}
+
 // hypervisorHostMAC: MAC del host de un hipervisor claro en `kept` (MACs OUI
 // de hipervisor + exactamente un host normal, siendo ese host un Device del
 // router). Vacío+false si el puerto no es un hipervisor claro.
@@ -383,6 +405,81 @@ func inferTopology(polled map[string]*routerPolled, devices []Device) ([]Device,
 		}
 	}
 
+	// #1325: switches hoja inferidos tras switches gestionados. Un switch
+	// gestionado (distnode kind="managed") aprende en SU FDB los clientes
+	// cableados de un switch hoja no gestionado: cada puerto que NO sea su
+	// uplink (root port, donde aprende la bridge-MAC del gateway) y que
+	// aprenda >= 2 clientes cableados -> nodo inferido hoja anclado al switch
+	// (Parent) para que cuelgue de él en el mapa, no del router. Los APs
+	// (no-switch) siguen excluidos: su puerto multi-MAC es su propio uplink.
+	// La fase FDB no los veía porque keptMacsForPort filtra por RouterID y
+	// los clientes de un switch se atribuyen al DHCP server (el gateway).
+	if gatewayID != "" {
+		switchIDByMac := map[string]string{}
+		for id, p := range polled {
+			if p != nil && p.brMac != "" && p.cfg.Type == "managed-switch" {
+				switchIDByMac[strings.ToUpper(p.brMac)] = id
+			}
+		}
+		gwMac := ""
+		if gw := polled[gatewayID]; gw != nil {
+			gwMac = strings.ToUpper(gw.brMac)
+		}
+		var managed []DistributionNode
+		for _, dn := range dists {
+			if dn.Kind == "managed" && dn.Mac != "" {
+				managed = append(managed, dn)
+			}
+		}
+		for _, dn := range managed {
+			switchID, ok := switchIDByMac[strings.ToUpper(dn.Mac)]
+			if !ok {
+				continue
+			}
+			p := polled[switchID]
+			if p == nil {
+				continue
+			}
+			rootPort := ""
+			if gwMac != "" {
+				rootPort = p.fdb[gwMac]
+			}
+			byPort := fdbByPort(p.fdb)
+			ports := make([]string, 0, len(byPort))
+			for port := range byPort {
+				ports = append(ports, port)
+			}
+			sort.Strings(ports)
+			for _, port := range ports {
+				if port == rootPort {
+					continue // uplink del propio switch (bucle)
+				}
+				if lldpHandled[switchID][port] {
+					continue
+				}
+				occupied := false
+				for _, d2 := range dists {
+					if d2.RouterID == switchID && d2.Port == port && (d2.Kind == "managed" || d2.Kind == "inferred") {
+						occupied = true
+						break
+					}
+				}
+				if occupied {
+					continue // el puerto ya tiene distnode managed/inferred
+				}
+				kept := leafSwitchClients(byPort[port], byMAC, devices, routerMACs)
+				if len(kept) < 2 {
+					continue
+				}
+				id := fmt.Sprintf("dist-%s-%s", switchID, port)
+				dists = append(dists, DistributionNode{
+					ID: id, Kind: "inferred", RouterID: switchID, Port: port,
+					PortLabel: portLabel(p, port), MacCount: len(kept), Parent: dn.ID,
+				})
+			}
+		}
+	}
+
 	// Post-paso LLDP: un vecino cuya chassis-MAC es un Device conocido lo
 	// identifica (Device.Lldp), en el puerto que sea y aunque no multiplexe.
 	for _, routerID := range routerIDs {

+ 96 - 0
server-go/internal/adapters/topology_lldp_test.go

@@ -241,3 +241,99 @@ func TestTopoSemanticsCadenaLldp(t *testing.T) {
 		t.Fatalf("dist links:\n got: %+v\nwant: %+v", gotDist, wantDist)
 	}
 }
+
+// #1325: un switch gestionado (distnode managed) con un puerto NO-uplink que
+// aprende >= 2 clientes cableados -> nodo inferido hoja anclado al switch
+// (Parent). El uplink (root port), los puertos ya resueltos por LLDP y las
+// MACs de la propia flota no generan nodo hoja. Los clientes se atribuyen al
+// gateway (DHCP), no al switch: la fase FDB (keptMacsForPort) no los veía por
+// su filtro de RouterID; la nueva fase usa leafSwitchClients, sin ese filtro.
+func TestInferTopologySwitchHojaTrasGestionado(t *testing.T) {
+	gw := &routerPolled{cfg: RouterConfig{ID: "flint2", IsGateway: true}, brMac: "94:83:C4:00:00:01",
+		fdb: map[string]string{
+			macGS308E: "lan3", "04:D4:C4:8B:30:A7": "lan3", "DC:A6:32:4F:77:02": "lan3",
+		},
+		lldp: []LldpNeighbor{{Port: "lan3", Chassis: "GS308E", ChassisMac: macGS308E, Mgmt: "192.168.8.13", Caps: []string{"Bridge"}, PortDesc: "ge5"}},
+	}
+	gwDevices := []Device{
+		dev("04:D4:C4:8B:30:A7", "flint2", "cable"),
+		dev("DC:A6:32:4F:77:02", "flint2", "cable"),
+	}
+	swCfg := RouterConfig{ID: "swA", Name: "GS308E", Type: "managed-switch", AgentOnly: true}
+	managedRoot := distSummary{id: "dist-flint2-lan3", kind: "managed", routerID: "flint2", port: "lan3", mac: macGS308E, name: "GS308E", ip: "192.168.8.13", macCount: 2}
+
+	tests := []struct {
+		name    string
+		swFdb   map[string]string
+		swLldp  []LldpNeighbor
+		devices []Device
+		want    []distSummary
+	}{
+		{
+			name:  "hoja en puerto no-uplink",
+			swFdb: map[string]string{"94:83:C4:00:00:01": "ge1", "10:20:30:40:50:60": "ge3", "10:20:30:40:50:61": "ge3"},
+			devices: []Device{
+				dev("10:20:30:40:50:60", "flint2", "cable"),
+				dev("10:20:30:40:50:61", "flint2", "cable"),
+			},
+			want: []distSummary{
+				managedRoot,
+				{id: "dist-swA-ge3", kind: "inferred", routerID: "swA", port: "ge3", parent: "dist-flint2-lan3", macCount: 2},
+			},
+		},
+		{
+			// El uplink (root port) también aprende clientes en tránsito, pero
+			// es el puerto hacia el núcleo: no es un switch hoja.
+			name:  "uplink del switch no genera hoja",
+			swFdb: map[string]string{"94:83:C4:00:00:01": "ge1", "10:20:30:40:50:60": "ge1", "10:20:30:40:50:61": "ge1"},
+			devices: []Device{
+				dev("10:20:30:40:50:60", "flint2", "cable"),
+				dev("10:20:30:40:50:61", "flint2", "cable"),
+			},
+			want: []distSummary{managedRoot},
+		},
+		{
+			// El puerto ya tiene distnode managed (switch→switch por LLDP): no
+			// se duplica con un nodo hoja.
+			name:   "puerto ya resuelto por LLDP no duplica",
+			swFdb:  map[string]string{"94:83:C4:00:00:01": "ge1", macLGS352: "ge5", "10:20:30:40:50:60": "ge5"},
+			swLldp: []LldpNeighbor{{Port: "ge5", Chassis: "LGS352C", ChassisMac: macLGS352, Mgmt: "192.168.8.20", Caps: []string{"Bridge"}, PortDesc: "ge1"}},
+			devices: []Device{
+				dev(macLGS352, "swA", "cable"),
+				dev("10:20:30:40:50:60", "swA", "cable"),
+			},
+			want: []distSummary{
+				managedRoot,
+				{id: "dist-swA-ge5", kind: "managed", routerID: "swA", port: "ge5", parent: "dist-flint2-lan3", mac: macLGS352, name: "LGS352C", ip: "192.168.8.20", macCount: 2},
+			},
+		},
+		{
+			// La bridge-MAC de otro router de la flota no es un cliente: con un
+			// solo cliente cableado el umbral (>= 2) no se alcanza.
+			name:  "MACs de flota no cuentan",
+			swFdb: map[string]string{"94:83:C4:00:00:01": "ge1", "94:83:C4:00:00:02": "ge3", "10:20:30:40:50:60": "ge3"},
+			devices: []Device{
+				dev("10:20:30:40:50:60", "flint2", "cable"),
+			},
+			want: []distSummary{managedRoot},
+		},
+	}
+
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			polled := map[string]*routerPolled{
+				"flint2": gw,
+				"swA":    {cfg: swCfg, brMac: macGS308E, fdb: tt.swFdb, lldp: tt.swLldp},
+			}
+			if tt.name == "MACs de flota no cuentan" {
+				polled["ap1"] = &routerPolled{cfg: RouterConfig{ID: "ap1"}, brMac: "94:83:C4:00:00:02", fdb: map[string]string{}}
+			}
+			devices := append(append([]Device{}, gwDevices...), tt.devices...)
+			_, dists := inferTopology(polled, devices)
+			got := summarizeDists(dists)
+			if !reflect.DeepEqual(got, tt.want) {
+				t.Fatalf("dists:\n got: %+v\nwant: %+v", got, tt.want)
+			}
+		})
+	}
+}

+ 4 - 0
server-go/internal/adapters/types.go

@@ -426,6 +426,10 @@ type TopoLink struct {
 	// el padre es un switch sondeado y su EthPort da la velocidad negociada.
 	// 0 = desconocida (el front pinta "—" en vez de inventar).
 	SpeedMbps int `json:"speedMbps,omitempty"`
+	// Evidence (#1325): capa que resolvió el uplink del hijo ("override",
+	// "lldp", "device", "fdb"). Vacío = fallback al gateway (sin evidencia:
+	// el front no pinta tag). Solo en enlaces kind="uplink".
+	Evidence string `json:"evidence,omitempty"`
 }
 
 // RoamingDaemon clasifica el daemon de roaming/band-steering activo en la