/
pool.go
357 lines (291 loc) · 7.18 KB
/
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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
package csc
import (
"context"
"errors"
"sync"
"sync/atomic"
"time"
"github.com/gomodule/redigo/redis"
)
var ErrTooManyActiveClients = errors.New("too many active clients")
type Pool interface {
Get() (*Client, error)
Close() error
Options() *PoolOptions
put(*Client)
}
type PoolOptions struct {
RedisAddress string
RedisDatabase int
MaxActive int
MaxIdle int
IdleTimeout time.Duration
Wait bool
// key prefix to add to keys. in broadcasting mode this is used to invalidate only keys with this prefix
KeyPrefix string
MaxEntries int
}
type TrackingPool struct {
options PoolOptions
// number of active clients, used or in the free list
active uint32
// number of times a Get had to wait to receive a connection
waited uint64
// buffered channel representing available slots when there's a max active clients limit
ch chan struct{}
mu sync.Mutex
// available clients to reuse
free []*Client
}
func NewTrackingPool(opts PoolOptions) *TrackingPool {
p := &TrackingPool{
options: opts,
}
if p.options.Wait && p.options.MaxActive > 0 {
// setup slots
p.ch = make(chan struct{}, p.options.MaxActive)
for i := 0; i < p.options.MaxActive; i++ {
p.ch <- struct{}{}
}
}
return p
}
func (p *TrackingPool) Get() (*Client, error) {
// grab a slot, there're MaxActive slots available when waiting
if p.options.Wait && p.options.MaxActive > 0 {
// assume that we're waiting if there's no slot
waiting := len(p.ch) == 0
var start time.Time
if waiting {
atomic.AddUint64(&p.waited, 1)
if debugMode {
start = nowFunc()
dlog("tpool.waiting: %p", p)
}
}
select {
case <-p.ch:
}
if debugMode && waiting {
dlog("tclient.waited: %p, t=%dus", p, time.Since(start).Microseconds())
}
} else if p.options.MaxActive > 0 && int(atomic.LoadUint32(&p.active)) >= p.options.MaxActive {
return nil, ErrTooManyActiveClients
}
c := p.getFree()
if c != nil {
return c, nil
}
dconn, err := redis.Dial("tcp", p.options.RedisAddress, redis.DialDatabase(p.options.RedisDatabase))
if err != nil {
return nil, err
}
iconn, err := redis.Dial("tcp", p.options.RedisAddress, redis.DialDatabase(p.options.RedisDatabase))
if err != nil {
return nil, err
}
c = &Client{
pool: p,
conn: dconn,
cache: newCache(p.options.MaxEntries),
iconn: iconn,
}
cid, err := redis.Int(c.iconn.Do("CLIENT", "ID"))
if err != nil {
return nil, err
}
if _, err := c.conn.Do("CLIENT", "TRACKING", "ON", "REDIRECT", cid, "NOLOOP"); err != nil {
return nil, err
}
go func() {
if err := invalidationsReceiver(c.iconn, c.cache); err != nil {
c.setClosed()
}
}()
go expireWatcher(context.Background(), c.cache)
atomic.AddUint32(&p.active, 1)
return c, nil
}
// closes connections of all clients in the free list
func (p *TrackingPool) Close() error {
p.mu.Lock()
defer p.mu.Unlock()
dlog("tpool.close: %p\n", p)
for _, c := range p.free {
c.setClosed()
c.Close()
}
return nil
}
// getFree returns nil if there is no free client
func (p *TrackingPool) getFree() *Client {
p.mu.Lock()
defer p.mu.Unlock()
numFree := len(p.free)
dlog("tpool.getfree: %p n=%d\n", p, numFree)
if numFree > 0 {
c := p.free[0]
copy(p.free, p.free[1:])
p.free = p.free[:numFree-1]
return c
}
return nil
}
func (p *TrackingPool) put(c *Client) {
p.mu.Lock()
defer p.mu.Unlock()
dlog("tpool.put: %p n=%d\n", p, len(p.free))
p.free = append(p.free, c)
// notify that a slot has become available
if p.ch != nil {
p.ch <- struct{}{}
}
}
func (p *TrackingPool) Options() *PoolOptions {
return &p.options
}
type BroadcastingPool struct {
options PoolOptions
rpool *redis.Pool
iconn redis.Conn
conn redis.Conn
cache *cache
outOfSync uint32
closed uint32
}
// creates a new broadcasting pool and starts the background jobs
func NewBroadcastingPool(rpool *redis.Pool, opts PoolOptions) (*BroadcastingPool, error) {
p := &BroadcastingPool{
options: opts,
rpool: rpool,
cache: newCache(opts.MaxEntries),
}
if err := p.setupConnections(); err != nil {
return nil, err
}
go expireWatcher(context.Background(), p.cache)
go func() {
for !p.isClosed() {
time.Sleep(time.Second)
if p.isOutOfSync() {
dlog("bpool.conn.outofsync: %p\n", p)
p.conn.Close()
p.iconn.Close()
p.cache.flush()
if err := p.setupConnections(); err != nil {
Logger.Println("failed to reopen broadcasting pool connections:", err.Error())
continue
}
p.setOutofSync(false)
}
}
}()
return p, nil
}
func (p *BroadcastingPool) setupConnections() error {
dlog("bpool.conn.setup: %p\n", p)
p.conn = p.rpool.Get()
p.iconn = p.rpool.Get()
cid, err := redis.Int(p.iconn.Do("CLIENT", "ID"))
if err != nil {
return err
}
dlog("bpool.conn.iconn: %p cid=%d p=%s\n", p, cid, p.options.KeyPrefix)
args := redis.Args{}
args = append(args, "TRACKING", "ON", "REDIRECT", cid, "BCAST")
if p.options.KeyPrefix != "" {
args = append(args, "PREFIX", p.options.KeyPrefix)
}
if _, err := p.conn.Do("CLIENT", args...); err != nil {
return err
}
// ping the redirecting data conn periodically as a healthcheck
go func(conn redis.Conn) {
ticker := time.NewTicker(time.Second * 5)
fails := 0
for !p.isClosed() {
if fails >= 5 {
p.setOutofSync(true)
Logger.Println("broadcasting data connection failed, connections out-of-sync")
return
}
select {
case <-ticker.C:
_, err := conn.Do("PING")
if err != nil {
fails++
dlog("bpool.conn.pingfail: %p err=%s\n", p, err.Error())
continue
}
fails = 0
}
}
}(p.conn)
go func() {
if err := invalidationsReceiver(p.iconn, p.cache); err != nil {
Logger.Println("invalidation data connection failed, connections out-of-sync")
p.setOutofSync(true)
}
}()
return nil
}
func NewDefaultBroadcastingPool(opts PoolOptions) (*BroadcastingPool, error) {
return NewBroadcastingPool(
&redis.Pool{
Dial: func() (redis.Conn, error) {
return redis.Dial("tcp", opts.RedisAddress, redis.DialDatabase(opts.RedisDatabase))
},
TestOnBorrow: func(c redis.Conn, t time.Time) error {
if time.Since(t) < time.Second {
return nil
}
_, err := c.Do("PING")
return err
},
},
opts,
)
}
func (p *BroadcastingPool) Get() (*Client, error) {
c := &Client{
pool: p,
conn: p.rpool.Get(),
cache: p.cache,
}
return c, nil
}
func (p *BroadcastingPool) Close() error {
dlog("bpool.close: %p\n", p)
atomic.StoreUint32(&p.closed, 1)
p.conn.Close()
p.iconn.Close()
p.cache.flush()
return p.rpool.Close()
}
func (p *BroadcastingPool) isOutOfSync() bool {
return atomic.LoadUint32(&p.outOfSync) == 1
}
func (p *BroadcastingPool) isClosed() bool {
return atomic.LoadUint32(&p.closed) == 1
}
func (p *BroadcastingPool) setOutofSync(b bool) {
if b {
atomic.StoreUint32(&p.outOfSync, 1)
} else {
atomic.StoreUint32(&p.outOfSync, 0)
}
}
func (p *BroadcastingPool) Stats() Stats {
return p.cache.stats()
}
func (p *BroadcastingPool) put(c *Client) {
dlog("bpool.put: %p\n", p)
// in broadcasting mode we return the connection to the redigo pool by closing it
c.conn.Close()
}
func (p *BroadcastingPool) Flush() {
p.cache.flush()
}
func (p *BroadcastingPool) Options() *PoolOptions {
return &p.options
}