Skip to content

Commit

Permalink
Use an interface for load-balancing strategies
Browse files Browse the repository at this point in the history
  • Loading branch information
jedisct1 committed Mar 20, 2020
1 parent a1f3b34 commit b57cc19
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 26 deletions.
11 changes: 5 additions & 6 deletions dnscrypt-proxy/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -358,20 +358,19 @@ func ConfigLoad(proxy *Proxy, flags *ConfigFlags) error {
if len(config.ListenAddresses) == 0 && len(config.LocalDoH.ListenAddresses) == 0 {
dlog.Debug("No local IP/port configured")
}

lbStrategy := DefaultLBStrategy
lbStrategy := LBStrategy(DefaultLBStrategy)
switch strings.ToLower(config.LBStrategy) {
case "":
// default
case "p2":
lbStrategy = LBStrategyP2
lbStrategy = LBStrategyP2{}
case "ph":
lbStrategy = LBStrategyPH
lbStrategy = LBStrategyPH{}
case "fastest":
case "first":
lbStrategy = LBStrategyFirst
lbStrategy = LBStrategyFirst{}
case "random":
lbStrategy = LBStrategyRandom
lbStrategy = LBStrategyRandom{}
default:
dlog.Warnf("Unknown load balancing strategy: [%s]", config.LBStrategy)
}
Expand Down
48 changes: 28 additions & 20 deletions dnscrypt-proxy/serversInfo.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,17 +62,35 @@ type ServerInfo struct {
DOHClientCreds DOHClientCreds
}

type LBStrategy int
type LBStrategy interface {
getCandidate(serversCount int) int
}

const (
LBStrategyNone = LBStrategy(iota)
LBStrategyP2
LBStrategyPH
LBStrategyFirst
LBStrategyRandom
)
type LBStrategyP2 struct{}

func (LBStrategyP2) getCandidate(serversCount int) int {
return rand.Intn(Min(serversCount, 2))
}

type LBStrategyPH struct{}

func (LBStrategyPH) getCandidate(serversCount int) int {
return rand.Intn(Max(Min(serversCount, 2), serversCount/2))
}

const DefaultLBStrategy = LBStrategyP2
type LBStrategyFirst struct{}

func (LBStrategyFirst) getCandidate(int) int {
return 0
}

type LBStrategyRandom struct{}

func (LBStrategyRandom) getCandidate(serversCount int) int {
return rand.Intn(serversCount)
}

var DefaultLBStrategy = LBStrategyP2{}

type ServersInfo struct {
sync.RWMutex
Expand Down Expand Up @@ -209,17 +227,7 @@ func (serversInfo *ServersInfo) getOne() *ServerInfo {
if serversInfo.lbEstimator {
serversInfo.estimatorUpdate()
}
var candidate int
switch serversInfo.lbStrategy {
case LBStrategyFirst:
candidate = 0
case LBStrategyPH:
candidate = rand.Intn(Max(Min(serversCount, 2), serversCount/2))
case LBStrategyRandom:
candidate = rand.Intn(serversCount)
default:
candidate = rand.Intn(Min(serversCount, 2))
}
candidate := serversInfo.lbStrategy.getCandidate(serversCount)
serverInfo := serversInfo.inner[candidate]
dlog.Debugf("Using candidate [%s] RTT: %d", (*serverInfo).Name, int((*serverInfo).rtt.Value()))
serversInfo.Unlock()
Expand Down

0 comments on commit b57cc19

Please sign in to comment.