strategy_leastload.go 5.6 KB

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