portmonitor.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. package adapters
  2. import (
  3. "fmt"
  4. "strconv"
  5. "sync"
  6. "time"
  7. "github.com/gnacho/netpulse/server-go/internal/alerts"
  8. )
  9. const (
  10. flapWindow = 10 * time.Minute
  11. flapThreshold = 5
  12. ghostConsecutive = 3
  13. ghostMinHistory = 12
  14. snmpGhostMinDuration = 5 * time.Minute
  15. degradedConsec = 3
  16. degradedMinHistory = 12
  17. )
  18. type portKey struct {
  19. routerID string
  20. portID string
  21. }
  22. type portState struct {
  23. up bool
  24. transitions []time.Time
  25. speedMbps int
  26. speedHistory []int
  27. trafficTotal uint64
  28. zeroStreak int
  29. hadTraffic bool
  30. lastTrafficAt time.Time
  31. // Incidentes abiertos (issue #366): mientras la condición persiste hay
  32. // UNA sola alerta viva por puerto (EmitOrUpdate la refresca in situ);
  33. // la flag dispara la alerta de recuperación exactamente una vez.
  34. flapActive bool
  35. ghostActive bool
  36. degradedActive bool
  37. }
  38. type PortMonitor struct {
  39. mu sync.Mutex
  40. states map[portKey]*portState
  41. now func() time.Time
  42. ghostEnabled bool
  43. }
  44. func NewPortMonitor(ghostEnabled bool) *PortMonitor {
  45. return &PortMonitor{
  46. states: map[portKey]*portState{},
  47. now: time.Now,
  48. ghostEnabled: ghostEnabled,
  49. }
  50. }
  51. func (pm *PortMonitor) SetClock(f func() time.Time) {
  52. pm.mu.Lock()
  53. defer pm.mu.Unlock()
  54. pm.now = f
  55. }
  56. func (pm *PortMonitor) Observe(routerID string, ports []EthPort, engine *alerts.Engine) {
  57. pm.mu.Lock()
  58. defer pm.mu.Unlock()
  59. now := pm.now()
  60. for _, p := range ports {
  61. if p.ID == "" {
  62. continue
  63. }
  64. key := portKey{routerID, p.ID}
  65. st, ok := pm.states[key]
  66. if !ok {
  67. // Tras un reinicio del servidor no hay historial: la primera
  68. // observación es la línea de base del contador, no una muestra de
  69. // que el puerto "tuvo tráfico". Si no hacemos esto, un contador
  70. // congelado en un valor > 0 se interpreta como ghost port.
  71. st = &portState{up: p.Up, trafficTotal: p.RxBytes + p.TxBytes}
  72. pm.states[key] = st
  73. }
  74. pm.updateSpeedHistory(st, p)
  75. pm.checkFlapping(key, st, p, now, engine)
  76. pm.checkGhost(key, st, p, now, engine)
  77. pm.checkDegraded(key, st, p, now, engine)
  78. }
  79. }
  80. func (pm *PortMonitor) updateSpeedHistory(st *portState, p EthPort) {
  81. spd := parseSpeedMbps(p.Speed)
  82. if !p.Up || spd == 0 {
  83. st.speedHistory = nil
  84. st.speedMbps = 0
  85. return
  86. }
  87. st.speedHistory = append(st.speedHistory, spd)
  88. if len(st.speedHistory) > 200 {
  89. st.speedHistory = st.speedHistory[len(st.speedHistory)-200:]
  90. }
  91. st.speedMbps = spd
  92. }
  93. func (pm *PortMonitor) checkFlapping(key portKey, st *portState, p EthPort, now time.Time, engine *alerts.Engine) {
  94. if p.Up != st.up {
  95. st.transitions = append(st.transitions, now)
  96. st.up = p.Up
  97. }
  98. cutoff := now.Add(-flapWindow)
  99. kept := st.transitions[:0]
  100. for _, t := range st.transitions {
  101. if !t.Before(cutoff) {
  102. kept = append(kept, t)
  103. }
  104. }
  105. st.transitions = kept
  106. if len(st.transitions) >= flapThreshold {
  107. st.flapActive = true
  108. engine.EmitOrUpdate(alerts.AlertEvent{
  109. ID: fmt.Sprintf("alert-flap-%s-%s", key.routerID, key.portID),
  110. Category: alerts.CatSystem,
  111. Urgent: false,
  112. Severity: "warn",
  113. Title: fmt.Sprintf("Port flapping: %s on %s", p.Label, key.routerID),
  114. Description: fmt.Sprintf("%d transitions in %s", len(st.transitions), flapWindow),
  115. Hint: alerts.HintFor(alerts.HintPortFlapping),
  116. Type: alerts.HintPortFlapping,
  117. Vars: map[string]string{"port": p.Label, "router": key.routerID, "count": strconv.Itoa(len(st.transitions)), "window": flapWindow.String()},
  118. Time: "just now",
  119. RouterID: key.routerID,
  120. })
  121. } else if st.flapActive {
  122. st.flapActive = false
  123. engine.Emit(alerts.AlertEvent{
  124. ID: fmt.Sprintf("alert-flap-%s-%s-ok-%d", key.routerID, key.portID, now.Unix()),
  125. Category: alerts.CatSystem,
  126. Urgent: false,
  127. Severity: "ok",
  128. Title: fmt.Sprintf("Port stable again: %s on %s", p.Label, key.routerID),
  129. Description: fmt.Sprintf("Flapping stopped, fewer than %d transitions in %s", flapThreshold, flapWindow),
  130. Type: alerts.TypePortStable,
  131. Vars: map[string]string{"port": p.Label, "router": key.routerID, "threshold": strconv.Itoa(flapThreshold), "window": flapWindow.String()},
  132. Time: "just now",
  133. RouterID: key.routerID,
  134. })
  135. }
  136. }
  137. func (pm *PortMonitor) checkGhost(key portKey, st *portState, p EthPort, now time.Time, engine *alerts.Engine) {
  138. if !pm.ghostEnabled {
  139. return
  140. }
  141. total := p.RxBytes + p.TxBytes
  142. if !p.Up {
  143. st.zeroStreak = 0
  144. st.hadTraffic = false
  145. st.trafficTotal = 0
  146. st.lastTrafficAt = time.Time{}
  147. st.ghostActive = false
  148. return
  149. }
  150. if total < st.trafficTotal {
  151. // Contador reseteado (reboot del router): arranca una era nueva del
  152. // contador, no es un puerto muerto. Sin esto, el streak crecería
  153. // durante horas hasta superar el total pre-reboot (issue #365).
  154. st.trafficTotal = total
  155. st.hadTraffic = false
  156. st.zeroStreak = 0
  157. st.lastTrafficAt = time.Time{}
  158. st.ghostActive = false
  159. return
  160. }
  161. if total > st.trafficTotal {
  162. st.hadTraffic = true
  163. st.zeroStreak = 0
  164. st.lastTrafficAt = now
  165. } else if st.hadTraffic {
  166. st.zeroStreak++
  167. }
  168. st.trafficTotal = total
  169. if len(st.speedHistory) < ghostMinHistory {
  170. return
  171. }
  172. if st.zeroStreak >= ghostConsecutive {
  173. // issue #414: los puertos SNMP se sondean con menos frecuencia; exigir
  174. // también un tiempo mínimo de silencio para reducir falsos positivos.
  175. if p.Snmp && now.Sub(st.lastTrafficAt) < snmpGhostMinDuration {
  176. return
  177. }
  178. st.ghostActive = true
  179. engine.EmitOrUpdate(alerts.AlertEvent{
  180. ID: fmt.Sprintf("alert-ghost-%s-%s", key.routerID, key.portID),
  181. Category: alerts.CatSystem,
  182. Urgent: false,
  183. Severity: "warn",
  184. Title: fmt.Sprintf("Ghost port: %s went silent", p.Label),
  185. Description: fmt.Sprintf("Port had traffic but zero bytes for %d consecutive polls", st.zeroStreak),
  186. Hint: alerts.HintFor(alerts.HintGhostPort),
  187. Type: alerts.HintGhostPort,
  188. Vars: map[string]string{"port": p.Label, "polls": strconv.Itoa(st.zeroStreak)},
  189. Time: "just now",
  190. RouterID: key.routerID,
  191. })
  192. } else if st.ghostActive && st.zeroStreak == 0 {
  193. st.ghostActive = false
  194. engine.Emit(alerts.AlertEvent{
  195. ID: fmt.Sprintf("alert-ghost-%s-%s-ok-%d", key.routerID, key.portID, now.Unix()),
  196. Category: alerts.CatSystem,
  197. Urgent: false,
  198. Severity: "ok",
  199. Title: fmt.Sprintf("Ghost port recovered: %s on %s", p.Label, key.routerID),
  200. Description: "Port is moving traffic again",
  201. Type: alerts.TypeGhostPortRecovered,
  202. Vars: map[string]string{"port": p.Label, "router": key.routerID},
  203. Time: "just now",
  204. RouterID: key.routerID,
  205. })
  206. }
  207. }
  208. func (pm *PortMonitor) checkDegraded(key portKey, st *portState, p EthPort, now time.Time, engine *alerts.Engine) {
  209. if len(st.speedHistory) < degradedMinHistory {
  210. return
  211. }
  212. prev := dominantSpeed(st.speedHistory[:len(st.speedHistory)-degradedConsec])
  213. if prev == 0 {
  214. return
  215. }
  216. recent := st.speedHistory[len(st.speedHistory)-degradedConsec:]
  217. allBelow := true
  218. for _, s := range recent {
  219. if s >= prev/2 {
  220. allBelow = false
  221. break
  222. }
  223. }
  224. if allBelow && st.speedMbps < prev {
  225. st.degradedActive = true
  226. engine.EmitOrUpdate(alerts.AlertEvent{
  227. ID: fmt.Sprintf("alert-degraded-%s-%s", key.routerID, key.portID),
  228. Category: alerts.CatSystem,
  229. Urgent: false,
  230. Severity: "warn",
  231. Title: fmt.Sprintf("Degraded link: %s at %dMbps (was %dMbps)", p.Label, st.speedMbps, prev),
  232. Description: fmt.Sprintf("Port negotiated speed dropped from %d to %d Mbps for %d consecutive polls", prev, st.speedMbps, degradedConsec),
  233. Hint: alerts.HintFor(alerts.HintDegradedLink),
  234. Type: alerts.HintDegradedLink,
  235. Vars: map[string]string{"port": p.Label, "speed": strconv.Itoa(st.speedMbps), "prev": strconv.Itoa(prev), "polls": strconv.Itoa(degradedConsec)},
  236. Time: "just now",
  237. RouterID: key.routerID,
  238. })
  239. } else if st.degradedActive {
  240. st.degradedActive = false
  241. engine.Emit(alerts.AlertEvent{
  242. ID: fmt.Sprintf("alert-degraded-%s-%s-ok-%d", key.routerID, key.portID, now.Unix()),
  243. Category: alerts.CatSystem,
  244. Urgent: false,
  245. Severity: "ok",
  246. Title: fmt.Sprintf("Link speed recovered: %s on %s", p.Label, key.routerID),
  247. Description: fmt.Sprintf("Port negotiated speed is back to %d Mbps", st.speedMbps),
  248. Type: alerts.TypeLinkRecovered,
  249. Vars: map[string]string{"port": p.Label, "router": key.routerID, "speed": strconv.Itoa(st.speedMbps)},
  250. Time: "just now",
  251. RouterID: key.routerID,
  252. })
  253. }
  254. }
  255. func dominantSpeed(history []int) int {
  256. counts := map[int]int{}
  257. for _, s := range history {
  258. counts[s]++
  259. }
  260. best, bestN := 0, 0
  261. for spd, n := range counts {
  262. if n > bestN || (n == bestN && spd > best) {
  263. best, bestN = spd, n
  264. }
  265. }
  266. return best
  267. }