balancing.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. //go:build !confonly
  2. // +build !confonly
  3. package router
  4. import (
  5. "context"
  6. "github.com/v2fly/v2ray-core/v4/common/dice"
  7. "github.com/v2fly/v2ray-core/v4/features/extension"
  8. "github.com/v2fly/v2ray-core/v4/features/outbound"
  9. )
  10. type BalancingStrategy interface {
  11. PickOutbound([]string) string
  12. }
  13. type RandomStrategy struct{}
  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. }