vitals_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. package adapters
  2. import (
  3. "context"
  4. "testing"
  5. "github.com/gnacho/netpulse/agent/probe"
  6. )
  7. // #1568: una fuente SNMP puede tener solo CPU o solo temperatura. La lectura
  8. // presente debe llegar al contrato y marcar las vitals como disponibles; las
  9. // ausentes siguen siendo nil para que la UI no invente valores.
  10. func TestBuildRouterExposesPartialSnmpVitals(t *testing.T) {
  11. tests := []struct {
  12. name string
  13. cpu, temp int
  14. hasCPU, hasTemp bool
  15. wantCPU, wantTemp *int
  16. wantAvailable bool
  17. }{
  18. {name: "cpu only", cpu: 37, hasCPU: true, wantCPU: intPtr(37), wantAvailable: true},
  19. {name: "temp only", temp: 51, hasTemp: true, wantTemp: intPtr(51), wantAvailable: true},
  20. {name: "cpu and temp", cpu: 22, temp: 48, hasCPU: true, hasTemp: true, wantCPU: intPtr(22), wantTemp: intPtr(48), wantAvailable: true},
  21. {name: "no readings", cpu: 90, temp: 90, wantAvailable: false},
  22. }
  23. for _, tc := range tests {
  24. t.Run(tc.name, func(t *testing.T) {
  25. l := NewLive(nil, nil, nil, nil)
  26. p := &routerPolled{
  27. cfg: RouterConfig{ID: "sw1", Host: "192.168.1.10", SnmpEnabled: true},
  28. cpu: tc.cpu,
  29. temp: tc.temp,
  30. hasCpu: tc.hasCPU,
  31. hasTemp: tc.hasTemp,
  32. polledAt: 1000,
  33. }
  34. r := l.buildRouter(p, nil)
  35. if r.VitalsAvailable == nil || *r.VitalsAvailable != tc.wantAvailable {
  36. t.Fatalf("VitalsAvailable=%v, esperaba %v", r.VitalsAvailable, tc.wantAvailable)
  37. }
  38. if !equalOptionalInt(r.CPU, tc.wantCPU) || !equalOptionalInt(r.Temp, tc.wantTemp) || r.RAM != nil {
  39. t.Fatalf("vitals: cpu=%v (quiere %v) ram=%v temp=%v (quiere %v)", r.CPU, tc.wantCPU, r.RAM, r.Temp, tc.wantTemp)
  40. }
  41. })
  42. }
  43. }
  44. // #1568: el histórico usa los mismos flags que la tarjeta. Antes limpiaba CPU
  45. // y temperatura para cualquier fuente SNMP aunque el poller sí las tuviera.
  46. func TestMetricsRowsKeepPartialSnmpVitals(t *testing.T) {
  47. l := NewLive(nil, nil, nil, nil)
  48. l.lastPolled["sw1"] = &routerPolled{
  49. cfg: RouterConfig{ID: "sw1", Host: "192.168.1.10", SnmpEnabled: true},
  50. cpu: 37,
  51. temp: 51,
  52. hasCpu: true,
  53. hasTemp: true,
  54. polledAt: 1000,
  55. }
  56. l.lastPolled["sw2"] = &routerPolled{
  57. cfg: RouterConfig{ID: "sw2", Host: "192.168.1.11", SnmpEnabled: true},
  58. temp: 49,
  59. hasTemp: true,
  60. polledAt: 1000,
  61. }
  62. rows := l.GetMetricsRows(context.Background())
  63. if len(rows) != 2 {
  64. t.Fatalf("rows=%d, esperaba 2", len(rows))
  65. }
  66. byID := map[string]MetricsRow{}
  67. for _, row := range rows {
  68. byID[row.RouterID] = row
  69. }
  70. row := byID["sw1"]
  71. if row.CPU == nil || *row.CPU != 37 || row.Temp == nil || *row.Temp != 51 || row.RAM != nil {
  72. t.Fatalf("sw1: cpu=%v ram=%v temp=%v", row.CPU, row.RAM, row.Temp)
  73. }
  74. row = byID["sw2"]
  75. if row.CPU != nil || row.Temp == nil || *row.Temp != 49 || row.RAM != nil {
  76. t.Fatalf("sw2: cpu=%v ram=%v temp=%v", row.CPU, row.RAM, row.Temp)
  77. }
  78. }
  79. // Un pusher externo (routeros/asuswrt) declara CPU, memoria y temperatura en
  80. // el payload: son lecturas confirmadas, no huecos que pintar a cero. Antes solo
  81. // el sondeo SNMP ponía los flags, así que el null de #441 se llevaba las tres
  82. // vitals del equipo alimentado por pusher.
  83. func TestBuildRouterKeepsConfirmedPusherVitals(t *testing.T) {
  84. l := NewLive(nil, nil, nil, nil)
  85. cfg := RouterConfig{ID: "crs305", Host: "192.168.2.15", Name: "CRS305", Type: "external", AgentOnly: true}
  86. cpu, temp := 1, 48
  87. si := &probe.SysInfo{Uptime: 253000}
  88. si.Memory.Total = 536870912
  89. si.Memory.Free = 446193664
  90. payload := &probe.Payload{
  91. Router: "crs305", Ts: 1, Kind: "external", Version: "0.1.1",
  92. Data: probe.PayloadData{System: &probe.SystemData{CPU: &cpu, Temp: &temp, SysInfo: si}},
  93. }
  94. p := l.polledFromAgent(cfg, payload)
  95. r := l.buildRouter(p, nil)
  96. if r.CPU == nil || *r.CPU != cpu {
  97. t.Fatalf("CPU=%v, esperaba %d", r.CPU, cpu)
  98. }
  99. if r.Temp == nil || *r.Temp != temp {
  100. t.Fatalf("Temp=%v, esperaba %d", r.Temp, temp)
  101. }
  102. if r.RAM == nil || *r.RAM != p.ram {
  103. t.Fatalf("RAM=%v, esperaba %d (Mem.Total/Free del payload)", r.RAM, p.ram)
  104. }
  105. if r.VitalsAvailable == nil || !*r.VitalsAvailable {
  106. t.Fatalf("VitalsAvailable=%v, esperaba true", r.VitalsAvailable)
  107. }
  108. l.lastPolled[cfg.ID] = p
  109. rows := l.GetMetricsRows(context.Background())
  110. if len(rows) != 1 {
  111. t.Fatalf("rows=%d, esperaba 1", len(rows))
  112. }
  113. row := rows[0]
  114. if row.CPU == nil || *row.CPU != float64(cpu) || row.Temp == nil || *row.Temp != float64(temp) {
  115. t.Fatalf("histórico: cpu=%v temp=%v", row.CPU, row.Temp)
  116. }
  117. if row.RAM == nil || *row.RAM != float64(p.ram) {
  118. t.Fatalf("histórico: ram=%v, esperaba %d", row.RAM, p.ram)
  119. }
  120. }
  121. // #441 sigue vivo: un beacon externo sin sección system no inventa vitals.
  122. func TestBuildRouterPusherSinSystemSigueSinVitals(t *testing.T) {
  123. l := NewLive(nil, nil, nil, nil)
  124. cfg := RouterConfig{ID: "beacon", Host: "192.168.2.99", Name: "Beacon", Type: "external", AgentOnly: true}
  125. p := l.polledFromAgent(cfg, &probe.Payload{Router: "beacon", Ts: 1, Kind: "external"})
  126. r := l.buildRouter(p, nil)
  127. if r.CPU != nil || r.RAM != nil || r.Temp != nil {
  128. t.Fatalf("sin sección system las vitals siguen nil: cpu=%v ram=%v temp=%v", r.CPU, r.RAM, r.Temp)
  129. }
  130. if r.VitalsAvailable == nil || *r.VitalsAvailable {
  131. t.Fatalf("VitalsAvailable=%v, esperaba false", r.VitalsAvailable)
  132. }
  133. }
  134. // extrasCache se clave solo por ID: reasignar un router de un agente nativo a
  135. // un pusher que no trae seccion system no debe publicar las vitales que
  136. // confirmo la fuente anterior. Sin la etiqueta de origen, #1724 las marcaria
  137. // como lecturas propias del pusher y acabarian tambien en el historico.
  138. func TestBuildRouterDoesNotCrossTheAgentSourceBoundary(t *testing.T) {
  139. l := NewLive(nil, nil, nil, nil)
  140. cfg := RouterConfig{ID: "rt-ax92u", Host: "192.168.3.6", Name: "AX92U", Type: "external", AgentOnly: true}
  141. cpu, temp := 7, 61
  142. nativeSys := &probe.SysInfo{Uptime: 100000}
  143. nativeSys.Memory.Total = 536870912
  144. nativeSys.Memory.Free = 400000000
  145. l.polledFromAgent(cfg, &probe.Payload{
  146. Router: cfg.ID, Ts: 1, Kind: "native", Version: "3.0.30",
  147. Data: probe.PayloadData{System: &probe.SystemData{CPU: &cpu, Temp: &temp, SysInfo: nativeSys}},
  148. })
  149. // El router pasa a un pusher externo cuyo payload no trae seccion system
  150. // (REST, o un scraper que todavia no llega a esa parte).
  151. external := l.polledFromAgent(cfg, &probe.Payload{
  152. Router: cfg.ID, Ts: 2, Kind: "external", Version: "0.1.1",
  153. })
  154. if external.cpu != 0 || external.temp != 0 || external.ram != 0 {
  155. t.Fatalf("vitals heredadas de la otra fuente: cpu=%d temp=%d ram=%d", external.cpu, external.temp, external.ram)
  156. }
  157. if external.hasCpu || external.hasTemp || external.hasRam {
  158. t.Fatalf("los flags de confirmacion no pueden venir de otra fuente: %+v", external)
  159. }
  160. r := l.buildRouter(external, nil)
  161. if r.CPU != nil || r.Temp != nil || r.RAM != nil {
  162. t.Fatalf("cpu=%v temp=%v ram=%v, esperaba nil en la tarjeta del router", r.CPU, r.Temp, r.RAM)
  163. }
  164. if r.VitalsAvailable == nil || *r.VitalsAvailable {
  165. t.Fatalf("VitalsAvailable=%v, esperaba false", r.VitalsAvailable)
  166. }
  167. l.lastPolled[cfg.ID] = external
  168. rows := l.GetMetricsRows(context.Background())
  169. if len(rows) != 1 {
  170. t.Fatalf("rows=%d, esperaba 1", len(rows))
  171. }
  172. if rows[0].CPU != nil || rows[0].Temp != nil || rows[0].RAM != nil {
  173. t.Fatalf("historico con vitales de otra fuente: cpu=%v temp=%v ram=%v",
  174. rows[0].CPU, rows[0].Temp, rows[0].RAM)
  175. }
  176. // La proteccion no es "un externo nunca tiene nada": su propia seccion
  177. // system se publica, y cuando el propio externo confirma vitales el
  178. // antiparpadeo #441 sigue reciclándolas dentro de la misma fuente.
  179. boardOnly := l.polledFromAgent(cfg, &probe.Payload{
  180. Router: cfg.ID, Ts: 3, Kind: "external", Version: "0.1.1",
  181. Data: probe.PayloadData{System: &probe.SystemData{Board: &probe.BoardInfo{Model: "CRS305-1G-4S+"}}},
  182. })
  183. if rb := l.buildRouter(boardOnly, nil); rb.Model != "CRS305-1G-4S+" || rb.CPU != nil {
  184. t.Fatalf("board propio del externo: model=%q cpu=%v", rb.Model, rb.CPU)
  185. }
  186. confirmed := l.polledFromAgent(cfg, &probe.Payload{
  187. Router: cfg.ID, Ts: 4, Kind: "external", Version: "0.1.1",
  188. Data: probe.PayloadData{System: &probe.SystemData{CPU: &cpu}},
  189. })
  190. if !confirmed.hasCpu || confirmed.cpu != cpu {
  191. t.Fatalf("cpu=%d hasCpu=%v, el pusher confirmó 7", confirmed.cpu, confirmed.hasCpu)
  192. }
  193. recycled := l.polledFromAgent(cfg, &probe.Payload{
  194. Router: cfg.ID, Ts: 5, Kind: "external", Version: "0.1.1",
  195. })
  196. if !recycled.hasCpu || recycled.cpu != cpu {
  197. t.Fatalf("cpu=%d hasCpu=%v, dentro de la misma fuente el antiparpadeo #441 debe seguir vivo",
  198. recycled.cpu, recycled.hasCpu)
  199. }
  200. }
  201. // Un payload que solo trae Mem.Total, sin ninguna cifra de uso, no permite
  202. // derivar nada: memUsagePct cae a "available = free + buffered = 0" y daria un
  203. // 100 % de RAM inventado. Memoria desconocida, no memoria llena. Las demas
  204. // vitales del mismo payload siguen confirmadas.
  205. func TestBuildRouterTotalOnlyMemoryIsUnknown(t *testing.T) {
  206. l := NewLive(nil, nil, nil, nil)
  207. cfg := RouterConfig{ID: "bbox", Host: "192.168.1.1", Name: "Bbox", Type: "external", AgentOnly: true}
  208. cpu, temp := 3, 40
  209. totalOnly := &probe.SysInfo{Uptime: 1000}
  210. totalOnly.Memory.Total = 100
  211. p := l.polledFromAgent(cfg, &probe.Payload{
  212. Router: cfg.ID, Ts: 1, Kind: "external", Version: "0.1.1",
  213. Data: probe.PayloadData{System: &probe.SystemData{CPU: &cpu, Temp: &temp, SysInfo: totalOnly}},
  214. })
  215. if p.ram != 0 || p.hasRam {
  216. t.Fatalf("ram=%d hasRam=%v, con solo el total la memoria es desconocida", p.ram, p.hasRam)
  217. }
  218. r := l.buildRouter(p, nil)
  219. if r.RAM != nil {
  220. t.Fatalf("RAM=%v, esperaba nil (no 100)", r.RAM)
  221. }
  222. if r.CPU == nil || *r.CPU != cpu || r.Temp == nil || *r.Temp != temp {
  223. t.Fatalf("cpu=%v temp=%v, las otras vitales confirmadas no se tocan", r.CPU, r.Temp)
  224. }
  225. if r.VitalsAvailable == nil || !*r.VitalsAvailable {
  226. t.Fatalf("VitalsAvailable=%v, esperaba true", r.VitalsAvailable)
  227. }
  228. l.lastPolled[cfg.ID] = p
  229. rows := l.GetMetricsRows(context.Background())
  230. if len(rows) != 1 {
  231. t.Fatalf("rows=%d, esperaba 1", len(rows))
  232. }
  233. if rows[0].RAM != nil {
  234. t.Fatalf("historico: ram=%v, esperaba NULL", *rows[0].RAM)
  235. }
  236. if rows[0].CPU == nil || rows[0].Temp == nil {
  237. t.Fatalf("historico: cpu=%v temp=%v, esperando los valores confirmados", rows[0].CPU, rows[0].Temp)
  238. }
  239. // Con una sola cifra de uso ya es derivable: free = 40 de 100 es 60 %.
  240. WithFree := &probe.SysInfo{Uptime: 1000}
  241. WithFree.Memory.Total = 100
  242. WithFree.Memory.Free = 40
  243. p2 := l.polledFromAgent(cfg, &probe.Payload{
  244. Router: cfg.ID, Ts: 2, Kind: "external", Version: "0.1.1",
  245. Data: probe.PayloadData{System: &probe.SystemData{SysInfo: WithFree}},
  246. })
  247. if !p2.hasRam || p2.ram != 60 {
  248. t.Fatalf("ram=%d hasRam=%v, esperaba 60 confirmado", p2.ram, p2.hasRam)
  249. }
  250. }
  251. func intPtr(v int) *int { return &v }
  252. func equalOptionalInt(a, b *int) bool {
  253. if a == nil || b == nil {
  254. return a == nil && b == nil
  255. }
  256. return *a == *b
  257. }