forked from hyperledger/fabric-sdk-go
/
lbpolicyimpl.go
65 lines (49 loc) · 1.25 KB
/
lbpolicyimpl.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/*
Copyright SecureKey Technologies Inc. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package pgresolver
import (
"math/rand"
)
type randomLBP struct {
}
// NewRandomLBP returns a random load-balance policy
func NewRandomLBP() LoadBalancePolicy {
return &randomLBP{}
}
func (lbp *randomLBP) Choose(peerGroups []PeerGroup) PeerGroup {
logger.Debug("Invoking random LBP\n")
if len(peerGroups) == 0 {
logger.Warn("No available peer groups\n")
// Return an empty PeerGroup
return NewPeerGroup()
}
index := rand.Intn(len(peerGroups))
logger.Debugf("randomLBP - Choosing index %d\n", index)
return peerGroups[index]
}
type roundRobinLBP struct {
index int
}
// NewRoundRobinLBP returns a round-robin load-balance policy
func NewRoundRobinLBP() LoadBalancePolicy {
return &roundRobinLBP{index: -1}
}
func (lbp *roundRobinLBP) Choose(peerGroups []PeerGroup) PeerGroup {
if len(peerGroups) == 0 {
logger.Warn("No available peer groups\n")
// Return an empty PeerGroup
return NewPeerGroup()
}
if lbp.index == -1 {
lbp.index = rand.Intn(len(peerGroups))
} else {
lbp.index++
}
if lbp.index >= len(peerGroups) {
lbp.index = 0
}
logger.Debugf("roundRobinLBP - Choosing index %d\n", lbp.index)
return peerGroups[lbp.index]
}