| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008 |
- package adapters
- import (
- "fmt"
- "maps"
- "slices"
- "sort"
- "strings"
- )
- // ---------------------------------------------------------------------------
- // Inferencia de topología v5 (FDB): puertos físicos, switches/bridges e
- // hipervisores. Función pura (sin SSH ni BD) para ser testeable.
- //
- // Reglas (plan 2-Ago-2026; regla de anclaje refinada 2-Ago-2026):
- // - Un puerto físico (lanN) con UNA MAC aprendida = cableado directo →
- // Device.Port.
- // - Un puerto con VARIAS MACs = algo multiplexándolo (switch, hipervisor,
- // PLC…). El FDB no dice qué: OUI heterogéneo → "inferred" (círculo
- // dashed, sin afirmar); alguna MAC con OUI de hipervisor y exactamente
- // un host → "hypervisor" (sus VMs se anidan bajo el host).
- // - Se excluyen las MACs de los propios routers (su bridge br-lan) y las
- // de clientes atribuidos a OTROS routers (los clientes wifi de un AP
- // aparecen en el FDB del gateway por el puerto del uplink).
- // - Anclaje al GATEWAY (decisión del usuario 2-Ago-2026): los nodos
- // "inferred" SOLO se crean en el gateway. En un AP, un puerto multi-MAC
- // es casi seguro su UPLINK (aprende las MACs de toda la LAN) y el FDB
- // no puede distinguirlo de un switch local → no se afirma nada: esos
- // clientes quedan "sin evidencia" y el frontend los cuelgan del gateway.
- // Única excepción tras un AP: hipervisor con evidencia clara (MACs OUI
- // de hipervisor + exactamente un host) = servidor con VMs tras ese AP.
- // - LLDP (Fase 2, contrato C2): si en un puerto multi-MAC se anuncia un
- // vecino LLDP cuya chassis-MAC está entre las aprendidas, el equipo que
- // multiplexa queda IDENTIFICADO → nodo "managed" (nombre/mgmt-ip/caps
- // anunciados). Es evidencia positiva, como la de hipervisor: aplica
- // también tras un AP (el uplink al gateway no puede promover porque su
- // MAC está excluida de las aprendidas). Además, cualquier vecino cuya
- // chassis-MAC sea un Device conocido puebla Device.Lldp. Sin datos LLDP
- // todo sigue exactamente como antes (inferred/hypervisor + reglas OUI).
- // ---------------------------------------------------------------------------
- // hypervisorOUI: prefijos de MAC de hipervisores conocidos.
- var hypervisorOUI = []string{
- "BC:24:11", // Proxmox VE
- "00:50:56", // VMware (ESXi/Workstation)
- "00:0C:29", // VMware
- "00:15:5D", // Hyper-V
- "52:54:00", // KVM/QEMU
- "08:00:27", // VirtualBox
- }
- func isHypervisorMAC(mac string) bool {
- upper := strings.ToUpper(mac)
- for _, p := range hypervisorOUI {
- if strings.HasPrefix(upper, p) {
- return true
- }
- }
- return false
- }
- // fdbByPort invierte el FDB: puerto → MACs (el WAN no es distribución LAN).
- func fdbByPort(fdb map[string]string) map[string][]string {
- byPort := map[string][]string{}
- for mac, port := range fdb {
- if port == "wan" {
- continue
- }
- byPort[port] = append(byPort[port], mac)
- }
- return byPort
- }
- // fdbPortOf devuelve el puerto donde el FDB aprendio `mac`, comparando sin
- // distinguir mayusculas (las claves del FDB no vienen normalizadas). #2084:
- // si el vecino LLDP ya se aprende por otro puerto, el anuncio de este no es
- // un enlace hacia ese equipo.
- func fdbPortOf(fdb map[string]string, mac string) (string, bool) {
- for m, port := range fdb {
- if strings.EqualFold(m, mac) {
- return port, true
- }
- }
- return "", false
- }
- // keptMacsForPort: MACs del puerto `port` que cuentan como clientes reales
- // del router (excluye las bridge-MACs de routers y los clientes de OTROS
- // routers: los clientes wifi de un AP aparecen en el FDB del gateway por el
- // puerto del uplink).
- func keptMacsForPort(portMACs []string, routerID string, byMAC map[string]int, devices []Device, routerMACs map[string]bool) []string {
- kept := make([]string, 0, len(portMACs))
- for _, mac := range portMACs {
- if routerMACs[mac] {
- continue
- }
- if idx, ok := byMAC[mac]; ok {
- d := devices[idx]
- if d.RouterID != routerID {
- continue
- }
- if d.Band != "cable" && d.Band != "—" {
- continue
- }
- }
- kept = append(kept, mac)
- }
- return kept
- }
- // leafSwitchClients (#1325): MACs de un puerto del FDB de un SWITCH gestionado
- // que cuentan como clientes para el umbral de switch hoja (>= 2). Excluye las
- // bridge-MACs de la flota y los clientes wifi conocidos (los de un AP que
- // transitan por el switch). A diferencia de keptMacsForPort, NO filtra por
- // RouterID: los clientes cableados de un switch se atribuyen al DHCP server
- // (casi siempre el gateway), no al switch, y aquí importa el enlace físico.
- func leafSwitchClients(portMACs []string, byMAC map[string]int, devices []Device, routerMACs map[string]bool) []string {
- kept := make([]string, 0, len(portMACs))
- for _, mac := range portMACs {
- if routerMACs[mac] {
- continue
- }
- if idx, ok := byMAC[mac]; ok {
- if devices[idx].Band != "cable" && devices[idx].Band != "—" {
- continue
- }
- }
- kept = append(kept, mac)
- }
- return kept
- }
- // hypervisorHostMAC: MAC del host de un hipervisor claro en `kept` (MACs OUI
- // de hipervisor + exactamente un host normal, siendo ese host un Device del
- // router). Vacío+false si el puerto no es un hipervisor claro.
- func hypervisorHostMAC(kept []string, routerID string, byMAC map[string]int, devices []Device) (string, bool) {
- var vmMACs, hostMACs []string
- for _, mac := range kept {
- if isHypervisorMAC(mac) {
- vmMACs = append(vmMACs, mac)
- } else {
- hostMACs = append(hostMACs, mac)
- }
- }
- if len(vmMACs) > 0 && len(hostMACs) == 1 {
- if hidx, ok := byMAC[hostMACs[0]]; ok && devices[hidx].RouterID == routerID {
- return hostMACs[0], true
- }
- }
- return "", false
- }
- // attachKeptToDist: setPort para los clientes cableados del puerto y cuelga
- // del distnode a todos salvo al propio switch (SPEC-CANON D2: sin self-attach).
- func attachKeptToDist(devices []Device, byMAC map[string]int, routerID, distID, port, portLabel string, kept []string, switchMac string) {
- for _, mac := range kept {
- idx, ok := byMAC[mac]
- if !ok || devices[idx].RouterID != routerID {
- continue
- }
- devices[idx].Port = port
- devices[idx].PortLabel = portLabel
- if mac == switchMac {
- continue
- }
- devices[idx].AttachTo = distID
- }
- }
- // inferLldpLinks: Fase LLDP-first (issue #300), ANTES del análisis FDB. Usa
- // los vecinos LLDP como ground truth de los enlaces de infraestructura
- // (router↔switch y switch↔switch): crea el distnode "managed" de cada switch
- // identificado y encadena las cadenas switch→switch con Parent. Devuelve los
- // puertos ya resueltos por LLDP para que el bucle FDB los salte.
- //
- // Un vecino que identifica a un ROUTER regular (glinet/openwrt) NO genera
- // nodo managed: es un enlace router↔router (uplink), su puerto queda resuelto.
- // Un puerto hipervisor claro se deja para el FDB (la evidencia de hipervisor
- // manda sobre la de LLDP).
- func inferLldpLinks(polled map[string]*routerPolled, devices []Device, byMAC map[string]int, routerMACs map[string]bool, routers []routerIdentity) ([]DistributionNode, map[string]map[string]bool) {
- handled := map[string]map[string]bool{}
- markHandled := func(routerID, port string) {
- if handled[routerID] == nil {
- handled[routerID] = map[string]bool{}
- }
- handled[routerID][port] = true
- }
- distByMac := map[string]string{}
- routerIDs := slices.Sorted(maps.Keys(polled))
- var dists []DistributionNode
- for _, routerID := range routerIDs {
- p := polled[routerID]
- if len(p.lldp) == 0 {
- continue
- }
- byPort := fdbByPort(p.fdb)
- for i := range p.lldp {
- nb := &p.lldp[i]
- if nb.Port == "" {
- continue
- }
- if handled[routerID][nb.Port] {
- continue
- }
- kept := keptMacsForPort(byPort[nb.Port], routerID, byMAC, devices, routerMACs)
- if len(kept) == 0 {
- continue
- }
- ri := neighborIsRouter(nb, routers, routerID)
- if ri != nil {
- if ri.Type != "managed-switch" {
- // Router regular: enlace router↔router (uplink), no switch.
- markHandled(routerID, nb.Port)
- continue
- }
- // Router de tipo managed-switch: es un switch (issue #252).
- //
- // #2084: pero si este router ya aprende la MAC del vecino por
- // OTRO puerto, el enlace real es ese y el LLDP que llega aqui
- // viene de un segmento L2 compartido (un AP en medio). El caso
- // medido: A aprende la MAC de B en su LAG y recibe los LLDP de
- // B por un access port que spanning tree tiene en Discarding.
- // Materializar el nodo ahi dibujaba el mismo switch dos veces,
- // sobre una entrada FDB que oscila con cada trama LLDP.
- if ri.BrMac != "" {
- if learned, ok := fdbPortOf(p.fdb, ri.BrMac); ok && !strings.EqualFold(learned, nb.Port) {
- markHandled(routerID, nb.Port)
- continue
- }
- }
- } else if nb.ChassisMac == "" || !containsMAC(kept, nb.ChassisMac) {
- // Ni identidad de router ni chassis-MAC aprendida en el puerto:
- // no hay evidencia de que sea el equipo que multiplexa.
- continue
- }
- if _, isHyp := hypervisorHostMAC(kept, routerID, byMAC, devices); isHyp {
- continue
- }
- if len(kept) == 1 {
- continue // cableado directo, sin nodo de distribución
- }
- upper := strings.ToUpper(nb.ChassisMac)
- if upper != "" {
- if _, dup := distByMac[upper]; dup {
- markHandled(routerID, nb.Port)
- continue
- }
- }
- id := fmt.Sprintf("dist-%s-%s", routerID, nb.Port)
- parent := distByMac[strings.ToUpper(p.brMac)]
- if upper != "" {
- distByMac[upper] = id
- }
- dists = append(dists, DistributionNode{
- ID: id, Kind: "managed", RouterID: routerID, Port: nb.Port,
- PortLabel: portLabel(p, nb.Port), Parent: parent,
- MacCount: len(kept), Name: nb.displayName(), Ip: nb.Mgmt,
- Mac: nb.ChassisMac, Lldp: nb.info(),
- })
- if idx, ok := byMAC[nb.ChassisMac]; ok {
- devices[idx].Infra = "managed-switch"
- }
- attachKeptToDist(devices, byMAC, routerID, id, nb.Port, portLabel(p, nb.Port), kept, nb.ChassisMac)
- markHandled(routerID, nb.Port)
- }
- }
- return dists, handled
- }
- // cfgIsSwitch: el disyuntivo de rol "Switch" de buildRouter (#661/#1137):
- // agent-only, managed-switch, o external sondeado por SNMP. La pasada de
- // claim (#1417) usa el mismo criterio para decidir qué unidades de flota
- // pueden reclamar clientes con su FDB.
- func cfgIsSwitch(c RouterConfig) bool {
- return c.AgentOnly || c.Type == "managed-switch" || (c.Type == "external" && c.SnmpEnabled)
- }
- // claimSwitchFdbClients (#1417): los clientes cableados atribuidos al gateway
- // que la FDB de un switch de flota aprendió en un puerto que NO es su root
- // port están físicamente detrás de ese switch, aunque la única atribución
- // DHCP disponible sea la del gateway (los switches SNMP no dan DHCP ni LLDP
- // útil: para la atribución son clientes del gateway; ver leafSwitchClients).
- //
- // Reglas:
- // - Root port del switch = el puerto donde su FDB aprende la bridge-MAC del
- // gateway (#1373). Sin esa MAC en su FDB el switch no reclama nada: sin
- // root port no se distingue arriba de abajo.
- // - Si varios switches reclaman la misma MAC (el trunk de sw1 ve también a
- // los clientes de sw2), gana el más profundo según la evidencia de uplink
- // (override > lldp > fdb, la precedencia de BuildTopoSemantics); empate
- // de profundidad → id menor (determinista).
- // - Un puerto del switch con hoja inferida #1325 ya creada recibe los
- // attach de sus clientes (la hoja se llena; no se rodea).
- // - Solo se re-anclan devices atribuidos al gateway con banda cable/"—"
- // cuyo attach esté vacío o apunte a un distnode del gateway (el blob
- // sombra #1374): un attach a un device-hub (hipervisor) o a un distnode
- // de otro router no se toca. Los blobs del gateway que queden vacíos los
- // absorbe después la pasada #1374 sin dejar huérfanos.
- //
- // Mutates devices; dists solo se lee.
- func claimSwitchFdbClients(polled map[string]*routerPolled, devices []Device, dists []DistributionNode, gatewayID string, fdbEv, lldpEv, overrideEv map[string]topoParent) {
- if gatewayID == "" {
- return
- }
- gw := polled[gatewayID]
- if gw == nil || gw.brMac == "" {
- return
- }
- gwMac := strings.ToUpper(gw.brMac)
- routerMACs := map[string]bool{}
- ids := make([]string, 0, len(polled))
- for id, p := range polled {
- ids = append(ids, id)
- if p.brMac != "" {
- routerMACs[strings.ToUpper(p.brMac)] = true
- }
- }
- sort.Strings(ids)
- // Uplinks por precedencia (override > lldp > fdb) y profundidad desde el
- // gateway para el desempate entre switches.
- up := map[string]topoParent{}
- for rid, ev := range fdbEv {
- if rid != gatewayID {
- up[rid] = ev
- }
- }
- for rid, ev := range lldpEv {
- if rid != gatewayID {
- up[rid] = ev // el LLDP pisa la FDB (#1279)
- }
- }
- for rid, ev := range overrideEv {
- if rid != gatewayID && ev.parent != rid {
- up[rid] = ev // el override manual lo pisa todo (#1321)
- }
- }
- depth := map[string]int{gatewayID: 0}
- for iter := 0; iter <= len(ids); iter++ {
- changed := false
- for _, rid := range ids {
- if rid == gatewayID {
- continue
- }
- ev, ok := up[rid]
- if !ok {
- continue
- }
- if d, seen := depth[ev.parent]; seen && depth[rid] < d+1 {
- depth[rid] = d + 1
- changed = true
- }
- }
- if !changed {
- break
- }
- }
- // Reclamos por MAC: el switch más profundo gana.
- type swClaim struct {
- switchID string // switch que aprende la MAC (para portLabel)
- target string // id del switch o de su hoja #1325
- port string
- depth int
- }
- best := map[string]swClaim{}
- for _, sid := range ids {
- if sid == gatewayID {
- continue
- }
- p := polled[sid]
- if !cfgIsSwitch(p.cfg) || len(p.fdb) == 0 {
- continue
- }
- root := p.fdb[gwMac]
- if root == "" {
- continue // sin root port conocido: no se distingue arriba de abajo
- }
- for mac, port := range p.fdb {
- if port == root || mac == "" {
- continue
- }
- if routerMACs[mac] {
- continue
- }
- // Un puerto con hoja #1325 ya creada reclama para la hoja.
- target := sid
- for _, dn := range dists {
- if dn.RouterID == sid && dn.Port == port && (dn.Kind == "inferred" || dn.Kind == "managed") {
- target = dn.ID
- break
- }
- }
- c := swClaim{switchID: sid, target: target, port: port, depth: depth[sid]}
- if prev, ok := best[mac]; ok {
- if c.depth < prev.depth || (c.depth == prev.depth && target >= prev.target) {
- continue
- }
- }
- best[mac] = c
- }
- }
- if len(best) == 0 {
- return
- }
- // Aplicar: solo gateway-atribuidos cableados con attach vacío o a blob
- // del gateway; device-hubs y distnodes ajenos intactos.
- distRouter := map[string]string{}
- for _, dn := range dists {
- distRouter[dn.ID] = dn.RouterID
- }
- for i := range devices {
- d := &devices[i]
- if d.RouterID != gatewayID || (d.Band != "cable" && d.Band != "—") {
- continue
- }
- if d.AttachTo != "" && distRouter[d.AttachTo] != gatewayID {
- continue // device-hub, distnode de otro router o id desconocido
- }
- c, ok := best[strings.ToUpper(d.MAC)]
- if !ok {
- continue
- }
- d.AttachTo = c.target
- d.Port = c.port
- d.PortLabel = portLabel(polled[c.switchID], c.port)
- }
- }
- // containsMAC: ¿está mac (case-sensitive, como el FDB) en la lista?
- func containsMAC(macs []string, mac string) bool {
- for _, m := range macs {
- if m == mac {
- return true
- }
- }
- return false
- }
- // inferTopology enriquece devices con Port/AttachTo e infiere los
- // DistributionNode del FDB sondeado. `polled` lleva fdb (MAC→puerto, ya
- // filtrado a lanN/wan por parseBridgeFdb) y brMac por router.
- func inferTopology(polled map[string]*routerPolled, devices []Device) ([]Device, []DistributionNode) {
- byMAC := make(map[string]int, len(devices))
- for i, d := range devices {
- byMAC[d.MAC] = i
- }
- routerMACs := map[string]bool{}
- for _, p := range polled {
- if p.brMac != "" {
- routerMACs[p.brMac] = true
- }
- }
- var dists []DistributionNode
- // routers en orden determinista (el mapa polled no lo es)
- routerIDs := slices.Sorted(maps.Keys(polled))
- // Gateway con la misma prioridad que pickGateway (is_gateway → glinet →
- // primero): solo él puede anclar nodos "inferred".
- gatewayID := ""
- if gw := pickGatewayCfg(polled); gw != nil {
- gatewayID = gw.ID
- }
- // Identidades de routers para el matching LLDP tolerante (issue #252):
- // un vecino cuya mgmt-IP/nombre coincide con un router conocido identifica
- // el switch/AP aunque su chassis-ID no esté entre las MACs aprendidas.
- routers := routerIdentities(polled)
- // Fase LLDP-first (issue #300): enlaces de infraestructura por LLDP antes
- // del análisis FDB. Los puertos resueltos aquí se saltan en el bucle FDB.
- lldpDists, lldpHandled := inferLldpLinks(polled, devices, byMAC, routerMACs, routers)
- dists = append(dists, lldpDists...)
- for _, routerID := range routerIDs {
- p := polled[routerID]
- byPort := fdbByPort(p.fdb)
- ports := slices.Sorted(maps.Keys(byPort))
- for _, port := range ports {
- if lldpHandled[routerID][port] {
- continue
- }
- kept := keptMacsForPort(byPort[port], routerID, byMAC, devices, routerMACs)
- if len(kept) == 0 {
- continue
- }
- setPort := func() {
- for _, mac := range kept {
- if idx, ok := byMAC[mac]; ok && devices[idx].RouterID == routerID {
- devices[idx].Port = port
- devices[idx].PortLabel = portLabel(p, port)
- }
- }
- }
- if len(kept) == 1 {
- // cableado directo: puerto conocido, sin nodo de distribución
- setPort()
- continue
- }
- // puerto multi-MAC
- id := fmt.Sprintf("dist-%s-%s", routerID, port)
- var vmMACs, hostMACs []string
- for _, mac := range kept {
- if isHypervisorMAC(mac) {
- vmMACs = append(vmMACs, mac)
- } else {
- hostMACs = append(hostMACs, mac)
- }
- }
- if len(vmMACs) > 0 && len(hostMACs) == 1 {
- if hidx, ok := byMAC[hostMACs[0]]; ok && devices[hidx].RouterID == routerID {
- // Hipervisor con host identificado: evidencia clara, válida
- // también tras un AP (servidor con VMs colgando de ese AP).
- setPort()
- dists = append(dists, DistributionNode{
- ID: id, Kind: "hypervisor", RouterID: routerID, Port: port,
- PortLabel: portLabel(p, port),
- MacCount: len(kept), HostDeviceID: devices[hidx].ID, Name: devices[hidx].Name,
- })
- // SPEC-65 D65-2: sellado de infra — host = hypervisor,
- // las MACs con OUI de hipervisor anidadas bajo él = ct.
- devices[hidx].Infra = "hypervisor"
- for _, mac := range vmMACs {
- if idx, ok := byMAC[mac]; ok && devices[idx].RouterID == routerID {
- devices[idx].AttachTo = devices[hidx].ID
- devices[idx].Infra = "ct"
- }
- }
- continue
- }
- }
- // LLDP: los switches gestionados se resolvieron ya en la fase
- // LLDP-first (inferLldpLinks); este puerto solo llega aquí sin
- // evidencia LLDP, así que sigue el flujo FDB (hipervisor ya
- // descartado arriba).
- if routerID != gatewayID && !polled[routerID].cfg.AgentOnly {
- // AP con puerto multi-MAC sin evidencia de hipervisor: es casi
- // seguro su uplink (aprende las MACs de toda la LAN). No se
- // afirma switch local ni se anota puerto: los clientes quedan
- // "sin evidencia" y el frontend los ancla al gateway.
- continue
- }
- // Gateway, OUI heterogéneo (o hipervisor ambiguo sin host claro):
- // algo multiplexa ese puerto → nodo inferido colgando del gateway.
- setPort()
- dn := DistributionNode{
- ID: id, Kind: "inferred", RouterID: routerID, Port: port, PortLabel: portLabel(p, port), MacCount: len(kept),
- }
- if routerID == gatewayID {
- for _, rp := range polled {
- if !rp.cfg.AgentOnly {
- continue
- }
- swMacs := map[string]bool{}
- for mac := range rp.fdb {
- swMacs[mac] = true
- }
- allKnown := true
- for _, mac := range kept {
- if !swMacs[mac] {
- allKnown = false
- break
- }
- }
- if allKnown && len(kept) > 0 {
- dn.Name = rp.cfg.Name
- dn.Ip = rp.cfg.Host
- break
- }
- }
- }
- dists = append(dists, dn)
- for _, mac := range kept {
- if idx, ok := byMAC[mac]; ok && devices[idx].RouterID == routerID {
- devices[idx].AttachTo = id
- }
- }
- }
- }
- // #1325: switches hoja inferidos tras switches gestionados. Un switch
- // gestionado (distnode kind="managed") aprende en SU FDB los clientes
- // cableados de un switch hoja no gestionado: cada puerto que NO sea su
- // uplink (root port, donde aprende la bridge-MAC del gateway) y que
- // aprenda >= 2 clientes cableados -> nodo inferido hoja anclado al switch
- // (Parent) para que cuelgue de él en el mapa, no del router. Los APs
- // (no-switch) siguen excluidos: su puerto multi-MAC es su propio uplink.
- // La fase FDB no los veía porque keptMacsForPort filtra por RouterID y
- // los clientes de un switch se atribuyen al DHCP server (el gateway).
- if gatewayID != "" {
- gwMac := ""
- if gw := polled[gatewayID]; gw != nil {
- gwMac = strings.ToUpper(gw.brMac)
- }
- // #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
- }
- // 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]
- }
- byPort := fdbByPort(p.fdb)
- ports := slices.Sorted(maps.Keys(byPort))
- for _, port := range ports {
- if port == rootPort {
- continue // uplink del propio switch (bucle)
- }
- if lldpHandled[switchID][port] {
- continue
- }
- occupied := false
- for _, d2 := range dists {
- // #2084: cualquier nodo del mismo puerto lo ocupa, tambien
- // el de hipervisor. Antes solo se miraban managed/inferred,
- // asi que un puerto con hipervisor recibia ademas un nodo
- // inferred con el MISMO id y el grafo emitia dos entradas.
- if d2.RouterID == switchID && d2.Port == port {
- occupied = true
- break
- }
- }
- if occupied {
- continue // el puerto ya tiene distnode managed/inferred
- }
- kept := leafSwitchClients(byPort[port], byMAC, devices, routerMACs)
- if len(kept) < 2 {
- continue
- }
- id := fmt.Sprintf("dist-%s-%s", switchID, port)
- dists = append(dists, DistributionNode{
- ID: id, Kind: "inferred", RouterID: switchID, Port: port,
- PortLabel: portLabel(p, port), MacCount: len(kept), Parent: 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
- // router y el nodo inferido quedaba vacío.
- 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)
- }
- }
- }
- }
- }
- // Post-paso LLDP: un vecino cuya chassis-MAC es un Device conocido lo
- // identifica (Device.Lldp), en el puerto que sea y aunque no multiplexe.
- for _, routerID := range routerIDs {
- for i := range polled[routerID].lldp {
- nb := &polled[routerID].lldp[i]
- if nb.ChassisMac == "" {
- continue
- }
- if idx, ok := byMAC[nb.ChassisMac]; ok {
- devices[idx].Lldp = nb.info()
- }
- }
- }
- dists = dedupeDistributionNodes(dists)
- fillNodeSpeeds(polled, dists)
- return devices, dists
- }
- // dedupeDistributionNodes: un mismo puerto puede calificar por varias vias y
- // acabar con el mismo id mas de una vez (#2084). Se queda una sola entrada,
- // con precedencia determinista hypervisor > managed > inferred: manda la
- // evidencia mas fuerte y el orden de aparicion se conserva para el resto.
- func dedupeDistributionNodes(dists []DistributionNode) []DistributionNode {
- rank := map[string]int{"hypervisor": 3, "managed": 2, "inferred": 1}
- pos := make(map[string]int, len(dists))
- out := make([]DistributionNode, 0, len(dists))
- for _, d := range dists {
- if i, ok := pos[d.ID]; ok {
- if rank[d.Kind] > rank[out[i].Kind] {
- out[i] = d
- }
- continue
- }
- pos[d.ID] = len(out)
- out = append(out, d)
- }
- return out
- }
- // portLabel devuelve la etiqueta LuCI del puerto (issue #258) si el router
- // la define ("" si no existe): la app la usa como nombre preferente.
- func portLabel(p *routerPolled, port string) string {
- if p == nil || p.luci == nil {
- return ""
- }
- return p.luci.PortLabels[port]
- }
- // routerIdentity: datos de un router de la config para casar un vecino LLDP
- // aunque su chassis-ID no coincida con la bridge MAC. En OpenWrt/GLuON lldpd
- // suele anunciar como chassis la MAC de la primera interfaz (p.ej. eth0/WAN),
- // que NO es la br-lan que aprende el FDB del vecino: el matching exclusivo por
- // chassis-MAC dejaba links sin descubrir con lldpd instalado en todo (issue #252).
- type routerIdentity struct {
- ID, Name, Host string
- BrMac string
- // Type: tipo del router en la config ("glinet"|"openwrt"|"managed-switch"|…).
- // Distingue un switch gestionado (managed-switch) de un router regular:
- // un vecino LLDP que identifica a un router regular es un enlace
- // router↔router (uplink), no un switch que multiplexa (issue #300).
- Type string
- }
- // routerIdentities: identidades de todos los routers sondeados, en orden
- // determinista (el mapa polled no lo es).
- func routerIdentities(polled map[string]*routerPolled) []routerIdentity {
- ids := slices.Sorted(maps.Keys(polled))
- out := make([]routerIdentity, 0, len(ids))
- for _, id := range ids {
- p := polled[id]
- out = append(out, routerIdentity{ID: id, Name: p.cfg.Name, Host: p.cfg.Host, BrMac: p.brMac, Type: p.cfg.Type})
- }
- return out
- }
- // neighborIsRouter: el vecino LLDP identifica a un router conocido de la
- // config. Coincide por cualquiera de (prioridad): chassis-MAC = bridge MAC
- // (matching original, SPEC C2), mgmt-IP = Host, o nombre del chasis ≈ nombre
- // del router (case-insensitive). Los dos últimos son el fix tolerante al
- // chassis-ID distinto de la br-lan (issue #252). selfID se excluye (un router
- // no es su propio vecino). nil si no hay coincidencia.
- //
- // #1041: el match por nombre compara el PRIMER label DNS (case-insensitive):
- // un switch enrolado como "sw1.lan" debe casar con el chassis "sw1" que
- // anuncia lldpd, si no el uplink cae al gateway y el vecino duplica como
- // cliente. Antes exigía igualdad exacta del nombre completo.
- func neighborIsRouter(nb *LldpNeighbor, routers []routerIdentity, selfID string) *routerIdentity {
- if nb == nil {
- return nil
- }
- for i := range routers {
- r := &routers[i]
- if r.ID == selfID {
- continue
- }
- if nb.ChassisMac != "" && r.BrMac != "" && strings.EqualFold(nb.ChassisMac, r.BrMac) {
- return r
- }
- }
- for i := range routers {
- r := &routers[i]
- if r.ID == selfID {
- continue
- }
- if nb.Mgmt != "" && r.Host != "" && nb.Mgmt == r.Host {
- return r
- }
- }
- if chassis := firstDnsLabel(nb.Chassis); chassis != "" {
- for i := range routers {
- r := &routers[i]
- if r.ID == selfID {
- continue
- }
- // Los Host son IPs en la práctica: comparar primer label de una
- // IP sería "192"=="192" (falso positivo trivial). Solo nombres.
- if r.Name != "" && chassis == firstDnsLabel(r.Name) {
- return r
- }
- }
- }
- return nil
- }
- // firstDnsLabel normaliza a minúsculas y devuelve el primer label DNS
- // ("sw1.lan." → "sw1"). "" si no hay nada usable (#1041).
- func firstDnsLabel(s string) string {
- s = strings.TrimSuffix(strings.ToLower(strings.TrimSpace(s)), ".")
- if i := strings.Index(s, "."); i >= 0 {
- return s[:i]
- }
- return s
- }
- // fillNodeSpeeds pone la velocidad del PRIMER salto: lo que cuelga de una
- // boca del router va a la velocidad que el propio router negoció en ella, y
- // eso ya lo mide el agente. El sello de UniFi cubre lo que hay más allá
- // (bocas del switch); entre los dos, la tabla de enlaces deja de escribir
- // "1 Gbps" por defecto en filas que nadie ha medido.
- //
- // Solo sobre nodos que cuelgan directamente de un router (sin Parent) y a
- // los que nadie ha dado ya una velocidad.
- func fillNodeSpeeds(polled map[string]*routerPolled, dists []DistributionNode) {
- for i := range dists {
- if dists[i].SpeedMbps > 0 || dists[i].Parent != "" || dists[i].Port == "" {
- continue
- }
- p := polled[dists[i].RouterID]
- if p == nil {
- continue
- }
- for _, ep := range p.ports {
- if !ep.Up || !portMatchesName(ep, dists[i].Port) {
- continue
- }
- if mbps := parseSpeedMbps(ep.Speed); mbps > 0 {
- dists[i].SpeedMbps = mbps
- }
- break
- }
- }
- }
- // #1380: los enlaces con evidencia LLDP llevan la boca física del switch
- // ("3", del PortDesc LLDP) mientras la tabla de puertos del switch la
- // nombra "lan3". Se normaliza el prefijo "lan" (solo si va seguido de un
- // dígito) para casar ambos lados sin falsos positivos (lan10 != "1").
- func stripLANPrefix(s string) string {
- if len(s) > 3 && s[:3] == "lan" && s[3] >= '0' && s[3] <= '9' {
- return s[3:]
- }
- return s
- }
- // portMatchesName casa una boca sondeada (EthPort) con el nombre de puerto
- // que trae un enlace o un distnode. Comparar solo ep.ID se queda corto en
- // dos casos reales: los puertos SNMP viven con ID "snmp-<ifIndex>" y el
- // nombre humano ("xg2", "1/g9") en Iface, y el agente puede rotular el ID
- // con el rol ("wan") dejando la interfaz física ("eth0") en Iface, que es
- // justo la que reportan LLDP/FDB/override como childPort. Se prueban ID e
- // Iface con la misma normalización lan* y sin distinguir mayúsculas
- // (EqualFold cubre también la igualdad exacta); Label queda fuera porque es
- // campo de display ("LAN 1") y nunca sobrevive a la normalización. Sin dato
- // en el enlace, false para no afirmar velocidad.
- func portMatchesName(ep EthPort, name string) bool {
- if name == "" {
- return false
- }
- n := stripLANPrefix(name)
- for _, cand := range []string{ep.ID, ep.Iface} {
- if cand == "" {
- continue
- }
- if strings.EqualFold(stripLANPrefix(cand), n) {
- return true
- }
- }
- return false
- }
- // fillUplinkSpeeds (#1321): velocidad del uplink de una unidad cuando el
- // padre la reporta en esa boca (EthPort up + parseSpeedMbps, el mismo
- // criterio conservador de fillNodeSpeeds). El From del enlace puede ser el
- // router o un distnode suyo (salto #1060); en ambos casos la boca vive en
- // el router que la sondea. Sin dato, SpeedMbps queda a 0 y el front pinta
- // "—" en vez de afirmar una velocidad que nadie midió.
- func fillUplinkSpeeds(polled map[string]*routerPolled, dists []DistributionNode, links []TopoLink) {
- if len(links) == 0 {
- return
- }
- routerOfDist := map[string]string{}
- portOfDist := map[string]string{}
- for _, d := range dists {
- routerOfDist[d.ID] = d.RouterID
- portOfDist[d.ID] = d.Port
- }
- for i := range links {
- l := &links[i]
- if l.Kind != "uplink" || l.SpeedMbps > 0 || l.Port == "" {
- continue
- }
- routerID := l.From
- if r, ok := routerOfDist[l.From]; ok {
- routerID = r
- if p := portOfDist[l.From]; p != "" && p != l.Port {
- // El distnode ancla otra boca: su velocidad no describe
- // este enlace.
- continue
- }
- }
- p := polled[routerID]
- if p == nil {
- continue
- }
- for _, ep := range p.ports {
- if ep.Up && portMatchesName(ep, l.Port) {
- if mbps := parseSpeedMbps(ep.Speed); mbps > 0 {
- l.SpeedMbps = mbps
- }
- break
- }
- }
- }
- }
- // fillWiredSpeeds (#1384): velocidad de un enlace cableado cuando el padre
- // es un router de la flota sondeado directamente (gateway o switch
- // gestionado vía beacon, p. ej. el KP-9000) y midió esa boca (EthPort up +
- // parseSpeedMbps, el mismo criterio conservador de fillUplinkSpeeds). Es lo
- // que permite a la tabla de enlaces dar la velocidad del cable de un
- // hipervisor (citadel-01 en lan5 a 2,5 Gbps) aunque el device no traiga
- // speedMbps de ningún controlador.
- //
- // Solo enlaces que cuelgan DIRECTO del router: detrás de un distnode
- // (switch inferido/gestionado) o de otro device (los CTs de un hipervisor)
- // nadie midió la boca del dispositivo y SpeedMbps queda a 0 ("—" honesta).
- func fillWiredSpeeds(polled map[string]*routerPolled, dists []DistributionNode, links []TopoLink) {
- if len(links) == 0 {
- return
- }
- isDist := map[string]bool{}
- for _, d := range dists {
- isDist[d.ID] = true
- }
- for i := range links {
- l := &links[i]
- if l.Kind != "wired" || l.SpeedMbps > 0 || l.Port == "" {
- continue
- }
- if isDist[l.From] {
- continue
- }
- p := polled[l.From]
- if p == nil {
- continue
- }
- for _, ep := range p.ports {
- if ep.Up && portMatchesName(ep, l.Port) {
- if mbps := parseSpeedMbps(ep.Speed); mbps > 0 {
- l.SpeedMbps = mbps
- }
- break
- }
- }
- }
- }
- // fillUplinkSpeedsFromChild (#1429/#1471): los enlaces entre unidades
- // resueltos por FDB (los switches SNMP no aportan LLDP útil) ya identifican la
- // boca en AMBOS extremos (la evidencia FDB guarda también el childPort: la
- // boca del hijo hacia el padre, aprendida del propio FDB del hijo); desde
- // #1471 la evidencia LLDP trae ese mismo dato (el puerto local con el que la
- // unidad ve a su padre). Cuando el lado del padre no dio velocidad, se mira la
- // tabla de puertos del HIJO: un OpenWrt sabe la velocidad negociada de su
- // propia boca de uplink. El padre manda cuando ambos extremos reportan: son el
- // mismo cable y el dato del lado que sondea el enlace es el directo.
- func fillUplinkSpeedsFromChild(polled map[string]*routerPolled, evidence map[string]topoParent, links []TopoLink) {
- if len(links) == 0 {
- return
- }
- for i := range links {
- l := &links[i]
- if l.Kind != "uplink" || l.SpeedMbps > 0 {
- continue
- }
- ev, ok := evidence[l.To]
- if !ok || ev.childPort == "" {
- continue
- }
- p := polled[l.To]
- if p == nil {
- continue
- }
- for _, ep := range p.ports {
- if ep.Up && portMatchesName(ep, ev.childPort) {
- if mbps := parseSpeedMbps(ep.Speed); mbps > 0 {
- l.SpeedMbps = mbps
- }
- break
- }
- }
- }
- }
|