router_strategy.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package conf
  2. import (
  3. "github.com/golang/protobuf/proto"
  4. "github.com/v2fly/v2ray-core/v4/app/observatory/burst"
  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. // weight settings
  25. Costs []*router.StrategyWeight `json:"costs,omitempty"`
  26. // ping rtt baselines
  27. Baselines []Duration `json:"baselines,omitempty"`
  28. // expected nodes count to select
  29. Expected int32 `json:"expected,omitempty"`
  30. // max acceptable rtt, filter away high delay nodes. defalut 0
  31. MaxRTT Duration `json:"maxRTT,omitempty"`
  32. // acceptable failure rate
  33. Tolerance float64 `json:"tolerance,omitempty"`
  34. }
  35. // healthCheckSettings holds settings for health Checker
  36. type healthCheckSettings struct {
  37. Destination string `json:"destination"`
  38. Connectivity string `json:"connectivity"`
  39. Interval Duration `json:"interval"`
  40. SamplingCount int `json:"sampling"`
  41. Timeout Duration `json:"timeout"`
  42. }
  43. func (h healthCheckSettings) Build() (proto.Message, error) {
  44. return &burst.HealthPingConfig{
  45. Destination: h.Destination,
  46. Connectivity: h.Connectivity,
  47. Interval: int64(h.Interval),
  48. Timeout: int64(h.Timeout),
  49. SamplingCount: int32(h.SamplingCount),
  50. }, nil
  51. }
  52. // Build implements Buildable.
  53. func (v *strategyLeastLoadConfig) Build() (proto.Message, error) {
  54. config := &router.StrategyLeastLoadConfig{}
  55. config.Costs = v.Costs
  56. config.Tolerance = float32(v.Tolerance)
  57. if config.Tolerance < 0 {
  58. config.Tolerance = 0
  59. }
  60. if config.Tolerance > 1 {
  61. config.Tolerance = 1
  62. }
  63. config.Expected = v.Expected
  64. if config.Expected < 0 {
  65. config.Expected = 0
  66. }
  67. config.MaxRTT = int64(v.MaxRTT)
  68. if config.MaxRTT < 0 {
  69. config.MaxRTT = 0
  70. }
  71. config.Baselines = make([]int64, 0)
  72. for _, b := range v.Baselines {
  73. if b <= 0 {
  74. continue
  75. }
  76. config.Baselines = append(config.Baselines, int64(b))
  77. }
  78. return config, nil
  79. }