portmonitor_test.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. package adapters
  2. import (
  3. "strings"
  4. "testing"
  5. "time"
  6. "github.com/gnacho/netpulse/server-go/internal/alerts"
  7. )
  8. func TestPortMonitorFlapping(t *testing.T) {
  9. pm := NewPortMonitor(true)
  10. engine := alerts.New(nil, nil)
  11. now := time.Date(2026, 8, 28, 12, 0, 0, 0, time.UTC)
  12. pm.SetClock(func() time.Time { return now })
  13. port := EthPort{ID: "eth0", Label: "LAN1", Up: true, Speed: "1 Gbps"}
  14. pm.Observe("r1", []EthPort{port}, engine)
  15. for i := 0; i < flapThreshold; i++ {
  16. port.Up = !port.Up
  17. now = now.Add(30 * time.Second)
  18. pm.SetClock(func() time.Time { return now })
  19. pm.Observe("r1", []EthPort{port}, engine)
  20. }
  21. found := false
  22. for _, ev := range engine.List() {
  23. if ev.Title == "Port flapping: LAN1 on r1" {
  24. found = true
  25. if ev.Category != alerts.CatSystem {
  26. t.Errorf("category = %q, want %q", ev.Category, alerts.CatSystem)
  27. }
  28. if ev.Hint == "" {
  29. t.Error("hint should not be empty")
  30. }
  31. break
  32. }
  33. }
  34. if !found {
  35. t.Error("flapping alert not emitted")
  36. }
  37. }
  38. func TestPortMonitorFlappingNoAlertBelowThreshold(t *testing.T) {
  39. pm := NewPortMonitor(true)
  40. engine := alerts.New(nil, nil)
  41. now := time.Date(2026, 8, 28, 12, 0, 0, 0, time.UTC)
  42. pm.SetClock(func() time.Time { return now })
  43. port := EthPort{ID: "eth0", Label: "LAN1", Up: true, Speed: "1 Gbps"}
  44. pm.Observe("r1", []EthPort{port}, engine)
  45. for i := 0; i < flapThreshold-1; i++ {
  46. port.Up = !port.Up
  47. now = now.Add(30 * time.Second)
  48. pm.SetClock(func() time.Time { return now })
  49. pm.Observe("r1", []EthPort{port}, engine)
  50. }
  51. for _, ev := range engine.List() {
  52. if ev.Title == "Port flapping: LAN1 on r1" {
  53. t.Error("flapping alert should not fire below threshold")
  54. }
  55. }
  56. }
  57. func TestPortMonitorFlappingWindowExpiry(t *testing.T) {
  58. pm := NewPortMonitor(true)
  59. engine := alerts.New(nil, nil)
  60. now := time.Date(2026, 8, 28, 12, 0, 0, 0, time.UTC)
  61. pm.SetClock(func() time.Time { return now })
  62. port := EthPort{ID: "eth0", Label: "LAN1", Up: true, Speed: "1 Gbps"}
  63. pm.Observe("r1", []EthPort{port}, engine)
  64. for i := 0; i < flapThreshold-1; i++ {
  65. port.Up = !port.Up
  66. now = now.Add(30 * time.Second)
  67. pm.SetClock(func() time.Time { return now })
  68. pm.Observe("r1", []EthPort{port}, engine)
  69. }
  70. now = now.Add(flapWindow + time.Minute)
  71. pm.SetClock(func() time.Time { return now })
  72. port.Up = !port.Up
  73. pm.Observe("r1", []EthPort{port}, engine)
  74. for _, ev := range engine.List() {
  75. if ev.Title == "Port flapping: LAN1 on r1" {
  76. t.Error("flapping alert should not fire after window expires")
  77. }
  78. }
  79. }
  80. func TestPortMonitorGhostPort(t *testing.T) {
  81. pm := NewPortMonitor(true)
  82. engine := alerts.New(nil, nil)
  83. now := time.Date(2026, 8, 28, 12, 0, 0, 0, time.UTC)
  84. pm.SetClock(func() time.Time { return now })
  85. port := EthPort{ID: "eth0", Label: "LAN1", Up: true, RxBytes: 0, TxBytes: 0, Speed: "1 Gbps"}
  86. pm.Observe("r1", []EthPort{port}, engine)
  87. for i := 0; i < ghostMinHistory; i++ {
  88. port.RxBytes += 1000
  89. port.TxBytes += 500
  90. now = now.Add(45 * time.Second)
  91. pm.SetClock(func() time.Time { return now })
  92. pm.Observe("r1", []EthPort{port}, engine)
  93. }
  94. for i := 0; i < ghostConsecutive; i++ {
  95. now = now.Add(45 * time.Second)
  96. pm.SetClock(func() time.Time { return now })
  97. pm.Observe("r1", []EthPort{port}, engine)
  98. }
  99. found := false
  100. for _, ev := range engine.List() {
  101. if ev.Title == "Ghost port: LAN1 went silent" {
  102. found = true
  103. if ev.Category != alerts.CatSystem {
  104. t.Errorf("category = %q, want %q", ev.Category, alerts.CatSystem)
  105. }
  106. break
  107. }
  108. }
  109. if !found {
  110. t.Error("ghost port alert not emitted")
  111. }
  112. }
  113. func TestPortMonitorGhostPortNoAlertWithoutHistory(t *testing.T) {
  114. pm := NewPortMonitor(true)
  115. engine := alerts.New(nil, nil)
  116. now := time.Date(2026, 8, 28, 12, 0, 0, 0, time.UTC)
  117. pm.SetClock(func() time.Time { return now })
  118. port := EthPort{ID: "eth0", Label: "LAN1", Up: true, RxBytes: 100, TxBytes: 100, Speed: "1 Gbps"}
  119. for i := 0; i < ghostConsecutive+2; i++ {
  120. now = now.Add(45 * time.Second)
  121. pm.SetClock(func() time.Time { return now })
  122. pm.Observe("r1", []EthPort{port}, engine)
  123. }
  124. for _, ev := range engine.List() {
  125. if ev.Title == "Ghost port: LAN1 went silent" {
  126. t.Error("ghost port should not fire without sufficient history")
  127. }
  128. }
  129. }
  130. func TestPortMonitorDegradedLink(t *testing.T) {
  131. pm := NewPortMonitor(true)
  132. engine := alerts.New(nil, nil)
  133. now := time.Date(2026, 8, 28, 12, 0, 0, 0, time.UTC)
  134. pm.SetClock(func() time.Time { return now })
  135. port := EthPort{ID: "eth0", Label: "LAN1", Up: true, Speed: "1 Gbps", RxBytes: 100, TxBytes: 100}
  136. for i := 0; i < degradedMinHistory; i++ {
  137. port.RxBytes += 1000
  138. port.TxBytes += 500
  139. now = now.Add(45 * time.Second)
  140. pm.SetClock(func() time.Time { return now })
  141. pm.Observe("r1", []EthPort{port}, engine)
  142. }
  143. port.Speed = "100 Mbps"
  144. for i := 0; i < degradedConsec; i++ {
  145. port.RxBytes += 500
  146. port.TxBytes += 200
  147. now = now.Add(45 * time.Second)
  148. pm.SetClock(func() time.Time { return now })
  149. pm.Observe("r1", []EthPort{port}, engine)
  150. }
  151. found := false
  152. for _, ev := range engine.List() {
  153. if ev.Title == "Degraded link: LAN1 at 100Mbps (was 1000Mbps)" {
  154. found = true
  155. if ev.Category != alerts.CatSystem {
  156. t.Errorf("category = %q, want %q", ev.Category, alerts.CatSystem)
  157. }
  158. break
  159. }
  160. }
  161. if !found {
  162. t.Errorf("degraded link alert not emitted; alerts: %v", engine.List())
  163. }
  164. }
  165. func TestPortMonitorDegradedLinkNoAlertWhenStable(t *testing.T) {
  166. pm := NewPortMonitor(true)
  167. engine := alerts.New(nil, nil)
  168. now := time.Date(2026, 8, 28, 12, 0, 0, 0, time.UTC)
  169. pm.SetClock(func() time.Time { return now })
  170. port := EthPort{ID: "eth0", Label: "LAN1", Up: true, Speed: "1 Gbps", RxBytes: 100, TxBytes: 100}
  171. for i := 0; i < degradedMinHistory+degradedConsec; i++ {
  172. port.RxBytes += 1000
  173. port.TxBytes += 500
  174. now = now.Add(45 * time.Second)
  175. pm.SetClock(func() time.Time { return now })
  176. pm.Observe("r1", []EthPort{port}, engine)
  177. }
  178. for _, ev := range engine.List() {
  179. if ev.Title == "Degraded link: LAN1 at 1000Mbps (was 1000Mbps)" {
  180. t.Error("degraded link should not fire when speed is stable")
  181. }
  182. }
  183. }
  184. func TestDominantSpeed(t *testing.T) {
  185. cases := []struct {
  186. in []int
  187. want int
  188. }{
  189. {[]int{1000, 1000, 1000, 100}, 1000},
  190. {[]int{100, 100, 100, 1000}, 100},
  191. {[]int{}, 0},
  192. {[]int{1000}, 1000},
  193. }
  194. for _, tc := range cases {
  195. got := dominantSpeed(tc.in)
  196. if got != tc.want {
  197. t.Errorf("dominantSpeed(%v) = %d, want %d", tc.in, got, tc.want)
  198. }
  199. }
  200. }
  201. // buildGhostPort deja el monitor listo para el umbral de ghost: historia
  202. // suficiente y tráfico creciente. Devuelve el reloj mutable.
  203. func buildGhostPort(t *testing.T, pm *PortMonitor, engine *alerts.Engine) (EthPort, func(time.Time)) {
  204. t.Helper()
  205. now := time.Date(2026, 8, 29, 12, 0, 0, 0, time.UTC)
  206. setClock := func(n time.Time) { pm.SetClock(func() time.Time { return n }) }
  207. setClock(now)
  208. port := EthPort{ID: "eth0", Label: "LAN1", Up: true, RxBytes: 0, TxBytes: 0, Speed: "1 Gbps"}
  209. pm.Observe("r1", []EthPort{port}, engine)
  210. for i := 0; i < ghostMinHistory; i++ {
  211. port.RxBytes += 1000
  212. port.TxBytes += 500
  213. now = now.Add(45 * time.Second)
  214. setClock(now)
  215. pm.Observe("r1", []EthPort{port}, engine)
  216. }
  217. return port, setClock
  218. }
  219. func findAlerts(engine *alerts.Engine, title string) (int, alerts.AlertEvent) {
  220. n := 0
  221. var last alerts.AlertEvent
  222. for _, ev := range engine.List() {
  223. if ev.Title == title {
  224. n++
  225. last = ev
  226. }
  227. }
  228. return n, last
  229. }
  230. // issue #366: un incidente persistente refresca UNA sola alerta (EmitOrUpdate)
  231. // en vez de colar una nueva por cada ventana de dedup.
  232. func TestPortMonitorGhostConsolidatesIntoOneAlert(t *testing.T) {
  233. pm := NewPortMonitor(true)
  234. engine := alerts.New(nil, nil)
  235. port, setClock := buildGhostPort(t, pm, engine)
  236. now := time.Date(2026, 8, 29, 13, 0, 0, 0, time.UTC)
  237. for i := 0; i < 20; i++ {
  238. now = now.Add(6 * time.Minute)
  239. setClock(now)
  240. pm.Observe("r1", []EthPort{port}, engine)
  241. }
  242. n, last := findAlerts(engine, "Ghost port: LAN1 went silent")
  243. if n != 1 {
  244. t.Fatalf("ghost alerts = %d, want 1 (consolidated)", n)
  245. }
  246. if last.Ts < now.Unix()-120 {
  247. t.Errorf("consolidated alert ts %d should be recent (near %d)", last.Ts, now.Unix())
  248. }
  249. if last.ID != "alert-ghost-r1-eth0" {
  250. t.Errorf("alert ID = %q, want stable alert-ghost-r1-eth0", last.ID)
  251. }
  252. }
  253. // issue #365: un reset de contadores (reboot) NO es un puerto muerto.
  254. func TestPortMonitorGhostCounterResetNoAlert(t *testing.T) {
  255. pm := NewPortMonitor(true)
  256. engine := alerts.New(nil, nil)
  257. port, setClock := buildGhostPort(t, pm, engine)
  258. // Reboot: contadores caen de ~27k a 42 y vuelven a crecer desde ahí.
  259. port.RxBytes, port.TxBytes = 42, 0
  260. now := time.Date(2026, 8, 29, 13, 0, 0, 0, time.UTC)
  261. for i := 0; i < ghostConsecutive+3; i++ {
  262. if i > 0 {
  263. port.RxBytes += 100
  264. }
  265. now = now.Add(45 * time.Second)
  266. setClock(now)
  267. pm.Observe("r1", []EthPort{port}, engine)
  268. }
  269. if n, _ := findAlerts(engine, "Ghost port: LAN1 went silent"); n != 0 {
  270. t.Fatalf("ghost alerts after counter reset = %d, want 0", n)
  271. }
  272. }
  273. // issue #366: al volver el tráfico se emite UNA alerta ok de recuperación.
  274. func TestPortMonitorGhostRecovery(t *testing.T) {
  275. pm := NewPortMonitor(true)
  276. engine := alerts.New(nil, nil)
  277. port, setClock := buildGhostPort(t, pm, engine)
  278. now := time.Date(2026, 8, 29, 13, 0, 0, 0, time.UTC)
  279. for i := 0; i < ghostConsecutive; i++ {
  280. now = now.Add(45 * time.Second)
  281. setClock(now)
  282. pm.Observe("r1", []EthPort{port}, engine)
  283. }
  284. if n, _ := findAlerts(engine, "Ghost port: LAN1 went silent"); n != 1 {
  285. t.Fatalf("ghost alert not emitted before recovery")
  286. }
  287. // El tráfico vuelve y se mantiene: una única recuperación.
  288. for round := 0; round < 2; round++ {
  289. for i := 0; i < 4; i++ {
  290. port.RxBytes += 500
  291. now = now.Add(45 * time.Second)
  292. setClock(now)
  293. pm.Observe("r1", []EthPort{port}, engine)
  294. }
  295. }
  296. n, last := findAlerts(engine, "Ghost port recovered: LAN1 on r1")
  297. if n != 1 {
  298. t.Fatalf("recovery alerts = %d, want 1", n)
  299. }
  300. if last.Type != alerts.TypeGhostPortRecovered {
  301. t.Fatalf("Type=%q, want %q", last.Type, alerts.TypeGhostPortRecovered)
  302. }
  303. if last.Vars["port"] != "LAN1" || last.Vars["router"] != "r1" {
  304. t.Fatalf("Vars=%v", last.Vars)
  305. }
  306. }
  307. // issue #419: cuando ghost port esta desactivado, no se emiten alertas de
  308. // puerto fantasma ni de recuperacion.
  309. func TestPortMonitorGhostDisabled(t *testing.T) {
  310. pm := NewPortMonitor(false)
  311. engine := alerts.New(nil, nil)
  312. now := time.Date(2026, 8, 28, 12, 0, 0, 0, time.UTC)
  313. pm.SetClock(func() time.Time { return now })
  314. port := EthPort{ID: "eth0", Label: "LAN1", Up: true, RxBytes: 0, TxBytes: 0, Speed: "1 Gbps"}
  315. pm.Observe("r1", []EthPort{port}, engine)
  316. for i := 0; i < ghostMinHistory; i++ {
  317. port.RxBytes += 1000
  318. port.TxBytes += 500
  319. now = now.Add(45 * time.Second)
  320. pm.SetClock(func() time.Time { return now })
  321. pm.Observe("r1", []EthPort{port}, engine)
  322. }
  323. for i := 0; i < ghostConsecutive+2; i++ {
  324. now = now.Add(45 * time.Second)
  325. pm.SetClock(func() time.Time { return now })
  326. pm.Observe("r1", []EthPort{port}, engine)
  327. }
  328. for _, ev := range engine.List() {
  329. if strings.Contains(ev.Title, "Ghost port") {
  330. t.Fatalf("ghost alert emitted while disabled: %s", ev.Title)
  331. }
  332. }
  333. }
  334. // issue #405: un reinicio del servidor pierde el estado; un contador
  335. // congelado en valor > 0 no debe interpretarse como ghost port.
  336. func TestPortMonitorGhostNoAlertAfterServerRestart(t *testing.T) {
  337. pm := NewPortMonitor(true)
  338. engine := alerts.New(nil, nil)
  339. now := time.Date(2026, 8, 30, 22, 16, 0, 0, time.UTC)
  340. pm.SetClock(func() time.Time { return now })
  341. // Tras reinicio no hay historial. El puerto reporta un total constante > 0.
  342. port := EthPort{ID: "eth0", Label: "LAN3", Up: true, Speed: "1 Gbps", RxBytes: 12345, TxBytes: 6789}
  343. for i := 0; i < 15; i++ {
  344. now = now.Add(15 * time.Second)
  345. pm.SetClock(func() time.Time { return now })
  346. pm.Observe("gateway", []EthPort{port}, engine)
  347. }
  348. if n, _ := findAlerts(engine, "Ghost port: LAN3 went silent"); n != 0 {
  349. t.Fatalf("ghost alerts after server restart = %d, want 0", n)
  350. }
  351. // A partir de aquí el puerto sí muestra tráfico creciente y luego se calla;
  352. // ahora sí debe saltar la alerta porque hay historia real de warm-up.
  353. for i := 0; i < ghostMinHistory; i++ {
  354. port.RxBytes += 1000
  355. port.TxBytes += 500
  356. now = now.Add(15 * time.Second)
  357. pm.SetClock(func() time.Time { return now })
  358. pm.Observe("gateway", []EthPort{port}, engine)
  359. }
  360. for i := 0; i < ghostConsecutive; i++ {
  361. now = now.Add(15 * time.Second)
  362. pm.SetClock(func() time.Time { return now })
  363. pm.Observe("gateway", []EthPort{port}, engine)
  364. }
  365. if n, _ := findAlerts(engine, "Ghost port: LAN3 went silent"); n != 1 {
  366. t.Fatalf("ghost alert after real warm-up = %d, want 1", n)
  367. }
  368. }