|
| 1 | +package router |
| 2 | + |
| 3 | +import ( |
| 4 | + "bufio" |
| 5 | + "context" |
| 6 | + "fmt" |
| 7 | + "math" |
| 8 | + "net/http" |
| 9 | + "net/url" |
| 10 | + "time" |
| 11 | + |
| 12 | + "v2ray.com/core/common/net" |
| 13 | + "v2ray.com/core/common/session" |
| 14 | + "v2ray.com/core/common/task" |
| 15 | + "v2ray.com/core/features/outbound" |
| 16 | + "v2ray.com/core/transport" |
| 17 | + "v2ray.com/core/transport/pipe" |
| 18 | +) |
| 19 | + |
| 20 | +// OptimalStrategy pick outbound by net speed |
| 21 | +type OptimalStrategy struct { |
| 22 | + timeout time.Duration |
| 23 | + interval time.Duration |
| 24 | + url *url.URL |
| 25 | + count uint32 |
| 26 | + score float64 |
| 27 | + obm outbound.Manager |
| 28 | + tag string |
| 29 | + tags []string |
| 30 | + periodic *task.Periodic |
| 31 | +} |
| 32 | + |
| 33 | +// NewOptimalStrategy create new strategy |
| 34 | +func NewOptimalStrategy(config *OptimalStrategyConfig) *OptimalStrategy { |
| 35 | + s := &OptimalStrategy{} |
| 36 | + if config.Timeout == 0 { |
| 37 | + s.timeout = time.Second * 5 |
| 38 | + } else { |
| 39 | + s.timeout = time.Second * time.Duration(config.Timeout) |
| 40 | + } |
| 41 | + if config.Interval == 0 { |
| 42 | + s.interval = time.Second * 60 * 10 |
| 43 | + } else { |
| 44 | + s.interval = time.Second * time.Duration(config.Interval) |
| 45 | + } |
| 46 | + if config.URL == "" { |
| 47 | + s.url, _ = url.Parse("https://www.google.com") |
| 48 | + } else { |
| 49 | + var err error |
| 50 | + s.url, err = url.Parse(config.URL) |
| 51 | + if err != nil { |
| 52 | + panic(err) |
| 53 | + } |
| 54 | + if s.url.Scheme != "http" && s.url.Scheme != "https" { |
| 55 | + panic("Only http/https url support") |
| 56 | + } |
| 57 | + } |
| 58 | + if config.Count == 0 { |
| 59 | + s.count = 3 |
| 60 | + } else { |
| 61 | + s.count = config.Count |
| 62 | + } |
| 63 | + s.score = 0 |
| 64 | + |
| 65 | + return s |
| 66 | +} |
| 67 | + |
| 68 | +// PickOutbound implement BalancingStrategy interface |
| 69 | +func (s *OptimalStrategy) PickOutbound(obm outbound.Manager, tags []string) string { |
| 70 | + if len(tags) == 0 { |
| 71 | + panic("0 tags") |
| 72 | + } else if len(tags) == 1 { |
| 73 | + return s.tag |
| 74 | + } |
| 75 | + |
| 76 | + s.obm = obm |
| 77 | + s.tags = tags |
| 78 | + |
| 79 | + if s.periodic == nil { |
| 80 | + s.periodic = &task.Periodic{ |
| 81 | + Interval: s.interval, |
| 82 | + Execute: s.run, |
| 83 | + } |
| 84 | + s.periodic.Start() |
| 85 | + s.tag = s.tags[0] |
| 86 | + return s.tag |
| 87 | + } |
| 88 | + |
| 89 | + return s.tag |
| 90 | +} |
| 91 | + |
| 92 | +// periodic execute function |
| 93 | +func (s *OptimalStrategy) run() error { |
| 94 | + s.score = 0 |
| 95 | + |
| 96 | + for _, tag := range s.tags { |
| 97 | + scores := make([]float64, 0, s.count) |
| 98 | + go s.testOutboud(tag, scores) |
| 99 | + } |
| 100 | + |
| 101 | + return nil |
| 102 | +} |
| 103 | + |
| 104 | +// Test outbound's network state with multi-round |
| 105 | +func (s *OptimalStrategy) testOutboud(tag string, scores []float64) { |
| 106 | + // calculate average score and end test round |
| 107 | + if len(scores) >= int(s.count) { |
| 108 | + var minScore float64 = float64(math.MaxInt64) |
| 109 | + var maxScore float64 = float64(math.MinInt64) |
| 110 | + var sumScore float64 |
| 111 | + var score float64 |
| 112 | + |
| 113 | + for _, score := range scores { |
| 114 | + if score < minScore { |
| 115 | + minScore = score |
| 116 | + } |
| 117 | + if score > maxScore { |
| 118 | + maxScore = score |
| 119 | + } |
| 120 | + sumScore += score |
| 121 | + } |
| 122 | + if len(scores) < 3 { |
| 123 | + score = sumScore / float64(len(scores)) |
| 124 | + } else { |
| 125 | + score = (sumScore - minScore - maxScore) / float64(s.count-2) |
| 126 | + } |
| 127 | + newError(fmt.Sprintf("Balance OptimalStrategy get %s's score: %.2f", tag, score)).AtDebug().WriteToLog() |
| 128 | + |
| 129 | + if s.score < score { |
| 130 | + s.score = score |
| 131 | + s.tag = tag |
| 132 | + newError(fmt.Sprintf("Balance OptimalStrategy now pick detour [%s](score: %.2f) from %s", s.tag, s.score, s.tags)).AtInfo().WriteToLog() |
| 133 | + } |
| 134 | + return |
| 135 | + } |
| 136 | + // test outbound by fetch url |
| 137 | + oh := s.obm.GetHandler(tag) |
| 138 | + if oh == nil { |
| 139 | + newError("Wrong OptimalStrategy tag").AtError().WriteToLog() |
| 140 | + return |
| 141 | + } |
| 142 | + |
| 143 | + client := &http.Client{ |
| 144 | + Transport: &http.Transport{ |
| 145 | + DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) { |
| 146 | + netDestination, err := net.ParseDestination(fmt.Sprintf("%s:%s", network, addr)) |
| 147 | + if err != nil { |
| 148 | + return nil, err |
| 149 | + } |
| 150 | + |
| 151 | + uplinkReader, uplinkWriter := pipe.New() |
| 152 | + downlinkReader, downlinkWriter := pipe.New() |
| 153 | + ctx = session.ContextWithOutbound( |
| 154 | + ctx, |
| 155 | + &session.Outbound{ |
| 156 | + Target: netDestination, |
| 157 | + }) |
| 158 | + go oh.Dispatch(ctx, &transport.Link{Reader: uplinkReader, Writer: downlinkWriter}) |
| 159 | + |
| 160 | + return net.NewConnection(net.ConnectionInputMulti(uplinkWriter), net.ConnectionOutputMulti(downlinkReader)), nil |
| 161 | + }, |
| 162 | + MaxConnsPerHost: 1, |
| 163 | + MaxIdleConns: 1, |
| 164 | + }, |
| 165 | + Timeout: s.timeout, |
| 166 | + } |
| 167 | + startAt := time.Now() |
| 168 | + // send http request though this outbound |
| 169 | + req, _ := http.NewRequest("GET", s.url.String(), nil) |
| 170 | + resp, err := client.Do(req) |
| 171 | + // use http response speed or time(no http content) as score |
| 172 | + score := 0.0 |
| 173 | + if err != nil { |
| 174 | + newError(err).AtError().WriteToLog() |
| 175 | + } else { |
| 176 | + contentSize := 0 |
| 177 | + scanner := bufio.NewScanner(resp.Body) |
| 178 | + for scanner.Scan() { |
| 179 | + contentSize += len(scanner.Bytes()) |
| 180 | + } |
| 181 | + if contentSize != 0 { |
| 182 | + score = float64(contentSize) / (float64(time.Now().UnixNano()-startAt.UnixNano()) / float64(time.Second)) |
| 183 | + } else { |
| 184 | + // assert http header's Byte size is 100B |
| 185 | + score = 100 / (float64(time.Now().UnixNano()-startAt.UnixNano()) / float64(time.Second)) |
| 186 | + } |
| 187 | + } |
| 188 | + // next test round |
| 189 | + resp.Body.Close() |
| 190 | + client.CloseIdleConnections() |
| 191 | + s.testOutboud( |
| 192 | + tag, |
| 193 | + append(scores, score), |
| 194 | + ) |
| 195 | +} |
0 commit comments