balancing.go 872 B

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