1
0

strategy_leastload.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  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 (l *LeastLoadStrategy) InjectContext(ctx context.Context) {
  53. l.ctx = ctx
  54. }
  55. func (s *LeastLoadStrategy) PickOutbound(candidates []string) string {
  56. selects := s.pickOutbounds(candidates)
  57. count := len(selects)
  58. if count == 0 {
  59. // goes to fallbackTag
  60. return ""
  61. }
  62. return selects[dice.Roll(count)].Tag
  63. }
  64. func (s *LeastLoadStrategy) pickOutbounds(candidates []string) []*node {
  65. qualified := s.getNodes(candidates, time.Duration(s.settings.MaxRTT))
  66. selects := s.selectLeastLoad(qualified)
  67. return selects
  68. }
  69. // selectLeastLoad selects nodes according to Baselines and Expected Count.
  70. //
  71. // The strategy always improves network response speed, not matter which mode below is configured.
  72. // But they can still have different priorities.
  73. //
  74. // 1. Bandwidth priority: no Baseline + Expected Count > 0.: selects `Expected Count` of nodes.
  75. // (one if Expected Count <= 0)
  76. //
  77. // 2. Bandwidth priority advanced: Baselines + Expected Count > 0.
  78. // Select `Expected Count` amount of nodes, and also those near them according to baselines.
  79. // In other words, it selects according to different Baselines, until one of them matches
  80. // the Expected Count, if no Baseline matches, Expected Count applied.
  81. //
  82. // 3. Speed priority: Baselines + `Expected Count <= 0`.
  83. // go through all baselines until find selects, if not, select none. Used in combination
  84. // with 'balancer.fallbackTag', it means: selects qualified nodes or use the fallback.
  85. func (s *LeastLoadStrategy) selectLeastLoad(nodes []*node) []*node {
  86. if len(nodes) == 0 {
  87. errors.LogInfo(s.ctx, "least load: no qualified outbound")
  88. return nil
  89. }
  90. expected := int(s.settings.Expected)
  91. availableCount := len(nodes)
  92. if expected > availableCount {
  93. return nodes
  94. }
  95. if expected <= 0 {
  96. expected = 1
  97. }
  98. if len(s.settings.Baselines) == 0 {
  99. return nodes[:expected]
  100. }
  101. count := 0
  102. // go through all base line until find expected selects
  103. for _, b := range s.settings.Baselines {
  104. baseline := time.Duration(b)
  105. for i := count; i < availableCount; i++ {
  106. if nodes[i].RTTDeviationCost >= baseline {
  107. break
  108. }
  109. count = i + 1
  110. }
  111. // don't continue if find expected selects
  112. if count >= expected {
  113. errors.LogDebug(s.ctx, "applied baseline: ", baseline)
  114. break
  115. }
  116. }
  117. if s.settings.Expected > 0 && count < expected {
  118. count = expected
  119. }
  120. return nodes[:count]
  121. }
  122. func (s *LeastLoadStrategy) getNodes(candidates []string, maxRTT time.Duration) []*node {
  123. if s.observer == nil {
  124. common.Must(core.RequireFeatures(s.ctx, func(observatory extension.Observatory) error {
  125. s.observer = observatory
  126. return nil
  127. }))
  128. }
  129. observeResult, err := s.observer.GetObservation(s.ctx)
  130. if err != nil {
  131. errors.LogInfoInner(s.ctx, err, "cannot get observation")
  132. return make([]*node, 0)
  133. }
  134. results := observeResult.(*observatory.ObservationResult)
  135. outboundlist := outboundList(candidates)
  136. var ret []*node
  137. for _, v := range results.Status {
  138. if v.Alive && (v.Delay < maxRTT.Milliseconds() || maxRTT == 0) && outboundlist.contains(v.OutboundTag) {
  139. record := &node{
  140. Tag: v.OutboundTag,
  141. CountAll: 1,
  142. CountFail: 1,
  143. RTTAverage: time.Duration(v.Delay) * time.Millisecond,
  144. RTTDeviation: time.Duration(v.Delay) * time.Millisecond,
  145. RTTDeviationCost: time.Duration(s.costs.Apply(v.OutboundTag, float64(time.Duration(v.Delay)*time.Millisecond))),
  146. }
  147. if v.HealthPing != nil {
  148. record.RTTAverage = time.Duration(v.HealthPing.Average)
  149. record.RTTDeviation = time.Duration(v.HealthPing.Deviation)
  150. record.RTTDeviationCost = time.Duration(s.costs.Apply(v.OutboundTag, float64(v.HealthPing.Deviation)))
  151. record.CountAll = int(v.HealthPing.All)
  152. record.CountFail = int(v.HealthPing.Fail)
  153. }
  154. ret = append(ret, record)
  155. }
  156. }
  157. leastloadSort(ret)
  158. return ret
  159. }
  160. func leastloadSort(nodes []*node) {
  161. sort.Slice(nodes, func(i, j int) bool {
  162. left := nodes[i]
  163. right := nodes[j]
  164. if left.RTTDeviationCost != right.RTTDeviationCost {
  165. return left.RTTDeviationCost < right.RTTDeviationCost
  166. }
  167. if left.RTTAverage != right.RTTAverage {
  168. return left.RTTAverage < right.RTTAverage
  169. }
  170. if left.CountFail != right.CountFail {
  171. return left.CountFail < right.CountFail
  172. }
  173. if left.CountAll != right.CountAll {
  174. return left.CountAll > right.CountAll
  175. }
  176. return left.Tag < right.Tag
  177. })
  178. }