strategy_leastload.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. package router
  2. import (
  3. "context"
  4. "math"
  5. "sort"
  6. "time"
  7. "github.com/golang/protobuf/proto"
  8. core "github.com/v2fly/v2ray-core/v4"
  9. "github.com/v2fly/v2ray-core/v4/app/observatory"
  10. "github.com/v2fly/v2ray-core/v4/common"
  11. "github.com/v2fly/v2ray-core/v4/common/dice"
  12. "github.com/v2fly/v2ray-core/v4/features"
  13. "github.com/v2fly/v2ray-core/v4/features/extension"
  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. }
  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. if s.observer == nil {
  125. common.Must(core.RequireFeatures(s.ctx, func(observatory extension.Observatory) error {
  126. s.observer = observatory
  127. return nil
  128. }))
  129. }
  130. var result proto.Message
  131. if s.settings.ObserverTag == "" {
  132. observeResult, err := s.observer.GetObservation(s.ctx)
  133. if err != nil {
  134. newError("cannot get observation").Base(err).WriteToLog()
  135. return make([]*node, 0)
  136. }
  137. result = observeResult
  138. } else {
  139. observeResult, err := common.Must2(s.observer.(features.TaggedFeatures).GetFeaturesByTag(s.settings.ObserverTag)).(extension.Observatory).GetObservation(s.ctx)
  140. if err != nil {
  141. newError("cannot get observation").Base(err).WriteToLog()
  142. return make([]*node, 0)
  143. }
  144. result = observeResult
  145. }
  146. results := result.(*observatory.ObservationResult)
  147. outboundlist := outboundList(candidates)
  148. var ret []*node
  149. for _, v := range results.Status {
  150. if v.Alive && (v.Delay < maxRTT.Milliseconds() || maxRTT == 0) && outboundlist.contains(v.OutboundTag) {
  151. record := &node{
  152. Tag: v.OutboundTag,
  153. CountAll: 1,
  154. CountFail: 1,
  155. RTTAverage: time.Duration(v.Delay) * time.Millisecond,
  156. RTTDeviation: time.Duration(v.Delay) * time.Millisecond,
  157. RTTDeviationCost: time.Duration(s.costs.Apply(v.OutboundTag, float64(time.Duration(v.Delay)*time.Millisecond))),
  158. }
  159. if v.HealthPing != nil {
  160. record.RTTAverage = time.Duration(v.HealthPing.Average)
  161. record.RTTDeviation = time.Duration(v.HealthPing.Deviation)
  162. record.RTTDeviationCost = time.Duration(s.costs.Apply(v.OutboundTag, float64(v.HealthPing.Deviation)))
  163. record.CountAll = int(v.HealthPing.All)
  164. record.CountFail = int(v.HealthPing.Fail)
  165. }
  166. ret = append(ret, record)
  167. }
  168. }
  169. leastloadSort(ret)
  170. return ret
  171. }
  172. func leastloadSort(nodes []*node) {
  173. sort.Slice(nodes, func(i, j int) bool {
  174. left := nodes[i]
  175. right := nodes[j]
  176. if left.RTTDeviationCost != right.RTTDeviationCost {
  177. return left.RTTDeviationCost < right.RTTDeviationCost
  178. }
  179. if left.RTTAverage != right.RTTAverage {
  180. return left.RTTAverage < right.RTTAverage
  181. }
  182. if left.CountFail != right.CountFail {
  183. return left.CountFail < right.CountFail
  184. }
  185. if left.CountAll != right.CountAll {
  186. return left.CountAll > right.CountAll
  187. }
  188. return left.Tag < right.Tag
  189. })
  190. }
  191. func init() {
  192. common.Must(common.RegisterConfig((*StrategyLeastLoadConfig)(nil), nil))
  193. }