-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathloadbalancer.go
220 lines (187 loc) · 5.22 KB
/
loadbalancer.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
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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
package handbalancer
import (
"errors"
"fmt"
"github.com/OrangeFlag/handbalancer/model"
"github.com/OrangeFlag/handbalancer/strategy"
"github.com/afex/hystrix-go/hystrix"
"strings"
"sync"
"sync/atomic"
)
type Balancer struct {
name string
pool model.Pool
requests chan *model.Request
done chan *model.Worker
strategy strategy.LoadBalancingStrategy
poolMutex sync.Mutex
}
var (
balancersMutex *sync.RWMutex
balancers map[string]*Balancer
)
func init() {
balancersMutex = &sync.RWMutex{}
balancers = make(map[string]*Balancer)
}
func NewBalancer(name string, strategy strategy.LoadBalancingStrategy) *Balancer {
return NewBalancerL(name, strategy, 100)
}
func NewBalancerL(name string, strategy strategy.LoadBalancingStrategy, chanLen int) *Balancer {
b := &Balancer{
name: name,
pool: make(model.Pool, 0),
requests: make(chan *model.Request, chanLen),
done: make(chan *model.Worker, chanLen),
strategy: strategy,
}
b.balance()
return b
}
func AddBalancer(balancer *Balancer) error {
balancersMutex.Lock()
defer balancersMutex.Unlock()
balancers[balancer.name] = balancer
return nil
}
func GetBalancer(name string) (*Balancer, error) {
balancersMutex.RLock()
defer balancersMutex.RUnlock()
if value, ok := balancers[name]; ok {
return value, nil
} else {
return nil, errors.New(fmt.Sprintf("there is no balancer with name: %s", name))
}
}
type CircuitBreakerConfig struct {
// Timeout is how long to wait for command to bitcoinMininode, in milliseconds
Timeout int
// MaxConcurrentRequests is how many commands of the same type can run at the same time
MaxConcurrentRequests int
// RequestVolumeThreshold is the minimum number of requests needed before a circuit can be tripped due to health
RequestVolumeThreshold int
// SleepWindow is how long, in milliseconds, to wait after a circuit opens before testing for recovery
SleepWindow int
// ErrorPercentThreshold causes circuits to open once the rolling measure of errors exceeds this percent of requests
ErrorPercentThreshold int
}
func (b *Balancer) AddPerformer(name string, performer func(interface{}) (interface{}, error), fallback func(error) error, circuitBreakerConfig *CircuitBreakerConfig) {
b.AddPerformerW(name, performer, fallback, circuitBreakerConfig, 1)
}
func (b *Balancer) AddPerformerW(name string, performer func(interface{}) (interface{}, error), fallback func(error) error, circuitBreakerConfig *CircuitBreakerConfig, weight int) {
b.poolMutex.Lock()
defer b.poolMutex.Unlock()
performerName := strings.Join([]string{b.name, name}, "-")
if circuitBreakerConfig == nil {
circuitBreakerConfig = &CircuitBreakerConfig{
Timeout: 10000,
MaxConcurrentRequests: 100,
RequestVolumeThreshold: 5,
SleepWindow: 5000,
ErrorPercentThreshold: 25,
}
}
hystrix.ConfigureCommand(performerName, hystrix.CommandConfig(*circuitBreakerConfig))
pool := make([]*model.Worker, b.pool.Len()+weight)
copy(pool, b.pool)
performerHystrix := func(input interface{}) (interface{}, error) {
output := make(chan interface{}, 1)
errs := hystrix.Go(performerName, func() error {
if ret, err := performer(input); err != nil {
return err
} else {
output <- ret
}
return nil
}, fallback)
select {
case out := <-output:
return out, nil
case err := <-errs:
return nil, err
}
}
for i := b.pool.Len(); i < b.pool.Len()+weight; i++ {
w := &model.Worker{
Name: performerName,
Requests: make(chan *model.Request, circuitBreakerConfig.MaxConcurrentRequests/weight*2),
Performer: performerHystrix}
pool[i] = w
go w.Work(b.done)
}
b.pool = pool
b.strategy.SetPool(&b.pool)
}
func (b *Balancer) balanceDispatch() {
for {
select {
case req := <-b.requests:
b.dispatch(req)
}
}
}
func (b *Balancer) balanceCompleted() {
for {
select {
case w := <-b.done:
b.completed(w)
}
}
}
func (b *Balancer) balance() {
go b.balanceDispatch()
go b.balanceCompleted()
}
func (b *Balancer) dispatch(req *model.Request) {
w := b.strategy.Next()
if w == nil {
req.ErrorChan <- fmt.Errorf("received worker is nil")
} else {
w.Requests <- req
atomic.AddUint64(&w.Pending, 1)
// fmt.Printf("started %p; now %d\n", w, w.Pending)
}
}
func (b *Balancer) completed(w *model.Worker) {
atomic.AddUint64(&w.Pending, ^uint64(0))
}
func Do(name string, run model.RunFunc, fallback model.FallbackFunc) (interface{}, error) {
resultChan, errChan := Go(name, run, fallback)
select {
case result := <-resultChan:
return result, nil
case err := <-errChan:
return nil, err
}
}
func Go(name string, run model.RunFunc, fallback model.FallbackFunc) (chan interface{}, chan error) {
balancer, err := GetBalancer(name)
errChan := make(chan error, 3)
if err != nil {
errChan <- err
return nil, errChan
}
handler := func() (interface{}, error) {
value, err := run()
if err != nil {
if fallback != nil {
if value, err = fallback(err); err != nil {
return nil, err
} else {
return value, nil
}
} else {
return nil, err
}
}
return value, nil
}
resultChan := make(chan interface{})
balancer.requests <- &model.Request{
Func: handler,
ResultChan: resultChan,
ErrorChan: errChan,
}
return resultChan, errChan
}