balancing.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // +build !confonly
  2. package router
  3. import (
  4. "context"
  5. "github.com/v2fly/v2ray-core/v4/common/dice"
  6. "github.com/v2fly/v2ray-core/v4/features/extension"
  7. "github.com/v2fly/v2ray-core/v4/features/outbound"
  8. )
  9. type BalancingStrategy interface {
  10. PickOutbound([]string) string
  11. }
  12. type RandomStrategy struct{}
  13. func (s *RandomStrategy) PickOutbound(tags []string) string {
  14. n := len(tags)
  15. if n == 0 {
  16. panic("0 tags")
  17. }
  18. return tags[dice.Roll(n)]
  19. }
  20. type Balancer struct {
  21. selectors []string
  22. strategy BalancingStrategy
  23. ohm outbound.Manager
  24. }
  25. func (b *Balancer) PickOutbound() (string, error) {
  26. hs, ok := b.ohm.(outbound.HandlerSelector)
  27. if !ok {
  28. return "", newError("outbound.Manager is not a HandlerSelector")
  29. }
  30. tags := hs.Select(b.selectors)
  31. if len(tags) == 0 {
  32. return "", newError("no available outbounds selected")
  33. }
  34. tag := b.strategy.PickOutbound(tags)
  35. if tag == "" {
  36. return "", newError("balancing strategy returns empty tag")
  37. }
  38. return tag, nil
  39. }
  40. func (b *Balancer) InjectContext(ctx context.Context) {
  41. if contextReceiver, ok := b.strategy.(extension.ContextReceiver); ok {
  42. contextReceiver.InjectContext(ctx)
  43. }
  44. }