-
-
Notifications
You must be signed in to change notification settings - Fork 182
/
cluster.go
398 lines (333 loc) · 8.65 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
package gorethink
import (
"fmt"
"math"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/Sirupsen/logrus"
"github.com/cenkalti/backoff"
)
// 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.
nodes []*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{
seeds: hosts,
opts: opts,
}
//Check that hosts in the ClusterConfig is not empty
c.connectNodes(c.getSeeds())
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) {
node, err := c.GetRandomNode()
if err != nil {
return nil, err
}
return node.Query(q)
}
// Exec executes a ReQL query using the cluster to connect to the database
func (c *Cluster) Exec(q Query) (err error) {
node, err := c.GetRandomNode()
if err != nil {
return err
}
return node.Exec(q)
}
// 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, err := c.GetRandomNode()
if err != nil {
return err
}
cursor, err := node.Query(newQuery(
DB("rethinkdb").Table("server_status").Changes(),
map[string]interface{}{},
c.opts,
))
if err != nil {
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)
}
}
return cursor.Err()
}
func (c *Cluster) connectNodes(hosts []Host) {
// Add existing nodes to map
nodeSet := map[string]*Node{}
for _, node := range c.GetNodes() {
nodeSet[node.ID] = node
}
// Attempt to connect to each seed host
for _, host := range hosts {
conn, err := NewConnection(host.String(), c.opts)
if err != nil {
log.Warnf("Error creating connection %s", err.Error())
continue
}
defer conn.Close()
_, cursor, err := conn.Query(newQuery(
DB("rethinkdb").Table("server_status"),
map[string]interface{}{},
c.opts,
))
if err != nil {
log.Warnf("Error fetching cluster status %s", err)
continue
}
var results []nodeStatus
err = cursor.All(&results)
if err != nil {
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
}
}
}
}
nodes := []*Node{}
for _, node := range nodeSet {
nodes = append(nodes, node)
}
c.setNodes(nodes)
}
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
}
// GetRandomNode returns a random node on the cluster
// TODO(dancannon) replace with hostpool
func (c *Cluster) GetRandomNode() (*Node, error) {
if !c.IsConnected() {
return nil, ErrClusterClosed
}
// Must copy array reference for copy on write semantics to work.
nodeArray := c.GetNodes()
length := len(nodeArray)
for i := 0; i < length; i++ {
// Must handle concurrency with other non-tending goroutines, so nodeIndex is consistent.
index := int(math.Abs(float64(c.nextNodeIndex() % int64(length))))
node := nodeArray[index]
if !node.Closed() && node.IsHealthy() {
return node, nil
}
}
return nil, ErrNoConnections
}
// GetNodes returns a list of all nodes in the cluster
func (c *Cluster) GetNodes() []*Node {
c.mu.RLock()
nodes := c.nodes
c.mu.RUnlock()
return nodes
}
// GetHealthyNodes returns a list of all healthy nodes in the cluster
func (c *Cluster) GetHealthyNodes() []*Node {
c.mu.RLock()
nodes := []*Node{}
for _, node := range c.nodes {
if node.IsHealthy() {
nodes = append(nodes, node)
}
}
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.Lock()
c.nodes = append(c.nodes, node)
c.mu.Unlock()
}
func (c *Cluster) addNodes(nodesToAdd []*Node) {
c.mu.Lock()
c.nodes = append(c.nodes, nodesToAdd...)
c.mu.Unlock()
}
func (c *Cluster) setNodes(nodes []*Node) {
c.mu.Lock()
c.nodes = nodes
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)
}