-
Notifications
You must be signed in to change notification settings - Fork 488
/
connect_pool.go
202 lines (172 loc) · 4.24 KB
/
connect_pool.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
package net
import (
"context"
"net"
"strings"
"sync"
"time"
)
const (
defaultHostCheckTimeGap = 500 * time.Millisecond
defaultHostCheckTimeout = 200 * time.Millisecond
defaultBreakerFailTimes = 3
defaultBreakerTryTimes = 5
)
type connectType string
const (
connectRobin connectType = "robin"
connectFirst connectType = "first"
)
// ConnectPool describe a connection pools,
// provides health check and circuit breaker to maintains those connection via different address.
type ConnectPool struct {
ConnectType connectType
HostCheckTimeGap time.Duration
HostCheckTimeout time.Duration
BreakerFailTimes int
BreakerTryTimes int
address []string
available []string
avaLock sync.RWMutex
status map[string]*circuitBreaker
lastPick int
lastLock sync.Mutex
ctx context.Context
cancel context.CancelFunc
}
// NewConnectPool get a new ConnectPool with given address.
// Those address should be the same service and equal to each other.
func NewConnectPool(address []string) *ConnectPool {
return &ConnectPool{
ConnectType: connectRobin,
HostCheckTimeGap: defaultHostCheckTimeGap,
HostCheckTimeout: defaultHostCheckTimeout,
BreakerFailTimes: defaultBreakerFailTimes,
BreakerTryTimes: defaultBreakerTryTimes,
address: address,
lastPick: -1,
}
}
// Start the connect pool.
func (cp *ConnectPool) Start() {
cp.ctx, cp.cancel = context.WithCancel(context.Background())
cp.init()
go cp.start()
}
// Stop the connect pool.
func (cp *ConnectPool) Stop() {
if cp.cancel != nil {
cp.cancel()
}
}
// GetAddress return a available address(for now) in address list.
func (cp *ConnectPool) GetAddress() string {
cp.avaLock.RLock()
defer cp.avaLock.RUnlock()
total := len(cp.available)
if total == 0 {
return ""
}
switch cp.ConnectType {
case connectRobin:
cp.lastLock.Lock()
cp.lastPick = (cp.lastPick + 1) % total
cp.lastLock.Unlock()
return cp.available[cp.lastPick]
case connectFirst:
return cp.available[0]
default:
return cp.available[0]
}
}
func (cp *ConnectPool) init() {
cp.status = make(map[string]*circuitBreaker)
for _, addr := range cp.address {
cp.status[addr] = &circuitBreaker{
address: addr,
host: strings.TrimPrefix(strings.TrimPrefix(addr, "http://"), "https://"),
status: cbOpen,
hostCheckTimeout: cp.HostCheckTimeout,
breakerTryTimes: cp.BreakerTryTimes,
breakerFailTimes: cp.BreakerFailTimes,
}
}
cp.available = cp.address
}
func (cp *ConnectPool) start() {
tick := time.NewTicker(cp.HostCheckTimeGap)
for {
select {
case <-cp.ctx.Done():
return
case <-tick.C:
cp.check()
}
}
}
func (cp *ConnectPool) check() {
var wg sync.WaitGroup
for _, cb := range cp.status {
wg.Add(1)
go cb.check(&wg)
}
wg.Wait()
// if there is only one address, do not do the fresh.
if len(cp.address) == 1 {
return
}
newAvailable := make([]string, 0)
for _, addr := range cp.address {
if cb, ok := cp.status[addr]; ok && cb.isOpen() {
newAvailable = append(newAvailable, addr)
}
}
cp.avaLock.Lock()
cp.available = newAvailable
cp.avaLock.Unlock()
}
// A circuit breaker work for host checking, which contains just two status: open/close.
// This circuit breaker does not guarantee save for goroutine, it should be called in order.
type circuitBreaker struct {
address string
host string
successTime int
failureTime int
status cbStatus
breakerTryTimes int
breakerFailTimes int
hostCheckTimeout time.Duration
}
func (cb *circuitBreaker) isOpen() bool {
return cb.status == cbOpen
}
func (cb *circuitBreaker) check(wg *sync.WaitGroup) {
defer wg.Done()
_, err := net.DialTimeout("tcp", cb.host, cb.hostCheckTimeout)
if err != nil {
cb.doFailure()
return
}
cb.doSuccess()
}
func (cb *circuitBreaker) doSuccess() {
cb.failureTime = 0
cb.successTime++
if cb.status == cbClose && cb.successTime >= cb.breakerTryTimes {
cb.status = cbOpen
}
cb.successTime %= cb.breakerTryTimes
}
func (cb *circuitBreaker) doFailure() {
cb.successTime = 0
cb.failureTime++
if cb.status == cbOpen && cb.failureTime >= cb.breakerFailTimes {
cb.status = cbClose
}
cb.failureTime %= cb.breakerFailTimes
}
type cbStatus string
const (
cbOpen cbStatus = "open"
cbClose cbStatus = "close"
)