1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-11-10 06:16:53 -05:00
v2fly/app/router/strategy_random.go

93 lines
2.5 KiB
Go
Raw Normal View History

package router
import (
"context"
2024-03-13 15:32:51 -04:00
"google.golang.org/protobuf/runtime/protoiface"
core "github.com/v2fly/v2ray-core/v5"
"github.com/v2fly/v2ray-core/v5/app/observatory"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/dice"
"github.com/v2fly/v2ray-core/v5/features"
"github.com/v2fly/v2ray-core/v5/features/extension"
)
// RandomStrategy represents a random balancing strategy
type RandomStrategy struct {
ctx context.Context
settings *StrategyRandomConfig
observatory extension.Observatory
}
2021-06-18 19:13:09 -04:00
func (s *RandomStrategy) GetPrincipleTarget(strings []string) []string {
return strings
}
// NewRandomStrategy creates a new RandomStrategy with settings
func NewRandomStrategy(settings *StrategyRandomConfig) *RandomStrategy {
return &RandomStrategy{
settings: settings,
}
}
func (s *RandomStrategy) InjectContext(ctx context.Context) {
if s != nil {
s.ctx = ctx
}
}
func (s *RandomStrategy) PickOutbound(candidates []string) string {
if s != nil && s.settings.AliveOnly {
// candidates are considered alive unless observed otherwise
if s.observatory == nil {
core.RequireFeatures(s.ctx, func(observatory extension.Observatory) error {
s.observatory = observatory
return nil
})
}
if s.observatory != nil {
var observeReport protoiface.MessageV1
var err error
if s.settings.ObserverTag == "" {
observeReport, err = s.observatory.GetObservation(s.ctx)
} else {
observeReport, err = common.Must2(s.observatory.(features.TaggedFeatures).GetFeaturesByTag(s.settings.ObserverTag)).(extension.Observatory).GetObservation(s.ctx)
}
if err == nil {
aliveTags := make([]string, 0)
if result, ok := observeReport.(*observatory.ObservationResult); ok {
status := result.Status
statusMap := make(map[string]*observatory.OutboundStatus)
for _, outboundStatus := range status {
statusMap[outboundStatus.OutboundTag] = outboundStatus
}
for _, candidate := range candidates {
if outboundStatus, found := statusMap[candidate]; found {
if outboundStatus.Alive {
aliveTags = append(aliveTags, candidate)
}
} else {
// unfound candidate is considered alive
aliveTags = append(aliveTags, candidate)
}
}
candidates = aliveTags
}
}
}
}
count := len(candidates)
if count == 0 {
// goes to fallbackTag
return ""
}
return candidates[dice.Roll(count)]
}
2021-09-07 06:48:24 -04:00
func init() {
common.Must(common.RegisterConfig((*StrategyRandomConfig)(nil), nil))
}