Bladeren bron

fix(topology): infer the leaf switch behind any managed unit and fan clients outward (#1791) (#1913)

* fix(topology): infer the leaf switch behind any managed unit (#1791)

* fix(ui): fan wired clients away from their unit, not always west (#1791)

* docs(changelog): cover the leaf switch and the fan direction (#1791)
Nacho 4 weken geleden
bovenliggende
commit
917d05e1b7

+ 3 - 0
CHANGELOG.md

@@ -19,6 +19,9 @@ y este proyecto se adhiere a [Versionado Semántico](https://semver.org/lang/es/
 
 ### Fixed
 
+- An unmanaged switch behind a managed one is inferred again (#1791). The inference required a managed distribution node whose MAC matched the bridge address of the switch exactly, and it only accepted units of type managed-switch. An SNMP switch usually announces an LLDP chassis MAC that is not its bridge address, and a unit declared as external with SNMP did not pass the type check at all, so the leaf switch never appeared and its clients stayed in the fan-out of the managed switch. Every managed unit with a forwarding table is walked now, and when no node matches its MAC the leaf hangs from the fleet unit itself, keeping the physical port on each client. Access points with an agent are still excluded, because their multi-MAC port is their uplink.
+- Wired clients fan away from their unit instead of always to the west (#1791). The fixed arc sent every chip towards the gateway when the unit sat on the right edge, on top of the links between units. The arc is now centred on the direction from the gateway to the unit, so a unit on the right fans its clients to the right and a unit on the left keeps the layout it had.
+
 - Traffic charts no longer invent a ramp between two buckets (#1901). A point in these series means "the highest rate seen inside this bucket", so a straight segment to the next point claims the link spent the whole gap climbing, and a one minute burst inside an hour renders as a triangle that spans the neighbouring hours. The WAN chart, the fleet sparkline and the aggregated port ranges now draw steps, which say exactly what was measured and no more. The 24h port chart keeps its straight segments because it reads raw instantaneous samples, and the latency chart is untouched since it is not a max-per-bucket series. One detail differs from the report: every WAN range is bucketed, including 1h, whose points are three minute maxima, so the step applies there too instead of only to the hourly view.
 
 - Discovery no longer offers a unit that is already in the fleet (#1895). A candidate was marked as already added only when its IP was byte-identical to the host string in the configuration, so a unit added by DNS name, by a name with different case or a trailing dot, or by an IP with a port showed up with an Add button while the gateway, added by plain IP, was the only one recognised. The comparison now normalises case, port and the trailing dot, resolves configured names to their addresses, and also matches the reverse DNS name of the candidate, with name resolution bounded so a stale name cannot slow the scan down.

+ 13 - 3
app/src/components/topology/model.ts

@@ -961,11 +961,21 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
       // router y otros routers) — regla de máxima distancia, sin arcos
       // hardcodeados por red. El radio se ajusta para que quede fuera del
       // círculo de sus propios cableados y dentro del viewport.
+      // #1791: el abanico cableado se abre HACIA FUERA de la unidad (desde el
+      // gateway hacia ella), no siempre al oeste. Con el arco fijo [150,210],
+      // una unidad en el borde derecho abanicaba a sus clientes hacia el
+      // gateway, por encima de los enlaces entre unidades: el reporter lo
+      // pidio como "fan clients to the right for units on the RIGHT edge".
+      // En una unidad a la izquierda el resultado es el de antes (180 grados).
+      const outward = gatewayNode
+        ? angleTo(gatewayNode.x, gatewayNode.y, node.x, node.y)
+        : (AP_WIRED_FAN[0] + AP_WIRED_FAN[1]) / 2
+      const wiredFan: [number, number] = [outward - 30, outward + 30]
       const farWest = anchors.filter((a) => a.kind === 'hub' && hypervisorHosts.has(a.id))
       const rest = anchors.filter((a) => !farWest.includes(a))
       const farWestItems = farWest.map((a) => ({ ...a, x: 0, y: 0 }))
       const restItems = rest.map((a) => ({ ...a, x: 0, y: 0 }))
-      fanLayout(restItems, node, ROUTER_FAN_RADIUS, AP_WIRED_FAN[0], AP_WIRED_FAN[1])
+      fanLayout(restItems, node, ROUTER_FAN_RADIUS, wiredFan[0], wiredFan[1])
       // Vecinos desde los que alejarse: gateway, los distnodes del switch/AP y
       // los demás routers (APs/switches) — el host se abre paso en el hueco.
       const neighbors: { x: number; y: number }[] = []
@@ -982,11 +992,11 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
       if (gatewayNode) {
         hostArcs.push(...arcAround(angleTo(node.x, node.y, gatewayNode.x, gatewayNode.y), 27))
       }
-      hostArcs.push([AP_WIRED_FAN[0] - 10, AP_WIRED_FAN[1] + 10])
+      hostArcs.push([wiredFan[0] - 10, wiredFan[1] + 10])
       const gapAngle = widestGapCenterInArcs(node, neighbors, HUB_HOST_RADIUS, hostArcs)
       fanLayout(farWestItems, node, HUB_HOST_RADIUS, gapAngle - 20, gapAngle + 20)
       placed.push(...restItems, ...farWestItems)
-      fanArcByRouter.set(node.id, [[AP_WIRED_FAN[0] - 8, AP_WIRED_FAN[1] + 8]])
+      fanArcByRouter.set(node.id, [[wiredFan[0] - 8, wiredFan[1] + 8]])
     }
 
     for (const p of placed) {

+ 35 - 18
server-go/internal/adapters/topology.go

@@ -576,31 +576,43 @@ func inferTopology(polled map[string]*routerPolled, devices []Device) ([]Device,
 	// 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 {
+		// #1791: se recorre la unidad gestionada aunque NINGUN distnode la case
+		// por MAC. Antes hacian falta dos cosas a la vez: un distnode "managed"
+		// con Mac, y que esa Mac fuera exactamente el bridge address del switch
+		// (y solo si cfg.Type == "managed-switch"). Un switch SNMP suele
+		// anunciar por LLDP una chassis-MAC distinta de su bridge address, y un
+		// switch declarado external+SNMP ni siquiera entraba por el tipo, asi
+		// que el switch hoja nunca se inferia y sus clientes se quedaban en el
+		// fan-out del switch gestionado. Sin ancla por MAC el nodo hoja cuelga
+		// de la propia unidad de flota (Parent vacio).
+		type swCandidate struct{ id, parent string }
+		var candidates []swCandidate
+		for _, id := range routerIDs {
+			p := polled[id]
+			if p == nil || p.brMac == "" || len(p.fdb) == 0 {
 				continue
 			}
-			p := polled[switchID]
-			if p == nil {
+			// Solo switches gestionados de verdad: un AP con agente (AgentOnly)
+			// sigue fuera, porque su puerto multi-MAC es su propio uplink.
+			if p.cfg.Type != "managed-switch" && !(p.cfg.Type == "external" && p.cfg.SnmpEnabled) {
 				continue
 			}
+			parent := ""
+			for _, dn := range dists {
+				if dn.Kind == "managed" && dn.Mac != "" && strings.EqualFold(dn.Mac, p.brMac) {
+					parent = dn.ID
+					break
+				}
+			}
+			candidates = append(candidates, swCandidate{id: id, parent: parent})
+		}
+		for _, cand := range candidates {
+			switchID := cand.id
+			p := polled[switchID]
 			rootPort := ""
 			if gwMac != "" {
 				rootPort = p.fdb[gwMac]
@@ -635,7 +647,7 @@ func inferTopology(polled map[string]*routerPolled, devices []Device) ([]Device,
 				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,
+					PortLabel: portLabel(p, port), MacCount: len(kept), Parent: cand.parent,
 				})
 				// #1791: los clientes del puerto cuelgan del nodo hoja, no del
 				// gateway que les dio la IP. Sin AttachTo, hubOf los anclaba al
@@ -643,6 +655,11 @@ func inferTopology(polled map[string]*routerPolled, devices []Device) ([]Device,
 				for _, mac := range kept {
 					if idx, ok := byMAC[mac]; ok {
 						devices[idx].AttachTo = id
+						// El puerto fisico del switch se conserva: claim no
+						// re-ancla los clientes de una hoja (#1417), asi que
+						// sin esto el chip perdia el dato.
+						devices[idx].Port = port
+						devices[idx].PortLabel = portLabel(p, port)
 					}
 				}
 			}

+ 28 - 16
server-go/internal/adapters/topology_claim_test.go

@@ -5,13 +5,15 @@ import "testing"
 // #1417: flota con switches gestionados sondeados por SNMP como "external"
 // (el montaje de #1137). El gateway los ve por LLDP en su puerto de uplink;
 // como su Type no es "managed-switch", inferLldpLinks trata el enlace como
-// router↔router y marca el puerto como resuelto SIN crear distnode ni anclar
-// a los clientes cableados del puerto. La inferencia de hojas #1325 tampoco
-// cubre estos switches (filtra Type=="managed-switch"). Resultado: los
-// clientes cableados del switch quedan sin AttachTo y el mapa los cuelga del
-// gateway. claimSwitchFdbClients reclama para cada switch de flota los
-// clientes cableados (atribuidos al gateway) que SU FDB aprendió en un
-// puerto que no es su root port.
+// router↔router y marca el puerto como resuelto SIN crear distnode.
+// claimSwitchFdbClients reclama para cada switch de flota los clientes
+// cableados (atribuidos al gateway) que SU FDB aprendió en un puerto que no
+// es su root port.
+//
+// Desde #1791 la inferencia de hojas #1325 SI cubre estos switches: un puerto
+// con 2+ clientes genera su nodo "inferred" y los clientes cuelgan de el con
+// su puerto fisico. Los puertos con un solo cliente los sigue resolviendo
+// claim, que no re-ancla los clientes de una hoja ya creada.
 
 const (
 	claimGwMac   = "AA:BB:CC:00:00:01"
@@ -72,24 +74,34 @@ func TestClaim1417SonosDetrasDeSwitchSNMP(t *testing.T) {
 		dev("11:11:11:11:11:09", "gateway", "cable"),
 	}
 	devices, dists := inferTopology(polled, devices)
-	for i, d := range devices[:4] {
-		if d.AttachTo != "" {
-			t.Fatalf("prepara: sonos %d ya anclado a %q (fixture sin el bug)", i, d.AttachTo)
+	// #1791: Port 5 de sw1 aprende dos clientes, asi que su hoja ya existe y
+	// los dos cuelgan de ella con el puerto fisico conservado.
+	if len(dists) != 1 || dists[0].ID != "dist-sw1-Port 5" || dists[0].Kind != "inferred" {
+		t.Fatalf("prepara: hoja de sw1 ausente: %+v", dists)
+	}
+	for i := 0; i < 2; i++ {
+		if devices[i].AttachTo != "dist-sw1-Port 5" || devices[i].Port != "Port 5" {
+			t.Fatalf("prepara: sonos%d = (%q, %q), quiero la hoja con Port 5", i+1, devices[i].AttachTo, devices[i].Port)
 		}
 	}
-	if len(dists) != 0 {
-		t.Fatalf("prepara: distnodes inesperados: %+v", dists)
+	if devices[2].AttachTo != "" || devices[3].AttachTo != "" {
+		t.Fatalf("prepara: sonos3/sonos4 no deben anclarse aun: %q %q", devices[2].AttachTo, devices[3].AttachTo)
 	}
 	gwID := "gateway"
 	claimSwitchFdbClients(polled, devices, dists, gwID,
 		fleetFdbEvidence(polled, gwID, nil, nil), fleetLldpEvidence(polled, gwID), nil)
 
-	// sonos1/2: acceso de sw1 por "Port 5"; sonos3: "Port 6".
-	for i, wantPort := range []string{"Port 5", "Port 5", "Port 6"} {
-		if devices[i].AttachTo != "sw1" || devices[i].Port != wantPort {
-			t.Fatalf("sonos%d: got (%q, %q), want (sw1, %q)", i+1, devices[i].AttachTo, devices[i].Port, wantPort)
+	// sonos1/2: la hoja de sw1 los conserva (claim no re-ancla una hoja) y el
+	// puerto fisico sigue en el chip. sonos3, solo en su puerto, lo reclama
+	// claim para el propio switch, como antes.
+	for i := 0; i < 2; i++ {
+		if devices[i].AttachTo != "dist-sw1-Port 5" || devices[i].Port != "Port 5" {
+			t.Fatalf("sonos%d: got (%q, %q), want (dist-sw1-Port 5, Port 5)", i+1, devices[i].AttachTo, devices[i].Port)
 		}
 	}
+	if devices[2].AttachTo != "sw1" || devices[2].Port != "Port 6" {
+		t.Fatalf("sonos3: got (%q, %q), want (sw1, Port 6)", devices[2].AttachTo, devices[2].Port)
+	}
 	// sonos4 lo ven sw1 (trunk) y sw2 (acceso): gana el más profundo.
 	if devices[3].AttachTo != "sw2" || devices[3].Port != "Port 3" {
 		t.Fatalf("sonos4: got (%q, %q), want (sw2, Port 3)", devices[3].AttachTo, devices[3].Port)

+ 100 - 0
server-go/internal/adapters/topology_leaf_1791_test.go

@@ -0,0 +1,100 @@
+package adapters
+
+import "testing"
+
+// #1791: el switch hoja detras de un switch gestionado no se inferia cuando
+// ningun distnode "managed" casaba por MAC con el bridge address del switch.
+// En su red el switch es SNMP (external+SNMP) y no hay LLDP que lo identifique,
+// asi que la inferencia nunca arrancaba y los clientes quedaban en el fan-out.
+func TestInferTopologyLeafTrasSwitchSnmpSinDistnode(t *testing.T) {
+	gwMac := "94:83:C4:00:00:01"
+	swMac := "78:55:36:00:00:02"
+	polled := map[string]*routerPolled{
+		"gw": {cfg: RouterConfig{ID: "gw", IsGateway: true}, brMac: gwMac, fdb: map[string]string{swMac: "lan2"}},
+		"sw": {cfg: RouterConfig{ID: "sw", Type: "external", SnmpEnabled: true}, brMac: swMac, fdb: map[string]string{
+			gwMac:               "1", // root port: el uplink no genera nodo
+			"AA:BB:CC:00:00:11": "3",
+			"AA:BB:CC:00:00:12": "3",
+		}},
+	}
+	devices := []Device{
+		dev("AA:BB:CC:00:00:11", "gw", "cable"),
+		dev("AA:BB:CC:00:00:12", "gw", "cable"),
+	}
+	devices, dists := inferTopology(polled, devices)
+	var leaf *DistributionNode
+	for i := range dists {
+		if dists[i].ID == "dist-sw-3" {
+			leaf = &dists[i]
+		}
+	}
+	if leaf == nil {
+		t.Fatalf("no se infirio el switch hoja: %+v", dists)
+	}
+	if leaf.Kind != "inferred" || leaf.RouterID != "sw" || leaf.MacCount != 2 {
+		t.Fatalf("leaf = %+v", *leaf)
+	}
+	// Sin distnode que case por MAC, el nodo cuelga de la unidad de flota.
+	if leaf.Parent != "" {
+		t.Fatalf("parent = %q, quiero vacio (cuelga de la unidad)", leaf.Parent)
+	}
+	for _, d := range devices {
+		if d.AttachTo != "dist-sw-3" {
+			t.Fatalf("%s attachTo = %q, quiero dist-sw-3", d.MAC, d.AttachTo)
+		}
+	}
+}
+
+// Mismo caso con el tipo managed-switch y sin LLDP: antes tambien fallaba,
+// porque el ancla exigia un distnode managed con la chassis-MAC exacta.
+func TestInferTopologyLeafTrasManagedSwitchSinLldp(t *testing.T) {
+	gwMac := "94:83:C4:00:00:01"
+	swMac := "78:55:36:00:00:02"
+	polled := map[string]*routerPolled{
+		"gw": {cfg: RouterConfig{ID: "gw", IsGateway: true}, brMac: gwMac, fdb: map[string]string{swMac: "lan2"}},
+		"sw": {cfg: RouterConfig{ID: "sw", Type: "managed-switch"}, brMac: swMac, fdb: map[string]string{
+			gwMac:               "1",
+			"AA:BB:CC:00:00:11": "5",
+			"AA:BB:CC:00:00:12": "5",
+		}},
+	}
+	devices := []Device{
+		dev("AA:BB:CC:00:00:11", "gw", "cable"),
+		dev("AA:BB:CC:00:00:12", "gw", "cable"),
+	}
+	_, dists := inferTopology(polled, devices)
+	found := false
+	for _, dn := range dists {
+		if dn.ID == "dist-sw-5" && dn.Kind == "inferred" {
+			found = true
+		}
+	}
+	if !found {
+		t.Fatalf("managed-switch sin LLDP no genero el nodo hoja: %+v", dists)
+	}
+}
+
+// El guardarraíl se mantiene: un AP con agente (AgentOnly) NO genera nodos
+// hoja, porque su puerto multi-MAC es su uplink y no un switch local.
+func TestInferTopologyApConAgenteNoGeneraHojas(t *testing.T) {
+	gwMac := "94:83:C4:00:00:01"
+	apMac := "8C:DE:F9:00:00:03"
+	polled := map[string]*routerPolled{
+		"gw": {cfg: RouterConfig{ID: "gw", IsGateway: true}, brMac: gwMac, fdb: map[string]string{apMac: "lan2"}},
+		"ap": {cfg: RouterConfig{ID: "ap", Type: "openwrt", AgentOnly: true}, brMac: apMac, fdb: map[string]string{
+			gwMac:               "lan1",
+			"AA:BB:CC:00:00:11": "lan2",
+			"AA:BB:CC:00:00:12": "lan2",
+		}},
+	}
+	devices := []Device{
+		dev("AA:BB:CC:00:00:11", "gw", "cable"),
+		dev("AA:BB:CC:00:00:12", "gw", "cable"),
+	}
+	_, dists := inferTopology(polled, devices)
+	for _, dn := range dists {
+		if dn.Kind == "inferred" && dn.RouterID == "ap" {
+			t.Fatalf("un AP con agente no debe generar nodos hoja: %+v", dn)
+		}
+	}
+}