clientbw_test.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. // clientbw_test.go — ingesta del tráfico por cliente (#551): resolución de
  2. // fuentes (nlbwmon preferente, hostapd fallback) y conversión de contadores
  3. // absolutos a samples delta en la store client_bw_raw.
  4. package adapters
  5. import (
  6. "testing"
  7. "time"
  8. "github.com/gnacho/netpulse/agent/probe"
  9. "github.com/gnacho/netpulse/server-go/internal/db"
  10. )
  11. // TestResolveClientBwSources: nlbwmon gana cuando está disponible con hosts;
  12. // si no, hostapd bytes por estación; sin datos → no ok.
  13. func TestResolveClientBwSources(t *testing.T) {
  14. wireless := map[string]WirelessClient{
  15. "AA:BB:CC:DD:EE:01": {SignalDbm: -50, RxBytes: 111, TxBytes: 222},
  16. "AA:BB:CC:DD:EE:02": {SignalDbm: -60}, // sin bytes → no cuenta
  17. }
  18. nlbw := &probe.ClientBwData{Available: true, Hosts: map[string]probe.NlbwCounter{
  19. "AA:BB:CC:DD:EE:0F": {RxBytes: 1000, TxBytes: 2000},
  20. }}
  21. // nlbwmon preferente: cubre hasta MACs que no están en wireless.
  22. samples, source, ok := resolveClientBwSources(wireless, nlbw)
  23. if !ok || source != "nlbwmon" || len(samples) != 1 {
  24. t.Fatalf("nlbwmon: ok=%v source=%s samples=%+v", ok, source, samples)
  25. }
  26. if samples[0].mac != "AA:BB:CC:DD:EE:0F" || samples[0].rx != 1000 {
  27. t.Fatalf("muestra nlbwmon: %+v", samples[0])
  28. }
  29. // Sin nlbwmon → hostapd bytes (solo estaciones con contadores).
  30. samples, source, ok = resolveClientBwSources(wireless, nil)
  31. if !ok || source != "hostapd" || len(samples) != 1 {
  32. t.Fatalf("hostapd: ok=%v source=%s samples=%+v", ok, source, samples)
  33. }
  34. if samples[0].mac != "AA:BB:CC:DD:EE:01" || samples[0].rx != 111 || samples[0].tx != 222 {
  35. t.Fatalf("muestra hostapd: %+v", samples[0])
  36. }
  37. // nlbwmon instalado pero vacío (Available con Hosts {}) → cae a hostapd.
  38. nlbwEmpty := &probe.ClientBwData{Available: true, Hosts: map[string]probe.NlbwCounter{}}
  39. _, source, ok = resolveClientBwSources(wireless, nlbwEmpty)
  40. if !ok || source != "hostapd" {
  41. t.Fatalf("nlbwmon vacío: source=%s ok=%v", source, ok)
  42. }
  43. // Sin datos en ninguna fuente → no ok.
  44. _, _, ok = resolveClientBwSources(map[string]WirelessClient{"AA:BB:CC:DD:EE:02": {SignalDbm: -60}}, nil)
  45. if ok {
  46. t.Fatal("sin contadores debería dar ok=false")
  47. }
  48. }
  49. // TestRecordClientBwSamplesDeltas: la ingesta convierte contadores absolutos
  50. // en deltas con bps, ignora reinicios (contador que baja) y siembra sin
  51. // escribir en la primera observación.
  52. func TestRecordClientBwSamplesDeltas(t *testing.T) {
  53. d := openLiveTestDB(t)
  54. l := &Live{db: d}
  55. t0 := time.Now()
  56. // Primera observación: siembra, no escribe nada.
  57. l.recordClientBwSamples("gw", t0, []clientBwSample{
  58. {mac: "AA:BB:CC:DD:EE:01", rx: 10000, tx: 5000},
  59. }, "hostapd")
  60. if n := countRawClientBW(t, d); n != 0 {
  61. t.Fatalf("primera observación no debe escribir: %d filas", n)
  62. }
  63. // Segunda observación 10 s después con +1000/+500 → delta 1000/500,
  64. // bps = bytes*8/dt = 800 y 400.
  65. t1 := t0.Add(10 * time.Second)
  66. l.recordClientBwSamples("gw", t1, []clientBwSample{
  67. {mac: "AA:BB:CC:DD:EE:01", rx: 11000, tx: 5500},
  68. }, "hostapd")
  69. if n := countRawClientBW(t, d); n != 1 {
  70. t.Fatalf("segunda observación debe escribir 1 fila: %d", n)
  71. }
  72. var rxBytes, txBytes int64
  73. var rxBps, txBps float64
  74. err := d.QueryRow("SELECT rx_bytes, tx_bytes, rx_bps, tx_bps FROM client_bw_raw").Scan(&rxBytes, &txBytes, &rxBps, &txBps)
  75. if err != nil {
  76. t.Fatalf("query: %v", err)
  77. }
  78. if rxBytes != 1000 || txBytes != 500 {
  79. t.Fatalf("delta: rx=%d tx=%d (want 1000/500)", rxBytes, txBytes)
  80. }
  81. if rxBps != 800 || txBps != 400 {
  82. t.Fatalf("bps: rx=%.0f tx=%.0f (want 800/400)", rxBps, txBps)
  83. }
  84. // El rate del último intervalo queda en memoria para el TrafficMbps.
  85. if rrx, rtx := l.clientBwRateFor("AA:BB:CC:DD:EE:01"); rrx != 800 || rtx != 400 {
  86. t.Fatalf("rate en memoria: rx=%.0f tx=%.0f (want 800/400)", rrx, rtx)
  87. }
  88. // Reinicio del contador (hostapd se reinició al reasociar / nlbwmon nuevo
  89. // periodo): contador BAJA → re-siembra, no escribe delta gigante.
  90. t2 := t1.Add(10 * time.Second)
  91. l.recordClientBwSamples("gw", t2, []clientBwSample{
  92. {mac: "AA:BB:CC:DD:EE:01", rx: 100, tx: 50},
  93. }, "hostapd")
  94. if n := countRawClientBW(t, d); n != 1 {
  95. t.Fatalf("reinicio no debe escribir: %d filas", n)
  96. }
  97. // Tras el reinicio, siguiente delta normal sí escribe (base re-sembrada).
  98. t3 := t2.Add(10 * time.Second)
  99. l.recordClientBwSamples("gw", t3, []clientBwSample{
  100. {mac: "AA:BB:CC:DD:EE:01", rx: 600, tx: 300},
  101. }, "hostapd")
  102. if n := countRawClientBW(t, d); n != 2 {
  103. t.Fatalf("delta post-reinicio debe escribir: %d filas", n)
  104. }
  105. var rx2 int64
  106. if err := d.QueryRow("SELECT rx_bytes FROM client_bw_raw ORDER BY ts DESC LIMIT 1").Scan(&rx2); err != nil {
  107. t.Fatalf("query rx2: %v", err)
  108. }
  109. if rx2 != 500 { // 600 - 100
  110. t.Fatalf("delta post-reinicio: %d (want 500)", rx2)
  111. }
  112. // Sin DB → no panic, no op.
  113. (&Live{db: nil}).recordClientBwSamples("gw", t0, []clientBwSample{{mac: "x", rx: 1}}, "hostapd")
  114. }
  115. // TestRecordClientBwSamplesPorRouterYMac: los estados se segregan por router
  116. // y por MAC (un cliente en dos routers no comparte contador).
  117. func TestRecordClientBwSamplesPorRouterYMac(t *testing.T) {
  118. d := openLiveTestDB(t)
  119. l := &Live{db: d}
  120. t0 := time.Now()
  121. t1 := t0.Add(10 * time.Second)
  122. l.recordClientBwSamples("gw", t0, []clientBwSample{{mac: "AA:BB:CC:DD:EE:01", rx: 100}}, "hostapd")
  123. l.recordClientBwSamples("ap1", t0, []clientBwSample{{mac: "AA:BB:CC:DD:EE:01", rx: 100}}, "hostapd")
  124. l.recordClientBwSamples("gw", t1, []clientBwSample{{mac: "AA:BB:CC:DD:EE:01", rx: 200}}, "hostapd")
  125. l.recordClientBwSamples("ap1", t1, []clientBwSample{{mac: "AA:BB:CC:DD:EE:01", rx: 300}}, "hostapd")
  126. var n int
  127. if err := d.QueryRow("SELECT COUNT(*) FROM client_bw_raw").Scan(&n); err != nil {
  128. t.Fatalf("count: %v", err)
  129. }
  130. if n != 2 {
  131. t.Fatalf("filas: %d (want 2, una por router)", n)
  132. }
  133. var apRx int64
  134. if err := d.QueryRow("SELECT rx_bytes FROM client_bw_raw WHERE router_id='ap1'").Scan(&apRx); err != nil {
  135. t.Fatalf("query ap1: %v", err)
  136. }
  137. if apRx != 200 { // 300-100
  138. t.Fatalf("delta ap1: %d (want 200)", apRx)
  139. }
  140. }
  141. func countRawClientBW(t *testing.T, d *db.DB) int {
  142. t.Helper()
  143. var n int
  144. if err := d.QueryRow("SELECT COUNT(*) FROM client_bw_raw").Scan(&n); err != nil {
  145. t.Fatalf("count raw: %v", err)
  146. }
  147. return n
  148. }
  149. // TestClientBwRateForPriorizaFuente: cuando una MAC es reportada por nlbwmon
  150. // (router que enruta) y por hostapd a la vez, el rate de la lista usa el de
  151. // nlbwmon (el del gateway ya contabiliza todo el tráfico; sumar doblaría).
  152. func TestClientBwRateForPriorizaFuente(t *testing.T) {
  153. d := openLiveTestDB(t)
  154. l := &Live{db: d}
  155. t0 := time.Now()
  156. t1 := t0.Add(10 * time.Second)
  157. // hostapd en ap1 y nlbwmon en gw reportan la misma MAC.
  158. l.recordClientBwSamples("ap1", t0, []clientBwSample{{mac: "AA:BB:CC:DD:EE:01", rx: 10000}}, "hostapd")
  159. l.recordClientBwSamples("gw", t0, []clientBwSample{{mac: "AA:BB:CC:DD:EE:01", rx: 20000}}, "nlbwmon")
  160. l.recordClientBwSamples("ap1", t1, []clientBwSample{{mac: "AA:BB:CC:DD:EE:01", rx: 10100}}, "hostapd")
  161. l.recordClientBwSamples("gw", t1, []clientBwSample{{mac: "AA:BB:CC:DD:EE:01", rx: 20200}}, "nlbwmon")
  162. rx, tx := l.clientBwRateFor("AA:BB:CC:DD:EE:01")
  163. // 200 bytes en 10 s → 160 bps (nlbwmon), no 80 del hostapd.
  164. if rx != 160 {
  165. t.Fatalf("rate rx: %.0f (want 160 del nlbwmon)", rx)
  166. }
  167. if tx != 0 {
  168. t.Fatalf("rate tx: %.0f (want 0)", tx)
  169. }
  170. }