router_strategy.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package conf
  2. import (
  3. "time"
  4. "github.com/golang/protobuf/proto"
  5. "github.com/v2fly/v2ray-core/v4/app/router"
  6. )
  7. const (
  8. strategyRandom string = "random"
  9. strategyLeastLoad string = "leastload"
  10. strategyLeastPing string = "leastping"
  11. )
  12. var (
  13. strategyConfigLoader = NewJSONConfigLoader(ConfigCreatorCache{
  14. strategyRandom: func() interface{} { return new(strategyEmptyConfig) },
  15. strategyLeastLoad: func() interface{} { return new(strategyLeastLoadConfig) },
  16. }, "type", "settings")
  17. )
  18. type strategyEmptyConfig struct {
  19. }
  20. func (v *strategyEmptyConfig) Build() (proto.Message, error) {
  21. return nil, nil
  22. }
  23. type strategyLeastLoadConfig struct {
  24. // note the time values of the HealthCheck holds is not
  25. // 'time.Duration' but plain number, sice they were parsed
  26. // directly from json
  27. HealthCheck *router.HealthPingSettings `json:"healthCheck,omitempty"`
  28. // weight settings
  29. Costs []*router.StrategyWeight `json:"costs,omitempty"`
  30. // ping rtt baselines (ms)
  31. Baselines []int `json:"baselines,omitempty"`
  32. // expected nodes count to select
  33. Expected int32 `json:"expected,omitempty"`
  34. // max acceptable rtt (ms), filter away high delay nodes. defalut 0
  35. MaxRTT int `json:"maxRTT,omitempty"`
  36. // acceptable failure rate
  37. Tolerance float64 `json:"tolerance,omitempty"`
  38. }
  39. // Build implements Buildable.
  40. func (v *strategyLeastLoadConfig) Build() (proto.Message, error) {
  41. config := &router.StrategyLeastLoadConfig{
  42. HealthCheck: &router.HealthPingConfig{},
  43. }
  44. if v.HealthCheck != nil {
  45. config.HealthCheck = &router.HealthPingConfig{
  46. Destination: v.HealthCheck.Destination,
  47. Connectivity: v.HealthCheck.Connectivity,
  48. Interval: int64(v.HealthCheck.Interval * time.Second),
  49. Timeout: int64(v.HealthCheck.Timeout * time.Second),
  50. SamplingCount: int32(v.HealthCheck.SamplingCount),
  51. }
  52. }
  53. config.Costs = v.Costs
  54. config.Tolerance = float32(v.Tolerance)
  55. if config.Tolerance < 0 {
  56. config.Tolerance = 0
  57. }
  58. if config.Tolerance > 1 {
  59. config.Tolerance = 1
  60. }
  61. config.Expected = v.Expected
  62. if config.Expected < 0 {
  63. config.Expected = 0
  64. }
  65. config.MaxRTT = int64(time.Duration(v.MaxRTT) * time.Millisecond)
  66. if config.MaxRTT < 0 {
  67. config.MaxRTT = 0
  68. }
  69. config.Baselines = make([]int64, 0)
  70. for _, b := range v.Baselines {
  71. if b <= 0 {
  72. continue
  73. }
  74. config.Baselines = append(config.Baselines, int64(time.Duration(b)*time.Millisecond))
  75. }
  76. return config, nil
  77. }