snmp_live.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665
  1. package adapters
  2. import (
  3. "fmt"
  4. "log"
  5. "math"
  6. "net"
  7. "os"
  8. "strings"
  9. "time"
  10. "github.com/gnacho/netpulse/server-go/internal/alerts"
  11. npsnmp "github.com/gnacho/netpulse/server-go/internal/snmp"
  12. "golang.org/x/net/icmp"
  13. "golang.org/x/net/ipv4"
  14. )
  15. // snmpSessionConfig traduce la configuración de la unidad al contrato del
  16. // poller. En v1/v2c va la comunidad y en v3 las credenciales USM (#2042):
  17. // mandar las dos cosas no rompe nada, pero deja el error más claro cuando
  18. // falta lo que la versión pide.
  19. func snmpSessionConfig(cfg RouterConfig) npsnmp.Config {
  20. c := npsnmp.Config{
  21. Host: cfg.Host,
  22. Port: cfg.SnmpPort,
  23. Version: npsnmp.ParseVersion(cfg.SnmpVersion),
  24. }
  25. if cfg.SnmpVersion == "3" {
  26. c.V3User = cfg.SnmpV3User
  27. c.V3SecurityLevel = cfg.SnmpV3SecurityLevel
  28. c.V3AuthProto = cfg.SnmpV3AuthProto
  29. c.V3AuthPass = cfg.SnmpV3AuthPass
  30. c.V3PrivProto = cfg.SnmpV3PrivProto
  31. c.V3PrivPass = cfg.SnmpV3PrivPass
  32. } else {
  33. c.Community = cfg.SnmpCommunity
  34. }
  35. return c
  36. }
  37. func (l *Live) pollRouterSNMP(cfg RouterConfig) (*routerPolled, error) {
  38. // issue #414: si no ha pasado el intervalo configurado, reutiliza el último
  39. // sondeo real para no martillear al switch con SNMP cada 5 s.
  40. interval := cfg.SnmpPollInterval
  41. if interval <= 0 {
  42. interval = 60
  43. }
  44. now := l.now()
  45. l.mu.Lock()
  46. last, hasLast := l.lastPolled[cfg.ID]
  47. lastPoll := l.snmpLastPoll[cfg.ID]
  48. l.mu.Unlock()
  49. if hasLast && last != nil && now.Sub(lastPoll) < time.Duration(interval)*time.Second {
  50. return last, nil
  51. }
  52. session, err := npsnmp.NewSession(snmpSessionConfig(cfg))
  53. if err != nil {
  54. // #930: error de sesión = fallo del poll SNMP (lastErr + consecFail).
  55. l.recordSnmpFailure(cfg, err)
  56. return nil, fmt.Errorf("snmp %s: %w", cfg.Host, err)
  57. }
  58. defer npsnmp.CloseSession(session)
  59. sysInfo, sysErr := npsnmp.PollSystem(session)
  60. if sysErr != nil {
  61. log.Printf("[netpulse] SNMP system %s: %v", cfg.LogLabel(), sysErr)
  62. }
  63. // #1256 + #1725: temperatura del chasis en switches MikroTik. Se lee la
  64. // health table por el NOMBRE de la sonda ("cpu-temperature"), no por el
  65. // índice 52 con `.0` que #1256 fijó de un SwOS: en RouterOS la tabla está
  66. // ahí mismo pero en otra fila, y el Get nunca contestaba (medido:
  67. // NoSuchObject en un CRS305 con 51 °C disponibles). Best-effort: los
  68. // switches que no exponen nada dejan hasTemp false (vitals a null como
  69. // antes, #441).
  70. descr := ""
  71. if sysInfo != nil {
  72. descr = sysInfo.Descr
  73. }
  74. mikroTemp, hasTemp := npsnmp.PollMikrotikTemp(session, descr)
  75. // Netgear FastPath (XS708T, GS728TXP/S3300…): CPU por proceso y sensores
  76. // de temperatura en su MIB privada (4526.11). Best-effort igual que el
  77. // MikroTik: sin esos árboles, ok=false y los vitales siguen a null.
  78. ngCpu, hasNgCpu, ngTemp, hasNgTemp := npsnmp.PollNetgearVitals(session)
  79. // #1725: HOST-RESOURCES (hrProcessorLoad / hrStorageTable "main memory")
  80. // para los equipos sin MIB privada de vitales (RouterOS por SNMP es el
  81. // caso real). Se pregunta primero y una sola vez por equipo
  82. // (hostResourcesKnown), porque hay agentes que descartan el árbol en
  83. // silencio y cada operación así cuesta DefaultTimeout×(Retries+1)=10 s.
  84. hrCpu, hasHrCpu, hrRam, hasHrRam := 0, false, 0, false
  85. if l.hostResourcesKnown(cfg.ID, func() bool { return npsnmp.HostResourcesPresent(session) }) {
  86. hrCpu, hasHrCpu, hrRam, hasHrRam = npsnmp.PollHostResourcesVitals(session)
  87. }
  88. // #1036: MAC propia del switch (dot1dBaseBridgeAddress). Sin ella el
  89. // equipo no tenía MAC en flota ni casaba por MAC en topología. Cache:
  90. // si el OID no contesta en este poll se conserva la última conocida.
  91. brMac, _ := npsnmp.PollBridgeAddress(session)
  92. l.mu.Lock()
  93. if brMac == "" {
  94. brMac = l.snmpBrMac[cfg.ID]
  95. } else {
  96. l.snmpBrMac[cfg.ID] = brMac
  97. }
  98. l.mu.Unlock()
  99. // #1767: ENTITY-MIB identity (firmware and short model). Generic RFC
  100. // 6933 columns; one walk, and a switch without the table leaves both
  101. // fields empty. Best-effort like the bridge MAC above.
  102. entity, _ := npsnmp.PollEntityInfo(session)
  103. // #1802: TP-Link firmware ignores ENTITY-MIB and HOST-RESOURCES-MIB but
  104. // publishes the same identity and vitals in its enterprise subtree. The
  105. // sysObjectID selects the vendor before paying for its OIDs; the private
  106. // MIB wins over the generic fallback, as the panel of the unit does.
  107. tpLink := npsnmp.TpLinkInfo{}
  108. if sysInfo != nil && npsnmp.IsTpLink(sysInfo.ObjectID) {
  109. tpLink = npsnmp.PollTpLinkInfo(session)
  110. }
  111. // Netgear FastPath publica además el chip del switch en su subtree
  112. // (BCM53412 / BCM53346). Ninguna otra fuente SNMP lo da: las unidades
  113. // OpenWrt lo leen por agente, y un gestionado sin agente no tiene dónde
  114. // decirlo. El firmware y el modelo corto también están aquí, pero ENTITY-MIB
  115. // ya los responde en esta familia, así que se usan solo de respaldo.
  116. netgear := npsnmp.NetgearIdentity{}
  117. if sysInfo != nil && npsnmp.IsNetgear(sysInfo.ObjectID) {
  118. netgear = npsnmp.PollNetgearIdentity(session)
  119. }
  120. ports, ifErr := npsnmp.PollIfTable(session)
  121. if ifErr != nil {
  122. log.Printf("[netpulse] SNMP ifTable %s: %v", cfg.LogLabel(), ifErr)
  123. }
  124. fdbPoll, fdbErr := npsnmp.PollFdbTable(session)
  125. fdb := fdbPoll.Entries
  126. if fdbErr != nil {
  127. log.Printf("[netpulse] SNMP FDB %s: %v", cfg.LogLabel(), fdbErr)
  128. } else {
  129. // #928: visibilidad mínima del resultado del FDB. Se loguea cuando el
  130. // conteo cambia respecto al ciclo anterior (o en el primer poll), no
  131. // cada 60 s: suficiente para diagnosticar "walk vacío/fallido" sin
  132. // inundar el journal. #948: la línea lleva además los PDUs crudos de
  133. // cada walk para distinguir "tabla vacía" de "datos no utilizables".
  134. l.mu.Lock()
  135. last, seen := l.snmpFdbCount[cfg.ID]
  136. l.snmpFdbCount[cfg.ID] = len(fdb)
  137. l.mu.Unlock()
  138. if !seen || last != len(fdb) {
  139. log.Printf("[netpulse] SNMP FDB %s: %d entries (source %s, pdus dot1d=%d dot1q=%d)", cfg.LogLabel(), len(fdb), fdbPoll.Source, fdbPoll.RawDot1d, fdbPoll.RawDot1q)
  140. }
  141. }
  142. // #930: salud del poll SNMP. Un poll se considera fallido cuando la
  143. // sesión falla (arriba), el Get de sistema no responde o el walk ifTable
  144. // no devuelve puertos. En fallo NO se devuelve error al caller (el router
  145. // puede estar vivo: es la comunidad/el puerto lo que falla); el error se
  146. // refleja en los contadores y, al 3.er fallo, en el ping de respaldo.
  147. if len(ports) == 0 {
  148. pollErr := ifErr
  149. if pollErr == nil {
  150. if sysErr != nil {
  151. pollErr = sysErr
  152. } else {
  153. pollErr = fmt.Errorf("snmp ifTable %s: no ports", cfg.Host)
  154. }
  155. }
  156. l.recordSnmpFailure(cfg, pollErr)
  157. } else {
  158. l.recordSnmpSuccess(cfg)
  159. }
  160. // #931: vecinos LLDP del switch vía LLDP-MIB (mismo contrato que la
  161. // sonda lldpd de los routers, #300). Alimenta routerPolled.lldp y con
  162. // ello la fase LLDP-first de la topología (inferLldpLinks). Un switch
  163. // sin LLDP devuelve (nil, nil) sin ruido; el error solo se loguea.
  164. lldpRem, lldpErr := npsnmp.PollLldpRemTable(session)
  165. if lldpErr != nil {
  166. log.Printf("[netpulse] SNMP LLDP %s: %v", cfg.LogLabel(), lldpErr)
  167. }
  168. portIdxToName := map[int]string{}
  169. for _, p := range ports {
  170. portIdxToName[p.Index] = p.DisplayName()
  171. }
  172. ethPorts := make([]EthPort, 0, len(ports))
  173. for _, p := range ports {
  174. name := p.DisplayName()
  175. label := name
  176. ethPorts = append(ethPorts, EthPort{
  177. ID: fmt.Sprintf("snmp-%d", p.Index),
  178. Label: label,
  179. Up: p.OperUp,
  180. Speed: p.SpeedString(),
  181. Iface: name,
  182. Family: p.Family,
  183. RxBytes: p.RxBytes,
  184. TxBytes: p.TxBytes,
  185. RxErrs: p.RxErrors,
  186. TxErrs: p.TxErrors,
  187. })
  188. }
  189. for i := range ethPorts {
  190. ethPorts[i].Snmp = true
  191. }
  192. prevPorts := l.snmpPrevPorts(cfg.ID)
  193. l.mu.Lock()
  194. l.snmpPortCache(cfg.ID, ethPorts)
  195. l.mu.Unlock()
  196. for i := range ethPorts {
  197. prev, ok := prevPorts[ethPorts[i].ID]
  198. if !ok {
  199. continue
  200. }
  201. dt := time.Since(prev.at).Seconds()
  202. if dt <= 0 {
  203. continue
  204. }
  205. if ethPorts[i].RxBytes >= prev.rxBytes {
  206. ethPorts[i].RxBps = math.Round(float64(ethPorts[i].RxBytes-prev.rxBytes)*8/dt*10) / 10
  207. }
  208. if ethPorts[i].TxBytes >= prev.txBytes {
  209. ethPorts[i].TxBps = math.Round(float64(ethPorts[i].TxBytes-prev.txBytes)*8/dt*10) / 10
  210. }
  211. }
  212. // #661: el path SNMP nunca persistía las muestras de puerto, así que el
  213. // historial de tráfico del switch quedaba vacío aunque el sondeo leyera los
  214. // contadores correctamente. Ahora se registran (misma ruta que SSH/agente).
  215. l.recordPortSamples(cfg.ID, ethPorts)
  216. // FDB → mapa MAC→puerto. Antes se descartaban las entradas cuyo ifIndex no
  217. // resolvía a un puerto conocido, lo que dejaba el switch con 0 dispositivos
  218. // conectados aunque el FDB viniera lleno (#661). Se cae a bridgePort y a un
  219. // nombre generado para no perder MACs (el conteo de clientes solo necesita
  220. // la clave; el nombre es secundario).
  221. fdbMap := snmpFdbMap(fdb, portIdxToName)
  222. selfMacs := snmpSelfMacs(fdb, portIdxToName)
  223. l.portMon.Observe(cfg.ID, ethPorts, l.engine)
  224. // #661: agregado de red del switch (suma de la tasa de todos los puertos)
  225. // para que la tarjeta de la flota pinte un sparkline con bps reales en
  226. // lugar de la línea plana a 0 (los switches SNMP sí tienen contadores de
  227. // bytes, a diferencia de los beacons, que solo reportan tramas).
  228. netPtr := snmpAggregateNet(ethPorts)
  229. var uptimeSec float64
  230. if sysInfo != nil {
  231. uptimeSec = float64(sysInfo.UpTimeSec)
  232. }
  233. p := &routerPolled{
  234. cfg: cfg,
  235. uptimeSec: uptimeSec,
  236. hasUptime: sysInfo != nil,
  237. net: netPtr,
  238. ports: ethPorts,
  239. fdb: fdbMap,
  240. selfMacs: selfMacs,
  241. brMac: brMac,
  242. lldp: snmpLldpNeighbors(lldpRem, portIdxToName),
  243. polledAt: now.UnixMilli(),
  244. }
  245. // #1767: ENTITY-MIB is optional identity, not a vitals source.
  246. p.snmpFirmware = entity.Firmware
  247. p.snmpModelShort = entity.ModelShort
  248. // #1802: fill only what the generic readers could not answer.
  249. if p.snmpFirmware == "" {
  250. p.snmpFirmware = tpLink.Firmware
  251. }
  252. if p.snmpModelShort == "" {
  253. p.snmpModelShort = tpLink.Hardware
  254. }
  255. if p.snmpFirmware == "" {
  256. p.snmpFirmware = netgear.Firmware
  257. }
  258. if p.snmpModelShort == "" {
  259. p.snmpModelShort = netgear.ModelShort
  260. }
  261. // El chip no tiene equivalente genérico: lo que dice el firmware del
  262. // switch es la única fuente, y se conserva tal cual (sin recorte ni
  263. // sustituto por arquitectura, que es lo que #43 y #45 retiraron).
  264. if netgear.SoC != "" {
  265. p.snmpSoC = netgear.SoC
  266. }
  267. if tpLink.HasCPU {
  268. p.cpu, p.hasCpu = tpLink.CPU, true
  269. }
  270. if tpLink.HasMemory {
  271. p.ram, p.hasRam = tpLink.Memory, true
  272. }
  273. if sysInfo != nil {
  274. // #1256: sysDescr declara el modelo completo del equipo (p. ej.
  275. // "CSS610-8G-2S+ SwOS v2.21") y sysName el hostname que define el
  276. // usuario; buildRouter los reparte entre Model y Name.
  277. p.sysDescr = sysInfo.Descr
  278. p.sysName = sysInfo.Name
  279. }
  280. p.temp, p.hasTemp = mikroTemp, hasTemp
  281. if !p.hasTemp && hasNgTemp {
  282. p.temp, p.hasTemp = ngTemp, true
  283. }
  284. if hasNgCpu {
  285. p.cpu, p.hasCpu = ngCpu, true
  286. }
  287. // #1725: HOST-RESOURCES solo rellena huecos (veáse
  288. // applyHostResourcesVitals).
  289. applyHostResourcesVitals(p, hrCpu, hasHrCpu, hrRam, hasHrRam)
  290. l.mu.Lock()
  291. l.snmpLastPoll[cfg.ID] = now
  292. l.mu.Unlock()
  293. return p, nil
  294. }
  295. // snmpHrEntry (#1725): si el agente de este equipo publica HOST-RESOURCES, y
  296. // cuándo se preguntó por última vez.
  297. type snmpHrEntry struct {
  298. at time.Time
  299. ok bool
  300. }
  301. // snmpHrProbeTTL: cada cuánto se vuelve a preguntar. Un firmware nuevo puede
  302. // añadir el árbol, y seis horas es un margen con el que nadie espera ver una
  303. // vital distinta; a cambio, un equipo que lo descarta en silencio paga UN
  304. // timeout por ventana en lugar de uno por poll (pollRouterSNMP corre cada
  305. // snmp_poll_interval, 60 s por defecto).
  306. const snmpHrProbeTTL = 6 * time.Hour
  307. // hostResourcesKnown cachea la respuesta de la pregunta "¿este agente tiene
  308. // HOST-RESOURCES?". El probe va como callback porque el paquete adapters no
  309. // importa gosnmp: la sesión SNMP sigue siendo un detalle de internal/snmp.
  310. func (l *Live) hostResourcesKnown(routerID string, probe func() bool) bool {
  311. now := l.now()
  312. l.mu.Lock()
  313. entry, seen := l.snmpHr[routerID]
  314. l.mu.Unlock()
  315. if seen && now.Sub(entry.at) < snmpHrProbeTTL {
  316. return entry.ok
  317. }
  318. ok := probe()
  319. l.mu.Lock()
  320. if l.snmpHr == nil {
  321. l.snmpHr = map[string]snmpHrEntry{}
  322. }
  323. l.snmpHr[routerID] = snmpHrEntry{at: now, ok: ok}
  324. l.mu.Unlock()
  325. return ok
  326. }
  327. // applyHostResourcesVitals (#1725): HOST-RESOURCES es respaldo, no segunda
  328. // opinión. Una lectura privada (la health table de MikroTik, el FastPath de
  329. // Netgear) es lo que el panel del propio equipo muestra; el árbol genérico mide
  330. // de otra forma, así que aquí solo rellena lo que quedó sin bandera. Y sin
  331. // bandera no inventa: ok=false no escribe ni un cero (#441).
  332. func applyHostResourcesVitals(p *routerPolled, cpu int, okCpu bool, ramPct int, okRam bool) {
  333. if p == nil {
  334. return
  335. }
  336. if !p.hasCpu && okCpu {
  337. p.cpu, p.hasCpu = cpu, true
  338. }
  339. if !p.hasRam && okRam {
  340. p.ram, p.hasRam = ramPct, true
  341. }
  342. }
  343. // snmpPollStat (issue #930): salud del sondeo SNMP por router. En memoria,
  344. // protegido por l.mu. failingOpen marca el incidente ABIERTO (alerta emitida
  345. // y aún no recuperada) para no repetir la alerta hasta la recuperación.
  346. type snmpPollStat struct {
  347. Ok int64
  348. Fail int64
  349. ConsecFail int64
  350. LastOkMs int64
  351. LastFailMs int64
  352. LastErr string
  353. failingOpen bool
  354. }
  355. // snmpStat devuelve (creando si falta) el contador de salud SNMP del router.
  356. // Debe llamarse con l.mu tomado.
  357. func (l *Live) snmpStat(id string) *snmpPollStat {
  358. if l.snmpPollStats == nil {
  359. l.snmpPollStats = map[string]*snmpPollStat{}
  360. }
  361. s := l.snmpPollStats[id]
  362. if s == nil {
  363. s = &snmpPollStat{}
  364. l.snmpPollStats[id] = s
  365. }
  366. return s
  367. }
  368. // recordSnmpSuccess registra un poll SNMP con datos (#930): ok++,
  369. // consecFail=0. Si había un incidente abierto, lo resuelve y emite la alerta
  370. // ok de recuperación (patrón agente outdated/updated).
  371. func (l *Live) recordSnmpSuccess(cfg RouterConfig) {
  372. name := cfg.Name
  373. if name == "" {
  374. name = cfg.Host
  375. }
  376. now := time.Now().UnixMilli()
  377. l.mu.Lock()
  378. s := l.snmpStat(cfg.ID)
  379. s.Ok++
  380. s.ConsecFail = 0
  381. s.LastOkMs = now
  382. wasOpen := s.failingOpen
  383. s.failingOpen = false
  384. l.mu.Unlock()
  385. if wasOpen {
  386. log.Printf("[netpulse] SNMP recuperado %s", cfg.LogLabel())
  387. failID := fmt.Sprintf("alert-snmp-failing-%s", cfg.ID)
  388. l.engine.Resolve(failID)
  389. l.engine.Emit(AlertEvent{
  390. ID: fmt.Sprintf("alert-snmp-recovered-%s-%d", cfg.ID, now),
  391. Category: alerts.CatSystem, Urgent: false,
  392. Severity: "ok",
  393. Title: "SNMP polling recovered on " + name,
  394. Description: fmt.Sprintf("SNMP polling for %s is responding again", name),
  395. Type: alerts.TypeSnmpRecovered,
  396. Vars: map[string]string{"router": name},
  397. Resolves: []string{failID}, // #1349
  398. Time: "just now", RouterID: cfg.ID,
  399. })
  400. }
  401. }
  402. // recordSnmpFailure registra un poll SNMP fallido (#930): fail++,
  403. // consecFail++, lastErr. En la transición al 3.er fallo seguido hace un ping
  404. // de respaldo al host: si responde, emite una alerta warn "snmp-failing"
  405. // (una por incidente); si no responde, solo loguea (la caída del router ya
  406. // la cubre el alerteo de offline).
  407. func (l *Live) recordSnmpFailure(cfg RouterConfig, err error) {
  408. name := cfg.Name
  409. if name == "" {
  410. name = cfg.Host
  411. }
  412. now := time.Now().UnixMilli()
  413. l.mu.Lock()
  414. s := l.snmpStat(cfg.ID)
  415. s.Fail++
  416. s.ConsecFail++
  417. s.LastFailMs = now
  418. s.LastErr = err.Error()
  419. consec := s.ConsecFail
  420. open := s.failingOpen
  421. lastErr := s.LastErr
  422. l.mu.Unlock()
  423. switch {
  424. case consec == 1:
  425. log.Printf("[netpulse] SNMP failure %s: %v", cfg.LogLabel(), err)
  426. case consec == 3 && !open:
  427. pingFn := l.ping
  428. if pingFn == nil {
  429. pingFn = pingHost
  430. }
  431. if !pingFn(cfg.Host) {
  432. log.Printf("[netpulse] SNMP %s: 3 consecutive failures and no ping response (device down), no SNMP alert", cfg.LogLabel())
  433. return
  434. }
  435. // Marcar incidente abierto (re-check bajo lock para no duplicar en
  436. // carreras entre goroutines de distintos routers).
  437. l.mu.Lock()
  438. s2 := l.snmpStat(cfg.ID)
  439. already := s2.failingOpen
  440. s2.failingOpen = true
  441. l.mu.Unlock()
  442. if already {
  443. return
  444. }
  445. l.engine.Emit(AlertEvent{
  446. ID: fmt.Sprintf("alert-snmp-failing-%s", cfg.ID),
  447. Category: alerts.CatSystem, Urgent: false,
  448. Severity: "warn",
  449. Title: "SNMP polling failing on " + name,
  450. Description: fmt.Sprintf("%s responds to ping but SNMP polling has failed 3 times (%s) - check community/port", name, lastErr),
  451. Hint: alerts.HintFor(alerts.HintSnmpFailing),
  452. Type: alerts.HintSnmpFailing,
  453. Vars: map[string]string{"router": name, "error": lastErr},
  454. Time: "just now", RouterID: cfg.ID,
  455. })
  456. }
  457. }
  458. // pingHost hace un ping ICMP (echo request) sin privilegios (#930): usa un
  459. // socket UDP no privilegiado (ListenPacket("udp4"), soportado por el
  460. // ping_group_range del kernel) en vez de un socket raw que requeriría root.
  461. // Devuelve true si el host responde al echo dentro de ~2 s.
  462. func pingHost(host string) bool {
  463. ip, err := net.ResolveIPAddr("ip4", host)
  464. if err != nil {
  465. return false
  466. }
  467. c, err := icmp.ListenPacket("udp4", "0.0.0.0")
  468. if err != nil {
  469. return false
  470. }
  471. defer c.Close()
  472. msg := icmp.Message{
  473. Type: ipv4.ICMPTypeEcho,
  474. Code: 0,
  475. Body: &icmp.Echo{
  476. ID: os.Getpid() & 0xffff,
  477. Seq: 1,
  478. Data: []byte("netpulse"),
  479. },
  480. }
  481. b, err := msg.Marshal(nil)
  482. if err != nil {
  483. return false
  484. }
  485. if _, err := c.WriteTo(b, &net.UDPAddr{IP: ip.IP}); err != nil {
  486. return false
  487. }
  488. if err := c.SetReadDeadline(time.Now().Add(2 * time.Second)); err != nil {
  489. return false
  490. }
  491. rb := make([]byte, 1500)
  492. for {
  493. n, _, err := c.ReadFrom(rb)
  494. if err != nil {
  495. return false
  496. }
  497. rm, err := icmp.ParseMessage(1, rb[:n])
  498. if err != nil {
  499. continue
  500. }
  501. if rm.Type == ipv4.ICMPTypeEchoReply {
  502. if echo, ok := rm.Body.(*icmp.Echo); ok && echo.ID == os.Getpid()&0xffff {
  503. return true
  504. }
  505. }
  506. }
  507. }
  508. type snmpPortSample struct {
  509. at time.Time
  510. rxBytes uint64
  511. txBytes uint64
  512. }
  513. func (l *Live) snmpPrevPorts(routerID string) map[string]snmpPortSample {
  514. l.mu.Lock()
  515. defer l.mu.Unlock()
  516. if l.snmpPorts == nil {
  517. return nil
  518. }
  519. return l.snmpPorts[routerID]
  520. }
  521. func (l *Live) snmpPortCache(routerID string, ports []EthPort) {
  522. if l.snmpPorts == nil {
  523. l.snmpPorts = map[string]map[string]snmpPortSample{}
  524. }
  525. samples := map[string]snmpPortSample{}
  526. now := time.Now()
  527. for _, p := range ports {
  528. samples[p.ID] = snmpPortSample{at: now, rxBytes: p.RxBytes, txBytes: p.TxBytes}
  529. }
  530. l.snmpPorts[routerID] = samples
  531. }
  532. // snmpFdbMap convierte el FDB (MAC→puerto) en el mapa que consume la
  533. // topología/dispositivos. #661: NO descarta entradas cuyo ifIndex no resuelve
  534. // a un puerto conocido (antes eso dejaba el switch con 0 dispositivos);
  535. // cae a bridgePort y, en último caso, a un nombre generado.
  536. func snmpFdbMap(fdb []npsnmp.FdbEntry, portIdxToName map[int]string) map[string]string {
  537. out := map[string]string{}
  538. for _, e := range fdb {
  539. name := ""
  540. if n, ok := portIdxToName[e.IfIndex]; ok {
  541. name = n
  542. } else if n, ok := portIdxToName[e.BridgePortIndex]; ok {
  543. name = n
  544. }
  545. if name == "" {
  546. name = fmt.Sprintf("port-%d", e.IfIndex)
  547. }
  548. if snmpInternalPort(name) {
  549. continue
  550. }
  551. out[e.MAC] = name
  552. }
  553. return out
  554. }
  555. // snmpSelfMacs: MACs aprendidas en los puertos internos de la unidad (CPU,
  556. // stack, mgmt). Son identidades del propio equipo, no clientes: sirven para
  557. // absorberlas también donde las aprenda un vecino (p.ej. la br-lan del
  558. // gateway al gestionarlo), que es el segundo fantasma de #1489.
  559. func snmpSelfMacs(fdb []npsnmp.FdbEntry, portIdxToName map[int]string) []string {
  560. out := []string{}
  561. for _, e := range fdb {
  562. name := ""
  563. if n, ok := portIdxToName[e.IfIndex]; ok {
  564. name = n
  565. } else if n, ok := portIdxToName[e.BridgePortIndex]; ok {
  566. name = n
  567. }
  568. if name == "" || !snmpInternalPort(name) {
  569. continue
  570. }
  571. out = append(out, e.MAC)
  572. }
  573. return out
  574. }
  575. // snmpInternalPort: puerto interno del propio switch (CPU/stack/mgmt). La MAC
  576. // que aparece ahí es del equipo, no de un cliente: un NETGEAR aprende su
  577. // propio CPU MAC en su puerto interno y lo publicaba como cliente fantasma
  578. // (#1489). Heurística sobre el nombre del puerto, que es lo único que expone
  579. // la ifTable de estos switches para esa interfaz.
  580. func snmpInternalPort(name string) bool {
  581. u := strings.ToUpper(name)
  582. return strings.Contains(u, "CPU") || strings.Contains(u, "INTERNAL")
  583. }
  584. // snmpLldpNeighbors convierte los vecinos LLDP-MIB del switch al contrato
  585. // LldpNeighbor (#931). El puerto se nombra como en el FDB (DisplayName del
  586. // ifTable vía ifIndex; fallback al número de puerto de bridge, paridad con
  587. // snmpFdbMap #661) para que inferLldpLinks case el vecino con las MACs
  588. // aprendidas en esa boca.
  589. func snmpLldpNeighbors(rem []npsnmp.LldpRemEntry, portIdxToName map[int]string) []LldpNeighbor {
  590. if len(rem) == 0 {
  591. return nil
  592. }
  593. out := make([]LldpNeighbor, 0, len(rem))
  594. for _, e := range rem {
  595. port := portIdxToName[e.IfIndex]
  596. if port == "" {
  597. port = portIdxToName[e.LocalPortNum]
  598. }
  599. if port == "" {
  600. port = fmt.Sprintf("port-%d", e.LocalPortNum)
  601. }
  602. out = append(out, LldpNeighbor{
  603. Port: port,
  604. ChassisMac: e.ChassisMac,
  605. Chassis: e.Chassis,
  606. Mgmt: e.Mgmt,
  607. Caps: e.Caps,
  608. PortDesc: e.PortDesc,
  609. ChassisFromLocDesc: e.ChassisFromLocDesc,
  610. })
  611. }
  612. return out
  613. }
  614. // snmpAggregateNet suma la tasa (bps) de todos los puertos para dar una
  615. // métrica agregada al switch SNMP (#661). Devuelve nil si todo está a 0
  616. // (primera muestra sin delta o sin tráfico).
  617. func snmpAggregateNet(ports []EthPort) *NetDevBps {
  618. var aggRx, aggTx float64
  619. for i := range ports {
  620. aggRx += ports[i].RxBps
  621. aggTx += ports[i].TxBps
  622. }
  623. if aggRx == 0 && aggTx == 0 {
  624. return nil
  625. }
  626. rx, tx := aggRx, aggTx
  627. return &NetDevBps{RxBps: &rx, TxBps: &tx}
  628. }