status.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package probing
  2. import (
  3. "sync"
  4. "time"
  5. )
  6. var (
  7. // weight factor
  8. α = 0.125
  9. )
  10. type Status interface {
  11. Total() int64
  12. Loss() int64
  13. Health() bool
  14. // Estimated smoothed round trip time
  15. SRTT() time.Duration
  16. // Estimated clock difference
  17. ClockDiff() time.Duration
  18. StopNotify() <-chan struct{}
  19. }
  20. type status struct {
  21. mu sync.Mutex
  22. srtt time.Duration
  23. total int64
  24. loss int64
  25. health bool
  26. clockdiff time.Duration
  27. stopC chan struct{}
  28. }
  29. // SRTT = (1-α) * SRTT + α * RTT
  30. func (s *status) SRTT() time.Duration {
  31. s.mu.Lock()
  32. defer s.mu.Unlock()
  33. return s.srtt
  34. }
  35. func (s *status) Total() int64 {
  36. s.mu.Lock()
  37. defer s.mu.Unlock()
  38. return s.total
  39. }
  40. func (s *status) Loss() int64 {
  41. s.mu.Lock()
  42. defer s.mu.Unlock()
  43. return s.loss
  44. }
  45. func (s *status) Health() bool {
  46. s.mu.Lock()
  47. defer s.mu.Unlock()
  48. return s.health
  49. }
  50. func (s *status) ClockDiff() time.Duration {
  51. s.mu.Lock()
  52. defer s.mu.Unlock()
  53. return s.clockdiff
  54. }
  55. func (s *status) StopNotify() <-chan struct{} {
  56. return s.stopC
  57. }
  58. func (s *status) record(rtt time.Duration, when time.Time) {
  59. s.mu.Lock()
  60. defer s.mu.Unlock()
  61. s.total += 1
  62. s.health = true
  63. s.srtt = time.Duration((1-α)*float64(s.srtt) + α*float64(rtt))
  64. s.clockdiff = time.Now().Sub(when) - s.srtt/2
  65. }
  66. func (s *status) recordFailure() {
  67. s.mu.Lock()
  68. defer s.mu.Unlock()
  69. s.total++
  70. s.health = false
  71. s.loss += 1
  72. }
  73. func (s *status) reset() {
  74. s.mu.Lock()
  75. defer s.mu.Unlock()
  76. s.srtt = 0
  77. s.total = 0
  78. s.health = false
  79. s.clockdiff = 0
  80. }