Repository navigation
Expand file tree
/
Copy pathbalancer.go
More file actions
172 lines (150 loc) · 4.42 KB
/
Copy pathbalancer.go
File metadata and controls
172 lines (150 loc) · 4.42 KB
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
// package balancer provides weighted round-robin load balancing of network
// connections with the ability to specify quality of service (QOS) levels.
package balancer
import (
"fmt"
"math/rand"
"net"
"sort"
"github.com/getlantern/golog"
)
var (
log = golog.LoggerFor("balancer")
)
var (
emptyDialers = []*dialer{}
)
// Balancer balances connections established by one or more Dialers.
type Balancer struct {
dialers []*dialer
}
// New creates a new Balancer using the supplied Dialers.
func New(dialers ...*Dialer) *Balancer {
dhs := make([]*dialer, 0, len(dialers))
for _, d := range dialers {
dl := &dialer{Dialer: d}
dl.start()
dhs = append(dhs, dl)
}
// Sort dialers by QOS (ascending) for later selection
sort.Sort(byQOSAscending(dhs))
return &Balancer{
dialers: dhs,
}
}
// DialQOS dials network, addr using one of the currently active configured
// Dialers. It attempts to use a Dialer whose QOS is higher than targetQOS, but
// will use the highest QOS Dialer(s) if none meet targetQOS. When multiple
// Dialers meet the targetQOS, load is distributed amongst them randomly based
// on their relative Weights.
//
// If a Dialer fails to connect, Dial will keep falling back through the
// remaining Dialers until it either manages to connect, or runs out of dialers
// in which case it returns an error.
func (b *Balancer) DialQOS(network, addr string, targetQOS int) (net.Conn, error) {
dialers := b.dialers
for {
if len(dialers) == 0 {
return nil, fmt.Errorf("No dialers left to try")
}
var d *dialer
d, dialers = randomDialer(dialers, targetQOS)
if d == nil {
return nil, fmt.Errorf("No dialers left")
}
if d.Label != "" {
log.Debugf("Dialing %s://%s with %s", network, addr, d.Label)
}
conn, err := d.Dial(network, addr)
if err != nil {
log.Tracef("Unable to dial: %s", err)
d.onError(err)
continue
}
return conn, nil
}
}
// Dial is like DialQOS with a targetQOS of 0.
func (b *Balancer) Dial(network, addr string) (net.Conn, error) {
return b.DialQOS(network, addr, 0)
}
// Close closes this Balancer, stopping all background processing. You must call
// Close to avoid leaking goroutines.
func (b *Balancer) Close() {
oldDialers := b.dialers
b.dialers = nil
for _, d := range oldDialers {
d.stop()
}
}
func randomDialer(dialers []*dialer, targetQOS int) (chosen *dialer, others []*dialer) {
// Weed out inactive dialers and those with too low QOS
filtered, highestQOS := dialersMeetingQOS(dialers, targetQOS)
if len(filtered) == 0 {
log.Trace("No dialers meet targetQOS, using those with highest QOS")
filtered, _ = dialersMeetingQOS(dialers, highestQOS)
}
if len(filtered) == 0 {
log.Trace("Still no dialers!")
return nil, nil
}
totalWeights := 0
for _, d := range filtered {
totalWeights += d.Weight
}
// Pick a random server using a target value between 0 and the total weights
t := rand.Intn(totalWeights)
aw := 0
for _, d := range filtered {
aw += d.Weight
if aw > t {
log.Trace("Reached random target value, using this dialer")
return d, withoutDialer(dialers, d)
}
}
// We should never reach this
panic("No dialer found!")
}
func dialersMeetingQOS(dialers []*dialer, targetQOS int) ([]*dialer, int) {
filtered := make([]*dialer, 0)
highestQOS := 0
for _, d := range dialers {
if !d.isActive() {
log.Trace("Excluding inactive dialer")
continue
}
highestQOS = d.QOS // don't need to compare since dialers are already sorted by QOS (ascending)
if d.QOS >= targetQOS {
log.Tracef("Including dialer with QOS %d meeting targetQOS %d", d.QOS, targetQOS)
filtered = append(filtered, d)
}
}
return filtered, highestQOS
}
func withoutDialer(dialers []*dialer, d *dialer) []*dialer {
for i, existing := range dialers {
if existing == d {
return without(dialers, i)
}
}
log.Tracef("Dialer not found for removal: %s", d)
return dialers
}
func without(dialers []*dialer, i int) []*dialer {
if len(dialers) == 1 {
return emptyDialers
} else if i == len(dialers)-1 {
return dialers[:i]
} else {
c := make([]*dialer, len(dialers)-1)
copy(c[:i], dialers[:i])
copy(c[i:], dialers[i+1:])
return c
}
}
// byQOSAscending implements sort.Interface for []*dialer based on the QOS
// (ascending)
type byQOSAscending []*dialer
func (a byQOSAscending) Len() int { return len(a) }
func (a byQOSAscending) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a byQOSAscending) Less(i, j int) bool { return a[i].QOS < a[j].QOS }