strategy_leastload.go 8.7 KB

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