strategy_leastload.go 5.9 KB

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