topology.go 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008
  1. package adapters
  2. import (
  3. "fmt"
  4. "maps"
  5. "slices"
  6. "sort"
  7. "strings"
  8. )
  9. // ---------------------------------------------------------------------------
  10. // Inferencia de topología v5 (FDB): puertos físicos, switches/bridges e
  11. // hipervisores. Función pura (sin SSH ni BD) para ser testeable.
  12. //
  13. // Reglas (plan 2-Ago-2026; regla de anclaje refinada 2-Ago-2026):
  14. // - Un puerto físico (lanN) con UNA MAC aprendida = cableado directo →
  15. // Device.Port.
  16. // - Un puerto con VARIAS MACs = algo multiplexándolo (switch, hipervisor,
  17. // PLC…). El FDB no dice qué: OUI heterogéneo → "inferred" (círculo
  18. // dashed, sin afirmar); alguna MAC con OUI de hipervisor y exactamente
  19. // un host → "hypervisor" (sus VMs se anidan bajo el host).
  20. // - Se excluyen las MACs de los propios routers (su bridge br-lan) y las
  21. // de clientes atribuidos a OTROS routers (los clientes wifi de un AP
  22. // aparecen en el FDB del gateway por el puerto del uplink).
  23. // - Anclaje al GATEWAY (decisión del usuario 2-Ago-2026): los nodos
  24. // "inferred" SOLO se crean en el gateway. En un AP, un puerto multi-MAC
  25. // es casi seguro su UPLINK (aprende las MACs de toda la LAN) y el FDB
  26. // no puede distinguirlo de un switch local → no se afirma nada: esos
  27. // clientes quedan "sin evidencia" y el frontend los cuelgan del gateway.
  28. // Única excepción tras un AP: hipervisor con evidencia clara (MACs OUI
  29. // de hipervisor + exactamente un host) = servidor con VMs tras ese AP.
  30. // - LLDP (Fase 2, contrato C2): si en un puerto multi-MAC se anuncia un
  31. // vecino LLDP cuya chassis-MAC está entre las aprendidas, el equipo que
  32. // multiplexa queda IDENTIFICADO → nodo "managed" (nombre/mgmt-ip/caps
  33. // anunciados). Es evidencia positiva, como la de hipervisor: aplica
  34. // también tras un AP (el uplink al gateway no puede promover porque su
  35. // MAC está excluida de las aprendidas). Además, cualquier vecino cuya
  36. // chassis-MAC sea un Device conocido puebla Device.Lldp. Sin datos LLDP
  37. // todo sigue exactamente como antes (inferred/hypervisor + reglas OUI).
  38. // ---------------------------------------------------------------------------
  39. // hypervisorOUI: prefijos de MAC de hipervisores conocidos.
  40. var hypervisorOUI = []string{
  41. "BC:24:11", // Proxmox VE
  42. "00:50:56", // VMware (ESXi/Workstation)
  43. "00:0C:29", // VMware
  44. "00:15:5D", // Hyper-V
  45. "52:54:00", // KVM/QEMU
  46. "08:00:27", // VirtualBox
  47. }
  48. func isHypervisorMAC(mac string) bool {
  49. upper := strings.ToUpper(mac)
  50. for _, p := range hypervisorOUI {
  51. if strings.HasPrefix(upper, p) {
  52. return true
  53. }
  54. }
  55. return false
  56. }
  57. // fdbByPort invierte el FDB: puerto → MACs (el WAN no es distribución LAN).
  58. func fdbByPort(fdb map[string]string) map[string][]string {
  59. byPort := map[string][]string{}
  60. for mac, port := range fdb {
  61. if port == "wan" {
  62. continue
  63. }
  64. byPort[port] = append(byPort[port], mac)
  65. }
  66. return byPort
  67. }
  68. // fdbPortOf devuelve el puerto donde el FDB aprendio `mac`, comparando sin
  69. // distinguir mayusculas (las claves del FDB no vienen normalizadas). #2084:
  70. // si el vecino LLDP ya se aprende por otro puerto, el anuncio de este no es
  71. // un enlace hacia ese equipo.
  72. func fdbPortOf(fdb map[string]string, mac string) (string, bool) {
  73. for m, port := range fdb {
  74. if strings.EqualFold(m, mac) {
  75. return port, true
  76. }
  77. }
  78. return "", false
  79. }
  80. // keptMacsForPort: MACs del puerto `port` que cuentan como clientes reales
  81. // del router (excluye las bridge-MACs de routers y los clientes de OTROS
  82. // routers: los clientes wifi de un AP aparecen en el FDB del gateway por el
  83. // puerto del uplink).
  84. func keptMacsForPort(portMACs []string, routerID string, byMAC map[string]int, devices []Device, routerMACs map[string]bool) []string {
  85. kept := make([]string, 0, len(portMACs))
  86. for _, mac := range portMACs {
  87. if routerMACs[mac] {
  88. continue
  89. }
  90. if idx, ok := byMAC[mac]; ok {
  91. d := devices[idx]
  92. if d.RouterID != routerID {
  93. continue
  94. }
  95. if d.Band != "cable" && d.Band != "—" {
  96. continue
  97. }
  98. }
  99. kept = append(kept, mac)
  100. }
  101. return kept
  102. }
  103. // leafSwitchClients (#1325): MACs de un puerto del FDB de un SWITCH gestionado
  104. // que cuentan como clientes para el umbral de switch hoja (>= 2). Excluye las
  105. // bridge-MACs de la flota y los clientes wifi conocidos (los de un AP que
  106. // transitan por el switch). A diferencia de keptMacsForPort, NO filtra por
  107. // RouterID: los clientes cableados de un switch se atribuyen al DHCP server
  108. // (casi siempre el gateway), no al switch, y aquí importa el enlace físico.
  109. func leafSwitchClients(portMACs []string, byMAC map[string]int, devices []Device, routerMACs map[string]bool) []string {
  110. kept := make([]string, 0, len(portMACs))
  111. for _, mac := range portMACs {
  112. if routerMACs[mac] {
  113. continue
  114. }
  115. if idx, ok := byMAC[mac]; ok {
  116. if devices[idx].Band != "cable" && devices[idx].Band != "—" {
  117. continue
  118. }
  119. }
  120. kept = append(kept, mac)
  121. }
  122. return kept
  123. }
  124. // hypervisorHostMAC: MAC del host de un hipervisor claro en `kept` (MACs OUI
  125. // de hipervisor + exactamente un host normal, siendo ese host un Device del
  126. // router). Vacío+false si el puerto no es un hipervisor claro.
  127. func hypervisorHostMAC(kept []string, routerID string, byMAC map[string]int, devices []Device) (string, bool) {
  128. var vmMACs, hostMACs []string
  129. for _, mac := range kept {
  130. if isHypervisorMAC(mac) {
  131. vmMACs = append(vmMACs, mac)
  132. } else {
  133. hostMACs = append(hostMACs, mac)
  134. }
  135. }
  136. if len(vmMACs) > 0 && len(hostMACs) == 1 {
  137. if hidx, ok := byMAC[hostMACs[0]]; ok && devices[hidx].RouterID == routerID {
  138. return hostMACs[0], true
  139. }
  140. }
  141. return "", false
  142. }
  143. // attachKeptToDist: setPort para los clientes cableados del puerto y cuelga
  144. // del distnode a todos salvo al propio switch (SPEC-CANON D2: sin self-attach).
  145. func attachKeptToDist(devices []Device, byMAC map[string]int, routerID, distID, port, portLabel string, kept []string, switchMac string) {
  146. for _, mac := range kept {
  147. idx, ok := byMAC[mac]
  148. if !ok || devices[idx].RouterID != routerID {
  149. continue
  150. }
  151. devices[idx].Port = port
  152. devices[idx].PortLabel = portLabel
  153. if mac == switchMac {
  154. continue
  155. }
  156. devices[idx].AttachTo = distID
  157. }
  158. }
  159. // inferLldpLinks: Fase LLDP-first (issue #300), ANTES del análisis FDB. Usa
  160. // los vecinos LLDP como ground truth de los enlaces de infraestructura
  161. // (router↔switch y switch↔switch): crea el distnode "managed" de cada switch
  162. // identificado y encadena las cadenas switch→switch con Parent. Devuelve los
  163. // puertos ya resueltos por LLDP para que el bucle FDB los salte.
  164. //
  165. // Un vecino que identifica a un ROUTER regular (glinet/openwrt) NO genera
  166. // nodo managed: es un enlace router↔router (uplink), su puerto queda resuelto.
  167. // Un puerto hipervisor claro se deja para el FDB (la evidencia de hipervisor
  168. // manda sobre la de LLDP).
  169. func inferLldpLinks(polled map[string]*routerPolled, devices []Device, byMAC map[string]int, routerMACs map[string]bool, routers []routerIdentity) ([]DistributionNode, map[string]map[string]bool) {
  170. handled := map[string]map[string]bool{}
  171. markHandled := func(routerID, port string) {
  172. if handled[routerID] == nil {
  173. handled[routerID] = map[string]bool{}
  174. }
  175. handled[routerID][port] = true
  176. }
  177. distByMac := map[string]string{}
  178. routerIDs := slices.Sorted(maps.Keys(polled))
  179. var dists []DistributionNode
  180. for _, routerID := range routerIDs {
  181. p := polled[routerID]
  182. if len(p.lldp) == 0 {
  183. continue
  184. }
  185. byPort := fdbByPort(p.fdb)
  186. for i := range p.lldp {
  187. nb := &p.lldp[i]
  188. if nb.Port == "" {
  189. continue
  190. }
  191. if handled[routerID][nb.Port] {
  192. continue
  193. }
  194. kept := keptMacsForPort(byPort[nb.Port], routerID, byMAC, devices, routerMACs)
  195. if len(kept) == 0 {
  196. continue
  197. }
  198. ri := neighborIsRouter(nb, routers, routerID)
  199. if ri != nil {
  200. if ri.Type != "managed-switch" {
  201. // Router regular: enlace router↔router (uplink), no switch.
  202. markHandled(routerID, nb.Port)
  203. continue
  204. }
  205. // Router de tipo managed-switch: es un switch (issue #252).
  206. //
  207. // #2084: pero si este router ya aprende la MAC del vecino por
  208. // OTRO puerto, el enlace real es ese y el LLDP que llega aqui
  209. // viene de un segmento L2 compartido (un AP en medio). El caso
  210. // medido: A aprende la MAC de B en su LAG y recibe los LLDP de
  211. // B por un access port que spanning tree tiene en Discarding.
  212. // Materializar el nodo ahi dibujaba el mismo switch dos veces,
  213. // sobre una entrada FDB que oscila con cada trama LLDP.
  214. if ri.BrMac != "" {
  215. if learned, ok := fdbPortOf(p.fdb, ri.BrMac); ok && !strings.EqualFold(learned, nb.Port) {
  216. markHandled(routerID, nb.Port)
  217. continue
  218. }
  219. }
  220. } else if nb.ChassisMac == "" || !containsMAC(kept, nb.ChassisMac) {
  221. // Ni identidad de router ni chassis-MAC aprendida en el puerto:
  222. // no hay evidencia de que sea el equipo que multiplexa.
  223. continue
  224. }
  225. if _, isHyp := hypervisorHostMAC(kept, routerID, byMAC, devices); isHyp {
  226. continue
  227. }
  228. if len(kept) == 1 {
  229. continue // cableado directo, sin nodo de distribución
  230. }
  231. upper := strings.ToUpper(nb.ChassisMac)
  232. if upper != "" {
  233. if _, dup := distByMac[upper]; dup {
  234. markHandled(routerID, nb.Port)
  235. continue
  236. }
  237. }
  238. id := fmt.Sprintf("dist-%s-%s", routerID, nb.Port)
  239. parent := distByMac[strings.ToUpper(p.brMac)]
  240. if upper != "" {
  241. distByMac[upper] = id
  242. }
  243. dists = append(dists, DistributionNode{
  244. ID: id, Kind: "managed", RouterID: routerID, Port: nb.Port,
  245. PortLabel: portLabel(p, nb.Port), Parent: parent,
  246. MacCount: len(kept), Name: nb.displayName(), Ip: nb.Mgmt,
  247. Mac: nb.ChassisMac, Lldp: nb.info(),
  248. })
  249. if idx, ok := byMAC[nb.ChassisMac]; ok {
  250. devices[idx].Infra = "managed-switch"
  251. }
  252. attachKeptToDist(devices, byMAC, routerID, id, nb.Port, portLabel(p, nb.Port), kept, nb.ChassisMac)
  253. markHandled(routerID, nb.Port)
  254. }
  255. }
  256. return dists, handled
  257. }
  258. // cfgIsSwitch: el disyuntivo de rol "Switch" de buildRouter (#661/#1137):
  259. // agent-only, managed-switch, o external sondeado por SNMP. La pasada de
  260. // claim (#1417) usa el mismo criterio para decidir qué unidades de flota
  261. // pueden reclamar clientes con su FDB.
  262. func cfgIsSwitch(c RouterConfig) bool {
  263. return c.AgentOnly || c.Type == "managed-switch" || (c.Type == "external" && c.SnmpEnabled)
  264. }
  265. // claimSwitchFdbClients (#1417): los clientes cableados atribuidos al gateway
  266. // que la FDB de un switch de flota aprendió en un puerto que NO es su root
  267. // port están físicamente detrás de ese switch, aunque la única atribución
  268. // DHCP disponible sea la del gateway (los switches SNMP no dan DHCP ni LLDP
  269. // útil: para la atribución son clientes del gateway; ver leafSwitchClients).
  270. //
  271. // Reglas:
  272. // - Root port del switch = el puerto donde su FDB aprende la bridge-MAC del
  273. // gateway (#1373). Sin esa MAC en su FDB el switch no reclama nada: sin
  274. // root port no se distingue arriba de abajo.
  275. // - Si varios switches reclaman la misma MAC (el trunk de sw1 ve también a
  276. // los clientes de sw2), gana el más profundo según la evidencia de uplink
  277. // (override > lldp > fdb, la precedencia de BuildTopoSemantics); empate
  278. // de profundidad → id menor (determinista).
  279. // - Un puerto del switch con hoja inferida #1325 ya creada recibe los
  280. // attach de sus clientes (la hoja se llena; no se rodea).
  281. // - Solo se re-anclan devices atribuidos al gateway con banda cable/"—"
  282. // cuyo attach esté vacío o apunte a un distnode del gateway (el blob
  283. // sombra #1374): un attach a un device-hub (hipervisor) o a un distnode
  284. // de otro router no se toca. Los blobs del gateway que queden vacíos los
  285. // absorbe después la pasada #1374 sin dejar huérfanos.
  286. //
  287. // Mutates devices; dists solo se lee.
  288. func claimSwitchFdbClients(polled map[string]*routerPolled, devices []Device, dists []DistributionNode, gatewayID string, fdbEv, lldpEv, overrideEv map[string]topoParent) {
  289. if gatewayID == "" {
  290. return
  291. }
  292. gw := polled[gatewayID]
  293. if gw == nil || gw.brMac == "" {
  294. return
  295. }
  296. gwMac := strings.ToUpper(gw.brMac)
  297. routerMACs := map[string]bool{}
  298. ids := make([]string, 0, len(polled))
  299. for id, p := range polled {
  300. ids = append(ids, id)
  301. if p.brMac != "" {
  302. routerMACs[strings.ToUpper(p.brMac)] = true
  303. }
  304. }
  305. sort.Strings(ids)
  306. // Uplinks por precedencia (override > lldp > fdb) y profundidad desde el
  307. // gateway para el desempate entre switches.
  308. up := map[string]topoParent{}
  309. for rid, ev := range fdbEv {
  310. if rid != gatewayID {
  311. up[rid] = ev
  312. }
  313. }
  314. for rid, ev := range lldpEv {
  315. if rid != gatewayID {
  316. up[rid] = ev // el LLDP pisa la FDB (#1279)
  317. }
  318. }
  319. for rid, ev := range overrideEv {
  320. if rid != gatewayID && ev.parent != rid {
  321. up[rid] = ev // el override manual lo pisa todo (#1321)
  322. }
  323. }
  324. depth := map[string]int{gatewayID: 0}
  325. for iter := 0; iter <= len(ids); iter++ {
  326. changed := false
  327. for _, rid := range ids {
  328. if rid == gatewayID {
  329. continue
  330. }
  331. ev, ok := up[rid]
  332. if !ok {
  333. continue
  334. }
  335. if d, seen := depth[ev.parent]; seen && depth[rid] < d+1 {
  336. depth[rid] = d + 1
  337. changed = true
  338. }
  339. }
  340. if !changed {
  341. break
  342. }
  343. }
  344. // Reclamos por MAC: el switch más profundo gana.
  345. type swClaim struct {
  346. switchID string // switch que aprende la MAC (para portLabel)
  347. target string // id del switch o de su hoja #1325
  348. port string
  349. depth int
  350. }
  351. best := map[string]swClaim{}
  352. for _, sid := range ids {
  353. if sid == gatewayID {
  354. continue
  355. }
  356. p := polled[sid]
  357. if !cfgIsSwitch(p.cfg) || len(p.fdb) == 0 {
  358. continue
  359. }
  360. root := p.fdb[gwMac]
  361. if root == "" {
  362. continue // sin root port conocido: no se distingue arriba de abajo
  363. }
  364. for mac, port := range p.fdb {
  365. if port == root || mac == "" {
  366. continue
  367. }
  368. if routerMACs[mac] {
  369. continue
  370. }
  371. // Un puerto con hoja #1325 ya creada reclama para la hoja.
  372. target := sid
  373. for _, dn := range dists {
  374. if dn.RouterID == sid && dn.Port == port && (dn.Kind == "inferred" || dn.Kind == "managed") {
  375. target = dn.ID
  376. break
  377. }
  378. }
  379. c := swClaim{switchID: sid, target: target, port: port, depth: depth[sid]}
  380. if prev, ok := best[mac]; ok {
  381. if c.depth < prev.depth || (c.depth == prev.depth && target >= prev.target) {
  382. continue
  383. }
  384. }
  385. best[mac] = c
  386. }
  387. }
  388. if len(best) == 0 {
  389. return
  390. }
  391. // Aplicar: solo gateway-atribuidos cableados con attach vacío o a blob
  392. // del gateway; device-hubs y distnodes ajenos intactos.
  393. distRouter := map[string]string{}
  394. for _, dn := range dists {
  395. distRouter[dn.ID] = dn.RouterID
  396. }
  397. for i := range devices {
  398. d := &devices[i]
  399. if d.RouterID != gatewayID || (d.Band != "cable" && d.Band != "—") {
  400. continue
  401. }
  402. if d.AttachTo != "" && distRouter[d.AttachTo] != gatewayID {
  403. continue // device-hub, distnode de otro router o id desconocido
  404. }
  405. c, ok := best[strings.ToUpper(d.MAC)]
  406. if !ok {
  407. continue
  408. }
  409. d.AttachTo = c.target
  410. d.Port = c.port
  411. d.PortLabel = portLabel(polled[c.switchID], c.port)
  412. }
  413. }
  414. // containsMAC: ¿está mac (case-sensitive, como el FDB) en la lista?
  415. func containsMAC(macs []string, mac string) bool {
  416. for _, m := range macs {
  417. if m == mac {
  418. return true
  419. }
  420. }
  421. return false
  422. }
  423. // inferTopology enriquece devices con Port/AttachTo e infiere los
  424. // DistributionNode del FDB sondeado. `polled` lleva fdb (MAC→puerto, ya
  425. // filtrado a lanN/wan por parseBridgeFdb) y brMac por router.
  426. func inferTopology(polled map[string]*routerPolled, devices []Device) ([]Device, []DistributionNode) {
  427. byMAC := make(map[string]int, len(devices))
  428. for i, d := range devices {
  429. byMAC[d.MAC] = i
  430. }
  431. routerMACs := map[string]bool{}
  432. for _, p := range polled {
  433. if p.brMac != "" {
  434. routerMACs[p.brMac] = true
  435. }
  436. }
  437. var dists []DistributionNode
  438. // routers en orden determinista (el mapa polled no lo es)
  439. routerIDs := slices.Sorted(maps.Keys(polled))
  440. // Gateway con la misma prioridad que pickGateway (is_gateway → glinet →
  441. // primero): solo él puede anclar nodos "inferred".
  442. gatewayID := ""
  443. if gw := pickGatewayCfg(polled); gw != nil {
  444. gatewayID = gw.ID
  445. }
  446. // Identidades de routers para el matching LLDP tolerante (issue #252):
  447. // un vecino cuya mgmt-IP/nombre coincide con un router conocido identifica
  448. // el switch/AP aunque su chassis-ID no esté entre las MACs aprendidas.
  449. routers := routerIdentities(polled)
  450. // Fase LLDP-first (issue #300): enlaces de infraestructura por LLDP antes
  451. // del análisis FDB. Los puertos resueltos aquí se saltan en el bucle FDB.
  452. lldpDists, lldpHandled := inferLldpLinks(polled, devices, byMAC, routerMACs, routers)
  453. dists = append(dists, lldpDists...)
  454. for _, routerID := range routerIDs {
  455. p := polled[routerID]
  456. byPort := fdbByPort(p.fdb)
  457. ports := slices.Sorted(maps.Keys(byPort))
  458. for _, port := range ports {
  459. if lldpHandled[routerID][port] {
  460. continue
  461. }
  462. kept := keptMacsForPort(byPort[port], routerID, byMAC, devices, routerMACs)
  463. if len(kept) == 0 {
  464. continue
  465. }
  466. setPort := func() {
  467. for _, mac := range kept {
  468. if idx, ok := byMAC[mac]; ok && devices[idx].RouterID == routerID {
  469. devices[idx].Port = port
  470. devices[idx].PortLabel = portLabel(p, port)
  471. }
  472. }
  473. }
  474. if len(kept) == 1 {
  475. // cableado directo: puerto conocido, sin nodo de distribución
  476. setPort()
  477. continue
  478. }
  479. // puerto multi-MAC
  480. id := fmt.Sprintf("dist-%s-%s", routerID, port)
  481. var vmMACs, hostMACs []string
  482. for _, mac := range kept {
  483. if isHypervisorMAC(mac) {
  484. vmMACs = append(vmMACs, mac)
  485. } else {
  486. hostMACs = append(hostMACs, mac)
  487. }
  488. }
  489. if len(vmMACs) > 0 && len(hostMACs) == 1 {
  490. if hidx, ok := byMAC[hostMACs[0]]; ok && devices[hidx].RouterID == routerID {
  491. // Hipervisor con host identificado: evidencia clara, válida
  492. // también tras un AP (servidor con VMs colgando de ese AP).
  493. setPort()
  494. dists = append(dists, DistributionNode{
  495. ID: id, Kind: "hypervisor", RouterID: routerID, Port: port,
  496. PortLabel: portLabel(p, port),
  497. MacCount: len(kept), HostDeviceID: devices[hidx].ID, Name: devices[hidx].Name,
  498. })
  499. // SPEC-65 D65-2: sellado de infra — host = hypervisor,
  500. // las MACs con OUI de hipervisor anidadas bajo él = ct.
  501. devices[hidx].Infra = "hypervisor"
  502. for _, mac := range vmMACs {
  503. if idx, ok := byMAC[mac]; ok && devices[idx].RouterID == routerID {
  504. devices[idx].AttachTo = devices[hidx].ID
  505. devices[idx].Infra = "ct"
  506. }
  507. }
  508. continue
  509. }
  510. }
  511. // LLDP: los switches gestionados se resolvieron ya en la fase
  512. // LLDP-first (inferLldpLinks); este puerto solo llega aquí sin
  513. // evidencia LLDP, así que sigue el flujo FDB (hipervisor ya
  514. // descartado arriba).
  515. if routerID != gatewayID && !polled[routerID].cfg.AgentOnly {
  516. // AP con puerto multi-MAC sin evidencia de hipervisor: es casi
  517. // seguro su uplink (aprende las MACs de toda la LAN). No se
  518. // afirma switch local ni se anota puerto: los clientes quedan
  519. // "sin evidencia" y el frontend los ancla al gateway.
  520. continue
  521. }
  522. // Gateway, OUI heterogéneo (o hipervisor ambiguo sin host claro):
  523. // algo multiplexa ese puerto → nodo inferido colgando del gateway.
  524. setPort()
  525. dn := DistributionNode{
  526. ID: id, Kind: "inferred", RouterID: routerID, Port: port, PortLabel: portLabel(p, port), MacCount: len(kept),
  527. }
  528. if routerID == gatewayID {
  529. for _, rp := range polled {
  530. if !rp.cfg.AgentOnly {
  531. continue
  532. }
  533. swMacs := map[string]bool{}
  534. for mac := range rp.fdb {
  535. swMacs[mac] = true
  536. }
  537. allKnown := true
  538. for _, mac := range kept {
  539. if !swMacs[mac] {
  540. allKnown = false
  541. break
  542. }
  543. }
  544. if allKnown && len(kept) > 0 {
  545. dn.Name = rp.cfg.Name
  546. dn.Ip = rp.cfg.Host
  547. break
  548. }
  549. }
  550. }
  551. dists = append(dists, dn)
  552. for _, mac := range kept {
  553. if idx, ok := byMAC[mac]; ok && devices[idx].RouterID == routerID {
  554. devices[idx].AttachTo = id
  555. }
  556. }
  557. }
  558. }
  559. // #1325: switches hoja inferidos tras switches gestionados. Un switch
  560. // gestionado (distnode kind="managed") aprende en SU FDB los clientes
  561. // cableados de un switch hoja no gestionado: cada puerto que NO sea su
  562. // uplink (root port, donde aprende la bridge-MAC del gateway) y que
  563. // aprenda >= 2 clientes cableados -> nodo inferido hoja anclado al switch
  564. // (Parent) para que cuelgue de él en el mapa, no del router. Los APs
  565. // (no-switch) siguen excluidos: su puerto multi-MAC es su propio uplink.
  566. // La fase FDB no los veía porque keptMacsForPort filtra por RouterID y
  567. // los clientes de un switch se atribuyen al DHCP server (el gateway).
  568. if gatewayID != "" {
  569. gwMac := ""
  570. if gw := polled[gatewayID]; gw != nil {
  571. gwMac = strings.ToUpper(gw.brMac)
  572. }
  573. // #1791: se recorre la unidad gestionada aunque NINGUN distnode la case
  574. // por MAC. Antes hacian falta dos cosas a la vez: un distnode "managed"
  575. // con Mac, y que esa Mac fuera exactamente el bridge address del switch
  576. // (y solo si cfg.Type == "managed-switch"). Un switch SNMP suele
  577. // anunciar por LLDP una chassis-MAC distinta de su bridge address, y un
  578. // switch declarado external+SNMP ni siquiera entraba por el tipo, asi
  579. // que el switch hoja nunca se inferia y sus clientes se quedaban en el
  580. // fan-out del switch gestionado. Sin ancla por MAC el nodo hoja cuelga
  581. // de la propia unidad de flota (Parent vacio).
  582. type swCandidate struct{ id, parent string }
  583. var candidates []swCandidate
  584. for _, id := range routerIDs {
  585. p := polled[id]
  586. if p == nil || p.brMac == "" || len(p.fdb) == 0 {
  587. continue
  588. }
  589. // Solo switches gestionados de verdad: un AP con agente (AgentOnly)
  590. // sigue fuera, porque su puerto multi-MAC es su propio uplink.
  591. if p.cfg.Type != "managed-switch" && !(p.cfg.Type == "external" && p.cfg.SnmpEnabled) {
  592. continue
  593. }
  594. parent := ""
  595. for _, dn := range dists {
  596. if dn.Kind == "managed" && dn.Mac != "" && strings.EqualFold(dn.Mac, p.brMac) {
  597. parent = dn.ID
  598. break
  599. }
  600. }
  601. candidates = append(candidates, swCandidate{id: id, parent: parent})
  602. }
  603. for _, cand := range candidates {
  604. switchID := cand.id
  605. p := polled[switchID]
  606. rootPort := ""
  607. if gwMac != "" {
  608. rootPort = p.fdb[gwMac]
  609. }
  610. byPort := fdbByPort(p.fdb)
  611. ports := slices.Sorted(maps.Keys(byPort))
  612. for _, port := range ports {
  613. if port == rootPort {
  614. continue // uplink del propio switch (bucle)
  615. }
  616. if lldpHandled[switchID][port] {
  617. continue
  618. }
  619. occupied := false
  620. for _, d2 := range dists {
  621. // #2084: cualquier nodo del mismo puerto lo ocupa, tambien
  622. // el de hipervisor. Antes solo se miraban managed/inferred,
  623. // asi que un puerto con hipervisor recibia ademas un nodo
  624. // inferred con el MISMO id y el grafo emitia dos entradas.
  625. if d2.RouterID == switchID && d2.Port == port {
  626. occupied = true
  627. break
  628. }
  629. }
  630. if occupied {
  631. continue // el puerto ya tiene distnode managed/inferred
  632. }
  633. kept := leafSwitchClients(byPort[port], byMAC, devices, routerMACs)
  634. if len(kept) < 2 {
  635. continue
  636. }
  637. id := fmt.Sprintf("dist-%s-%s", switchID, port)
  638. dists = append(dists, DistributionNode{
  639. ID: id, Kind: "inferred", RouterID: switchID, Port: port,
  640. PortLabel: portLabel(p, port), MacCount: len(kept), Parent: cand.parent,
  641. })
  642. // #1791: los clientes del puerto cuelgan del nodo hoja, no del
  643. // gateway que les dio la IP. Sin AttachTo, hubOf los anclaba al
  644. // router y el nodo inferido quedaba vacío.
  645. for _, mac := range kept {
  646. if idx, ok := byMAC[mac]; ok {
  647. devices[idx].AttachTo = id
  648. // El puerto fisico del switch se conserva: claim no
  649. // re-ancla los clientes de una hoja (#1417), asi que
  650. // sin esto el chip perdia el dato.
  651. devices[idx].Port = port
  652. devices[idx].PortLabel = portLabel(p, port)
  653. }
  654. }
  655. }
  656. }
  657. }
  658. // Post-paso LLDP: un vecino cuya chassis-MAC es un Device conocido lo
  659. // identifica (Device.Lldp), en el puerto que sea y aunque no multiplexe.
  660. for _, routerID := range routerIDs {
  661. for i := range polled[routerID].lldp {
  662. nb := &polled[routerID].lldp[i]
  663. if nb.ChassisMac == "" {
  664. continue
  665. }
  666. if idx, ok := byMAC[nb.ChassisMac]; ok {
  667. devices[idx].Lldp = nb.info()
  668. }
  669. }
  670. }
  671. dists = dedupeDistributionNodes(dists)
  672. fillNodeSpeeds(polled, dists)
  673. return devices, dists
  674. }
  675. // dedupeDistributionNodes: un mismo puerto puede calificar por varias vias y
  676. // acabar con el mismo id mas de una vez (#2084). Se queda una sola entrada,
  677. // con precedencia determinista hypervisor > managed > inferred: manda la
  678. // evidencia mas fuerte y el orden de aparicion se conserva para el resto.
  679. func dedupeDistributionNodes(dists []DistributionNode) []DistributionNode {
  680. rank := map[string]int{"hypervisor": 3, "managed": 2, "inferred": 1}
  681. pos := make(map[string]int, len(dists))
  682. out := make([]DistributionNode, 0, len(dists))
  683. for _, d := range dists {
  684. if i, ok := pos[d.ID]; ok {
  685. if rank[d.Kind] > rank[out[i].Kind] {
  686. out[i] = d
  687. }
  688. continue
  689. }
  690. pos[d.ID] = len(out)
  691. out = append(out, d)
  692. }
  693. return out
  694. }
  695. // portLabel devuelve la etiqueta LuCI del puerto (issue #258) si el router
  696. // la define ("" si no existe): la app la usa como nombre preferente.
  697. func portLabel(p *routerPolled, port string) string {
  698. if p == nil || p.luci == nil {
  699. return ""
  700. }
  701. return p.luci.PortLabels[port]
  702. }
  703. // routerIdentity: datos de un router de la config para casar un vecino LLDP
  704. // aunque su chassis-ID no coincida con la bridge MAC. En OpenWrt/GLuON lldpd
  705. // suele anunciar como chassis la MAC de la primera interfaz (p.ej. eth0/WAN),
  706. // que NO es la br-lan que aprende el FDB del vecino: el matching exclusivo por
  707. // chassis-MAC dejaba links sin descubrir con lldpd instalado en todo (issue #252).
  708. type routerIdentity struct {
  709. ID, Name, Host string
  710. BrMac string
  711. // Type: tipo del router en la config ("glinet"|"openwrt"|"managed-switch"|…).
  712. // Distingue un switch gestionado (managed-switch) de un router regular:
  713. // un vecino LLDP que identifica a un router regular es un enlace
  714. // router↔router (uplink), no un switch que multiplexa (issue #300).
  715. Type string
  716. }
  717. // routerIdentities: identidades de todos los routers sondeados, en orden
  718. // determinista (el mapa polled no lo es).
  719. func routerIdentities(polled map[string]*routerPolled) []routerIdentity {
  720. ids := slices.Sorted(maps.Keys(polled))
  721. out := make([]routerIdentity, 0, len(ids))
  722. for _, id := range ids {
  723. p := polled[id]
  724. out = append(out, routerIdentity{ID: id, Name: p.cfg.Name, Host: p.cfg.Host, BrMac: p.brMac, Type: p.cfg.Type})
  725. }
  726. return out
  727. }
  728. // neighborIsRouter: el vecino LLDP identifica a un router conocido de la
  729. // config. Coincide por cualquiera de (prioridad): chassis-MAC = bridge MAC
  730. // (matching original, SPEC C2), mgmt-IP = Host, o nombre del chasis ≈ nombre
  731. // del router (case-insensitive). Los dos últimos son el fix tolerante al
  732. // chassis-ID distinto de la br-lan (issue #252). selfID se excluye (un router
  733. // no es su propio vecino). nil si no hay coincidencia.
  734. //
  735. // #1041: el match por nombre compara el PRIMER label DNS (case-insensitive):
  736. // un switch enrolado como "sw1.lan" debe casar con el chassis "sw1" que
  737. // anuncia lldpd, si no el uplink cae al gateway y el vecino duplica como
  738. // cliente. Antes exigía igualdad exacta del nombre completo.
  739. func neighborIsRouter(nb *LldpNeighbor, routers []routerIdentity, selfID string) *routerIdentity {
  740. if nb == nil {
  741. return nil
  742. }
  743. for i := range routers {
  744. r := &routers[i]
  745. if r.ID == selfID {
  746. continue
  747. }
  748. if nb.ChassisMac != "" && r.BrMac != "" && strings.EqualFold(nb.ChassisMac, r.BrMac) {
  749. return r
  750. }
  751. }
  752. for i := range routers {
  753. r := &routers[i]
  754. if r.ID == selfID {
  755. continue
  756. }
  757. if nb.Mgmt != "" && r.Host != "" && nb.Mgmt == r.Host {
  758. return r
  759. }
  760. }
  761. if chassis := firstDnsLabel(nb.Chassis); chassis != "" {
  762. for i := range routers {
  763. r := &routers[i]
  764. if r.ID == selfID {
  765. continue
  766. }
  767. // Los Host son IPs en la práctica: comparar primer label de una
  768. // IP sería "192"=="192" (falso positivo trivial). Solo nombres.
  769. if r.Name != "" && chassis == firstDnsLabel(r.Name) {
  770. return r
  771. }
  772. }
  773. }
  774. return nil
  775. }
  776. // firstDnsLabel normaliza a minúsculas y devuelve el primer label DNS
  777. // ("sw1.lan." → "sw1"). "" si no hay nada usable (#1041).
  778. func firstDnsLabel(s string) string {
  779. s = strings.TrimSuffix(strings.ToLower(strings.TrimSpace(s)), ".")
  780. if i := strings.Index(s, "."); i >= 0 {
  781. return s[:i]
  782. }
  783. return s
  784. }
  785. // fillNodeSpeeds pone la velocidad del PRIMER salto: lo que cuelga de una
  786. // boca del router va a la velocidad que el propio router negoció en ella, y
  787. // eso ya lo mide el agente. El sello de UniFi cubre lo que hay más allá
  788. // (bocas del switch); entre los dos, la tabla de enlaces deja de escribir
  789. // "1 Gbps" por defecto en filas que nadie ha medido.
  790. //
  791. // Solo sobre nodos que cuelgan directamente de un router (sin Parent) y a
  792. // los que nadie ha dado ya una velocidad.
  793. func fillNodeSpeeds(polled map[string]*routerPolled, dists []DistributionNode) {
  794. for i := range dists {
  795. if dists[i].SpeedMbps > 0 || dists[i].Parent != "" || dists[i].Port == "" {
  796. continue
  797. }
  798. p := polled[dists[i].RouterID]
  799. if p == nil {
  800. continue
  801. }
  802. for _, ep := range p.ports {
  803. if !ep.Up || !portMatchesName(ep, dists[i].Port) {
  804. continue
  805. }
  806. if mbps := parseSpeedMbps(ep.Speed); mbps > 0 {
  807. dists[i].SpeedMbps = mbps
  808. }
  809. break
  810. }
  811. }
  812. }
  813. // #1380: los enlaces con evidencia LLDP llevan la boca física del switch
  814. // ("3", del PortDesc LLDP) mientras la tabla de puertos del switch la
  815. // nombra "lan3". Se normaliza el prefijo "lan" (solo si va seguido de un
  816. // dígito) para casar ambos lados sin falsos positivos (lan10 != "1").
  817. func stripLANPrefix(s string) string {
  818. if len(s) > 3 && s[:3] == "lan" && s[3] >= '0' && s[3] <= '9' {
  819. return s[3:]
  820. }
  821. return s
  822. }
  823. // portMatchesName casa una boca sondeada (EthPort) con el nombre de puerto
  824. // que trae un enlace o un distnode. Comparar solo ep.ID se queda corto en
  825. // dos casos reales: los puertos SNMP viven con ID "snmp-<ifIndex>" y el
  826. // nombre humano ("xg2", "1/g9") en Iface, y el agente puede rotular el ID
  827. // con el rol ("wan") dejando la interfaz física ("eth0") en Iface, que es
  828. // justo la que reportan LLDP/FDB/override como childPort. Se prueban ID e
  829. // Iface con la misma normalización lan* y sin distinguir mayúsculas
  830. // (EqualFold cubre también la igualdad exacta); Label queda fuera porque es
  831. // campo de display ("LAN 1") y nunca sobrevive a la normalización. Sin dato
  832. // en el enlace, false para no afirmar velocidad.
  833. func portMatchesName(ep EthPort, name string) bool {
  834. if name == "" {
  835. return false
  836. }
  837. n := stripLANPrefix(name)
  838. for _, cand := range []string{ep.ID, ep.Iface} {
  839. if cand == "" {
  840. continue
  841. }
  842. if strings.EqualFold(stripLANPrefix(cand), n) {
  843. return true
  844. }
  845. }
  846. return false
  847. }
  848. // fillUplinkSpeeds (#1321): velocidad del uplink de una unidad cuando el
  849. // padre la reporta en esa boca (EthPort up + parseSpeedMbps, el mismo
  850. // criterio conservador de fillNodeSpeeds). El From del enlace puede ser el
  851. // router o un distnode suyo (salto #1060); en ambos casos la boca vive en
  852. // el router que la sondea. Sin dato, SpeedMbps queda a 0 y el front pinta
  853. // "—" en vez de afirmar una velocidad que nadie midió.
  854. func fillUplinkSpeeds(polled map[string]*routerPolled, dists []DistributionNode, links []TopoLink) {
  855. if len(links) == 0 {
  856. return
  857. }
  858. routerOfDist := map[string]string{}
  859. portOfDist := map[string]string{}
  860. for _, d := range dists {
  861. routerOfDist[d.ID] = d.RouterID
  862. portOfDist[d.ID] = d.Port
  863. }
  864. for i := range links {
  865. l := &links[i]
  866. if l.Kind != "uplink" || l.SpeedMbps > 0 || l.Port == "" {
  867. continue
  868. }
  869. routerID := l.From
  870. if r, ok := routerOfDist[l.From]; ok {
  871. routerID = r
  872. if p := portOfDist[l.From]; p != "" && p != l.Port {
  873. // El distnode ancla otra boca: su velocidad no describe
  874. // este enlace.
  875. continue
  876. }
  877. }
  878. p := polled[routerID]
  879. if p == nil {
  880. continue
  881. }
  882. for _, ep := range p.ports {
  883. if ep.Up && portMatchesName(ep, l.Port) {
  884. if mbps := parseSpeedMbps(ep.Speed); mbps > 0 {
  885. l.SpeedMbps = mbps
  886. }
  887. break
  888. }
  889. }
  890. }
  891. }
  892. // fillWiredSpeeds (#1384): velocidad de un enlace cableado cuando el padre
  893. // es un router de la flota sondeado directamente (gateway o switch
  894. // gestionado vía beacon, p. ej. el KP-9000) y midió esa boca (EthPort up +
  895. // parseSpeedMbps, el mismo criterio conservador de fillUplinkSpeeds). Es lo
  896. // que permite a la tabla de enlaces dar la velocidad del cable de un
  897. // hipervisor (citadel-01 en lan5 a 2,5 Gbps) aunque el device no traiga
  898. // speedMbps de ningún controlador.
  899. //
  900. // Solo enlaces que cuelgan DIRECTO del router: detrás de un distnode
  901. // (switch inferido/gestionado) o de otro device (los CTs de un hipervisor)
  902. // nadie midió la boca del dispositivo y SpeedMbps queda a 0 ("—" honesta).
  903. func fillWiredSpeeds(polled map[string]*routerPolled, dists []DistributionNode, links []TopoLink) {
  904. if len(links) == 0 {
  905. return
  906. }
  907. isDist := map[string]bool{}
  908. for _, d := range dists {
  909. isDist[d.ID] = true
  910. }
  911. for i := range links {
  912. l := &links[i]
  913. if l.Kind != "wired" || l.SpeedMbps > 0 || l.Port == "" {
  914. continue
  915. }
  916. if isDist[l.From] {
  917. continue
  918. }
  919. p := polled[l.From]
  920. if p == nil {
  921. continue
  922. }
  923. for _, ep := range p.ports {
  924. if ep.Up && portMatchesName(ep, l.Port) {
  925. if mbps := parseSpeedMbps(ep.Speed); mbps > 0 {
  926. l.SpeedMbps = mbps
  927. }
  928. break
  929. }
  930. }
  931. }
  932. }
  933. // fillUplinkSpeedsFromChild (#1429/#1471): los enlaces entre unidades
  934. // resueltos por FDB (los switches SNMP no aportan LLDP útil) ya identifican la
  935. // boca en AMBOS extremos (la evidencia FDB guarda también el childPort: la
  936. // boca del hijo hacia el padre, aprendida del propio FDB del hijo); desde
  937. // #1471 la evidencia LLDP trae ese mismo dato (el puerto local con el que la
  938. // unidad ve a su padre). Cuando el lado del padre no dio velocidad, se mira la
  939. // tabla de puertos del HIJO: un OpenWrt sabe la velocidad negociada de su
  940. // propia boca de uplink. El padre manda cuando ambos extremos reportan: son el
  941. // mismo cable y el dato del lado que sondea el enlace es el directo.
  942. func fillUplinkSpeedsFromChild(polled map[string]*routerPolled, evidence map[string]topoParent, links []TopoLink) {
  943. if len(links) == 0 {
  944. return
  945. }
  946. for i := range links {
  947. l := &links[i]
  948. if l.Kind != "uplink" || l.SpeedMbps > 0 {
  949. continue
  950. }
  951. ev, ok := evidence[l.To]
  952. if !ok || ev.childPort == "" {
  953. continue
  954. }
  955. p := polled[l.To]
  956. if p == nil {
  957. continue
  958. }
  959. for _, ep := range p.ports {
  960. if ep.Up && portMatchesName(ep, ev.childPort) {
  961. if mbps := parseSpeedMbps(ep.Speed); mbps > 0 {
  962. l.SpeedMbps = mbps
  963. }
  964. break
  965. }
  966. }
  967. }
  968. }