forked from apache/cassandra-gocql-driver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
policies.go
373 lines (311 loc) · 9.06 KB
/
policies.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
// Copyright (c) 2012 The gocql Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//This file will be the future home for more policies
package gocql
import (
"log"
"sync"
"sync/atomic"
"github.com/hailocab/go-hostpool"
)
// RetryableQuery is an interface that represents a query or batch statement that
// exposes the correct functions for the retry policy logic to evaluate correctly.
type RetryableQuery interface {
Attempts() int
GetConsistency() Consistency
}
// RetryPolicy interface is used by gocql to determine if a query can be attempted
// again after a retryable error has been received. The interface allows gocql
// users to implement their own logic to determine if a query can be attempted
// again.
//
// See SimpleRetryPolicy as an example of implementing and using a RetryPolicy
// interface.
type RetryPolicy interface {
Attempt(RetryableQuery) bool
}
// SimpleRetryPolicy has simple logic for attempting a query a fixed number of times.
//
// See below for examples of usage:
//
// //Assign to the cluster
// cluster.RetryPolicy = &gocql.SimpleRetryPolicy{NumRetries: 3}
//
// //Assign to a query
// query.RetryPolicy(&gocql.SimpleRetryPolicy{NumRetries: 1})
//
type SimpleRetryPolicy struct {
NumRetries int //Number of times to retry a query
}
// Attempt tells gocql to attempt the query again based on query.Attempts being less
// than the NumRetries defined in the policy.
func (s *SimpleRetryPolicy) Attempt(q RetryableQuery) bool {
return q.Attempts() <= s.NumRetries
}
// HostSelectionPolicy is an interface for selecting
// the most appropriate host to execute a given query.
type HostSelectionPolicy interface {
SetHosts
SetPartitioner
//Pick returns an iteration function over selected hosts
Pick(*Query) NextHost
}
// SelectedHost is an interface returned when picking a host from a host
// selection policy.
type SelectedHost interface {
Info() *HostInfo
Mark(error)
}
// NextHost is an iteration function over picked hosts
type NextHost func() SelectedHost
// RoundRobinHostPolicy is a round-robin load balancing policy, where each host
// is tried sequentially for each query.
func RoundRobinHostPolicy() HostSelectionPolicy {
return &roundRobinHostPolicy{hosts: []HostInfo{}}
}
type roundRobinHostPolicy struct {
hosts []HostInfo
pos uint32
mu sync.RWMutex
}
func (r *roundRobinHostPolicy) SetHosts(hosts []HostInfo) {
r.mu.Lock()
r.hosts = hosts
r.mu.Unlock()
}
func (r *roundRobinHostPolicy) SetPartitioner(partitioner string) {
// noop
}
func (r *roundRobinHostPolicy) Pick(qry *Query) NextHost {
// i is used to limit the number of attempts to find a host
// to the number of hosts known to this policy
var i int
return func() SelectedHost {
r.mu.RLock()
defer r.mu.RUnlock()
if len(r.hosts) == 0 {
return nil
}
// always increment pos to evenly distribute traffic in case of
// failures
pos := atomic.AddUint32(&r.pos, 1)
if i >= len(r.hosts) {
return nil
}
host := &r.hosts[(pos)%uint32(len(r.hosts))]
i++
return selectedRoundRobinHost{host}
}
}
// selectedRoundRobinHost is a host returned by the roundRobinHostPolicy and
// implements the SelectedHost interface
type selectedRoundRobinHost struct {
info *HostInfo
}
func (host selectedRoundRobinHost) Info() *HostInfo {
return host.info
}
func (host selectedRoundRobinHost) Mark(err error) {
// noop
}
// TokenAwareHostPolicy is a token aware host selection policy, where hosts are
// selected based on the partition key, so queries are sent to the host which
// owns the partition. Fallback is used when routing information is not available.
func TokenAwareHostPolicy(fallback HostSelectionPolicy) HostSelectionPolicy {
return &tokenAwareHostPolicy{fallback: fallback, hosts: []HostInfo{}}
}
type tokenAwareHostPolicy struct {
mu sync.RWMutex
hosts []HostInfo
partitioner string
tokenRing *tokenRing
fallback HostSelectionPolicy
}
func (t *tokenAwareHostPolicy) SetHosts(hosts []HostInfo) {
t.mu.Lock()
defer t.mu.Unlock()
// always update the fallback
t.fallback.SetHosts(hosts)
t.hosts = hosts
t.resetTokenRing()
}
func (t *tokenAwareHostPolicy) SetPartitioner(partitioner string) {
t.mu.Lock()
defer t.mu.Unlock()
if t.partitioner != partitioner {
t.fallback.SetPartitioner(partitioner)
t.partitioner = partitioner
t.resetTokenRing()
}
}
func (t *tokenAwareHostPolicy) resetTokenRing() {
if t.partitioner == "" {
// partitioner not yet set
return
}
// create a new token ring
tokenRing, err := newTokenRing(t.partitioner, t.hosts)
if err != nil {
log.Printf("Unable to update the token ring due to error: %s", err)
return
}
// replace the token ring
t.tokenRing = tokenRing
}
func (t *tokenAwareHostPolicy) Pick(qry *Query) NextHost {
if qry == nil {
return t.fallback.Pick(qry)
} else if qry.binding != nil && len(qry.values) == 0 {
// If this query was created using session.Bind we wont have the query
// values yet, so we have to pass down to the next policy.
// TODO: Remove this and handle this case
return t.fallback.Pick(qry)
}
routingKey, err := qry.GetRoutingKey()
if err != nil {
return t.fallback.Pick(qry)
}
if routingKey == nil {
return t.fallback.Pick(qry)
}
t.mu.RLock()
// TODO retrieve a list of hosts based on the replication strategy
host := t.tokenRing.GetHostForPartitionKey(routingKey)
t.mu.RUnlock()
if host == nil {
return t.fallback.Pick(qry)
}
// scope these variables for the same lifetime as the iterator function
var (
hostReturned bool
fallbackIter NextHost
)
return func() SelectedHost {
if !hostReturned {
hostReturned = true
return selectedTokenAwareHost{host}
}
// fallback
if fallbackIter == nil {
fallbackIter = t.fallback.Pick(qry)
}
fallbackHost := fallbackIter()
// filter the token aware selected hosts from the fallback hosts
if fallbackHost.Info() == host {
fallbackHost = fallbackIter()
}
return fallbackHost
}
}
// selectedTokenAwareHost is a host returned by the tokenAwareHostPolicy and
// implements the SelectedHost interface
type selectedTokenAwareHost struct {
info *HostInfo
}
func (host selectedTokenAwareHost) Info() *HostInfo {
return host.info
}
func (host selectedTokenAwareHost) Mark(err error) {
// noop
}
// HostPoolHostPolicy is a host policy which uses the bitly/go-hostpool library
// to distribute queries between hosts and prevent sending queries to
// unresponsive hosts. When creating the host pool that is passed to the policy
// use an empty slice of hosts as the hostpool will be populated later by gocql.
// See below for examples of usage:
//
// // Create host selection policy using a simple host pool
// cluster.PoolConfig.HostSelectionPolicy = HostPoolHostPolicy(hostpool.New(nil))
//
// // Create host selection policy using an epsilon greddy pool
// cluster.PoolConfig.HostSelectionPolicy = HostPoolHostPolicy(
// hostpool.NewEpsilonGreedy(nil, 0, &hostpool.LinearEpsilonValueCalculator{}),
// )
//
func HostPoolHostPolicy(hp hostpool.HostPool) HostSelectionPolicy {
return &hostPoolHostPolicy{hostMap: map[string]HostInfo{}, hp: hp}
}
type hostPoolHostPolicy struct {
hp hostpool.HostPool
hostMap map[string]HostInfo
mu sync.RWMutex
}
func (r *hostPoolHostPolicy) SetHosts(hosts []HostInfo) {
peers := make([]string, len(hosts))
hostMap := make(map[string]HostInfo, len(hosts))
for i, host := range hosts {
peers[i] = host.Peer
hostMap[host.Peer] = host
}
r.mu.Lock()
r.hp.SetHosts(peers)
r.hostMap = hostMap
r.mu.Unlock()
}
func (r *hostPoolHostPolicy) SetPartitioner(partitioner string) {
// noop
}
func (r *hostPoolHostPolicy) Pick(qry *Query) NextHost {
return func() SelectedHost {
r.mu.RLock()
defer r.mu.RUnlock()
if len(r.hostMap) == 0 {
return nil
}
hostR := r.hp.Get()
host, ok := r.hostMap[hostR.Host()]
if !ok {
return nil
}
return selectedHostPoolHost{&host, hostR}
}
}
// selectedHostPoolHost is a host returned by the hostPoolHostPolicy and
// implements the SelectedHost interface
type selectedHostPoolHost struct {
info *HostInfo
hostR hostpool.HostPoolResponse
}
func (host selectedHostPoolHost) Info() *HostInfo {
return host.info
}
func (host selectedHostPoolHost) Mark(err error) {
host.hostR.Mark(err)
}
//ConnSelectionPolicy is an interface for selecting an
//appropriate connection for executing a query
type ConnSelectionPolicy interface {
SetConns(conns []*Conn)
Pick(*Query) *Conn
}
type roundRobinConnPolicy struct {
conns []*Conn
pos uint32
mu sync.RWMutex
}
func RoundRobinConnPolicy() func() ConnSelectionPolicy {
return func() ConnSelectionPolicy {
return &roundRobinConnPolicy{}
}
}
func (r *roundRobinConnPolicy) SetConns(conns []*Conn) {
r.mu.Lock()
r.conns = conns
r.mu.Unlock()
}
func (r *roundRobinConnPolicy) Pick(qry *Query) *Conn {
pos := int(atomic.AddUint32(&r.pos, 1) - 1)
r.mu.RLock()
defer r.mu.RUnlock()
if len(r.conns) == 0 {
return nil
}
for i := 0; i < len(r.conns); i++ {
conn := r.conns[(pos+i)%len(r.conns)]
if conn.AvailableStreams() > 0 {
return conn
}
}
return nil
}