Skip to content

Commit

Permalink
Implemented priority + weight balancing #204
Browse files Browse the repository at this point in the history
  • Loading branch information
illarion committed Jun 13, 2019
1 parent d61e5b9 commit aa92203
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 5 deletions.
5 changes: 3 additions & 2 deletions config/gobetween.toml
Original file line number Diff line number Diff line change
Expand Up @@ -81,8 +81,9 @@ bind = "0.0.0.0:3000"
[servers.sample.discovery]
kind = "static"
static_list = [
"localhost:8000",
"localhost:8001"
"localhost:8000 weight=40 priority=1",
"localhost:8001 weight=60 priority=1",
"localhost:8002 weight=100 priority=0"
]

# ---------- udp example ----------- #
Expand Down
28 changes: 25 additions & 3 deletions src/balance/weight.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ package balance

import (
"errors"
"fmt"
"math/rand"

"github.com/yyyar/gobetween/core"
Expand All @@ -19,26 +20,47 @@ import (
type WeightBalancer struct{}

/**
* Elect backend based on weight strategy
* Elect backend based on weight with priority strategy. See https://tools.ietf.org/html/rfc2782, Priority and Weight sections
*/
func (b *WeightBalancer) Elect(context core.Context, backends []*core.Backend) (*core.Backend, error) {

if len(backends) == 0 {
return nil, errors.New("Can't elect backend, Backends empty")
}

lp := backends[0].Priority
lpBackends := make([]*core.Backend, 0)
totalWeight := 0

for _, backend := range backends {

if backend.Priority > lp {
continue
}

if backend.Priority < 0 {
return nil, fmt.Errorf("Invalid backend priority, shold not be less than 0: %v", backend.Priority)
}

if backend.Weight <= 0 {
return nil, errors.New("Invalid backend weight 0")
return nil, fmt.Errorf("Invalid backend weight, should not be less or equal to 0: %v", backend.Weight)
}

// got new lower priority, reset
if backend.Priority < lp {
lp = backend.Priority
lpBackends = make([]*core.Backend, 0)
totalWeight = 0
}

lpBackends = append(lpBackends, backend)
totalWeight += backend.Weight
}

r := rand.Intn(totalWeight)
pos := 0

for _, backend := range backends {
for _, backend := range lpBackends {
pos += backend.Weight
if r >= pos {
continue
Expand Down

0 comments on commit aa92203

Please sign in to comment.