health.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. package sdwan
  2. import (
  3. "context"
  4. "log"
  5. "math"
  6. "os/exec"
  7. "regexp"
  8. "strconv"
  9. "strings"
  10. "sync"
  11. "time"
  12. )
  13. var (
  14. rttRegex = regexp.MustCompile(`time=([0-9.]+)\s*ms`)
  15. lossRegex = regexp.MustCompile(`([0-9.]+)%\s*packet\s*loss`)
  16. )
  17. type probeSample struct {
  18. latency float64
  19. success bool
  20. t time.Time
  21. }
  22. // HealthMonitor periodically probes SD-WAN member interfaces and updates SLA telemetry.
  23. type HealthMonitor struct {
  24. mu sync.RWMutex
  25. samples map[string][]probeSample // memberID -> rolling probe samples
  26. cancel context.CancelFunc
  27. onStateChange func()
  28. }
  29. func NewHealthMonitor(onStateChange func()) *HealthMonitor {
  30. return &HealthMonitor{
  31. samples: make(map[string][]probeSample),
  32. onStateChange: onStateChange,
  33. }
  34. }
  35. // Start begins periodic background health checking for active SD-WAN members.
  36. func (h *HealthMonitor) Start(getGroups func() []*SDWANGroup) {
  37. ctx, cancel := context.WithCancel(context.Background())
  38. h.cancel = cancel
  39. go func() {
  40. ticker := time.NewTicker(3 * time.Second)
  41. defer ticker.Stop()
  42. for {
  43. select {
  44. case <-ctx.Done():
  45. return
  46. case <-ticker.C:
  47. groups := getGroups()
  48. h.runProbeIteration(groups)
  49. }
  50. }
  51. }()
  52. }
  53. // Stop terminates the probing goroutine.
  54. func (h *HealthMonitor) Stop() {
  55. if h.cancel != nil {
  56. h.cancel()
  57. }
  58. }
  59. func (h *HealthMonitor) runProbeIteration(groups []*SDWANGroup) {
  60. stateChanged := false
  61. for _, g := range groups {
  62. if g.Disabled {
  63. continue
  64. }
  65. for _, m := range g.Members {
  66. if m.Disabled || m.Interface == "" {
  67. m.Status = StatusDisabled
  68. continue
  69. }
  70. probeTarget := m.TargetProbe
  71. if probeTarget == "" {
  72. probeTarget = "1.1.1.1"
  73. }
  74. // Run ICMP ping probe
  75. latency, success := h.executeProbe(m.Interface, probeTarget)
  76. h.mu.Lock()
  77. history := h.samples[m.ID]
  78. history = append(history, probeSample{
  79. latency: latency,
  80. success: success,
  81. t: time.Now(),
  82. })
  83. if len(history) > 10 {
  84. history = history[len(history)-10:]
  85. }
  86. h.samples[m.ID] = history
  87. h.mu.Unlock()
  88. prevStatus := m.Status
  89. // Calculate telemetry
  90. m.LastChecked = time.Now()
  91. if success {
  92. m.ConsecutiveFails = 0
  93. } else {
  94. m.ConsecutiveFails++
  95. }
  96. h.calculateMetrics(m, history)
  97. // Determine status based on SLA thresholds
  98. if m.ConsecutiveFails >= 3 {
  99. m.Status = StatusDown
  100. } else {
  101. maxLat := float64(m.MaxLatency)
  102. if maxLat <= 0 {
  103. maxLat = 250.0
  104. }
  105. maxLoss := float64(m.MaxLoss)
  106. if maxLoss <= 0 {
  107. maxLoss = 20.0
  108. }
  109. if m.PacketLoss > maxLoss || m.LiveLatency > maxLat {
  110. m.Status = StatusDegraded
  111. } else {
  112. m.Status = StatusHealthy
  113. }
  114. }
  115. // Check if link transitioned between UP and DOWN
  116. if (prevStatus == StatusDown && m.Status != StatusDown) ||
  117. (prevStatus != StatusDown && m.Status == StatusDown) {
  118. stateChanged = true
  119. log.Printf("[SD-WAN] Health alert: %s status changed from %s to %s (latency: %.1fms, loss: %.1f%%)",
  120. m.Interface, prevStatus, m.Status, m.LiveLatency, m.PacketLoss)
  121. }
  122. }
  123. }
  124. if stateChanged && h.onStateChange != nil {
  125. h.onStateChange()
  126. }
  127. }
  128. func (h *HealthMonitor) executeProbe(iface, target string) (float64, bool) {
  129. // ping -c 1 -W 2 -I <iface> <target>
  130. cmd := exec.Command("ping", "-c", "1", "-W", "2", "-I", iface, target)
  131. out, err := cmd.CombinedOutput()
  132. if err != nil {
  133. return 0, false
  134. }
  135. str := string(out)
  136. if !strings.Contains(str, "1 received") && !strings.Contains(str, "1 packets received") {
  137. return 0, false
  138. }
  139. matches := rttRegex.FindStringSubmatch(str)
  140. if len(matches) > 1 {
  141. if val, err := strconv.ParseFloat(matches[1], 64); err == nil {
  142. return val, true
  143. }
  144. }
  145. return 1.0, true
  146. }
  147. func (h *HealthMonitor) calculateMetrics(m *SDWANMember, history []probeSample) {
  148. if len(history) == 0 {
  149. return
  150. }
  151. total := len(history)
  152. failed := 0
  153. var sumLat float64
  154. var countSuccess int
  155. var latencies []float64
  156. for _, s := range history {
  157. if !s.success {
  158. failed++
  159. } else {
  160. sumLat += s.latency
  161. countSuccess++
  162. latencies = append(latencies, s.latency)
  163. }
  164. }
  165. m.PacketLoss = (float64(failed) / float64(total)) * 100.0
  166. if countSuccess > 0 {
  167. avg := sumLat / float64(countSuccess)
  168. m.LiveLatency = math.Round(avg*10) / 10
  169. // Jitter calculation (average difference between consecutive probes)
  170. if len(latencies) >= 2 {
  171. var diffSum float64
  172. for i := 1; i < len(latencies); i++ {
  173. diffSum += math.Abs(latencies[i] - latencies[i-1])
  174. }
  175. m.Jitter = math.Round((diffSum/float64(len(latencies)-1))*10) / 10
  176. }
  177. } else {
  178. m.LiveLatency = 0
  179. m.Jitter = 0
  180. }
  181. }