system.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. package snmp
  2. import (
  3. "fmt"
  4. "math/big"
  5. "strings"
  6. "github.com/gosnmp/gosnmp"
  7. )
  8. type SystemInfo struct {
  9. Descr string
  10. ObjectID string
  11. Name string
  12. UpTimeSec uint64
  13. }
  14. func PollSystem(s *gosnmp.GoSNMP) (*SystemInfo, error) {
  15. oids := []string{OidSysDescr, OidSysObjectID, OidSysName, OidSysUpTime}
  16. result, err := s.Get(oids)
  17. if err != nil {
  18. return nil, fmt.Errorf("snmp system get: %w", err)
  19. }
  20. info := &SystemInfo{}
  21. for _, v := range result.Variables {
  22. switch v.Name {
  23. case OidSysDescr:
  24. info.Descr = stringVal(v)
  25. case OidSysObjectID:
  26. info.ObjectID = stringVal(v)
  27. case OidSysName:
  28. info.Name = stringVal(v)
  29. case OidSysUpTime:
  30. info.UpTimeSec = uint64Val(v) / 100
  31. }
  32. }
  33. return info, nil
  34. }
  35. func stringVal(v gosnmp.SnmpPDU) string {
  36. if v.Type == gosnmp.NoSuchObject || v.Type == gosnmp.NoSuchInstance {
  37. return ""
  38. }
  39. switch val := v.Value.(type) {
  40. case string:
  41. return val
  42. case []byte:
  43. return string(val)
  44. default:
  45. return fmt.Sprintf("%v", val)
  46. }
  47. }
  48. func uint64Val(v gosnmp.SnmpPDU) uint64 {
  49. if v.Type == gosnmp.NoSuchObject || v.Type == gosnmp.NoSuchInstance {
  50. return 0
  51. }
  52. if bi, ok := v.Value.(*big.Int); ok {
  53. return bi.Uint64()
  54. }
  55. return gosnmp.ToBigInt(v.Value).Uint64()
  56. }
  57. // PollBridgeAddress lee la MAC base del bridge (dot1dBaseBridgeAddress).
  58. // Devuelve "" (sin error) si el equipo no contesta el OID: es opcional y
  59. // NO debe tumbar el poll (#1036). La MAC se normaliza a MAYÚSCULAS, la
  60. // capitalización canónica del sistema (#960).
  61. func PollBridgeAddress(s *gosnmp.GoSNMP) (string, error) {
  62. result, err := s.Get([]string{OidDot1dBaseBridgeAddress})
  63. if err != nil {
  64. return "", nil
  65. }
  66. for _, v := range result.Variables {
  67. if v.Name != OidDot1dBaseBridgeAddress {
  68. continue
  69. }
  70. return macFromPDU(v), nil
  71. }
  72. return "", nil
  73. }
  74. // PollMikrotikTemp lee la temperatura de la health table de MikroTik (#1725).
  75. //
  76. // Antes era un Get del índice 52 que #1256 copió de un SwOS. En RouterOS la
  77. // tabla existe pero la sonda está en otro índice y sin el `.0` final
  78. // (`100.1.2.17 = "cpu-temperature"`, `100.1.3.17 = 48`), así que el Get nunca
  79. // contestaba y la vital se quedaba en null aunque el agente tuviera el dato.
  80. //
  81. // La tabla se camina SOLO si sysDescr declara el firmware de MikroTik
  82. // ("RouterOS…" o "…SwOS…"): hay agentes que DESCARTAN lo que no está en su
  83. // vista MIB en vez de responder NoSuchObject, y cada operación así cuesta
  84. // DefaultTimeout×(Retries+1) = 10 s (medido en un XS708T y un S3300). Con el
  85. // filtro, un equipo que no es MikroTik paga exactamente lo que pagaba antes.
  86. //
  87. // Si la tabla no da nada (o ni siquiera se intentó, porque PollSystem falló y
  88. // no hay descripción) se cae al Get histórico de #1256, que es lo que hoy
  89. // responde en un SwOS. Best-effort en cualquier caso: sin lectura válida
  90. // (0, false) y el poll sigue (#1036), nunca un cero (#441).
  91. func PollMikrotikTemp(s *gosnmp.GoSNMP, sysDescr string) (temp int, ok bool) {
  92. if s == nil {
  93. return 0, false
  94. }
  95. if declaresMikrotik(sysDescr) {
  96. names, errName := walkSafe(s, OidMikrotikHealthName)
  97. values, errVal := []gosnmp.SnmpPDU(nil), error(nil)
  98. if errName == nil && len(names) > 0 {
  99. // Sin nombres no hay nada que aparear: el segundo walk sería un
  100. // RTT más en cada poll de un equipo que no publica la tabla.
  101. values, errVal = walkSafe(s, OidMikrotikHealthValue)
  102. }
  103. if errName == nil && errVal == nil {
  104. if t, tok := ParseMikrotikHealth(mikrotikHealthRows(names, values)); tok {
  105. return t, true
  106. }
  107. }
  108. }
  109. result, err := s.Get([]string{OidMikrotikTemp})
  110. if err != nil {
  111. return 0, false
  112. }
  113. for _, v := range result.Variables {
  114. if v.Name != OidMikrotikTemp {
  115. continue
  116. }
  117. return mikrotikTempFromPDU(v)
  118. }
  119. return 0, false
  120. }
  121. // declaresMikrotik: el firmware del equipo en su propia descripción. RouterOS
  122. // publica "RouterOS CRS305-1G-4S+ 7.25" y SwOS "CSS610-8G-2S+ SwOS v2.21"
  123. // (#1256); ambos son el mismo árbol 14988.
  124. func declaresMikrotik(sysDescr string) bool {
  125. d := strings.ToLower(sysDescr)
  126. return strings.Contains(d, "routeros") || strings.Contains(d, "swos")
  127. }
  128. // mikrotikHealthRows cruza nombre y valor por el índice final del OID. Un
  129. // índice sin nombre o sin valor utilizable se descarta: la tabla de salud
  130. // tiene filas que no son temperatura (el .4 es un flag), y aparearlas por las
  131. // fuerzas daría una lectura con nombre equivocado.
  132. func mikrotikHealthRows(names, values []gosnmp.SnmpPDU) map[string]int {
  133. byIdx := map[int]int{}
  134. for _, v := range values {
  135. idx := trailingIndex(v.Name, OidMikrotikHealthValue)
  136. if idx == 0 {
  137. continue
  138. }
  139. if n, ok := mikrotikTempFromPDU(v); ok {
  140. byIdx[idx] = n
  141. }
  142. }
  143. out := map[string]int{}
  144. for _, n := range names {
  145. idx := trailingIndex(n.Name, OidMikrotikHealthName)
  146. name := strings.ToLower(strings.TrimSpace(stringVal(n)))
  147. if idx == 0 || name == "" {
  148. continue
  149. }
  150. if val, ok := byIdx[idx]; ok {
  151. out[name] = val
  152. }
  153. }
  154. return out
  155. }
  156. // ParseMikrotikHealth: la temperatura de la health table a partir de las filas
  157. // ya apareadas nombre→valor. `cpu-temperature` manda (es la que /system health
  158. // imprime como CPU); si el equipo la nombra de otra forma se toma el MÁXIMO de
  159. // las filas cuyo nombre contenga "temperature" (el punto caliente, el mismo
  160. // criterio que los sensores Netgear (ParseNetgearTemps) y así el orden del
  161. // walk no decide la lectura.
  162. func ParseMikrotikHealth(rows map[string]int) (temp int, ok bool) {
  163. if v, found := rows["cpu-temperature"]; found {
  164. return v, true
  165. }
  166. for name, v := range rows {
  167. if !strings.Contains(name, "temperature") {
  168. continue
  169. }
  170. if !ok || v > temp {
  171. temp, ok = v, true
  172. }
  173. }
  174. return temp, ok
  175. }
  176. // mikrotikTempFromPDU convierte el Gauge32 del OID de temperatura a (°C,
  177. // true). NoSuchObject/Instance u otro tipo de dato → (0, false): la vital
  178. // queda a null en la UI (#441), no a cero falso.
  179. func mikrotikTempFromPDU(v gosnmp.SnmpPDU) (int, bool) {
  180. if v.Type == gosnmp.NoSuchObject || v.Type == gosnmp.NoSuchInstance {
  181. return 0, false
  182. }
  183. // Solo tipos numéricos: ToBigInt parsea strings y octet strings, que
  184. // aquí serían un dato del equipo mal formado, no una temperatura.
  185. switch v.Type {
  186. case gosnmp.Gauge32, gosnmp.Integer, gosnmp.Counter32, gosnmp.Counter64:
  187. default:
  188. return 0, false
  189. }
  190. bi, okBig := v.Value.(*big.Int)
  191. if !okBig {
  192. bi = gosnmp.ToBigInt(v.Value)
  193. }
  194. if !bi.IsInt64() {
  195. return 0, false
  196. }
  197. n := bi.Int64()
  198. if n < -40 || n > 125 {
  199. return 0, false // fuera de rango físico: dato basura, no una temp
  200. }
  201. return int(n), true
  202. }