system_test.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. package snmp
  2. import (
  3. "fmt"
  4. "math/big"
  5. "strings"
  6. "testing"
  7. "github.com/gnacho/netpulse/server-go/internal/logonce"
  8. "github.com/gosnmp/gosnmp"
  9. )
  10. // #1036: la MAC base del bridge se normaliza a MAYÚSCULAS (#960) o "" si
  11. // el dato no es usable (OID ausente, vacío o longitud distinta de 6 octetos).
  12. func TestMacFromPDU(t *testing.T) {
  13. good := gosnmp.SnmpPDU{Name: OidDot1dBaseBridgeAddress, Type: gosnmp.OctetString, Value: []byte{0x02, 0x00, 0x00, 0x00, 0x00, 0x01}}
  14. if got := macFromPDU(good); got != "02:00:00:00:00:01" {
  15. t.Errorf("bytes: obtuve %q, esperaba 02:00:00:00:00:01", got)
  16. }
  17. str := gosnmp.SnmpPDU{Name: OidDot1dBaseBridgeAddress, Type: gosnmp.OctetString, Value: string([]byte{0x02, 0x00, 0x00, 0x00, 0x00, 0x02})}
  18. if got := macFromPDU(str); got != "02:00:00:00:00:02" {
  19. t.Errorf("string: obtuve %q, esperaba 02:00:00:00:00:02", got)
  20. }
  21. short := gosnmp.SnmpPDU{Name: OidDot1dBaseBridgeAddress, Type: gosnmp.OctetString, Value: []byte{0x01, 0x02}}
  22. if got := macFromPDU(short); got != "" {
  23. t.Errorf("PDU corta: obtuve %q, esperaba vacío", got)
  24. }
  25. long := gosnmp.SnmpPDU{Name: OidDot1dBaseBridgeAddress, Type: gosnmp.OctetString, Value: []byte{0x02, 0x00, 0x00, 0x00, 0x00, 0x01, 0x99}}
  26. if got := macFromPDU(long); got != "" {
  27. t.Errorf("PDU de 7 bytes: obtuve %q, esperaba vacío", got)
  28. }
  29. empty := gosnmp.SnmpPDU{Name: OidDot1dBaseBridgeAddress, Type: gosnmp.OctetString, Value: []byte{}}
  30. if got := macFromPDU(empty); got != "" {
  31. t.Errorf("PDU vacía: obtuve %q, esperaba vacío", got)
  32. }
  33. noObj := gosnmp.SnmpPDU{Name: OidDot1dBaseBridgeAddress, Type: gosnmp.NoSuchObject, Value: nil}
  34. if got := macFromPDU(noObj); got != "" {
  35. t.Errorf("nosuchobject: obtuve %q, esperaba vacío", got)
  36. }
  37. }
  38. // TestMacFromPDUWarnsOnce verifica que una PDU de longitud distinta de 6 bytes
  39. // registra un único aviso con prefijo [netpulse:snmp] nombrando su OID y
  40. // longitud, que un segundo sondeo idéntico no repite el aviso y que una PDU
  41. // vacía se descarta en silencio.
  42. func TestMacFromPDUWarnsOnce(t *testing.T) {
  43. var lines []string
  44. old := snmpWarn
  45. snmpWarn = logonce.NewWithLogf("[netpulse:snmp] ", func(f string, a ...any) {
  46. lines = append(lines, fmt.Sprintf(f, a...))
  47. })
  48. t.Cleanup(func() { snmpWarn = old })
  49. pdu := gosnmp.SnmpPDU{
  50. Name: OidDot1dBaseBridgeAddress,
  51. Type: gosnmp.OctetString,
  52. Value: []byte{0x02, 0x00, 0x00, 0x00, 0x00, 0x01, 0x99},
  53. }
  54. empty := gosnmp.SnmpPDU{
  55. Name: OidDot1dBaseBridgeAddress,
  56. Type: gosnmp.OctetString,
  57. Value: []byte{},
  58. }
  59. if got := macFromPDU(empty); got != "" {
  60. t.Fatalf("PDU vacía: obtuve %q, esperaba vacío", got)
  61. }
  62. if got := macFromPDU(pdu); got != "" {
  63. t.Fatalf("primera PDU de 7 bytes: obtuve %q, esperaba vacío", got)
  64. }
  65. if got := macFromPDU(pdu); got != "" {
  66. t.Fatalf("segunda PDU de 7 bytes: obtuve %q, esperaba vacío", got)
  67. }
  68. if len(lines) != 1 {
  69. t.Fatalf("avisos = %d (%q), esperaba exactamente 1", len(lines), lines)
  70. }
  71. if !strings.HasPrefix(lines[0], "[netpulse:snmp] ") ||
  72. !strings.Contains(lines[0], OidDot1dBaseBridgeAddress) ||
  73. !strings.Contains(lines[0], "len=7") {
  74. t.Fatalf("aviso inesperado: %q (esperaba prefijo [netpulse:snmp], OID %s y len=7)", lines[0], OidDot1dBaseBridgeAddress)
  75. }
  76. }
  77. // #1256: el Gauge32 del OID MikroTik da grados enteros; NoSuchInstance u
  78. // otro tipo dejan la vital a null (ok=false), y un valor fuera de rango
  79. // físico se descarta como basura.
  80. func TestMikrotikTempFromPDU(t *testing.T) {
  81. good := gosnmp.SnmpPDU{Name: OidMikrotikTemp, Type: gosnmp.Gauge32, Value: big.NewInt(60)}
  82. if n, ok := mikrotikTempFromPDU(good); !ok || n != 60 {
  83. t.Errorf("gauge 60: got (%d,%v)", n, ok)
  84. }
  85. noObj := gosnmp.SnmpPDU{Name: OidMikrotikTemp, Type: gosnmp.NoSuchInstance, Value: nil}
  86. if _, ok := mikrotikTempFromPDU(noObj); ok {
  87. t.Error("nosuchinstance debe dar ok=false")
  88. }
  89. str := gosnmp.SnmpPDU{Name: OidMikrotikTemp, Type: gosnmp.OctetString, Value: "60"}
  90. if _, ok := mikrotikTempFromPDU(str); ok {
  91. t.Error("octetstring debe dar ok=false")
  92. }
  93. hot := gosnmp.SnmpPDU{Name: OidMikrotikTemp, Type: gosnmp.Gauge32, Value: big.NewInt(900)}
  94. if _, ok := mikrotikTempFromPDU(hot); ok {
  95. t.Error("900 fuera de rango debe dar ok=false")
  96. }
  97. }
  98. // #1725: la health table de RouterOS. Muestra real de un CRS305 (RouterOS
  99. // 7.25), que es el caso que #1256 no cubría:
  100. //
  101. // .100.1.2.17 = STRING: "cpu-temperature"
  102. // .100.1.3.17 = INTEGER: 48
  103. // .100.1.4.17 = INTEGER: 1
  104. //
  105. // El Get de 100.1.3.52.0 no contestaba nunca aquí (NoSuchObject), así que la
  106. // temperatura se quedaba en null con el dato puesto en la tabla de al lado.
  107. func TestMikrotikHealthRowsPareaNombreYValor(t *testing.T) {
  108. names := []gosnmp.SnmpPDU{
  109. {Name: OidMikrotikHealthName + ".17", Type: gosnmp.OctetString, Value: "cpu-temperature"},
  110. {Name: OidMikrotikHealthName + ".18", Type: gosnmp.OctetString, Value: "switch-fan-state"},
  111. {Name: OidMikrotikHealthName + ".19", Type: gosnmp.OctetString, Value: "board-temperature"},
  112. }
  113. values := []gosnmp.SnmpPDU{
  114. {Name: OidMikrotikHealthValue + ".17", Type: gosnmp.Integer, Value: big.NewInt(48)},
  115. {Name: OidMikrotikHealthValue + ".18", Type: gosnmp.Integer, Value: big.NewInt(1)},
  116. {Name: OidMikrotikHealthValue + ".19", Type: gosnmp.Integer, Value: big.NewInt(51)},
  117. {Name: OidMikrotikHealthValue + ".52.0", Type: gosnmp.Integer, Value: big.NewInt(60)},
  118. }
  119. rows := mikrotikHealthRows(names, values)
  120. if len(rows) != 3 {
  121. t.Fatalf("filas = %d, want 3 (el scalar .52.0 no es una fila de la tabla): %v", len(rows), rows)
  122. }
  123. if rows["cpu-temperature"] != 48 || rows["board-temperature"] != 51 {
  124. t.Fatalf("apareadas mal: %v", rows)
  125. }
  126. if temp, ok := ParseMikrotikHealth(rows); !ok || temp != 48 {
  127. t.Fatalf("temp = %d/%v, want 48/true (cpu-temperature manda)", temp, ok)
  128. }
  129. }
  130. func TestParseMikrotikHealthFallbackYDescartes(t *testing.T) {
  131. // Equipo que no nombra la sonda "cpu-temperature": el punto caliente de
  132. // las filas de temperatura, no la primera que responde el walk.
  133. rows := map[string]int{"board-temperature": 47, "switch-temperature": 53, "fan-state": 1}
  134. if temp, ok := ParseMikrotikHealth(rows); !ok || temp != 53 {
  135. t.Errorf("temp = %d/%v, want 53 (máximo de las filas de temperatura)", temp, ok)
  136. }
  137. // cpu-temperature gana aunque haya otra fila más caliente: es la lectura
  138. // que /system health imprime como CPU.
  139. conCpu := map[string]int{"cpu-temperature": 48, "switch-temperature": 61}
  140. if temp, ok := ParseMikrotikHealth(conCpu); !ok || temp != 48 {
  141. t.Errorf("temp = %d/%v, want 48 (la sonda nombrada manda)", temp, ok)
  142. }
  143. if _, ok := ParseMikrotikHealth(map[string]int{"fan-state": 1, "pcie-power": 12}); ok {
  144. t.Error("una tabla sin ninguna fila de temperatura no da temperatura")
  145. }
  146. if _, ok := ParseMikrotikHealth(nil); ok {
  147. t.Error("tabla vacía ok=false: la vital se queda en null (#441)")
  148. }
  149. }
  150. // Las descripciones reales de los cuatro equipos de la flota que sirvieron de
  151. // muestra: dos MikroTik (un firmware y otro) y dos que no, para los que
  152. // preguntar la tabla costaría un timeout por poll.
  153. func TestDeclaresMikrotik(t *testing.T) {
  154. for _, descr := range []string{
  155. "RouterOS CRS305-1G-4S+ 7.25",
  156. "RouterOS hEX",
  157. "CSS610-8G-2S+ SwOS v2.21",
  158. } {
  159. if !declaresMikrotik(descr) {
  160. t.Errorf("%q es MikroTik y se descartó", descr)
  161. }
  162. }
  163. for _, descr := range []string{
  164. "FN SWITCH 8 PRO",
  165. "Netgear XS708T 8-Port 10-Gigabit Copper Smart Managed Pro Switch",
  166. "Linux ds1821plus 5.2",
  167. "",
  168. } {
  169. if declaresMikrotik(descr) {
  170. t.Errorf("%q no es MikroTik y se caminaría su tabla", descr)
  171. }
  172. }
  173. }