strategy_leastload.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. package router
  2. import (
  3. "fmt"
  4. "github.com/v2fly/v2ray-core/v4/app/observatory/burst"
  5. "math"
  6. "sort"
  7. "strings"
  8. "time"
  9. "github.com/v2fly/v2ray-core/v4/common/dice"
  10. "github.com/v2fly/v2ray-core/v4/features/routing"
  11. )
  12. // LeastLoadStrategy represents a least load balancing strategy
  13. type LeastLoadStrategy struct {
  14. settings *StrategyLeastLoadConfig
  15. costs *WeightManager
  16. }
  17. // NewLeastLoadStrategy creates a new LeastLoadStrategy with settings
  18. func NewLeastLoadStrategy(settings *StrategyLeastLoadConfig, dispatcher routing.Dispatcher) *LeastLoadStrategy {
  19. return &LeastLoadStrategy{
  20. settings: settings,
  21. costs: NewWeightManager(
  22. settings.Costs, 1,
  23. func(value, cost float64) float64 {
  24. return value * math.Pow(cost, 0.5)
  25. },
  26. ),
  27. }
  28. }
  29. // node is a minimal copy of HealthCheckResult
  30. // we don't use HealthCheckResult directly because
  31. // it may change by health checker during routing
  32. type node struct {
  33. Tag string
  34. CountAll int
  35. CountFail int
  36. RTTAverage time.Duration
  37. RTTDeviation time.Duration
  38. RTTDeviationCost time.Duration
  39. applied time.Duration
  40. }
  41. // GetInformation implements the routing.BalancingStrategy.
  42. func (s *LeastLoadStrategy) GetInformation(tags []string) *routing.StrategyInfo {
  43. qualified, others := s.getNodes(tags, time.Duration(s.settings.MaxRTT))
  44. selects := s.selectLeastLoad(qualified)
  45. // append qualified but not selected outbounds to others
  46. others = append(others, qualified[len(selects):]...)
  47. leastloadSort(others)
  48. titles, sl := s.getNodesInfo(selects)
  49. _, ot := s.getNodesInfo(others)
  50. return &routing.StrategyInfo{
  51. Settings: s.getSettings(),
  52. ValueTitles: titles,
  53. Selects: sl,
  54. Others: ot,
  55. }
  56. }
  57. // SelectAndPick implements the routing.BalancingStrategy.
  58. func (s *LeastLoadStrategy) SelectAndPick(candidates []string) string {
  59. qualified, _ := s.getNodes(candidates, time.Duration(s.settings.MaxRTT))
  60. selects := s.selectLeastLoad(qualified)
  61. count := len(selects)
  62. if count == 0 {
  63. // goes to fallbackTag
  64. return ""
  65. }
  66. return selects[dice.Roll(count)].Tag
  67. }
  68. // Pick implements the routing.BalancingStrategy.
  69. func (s *LeastLoadStrategy) Pick(candidates []string) string {
  70. count := len(candidates)
  71. if count == 0 {
  72. // goes to fallbackTag
  73. return ""
  74. }
  75. return candidates[dice.Roll(count)]
  76. }
  77. // selectLeastLoad selects nodes according to Baselines and Expected Count.
  78. //
  79. // The strategy always improves network response speed, not matter which mode below is configurated.
  80. // But they can still have different priorities.
  81. //
  82. // 1. Bandwidth priority: no Baseline + Expected Count > 0.: selects `Expected Count` of nodes.
  83. // (one if Expected Count <= 0)
  84. //
  85. // 2. Bandwidth priority advanced: Baselines + Expected Count > 0.
  86. // Select `Expected Count` amount of nodes, and also those near them according to baselines.
  87. // In other words, it selects according to different Baselines, until one of them matches
  88. // the Expected Count, if no Baseline matches, Expected Count applied.
  89. //
  90. // 3. Speed priority: Baselines + `Expected Count <= 0`.
  91. // go through all baselines until find selects, if not, select none. Used in combination
  92. // with 'balancer.fallbackTag', it means: selects qualified nodes or use the fallback.
  93. func (s *LeastLoadStrategy) selectLeastLoad(nodes []*node) []*node {
  94. if len(nodes) == 0 {
  95. newError("least load: no qualified outbound").AtInfo().WriteToLog()
  96. return nil
  97. }
  98. expected := int(s.settings.Expected)
  99. availableCount := len(nodes)
  100. if expected > availableCount {
  101. return nodes
  102. }
  103. if expected <= 0 {
  104. expected = 1
  105. }
  106. if len(s.settings.Baselines) == 0 {
  107. return nodes[:expected]
  108. }
  109. count := 0
  110. // go through all base line until find expected selects
  111. for _, b := range s.settings.Baselines {
  112. baseline := time.Duration(b)
  113. for i := 0; i < availableCount; i++ {
  114. if nodes[i].applied > baseline {
  115. break
  116. }
  117. count = i + 1
  118. }
  119. // don't continue if find expected selects
  120. if count >= expected {
  121. newError("applied baseline: ", baseline).AtDebug().WriteToLog()
  122. break
  123. }
  124. }
  125. if s.settings.Expected > 0 && count < expected {
  126. count = expected
  127. }
  128. return nodes[:count]
  129. }
  130. func (s *LeastLoadStrategy) getNodes(candidates []string, maxRTT time.Duration) ([]*node, []*node) {
  131. s.access.Lock()
  132. defer s.access.Unlock()
  133. results := s.Results
  134. qualified := make([]*node, 0)
  135. unqualified := make([]*node, 0)
  136. failed := make([]*node, 0)
  137. untested := make([]*node, 0)
  138. others := make([]*node, 0)
  139. for _, tag := range candidates {
  140. r, ok := results[tag]
  141. if !ok {
  142. untested = append(untested, &node{
  143. Tag: tag,
  144. RTTDeviationCost: 0,
  145. RTTDeviation: 0,
  146. RTTAverage: 0,
  147. applied: rttUntested,
  148. })
  149. continue
  150. }
  151. stats := r.Get()
  152. node := &node{
  153. Tag: tag,
  154. RTTDeviationCost: time.Duration(s.costs.Apply(tag, float64(stats.Deviation))),
  155. RTTDeviation: stats.Deviation,
  156. RTTAverage: stats.Average,
  157. CountAll: stats.All,
  158. CountFail: stats.Fail,
  159. }
  160. switch {
  161. case stats.All == 0:
  162. node.applied = rttUntested
  163. untested = append(untested, node)
  164. case maxRTT > 0 && stats.Average > maxRTT:
  165. node.applied = rttUnqualified
  166. unqualified = append(unqualified, node)
  167. case float64(stats.Fail)/float64(stats.All) > float64(s.settings.Tolerance):
  168. node.applied = rttFailed
  169. if stats.All-stats.Fail == 0 {
  170. // no good, put them after has-good nodes
  171. node.RTTDeviationCost = rttFailed
  172. node.RTTDeviation = rttFailed
  173. node.RTTAverage = rttFailed
  174. }
  175. failed = append(failed, node)
  176. default:
  177. node.applied = node.RTTDeviationCost
  178. qualified = append(qualified, node)
  179. }
  180. }
  181. if len(qualified) > 0 {
  182. leastloadSort(qualified)
  183. others = append(others, unqualified...)
  184. others = append(others, untested...)
  185. others = append(others, failed...)
  186. } else {
  187. qualified = untested
  188. others = append(others, unqualified...)
  189. others = append(others, failed...)
  190. }
  191. return qualified, others
  192. }
  193. func (s *LeastLoadStrategy) getSettings() []string {
  194. settings := make([]string, 0)
  195. sb := new(strings.Builder)
  196. for i, b := range s.settings.Baselines {
  197. if i > 0 {
  198. sb.WriteByte(' ')
  199. }
  200. sb.WriteString(time.Duration(b).String())
  201. }
  202. baselines := sb.String()
  203. if baselines == "" {
  204. baselines = "none"
  205. }
  206. maxRTT := time.Duration(s.settings.MaxRTT).String()
  207. if s.settings.MaxRTT == 0 {
  208. maxRTT = "none"
  209. }
  210. settings = append(settings, fmt.Sprintf(
  211. "leastload, expected: %d, baselines: %s, max rtt: %s, tolerance: %.2f",
  212. s.settings.Expected,
  213. baselines,
  214. maxRTT,
  215. s.settings.Tolerance,
  216. ))
  217. settings = append(settings, fmt.Sprintf(
  218. "health ping, interval: %s, sampling: %d, timeout: %s, destination: %s",
  219. s.HealthPing.Settings.Interval,
  220. s.HealthPing.Settings.SamplingCount,
  221. s.HealthPing.Settings.Timeout,
  222. s.HealthPing.Settings.Destination,
  223. ))
  224. return settings
  225. }
  226. func (s *LeastLoadStrategy) getNodesInfo(nodes []*node) ([]string, []*routing.OutboundInfo) {
  227. titles := []string{" ", "RTT STD+C ", "RTT STD. ", "RTT Avg. ", "Hit ", "Cost "}
  228. hasCost := len(s.settings.Costs) > 0
  229. if !hasCost {
  230. titles = []string{" ", "RTT STD. ", "RTT Avg. ", "Hit "}
  231. }
  232. items := make([]*routing.OutboundInfo, 0)
  233. for _, node := range nodes {
  234. item := &routing.OutboundInfo{
  235. Tag: node.Tag,
  236. }
  237. var status string
  238. cost := fmt.Sprintf("%.2f", s.costs.Get(node.Tag))
  239. switch node.applied {
  240. case rttFailed:
  241. status = "x"
  242. case rttUntested:
  243. status = "?"
  244. case rttUnqualified:
  245. status = ">"
  246. default:
  247. status = "OK"
  248. }
  249. if hasCost {
  250. item.Values = []string{
  251. status,
  252. durationString(node.RTTDeviationCost),
  253. durationString(node.RTTDeviation),
  254. durationString(node.RTTAverage),
  255. fmt.Sprintf("%d/%d", node.CountAll-node.CountFail, node.CountAll),
  256. cost,
  257. }
  258. } else {
  259. item.Values = []string{
  260. status,
  261. durationString(node.RTTDeviation),
  262. durationString(node.RTTAverage),
  263. fmt.Sprintf("%d/%d", node.CountAll-node.CountFail, node.CountAll),
  264. }
  265. }
  266. items = append(items, item)
  267. }
  268. return titles, items
  269. }
  270. func durationString(d time.Duration) string {
  271. if d <= 0 || d > time.Hour {
  272. return "-"
  273. }
  274. return d.String()
  275. }
  276. func leastloadSort(nodes []*node) {
  277. sort.Slice(nodes, func(i, j int) bool {
  278. left := nodes[i]
  279. right := nodes[j]
  280. if left.applied != right.applied {
  281. return left.applied < right.applied
  282. }
  283. if left.RTTDeviationCost != right.RTTDeviationCost {
  284. return left.RTTDeviationCost < right.RTTDeviationCost
  285. }
  286. if left.RTTAverage != right.RTTAverage {
  287. return left.RTTAverage < right.RTTAverage
  288. }
  289. if left.CountFail != right.CountFail {
  290. return left.CountFail < right.CountFail
  291. }
  292. if left.CountAll != right.CountAll {
  293. return left.CountAll > right.CountAll
  294. }
  295. return left.Tag < right.Tag
  296. })
  297. }