strategy_leastload.go 5.5 KB

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