snmp_merge.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. package adapters
  2. import (
  3. "fmt"
  4. "log"
  5. "strings"
  6. "time"
  7. npsnmp "github.com/gnacho/netpulse/server-go/internal/snmp"
  8. )
  9. // snmpSurfaceEntry (#1726): lo que SNMP sabe de una unidad y el payload del
  10. // pusher no. Se cachea por router para no sondear SNMP en cada push.
  11. type snmpSurfaceEntry struct {
  12. at time.Time
  13. byIface map[string]EthPort
  14. lldp []LldpNeighbor
  15. ok bool
  16. }
  17. // mergeSNMPSurface completa con SNMP un sondeo que ya llegó por pusher
  18. // (#1726). Una unidad puede tener snmp_enabled y a la vez estar alimentada
  19. // por un agente: hasta ahora el poller devolvía en cuanto había payload
  20. // fresco y la rama SNMP no se alcanzaba nunca, así que el ajuste era un
  21. // no-op silencioso. Aquí SNMP es segunda fuente: solo rellena lo que el
  22. // payload no trae (velocidad de boca, contadores de error y vecinos LLDP).
  23. // No toca vitals (CPU/RAM/temperatura), que manda el payload desde #1724, ni
  24. // el FDB, que sí trae el agente.
  25. func (l *Live) mergeSNMPSurface(cfg RouterConfig, p *routerPolled) {
  26. if !cfg.SnmpEnabled || p == nil {
  27. return
  28. }
  29. interval := cfg.SnmpPollInterval
  30. if interval <= 0 {
  31. interval = 60
  32. }
  33. now := l.now()
  34. l.mu.Lock()
  35. entry, has := l.snmpSurface[cfg.ID]
  36. l.mu.Unlock()
  37. if !has || now.Sub(entry.at) >= time.Duration(interval)*time.Second {
  38. entry = l.pollSNMPSurface(cfg, now)
  39. l.mu.Lock()
  40. if l.snmpSurface == nil {
  41. l.snmpSurface = map[string]snmpSurfaceEntry{}
  42. }
  43. l.snmpSurface[cfg.ID] = entry
  44. l.mu.Unlock()
  45. }
  46. if !entry.ok {
  47. return
  48. }
  49. applySNMPSurface(p, entry)
  50. }
  51. // pollSNMPSurface sondea solo la superficie que el pusher no puede dar: la
  52. // tabla de interfaces (velocidad de enlace y contadores de error) y los
  53. // vecinos LLDP. Deliberadamente no llama a recordPortSamples ni a
  54. // portMon.Observe: las muestras del pusher ya entran por otro camino con sus
  55. // propios IDs, y duplicarlas aquí intercalaría filas con ids "snmp-N".
  56. func (l *Live) pollSNMPSurface(cfg RouterConfig, now time.Time) snmpSurfaceEntry {
  57. entry := snmpSurfaceEntry{at: now}
  58. session, err := npsnmp.NewSession(snmpSessionConfig(cfg))
  59. if err != nil {
  60. l.recordSnmpFailure(cfg, err)
  61. return entry
  62. }
  63. defer npsnmp.CloseSession(session)
  64. ports, ifErr := npsnmp.PollIfTable(session)
  65. if ifErr != nil || len(ports) == 0 {
  66. pollErr := ifErr
  67. if pollErr == nil {
  68. pollErr = fmt.Errorf("snmp ifTable %s: no ports", cfg.Host)
  69. }
  70. l.recordSnmpFailure(cfg, pollErr)
  71. return entry
  72. }
  73. // Misma salud SNMP que el poll completo: si esta unidad deja de responder
  74. // por SNMP, la alerta de #930 sigue viéndose aunque el pusher vaya bien.
  75. l.recordSnmpSuccess(cfg)
  76. byIface := make(map[string]EthPort, len(ports))
  77. portIdxToName := make(map[int]string, len(ports))
  78. for _, ps := range ports {
  79. name := ps.DisplayName()
  80. portIdxToName[ps.Index] = name
  81. key := strings.ToLower(strings.TrimSpace(name))
  82. if key == "" {
  83. continue
  84. }
  85. byIface[key] = EthPort{
  86. ID: fmt.Sprintf("snmp-%d", ps.Index),
  87. Label: name,
  88. Up: ps.OperUp,
  89. Speed: ps.SpeedString(),
  90. Iface: name,
  91. RxErrs: ps.RxErrors,
  92. TxErrs: ps.TxErrors,
  93. Snmp: true,
  94. }
  95. }
  96. var lldp []LldpNeighbor
  97. if rem, lldpErr := npsnmp.PollLldpRemTable(session); lldpErr != nil {
  98. log.Printf("[netpulse] SNMP LLDP %s: %v", cfg.LogLabel(), lldpErr)
  99. } else {
  100. lldp = snmpLldpNeighbors(rem, portIdxToName)
  101. }
  102. entry.byIface = byIface
  103. entry.lldp = lldp
  104. entry.ok = true
  105. return entry
  106. }
  107. // applySNMPSurface rellena en el sondeo del pusher lo que SNMP sí trae. Las
  108. // bocas se casan por ifName/ifAlias (el payload trae el mismo nombre que la
  109. // tabla de interfaces del equipo). Un dato del payload nunca se pisa: solo se
  110. // rellena cuando viene vacío o a cero.
  111. func applySNMPSurface(p *routerPolled, entry snmpSurfaceEntry) {
  112. if p == nil || len(entry.byIface) == 0 {
  113. return
  114. }
  115. for i := range p.ports {
  116. port := &p.ports[i]
  117. key := strings.ToLower(strings.TrimSpace(port.Iface))
  118. if key == "" {
  119. key = strings.ToLower(strings.TrimSpace(port.Label))
  120. }
  121. ref, ok := entry.byIface[key]
  122. if !ok {
  123. continue
  124. }
  125. // ifHighSpeed=0 significa "sin enlace" o "no reportado", no una
  126. // velocidad: solo se propaga una cifra positiva y solo si el payload
  127. // no dio ninguna.
  128. if parseSpeedMbps(port.Speed) == 0 && parseSpeedMbps(ref.Speed) > 0 {
  129. port.Speed = ref.Speed
  130. }
  131. // El contrato del payload no distingue "no reporto errores" de "cero
  132. // errores", así que un 0 se trata como desconocido y SNMP lo completa.
  133. if port.RxErrs == 0 && ref.RxErrs > 0 {
  134. port.RxErrs = ref.RxErrs
  135. }
  136. if port.TxErrs == 0 && ref.TxErrs > 0 {
  137. port.TxErrs = ref.TxErrs
  138. }
  139. }
  140. // RouterOS por API no expone LLDP (#1726), así que en estas unidades la
  141. // topología cae a las MACs del FDB. Los vecinos de LLDP-MIB son mejores
  142. // que esa conjetura.
  143. if len(p.lldp) == 0 && len(entry.lldp) > 0 {
  144. p.lldp = entry.lldp
  145. p.lldpUnavailable = false
  146. p.lldpHint = ""
  147. }
  148. }