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. }
  14. func (s *RandomStrategy) PickOutbound(tags []string) string {
  15. n := len(tags)
  16. if n == 0 {
  17. panic("0 tags")
  18. }
  19. return tags[dice.Roll(n)]
  20. }
  21. type Balancer struct {
  22. selectors []string
  23. strategy BalancingStrategy
  24. ohm outbound.Manager
  25. }
  26. func (b *Balancer) PickOutbound() (string, error) {
  27. hs, ok := b.ohm.(outbound.HandlerSelector)
  28. if !ok {
  29. return "", newError("outbound.Manager is not a HandlerSelector")
  30. }
  31. tags := hs.Select(b.selectors)
  32. if len(tags) == 0 {
  33. return "", newError("no available outbounds selected")
  34. }
  35. tag := b.strategy.PickOutbound(tags)
  36. if tag == "" {
  37. return "", newError("balancing strategy returns empty tag")
  38. }
  39. return tag, nil
  40. }
  41. func (b *Balancer) InjectContext(ctx context.Context) {
  42. if contextReceiver, ok := b.strategy.(extension.ContextReceiver); ok {
  43. contextReceiver.InjectContext(ctx)
  44. }
  45. }