Skip to content

Commit

Permalink
Fixed iphash random selection of backends for the same client ip yyya…
Browse files Browse the repository at this point in the history
  • Loading branch information
illarion committed Aug 5, 2019
1 parent fef9717 commit e55008b
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 7 deletions.
5 changes: 5 additions & 0 deletions src/balance/iphash.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ package balance
import (
"errors"
"hash/fnv"
"sort"

"github.com/yyyar/gobetween/core"
)
Expand All @@ -30,6 +31,10 @@ func (b *IphashBalancer) Elect(context core.Context, backends []*core.Backend) (
return nil, errors.New("Can't elect backend, Backends empty")
}

sort.SliceStable(backends, func(i, j int) bool {
return backends[i].Target.String() < backends[j].Target.String()
})

hash := fnv.New32a()
hash.Write(context.Ip())
backend := backends[hash.Sum32()%uint32(len(backends))]
Expand Down
11 changes: 4 additions & 7 deletions src/balance/roundrobin.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,18 +31,15 @@ func (b *RoundrobinBalancer) Elect(context core.Context, backends []*core.Backen
return nil, errors.New("Can't elect backend, Backends empty")
}

sorted := make([]*core.Backend, len(backends))
copy(sorted, backends)

sort.SliceStable(sorted, func(i, j int) bool {
return sorted[i].Target.String() < sorted[j].Target.String()
sort.SliceStable(backends, func(i, j int) bool {
return backends[i].Target.String() < backends[j].Target.String()
})

if b.current >= len(sorted) {
if b.current >= len(backends) {
b.current = 0
}

backend := sorted[b.current]
backend := backends[b.current]
b.current += 1

return backend, nil
Expand Down

0 comments on commit e55008b

Please sign in to comment.