forked from rethinkdb/rethinkdb-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cluster.go
521 lines (432 loc) · 11 KB
/
cluster.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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
package gorethink
import (
"fmt"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/Sirupsen/logrus"
"github.com/cenk/backoff"
"github.com/hailocab/go-hostpool"
)
// A Cluster represents a connection to a RethinkDB cluster, a cluster is created
// by the Session and should rarely be created manually.
//
// The cluster keeps track of all nodes in the cluster and if requested can listen
// for cluster changes and start tracking a new node if one appears. Currently
// nodes are removed from the pool if they become unhealthy (100 failed queries).
// This should hopefully soon be replaced by a backoff system.
type Cluster struct {
opts *ConnectOpts
mu sync.RWMutex
seeds []Host // Initial host nodes specified by user.
hp hostpool.HostPool
nodes map[string]*Node // Active nodes in cluster.
closed bool
nodeIndex int64
}
// NewCluster creates a new cluster by connecting to the given hosts.
func NewCluster(hosts []Host, opts *ConnectOpts) (*Cluster, error) {
c := &Cluster{
hp: hostpool.NewEpsilonGreedy([]string{}, opts.HostDecayDuration, &hostpool.LinearEpsilonValueCalculator{}),
seeds: hosts,
opts: opts,
}
// Attempt to connect to each host and discover any additional hosts if host
// discovery is enabled
if err := c.connectNodes(c.getSeeds()); err != nil {
return nil, err
}
if !c.IsConnected() {
return nil, ErrNoConnectionsStarted
}
if opts.DiscoverHosts {
go c.discover()
}
return c, nil
}
// Query executes a ReQL query using the cluster to connect to the database
func (c *Cluster) Query(q Query) (cursor *Cursor, err error) {
for i := 0; i < c.numRetries(); i++ {
var node *Node
var hpr hostpool.HostPoolResponse
node, hpr, err = c.GetNextNode()
if err != nil {
return nil, err
}
cursor, err = node.Query(q)
hpr.Mark(err)
if !shouldRetryQuery(q, err) {
break
}
}
return cursor, err
}
// Exec executes a ReQL query using the cluster to connect to the database
func (c *Cluster) Exec(q Query) (err error) {
for i := 0; i < c.numRetries(); i++ {
var node *Node
var hpr hostpool.HostPoolResponse
node, hpr, err = c.GetNextNode()
if err != nil {
return err
}
err = node.Exec(q)
hpr.Mark(err)
if !shouldRetryQuery(q, err) {
break
}
}
return err
}
// Server returns the server name and server UUID being used by a connection.
func (c *Cluster) Server() (response ServerResponse, err error) {
for i := 0; i < c.numRetries(); i++ {
var node *Node
var hpr hostpool.HostPoolResponse
node, hpr, err = c.GetNextNode()
if err != nil {
return ServerResponse{}, err
}
response, err = node.Server()
hpr.Mark(err)
// This query should not fail so retry if any error is detected
if err == nil {
break
}
}
return response, err
}
// SetInitialPoolCap sets the initial capacity of the connection pool.
func (c *Cluster) SetInitialPoolCap(n int) {
for _, node := range c.GetNodes() {
node.SetInitialPoolCap(n)
}
}
// SetMaxIdleConns sets the maximum number of connections in the idle
// connection pool.
func (c *Cluster) SetMaxIdleConns(n int) {
for _, node := range c.GetNodes() {
node.SetMaxIdleConns(n)
}
}
// SetMaxOpenConns sets the maximum number of open connections to the database.
func (c *Cluster) SetMaxOpenConns(n int) {
for _, node := range c.GetNodes() {
node.SetMaxOpenConns(n)
}
}
// Close closes the cluster
func (c *Cluster) Close(optArgs ...CloseOpts) error {
if c.closed {
return nil
}
for _, node := range c.GetNodes() {
err := node.Close(optArgs...)
if err != nil {
return err
}
}
c.closed = true
return nil
}
// discover attempts to find new nodes in the cluster using the current nodes
func (c *Cluster) discover() {
// Keep retrying with exponential backoff.
b := backoff.NewExponentialBackOff()
// Never finish retrying (max interval is still 60s)
b.MaxElapsedTime = 0
// Keep trying to discover new nodes
for {
backoff.RetryNotify(func() error {
// If no hosts try seeding nodes
if len(c.GetNodes()) == 0 {
c.connectNodes(c.getSeeds())
}
return c.listenForNodeChanges()
}, b, func(err error, wait time.Duration) {
Log.Debugf("Error discovering hosts %s, waiting: %s", err, wait)
})
}
}
// listenForNodeChanges listens for changes to node status using change feeds.
// This function will block until the query fails
func (c *Cluster) listenForNodeChanges() error {
// Start listening to changes from a random active node
node, hpr, err := c.GetNextNode()
if err != nil {
return err
}
q, err := newQuery(
DB("rethinkdb").Table("server_status").Changes(),
map[string]interface{}{},
c.opts,
)
if err != nil {
return fmt.Errorf("Error building query: %s", err)
}
cursor, err := node.Query(q)
if err != nil {
hpr.Mark(err)
return err
}
// Keep reading node status updates from changefeed
var result struct {
NewVal nodeStatus `gorethink:"new_val"`
OldVal nodeStatus `gorethink:"old_val"`
}
for cursor.Next(&result) {
addr := fmt.Sprintf("%s:%d", result.NewVal.Network.Hostname, result.NewVal.Network.ReqlPort)
addr = strings.ToLower(addr)
switch result.NewVal.Status {
case "connected":
// Connect to node using exponential backoff (give up after waiting 5s)
// to give the node time to start-up.
b := backoff.NewExponentialBackOff()
b.MaxElapsedTime = time.Second * 5
backoff.Retry(func() error {
node, err := c.connectNodeWithStatus(result.NewVal)
if err == nil {
if !c.nodeExists(node) {
c.addNode(node)
Log.WithFields(logrus.Fields{
"id": node.ID,
"host": node.Host.String(),
}).Debug("Connected to node")
}
}
return err
}, b)
}
}
err = cursor.Err()
hpr.Mark(err)
return err
}
func (c *Cluster) connectNodes(hosts []Host) error {
// Add existing nodes to map
nodeSet := map[string]*Node{}
for _, node := range c.GetNodes() {
nodeSet[node.ID] = node
}
var attemptErr error
// Attempt to connect to each seed host
for _, host := range hosts {
conn, err := NewConnection(host.String(), c.opts)
if err != nil {
attemptErr = err
Log.Warnf("Error creating connection: %s", err.Error())
continue
}
defer conn.Close()
if c.opts.DiscoverHosts {
q, err := newQuery(
DB("rethinkdb").Table("server_status"),
map[string]interface{}{},
c.opts,
)
if err != nil {
Log.Warnf("Error building query: %s", err)
continue
}
_, cursor, err := conn.Query(q)
if err != nil {
attemptErr = err
Log.Warnf("Error fetching cluster status: %s", err)
continue
}
var results []nodeStatus
err = cursor.All(&results)
if err != nil {
attemptErr = err
continue
}
for _, result := range results {
node, err := c.connectNodeWithStatus(result)
if err == nil {
if _, ok := nodeSet[node.ID]; !ok {
Log.WithFields(logrus.Fields{
"id": node.ID,
"host": node.Host.String(),
}).Debug("Connected to node")
nodeSet[node.ID] = node
}
} else {
attemptErr = err
Log.Warnf("Error connecting to node: %s", err)
}
}
} else {
svrRsp, err := conn.Server()
if err != nil {
attemptErr = err
Log.Warnf("Error fetching server ID: %s", err)
continue
}
node, err := c.connectNode(svrRsp.ID, []Host{host})
if err == nil {
if _, ok := nodeSet[node.ID]; !ok {
Log.WithFields(logrus.Fields{
"id": node.ID,
"host": node.Host.String(),
}).Debug("Connected to node")
nodeSet[node.ID] = node
}
} else {
attemptErr = err
Log.Warnf("Error connecting to node: %s", err)
}
}
}
// If no nodes were contactable then return the last error, this does not
// include driver errors such as if there was an issue building the
// query
if len(nodeSet) == 0 {
return attemptErr
}
nodes := []*Node{}
for _, node := range nodeSet {
nodes = append(nodes, node)
}
c.setNodes(nodes)
return nil
}
func (c *Cluster) connectNodeWithStatus(s nodeStatus) (*Node, error) {
aliases := make([]Host, len(s.Network.CanonicalAddresses))
for i, aliasAddress := range s.Network.CanonicalAddresses {
aliases[i] = NewHost(aliasAddress.Host, int(s.Network.ReqlPort))
}
return c.connectNode(s.ID, aliases)
}
func (c *Cluster) connectNode(id string, aliases []Host) (*Node, error) {
var pool *Pool
var err error
for len(aliases) > 0 {
pool, err = NewPool(aliases[0], c.opts)
if err != nil {
aliases = aliases[1:]
continue
}
err = pool.Ping()
if err != nil {
aliases = aliases[1:]
continue
}
// Ping successful so break out of loop
break
}
if err != nil {
return nil, err
}
if len(aliases) == 0 {
return nil, ErrInvalidNode
}
return newNode(id, aliases, c, pool), nil
}
// IsConnected returns true if cluster has nodes and is not already closed.
func (c *Cluster) IsConnected() bool {
c.mu.RLock()
closed := c.closed
c.mu.RUnlock()
return (len(c.GetNodes()) > 0) && !closed
}
// AddSeeds adds new seed hosts to the cluster.
func (c *Cluster) AddSeeds(hosts []Host) {
c.mu.Lock()
c.seeds = append(c.seeds, hosts...)
c.mu.Unlock()
}
func (c *Cluster) getSeeds() []Host {
c.mu.RLock()
seeds := c.seeds
c.mu.RUnlock()
return seeds
}
// GetNextNode returns a random node on the cluster
func (c *Cluster) GetNextNode() (*Node, hostpool.HostPoolResponse, error) {
if !c.IsConnected() {
return nil, nil, ErrNoConnections
}
c.mu.RLock()
defer c.mu.RUnlock()
nodes := c.nodes
hpr := c.hp.Get()
if n, ok := nodes[hpr.Host()]; ok {
if !n.Closed() {
return n, hpr, nil
}
}
return nil, nil, ErrNoConnections
}
// GetNodes returns a list of all nodes in the cluster
func (c *Cluster) GetNodes() []*Node {
c.mu.RLock()
nodes := make([]*Node, 0, len(c.nodes))
for _, n := range c.nodes {
nodes = append(nodes, n)
}
c.mu.RUnlock()
return nodes
}
func (c *Cluster) nodeExists(search *Node) bool {
for _, node := range c.GetNodes() {
if node.ID == search.ID {
return true
}
}
return false
}
func (c *Cluster) addNode(node *Node) {
c.mu.RLock()
nodes := append(c.GetNodes(), node)
c.mu.RUnlock()
c.setNodes(nodes)
}
func (c *Cluster) addNodes(nodesToAdd []*Node) {
c.mu.RLock()
nodes := append(c.GetNodes(), nodesToAdd...)
c.mu.RUnlock()
c.setNodes(nodes)
}
func (c *Cluster) setNodes(nodes []*Node) {
nodesMap := make(map[string]*Node, len(nodes))
hosts := make([]string, len(nodes))
for i, node := range nodes {
host := node.Host.String()
nodesMap[host] = node
hosts[i] = host
}
c.mu.Lock()
c.nodes = nodesMap
c.hp.SetHosts(hosts)
c.mu.Unlock()
}
func (c *Cluster) removeNode(nodeID string) {
nodes := c.GetNodes()
nodeArray := make([]*Node, len(nodes)-1)
count := 0
// Add nodes that are not in remove list.
for _, n := range nodes {
if n.ID != nodeID {
nodeArray[count] = n
count++
}
}
// Do sanity check to make sure assumptions are correct.
if count < len(nodeArray) {
// Resize array.
nodeArray2 := make([]*Node, count)
copy(nodeArray2, nodeArray)
nodeArray = nodeArray2
}
c.setNodes(nodeArray)
}
func (c *Cluster) nextNodeIndex() int64 {
return atomic.AddInt64(&c.nodeIndex, 1)
}
func (c *Cluster) numRetries() int {
if n := c.opts.NumRetries; n > 0 {
return n
}
return 3
}