strategy_leastload.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. package router
  2. import (
  3. "context"
  4. "math"
  5. "sort"
  6. "time"
  7. "github.com/xtls/xray-core/app/observatory"
  8. "github.com/xtls/xray-core/common"
  9. "github.com/xtls/xray-core/common/dice"
  10. "github.com/xtls/xray-core/common/errors"
  11. "github.com/xtls/xray-core/core"
  12. "github.com/xtls/xray-core/features/extension"
  13. )
  14. // LeastLoadStrategy represents a least load balancing strategy
  15. type LeastLoadStrategy struct {
  16. settings *StrategyLeastLoadConfig
  17. costs *WeightManager
  18. observer extension.Observatory
  19. ctx context.Context
  20. }
  21. func (l *LeastLoadStrategy) GetPrincipleTarget(strings []string) []string {
  22. var ret []string
  23. nodes := l.pickOutbounds(strings)
  24. for _, v := range nodes {
  25. ret = append(ret, v.Tag)
  26. }
  27. return ret
  28. }
  29. // NewLeastLoadStrategy creates a new LeastLoadStrategy with settings
  30. func NewLeastLoadStrategy(settings *StrategyLeastLoadConfig) *LeastLoadStrategy {
  31. return &LeastLoadStrategy{
  32. settings: settings,
  33. costs: NewWeightManager(
  34. settings.Costs, 1,
  35. func(value, cost float64) float64 {
  36. return value * math.Pow(cost, 0.5)
  37. },
  38. ),
  39. }
  40. }
  41. // node is a minimal copy of HealthCheckResult
  42. // we don't use HealthCheckResult directly because
  43. // it may change by health checker during routing
  44. type node struct {
  45. Tag string
  46. CountAll int
  47. CountFail int
  48. RTTAverage time.Duration
  49. RTTDeviation time.Duration
  50. RTTDeviationCost time.Duration
  51. }
  52. func (s *LeastLoadStrategy) InjectContext(ctx context.Context) {
  53. s.ctx = ctx
  54. common.Must(core.RequireFeatures(s.ctx, func(observatory extension.Observatory) error {
  55. s.observer = observatory
  56. return nil
  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. errors.LogInfo(s.ctx, "least load: no qualified outbound")
  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 := count; 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. errors.LogDebug(s.ctx, "applied baseline: ", baseline)
  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. if s.observer == nil {
  128. errors.LogError(s.ctx, "observer is nil")
  129. return make([]*node, 0)
  130. }
  131. observeResult, err := s.observer.GetObservation(s.ctx)
  132. if err != nil {
  133. errors.LogInfoInner(s.ctx, err, "cannot get observation")
  134. return make([]*node, 0)
  135. }
  136. results := observeResult.(*observatory.ObservationResult)
  137. outboundlist := outboundList(candidates)
  138. var ret []*node
  139. for _, v := range results.Status {
  140. if v.Alive && (v.Delay < maxRTT.Milliseconds() || maxRTT == 0) && outboundlist.contains(v.OutboundTag) {
  141. record := &node{
  142. Tag: v.OutboundTag,
  143. CountAll: 1,
  144. CountFail: 1,
  145. RTTAverage: time.Duration(v.Delay) * time.Millisecond,
  146. RTTDeviation: time.Duration(v.Delay) * time.Millisecond,
  147. RTTDeviationCost: time.Duration(s.costs.Apply(v.OutboundTag, float64(time.Duration(v.Delay)*time.Millisecond))),
  148. }
  149. if v.HealthPing != nil {
  150. record.RTTAverage = time.Duration(v.HealthPing.Average)
  151. record.RTTDeviation = time.Duration(v.HealthPing.Deviation)
  152. record.RTTDeviationCost = time.Duration(s.costs.Apply(v.OutboundTag, float64(v.HealthPing.Deviation)))
  153. record.CountAll = int(v.HealthPing.All)
  154. record.CountFail = int(v.HealthPing.Fail)
  155. }
  156. ret = append(ret, record)
  157. }
  158. }
  159. leastloadSort(ret)
  160. return ret
  161. }
  162. func leastloadSort(nodes []*node) {
  163. sort.Slice(nodes, func(i, j int) bool {
  164. left := nodes[i]
  165. right := nodes[j]
  166. if left.RTTDeviationCost != right.RTTDeviationCost {
  167. return left.RTTDeviationCost < right.RTTDeviationCost
  168. }
  169. if left.RTTAverage != right.RTTAverage {
  170. return left.RTTAverage < right.RTTAverage
  171. }
  172. if left.CountFail != right.CountFail {
  173. return left.CountFail < right.CountFail
  174. }
  175. if left.CountAll != right.CountAll {
  176. return left.CountAll > right.CountAll
  177. }
  178. return left.Tag < right.Tag
  179. })
  180. }