strategy_leastload.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. package router
  2. import (
  3. "context"
  4. core "github.com/v2fly/v2ray-core/v4"
  5. "github.com/v2fly/v2ray-core/v4/app/observatory"
  6. "github.com/v2fly/v2ray-core/v4/common"
  7. "math"
  8. "sort"
  9. "time"
  10. "github.com/v2fly/v2ray-core/v4/common/dice"
  11. )
  12. // LeastLoadStrategy represents a least load balancing strategy
  13. type LeastLoadStrategy struct {
  14. settings *StrategyLeastLoadConfig
  15. costs *WeightManager
  16. observer *observatory.Observer
  17. ctx context.Context
  18. }
  19. // NewLeastLoadStrategy creates a new LeastLoadStrategy with settings
  20. func NewLeastLoadStrategy(settings *StrategyLeastLoadConfig) *LeastLoadStrategy {
  21. return &LeastLoadStrategy{
  22. settings: settings,
  23. costs: NewWeightManager(
  24. settings.Costs, 1,
  25. func(value, cost float64) float64 {
  26. return value * math.Pow(cost, 0.5)
  27. },
  28. ),
  29. }
  30. }
  31. // node is a minimal copy of HealthCheckResult
  32. // we don't use HealthCheckResult directly because
  33. // it may change by health checker during routing
  34. type node struct {
  35. Tag string
  36. CountAll int
  37. CountFail int
  38. RTTAverage time.Duration
  39. RTTDeviation time.Duration
  40. RTTDeviationCost time.Duration
  41. }
  42. func (l *LeastLoadStrategy) InjectContext(ctx context.Context) {
  43. l.ctx = ctx
  44. common.Must(core.RequireFeatures(ctx, func(observerInstance *observatory.Observer) {
  45. l.observer = observerInstance
  46. }))
  47. }
  48. func (s *LeastLoadStrategy) PickOutbound(candidates []string) string {
  49. qualified := s.getNodes(candidates, time.Duration(s.settings.MaxRTT))
  50. selects := s.selectLeastLoad(qualified)
  51. count := len(selects)
  52. if count == 0 {
  53. // goes to fallbackTag
  54. return ""
  55. }
  56. return selects[dice.Roll(count)].Tag
  57. }
  58. // selectLeastLoad selects nodes according to Baselines and Expected Count.
  59. //
  60. // The strategy always improves network response speed, not matter which mode below is configured.
  61. // But they can still have different priorities.
  62. //
  63. // 1. Bandwidth priority: no Baseline + Expected Count > 0.: selects `Expected Count` of nodes.
  64. // (one if Expected Count <= 0)
  65. //
  66. // 2. Bandwidth priority advanced: Baselines + Expected Count > 0.
  67. // Select `Expected Count` amount of nodes, and also those near them according to baselines.
  68. // In other words, it selects according to different Baselines, until one of them matches
  69. // the Expected Count, if no Baseline matches, Expected Count applied.
  70. //
  71. // 3. Speed priority: Baselines + `Expected Count <= 0`.
  72. // go through all baselines until find selects, if not, select none. Used in combination
  73. // with 'balancer.fallbackTag', it means: selects qualified nodes or use the fallback.
  74. func (s *LeastLoadStrategy) selectLeastLoad(nodes []*node) []*node {
  75. if len(nodes) == 0 {
  76. newError("least load: no qualified outbound").AtInfo().WriteToLog()
  77. return nil
  78. }
  79. expected := int(s.settings.Expected)
  80. availableCount := len(nodes)
  81. if expected > availableCount {
  82. return nodes
  83. }
  84. if expected <= 0 {
  85. expected = 1
  86. }
  87. if len(s.settings.Baselines) == 0 {
  88. return nodes[:expected]
  89. }
  90. count := 0
  91. // go through all base line until find expected selects
  92. for _, b := range s.settings.Baselines {
  93. baseline := time.Duration(b)
  94. for i := 0; i < availableCount; i++ {
  95. if nodes[i].RTTDeviationCost > baseline {
  96. break
  97. }
  98. count = i + 1
  99. }
  100. // don't continue if find expected selects
  101. if count >= expected {
  102. newError("applied baseline: ", baseline).AtDebug().WriteToLog()
  103. break
  104. }
  105. }
  106. if s.settings.Expected > 0 && count < expected {
  107. count = expected
  108. }
  109. return nodes[:count]
  110. }
  111. func (s *LeastLoadStrategy) getNodes(candidates []string, maxRTT time.Duration) []*node {
  112. observeResult, err := s.observer.GetObservation(s.ctx)
  113. if err != nil {
  114. newError("cannot get observation").Base(err)
  115. }
  116. results := observeResult.(*observatory.ObservationResult)
  117. outboundlist := outboundList(candidates)
  118. var ret []*node
  119. for _, v := range results.Status {
  120. if v.Alive && v.Delay < maxRTT.Milliseconds() && outboundlist.contains(v.OutboundTag) {
  121. record := &node{
  122. Tag: v.OutboundTag,
  123. CountAll: 1,
  124. CountFail: 1,
  125. RTTAverage: time.Duration(v.Delay) * time.Millisecond,
  126. RTTDeviation: time.Duration(v.Delay) * time.Millisecond,
  127. RTTDeviationCost: time.Duration(s.costs.Apply(v.OutboundTag, float64(time.Duration(v.Delay)*time.Millisecond))),
  128. }
  129. if v.HealthPing != nil {
  130. record.RTTAverage = time.Duration(v.HealthPing.Average)
  131. record.RTTDeviation = time.Duration(v.HealthPing.Deviation)
  132. record.RTTDeviationCost = time.Duration(s.costs.Apply(v.OutboundTag, float64(v.HealthPing.Deviation)))
  133. record.CountAll = int(v.HealthPing.All)
  134. record.CountFail = int(v.HealthPing.Fail)
  135. }
  136. ret = append(ret, record)
  137. }
  138. }
  139. leastloadSort(ret)
  140. return ret
  141. }
  142. func leastloadSort(nodes []*node) {
  143. sort.Slice(nodes, func(i, j int) bool {
  144. left := nodes[i]
  145. right := nodes[j]
  146. if left.RTTDeviationCost != right.RTTDeviationCost {
  147. return left.RTTDeviationCost < right.RTTDeviationCost
  148. }
  149. if left.RTTAverage != right.RTTAverage {
  150. return left.RTTAverage < right.RTTAverage
  151. }
  152. if left.CountFail != right.CountFail {
  153. return left.CountFail < right.CountFail
  154. }
  155. if left.CountAll != right.CountAll {
  156. return left.CountAll > right.CountAll
  157. }
  158. return left.Tag < right.Tag
  159. })
  160. }