topology.go 34 KB

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