-
Notifications
You must be signed in to change notification settings - Fork 642
Expand file tree
/
Copy pathquery_executor.go
More file actions
707 lines (601 loc) · 18.5 KB
/
query_executor.go
File metadata and controls
707 lines (601 loc) · 18.5 KB
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
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Content before git sha 34fdeebefcbf183ed7f916f931aa0586fdaa1b40
* Copyright (c) 2016, The Gocql authors,
* provided under the BSD-3-Clause License.
* See the NOTICE file distributed with this work for additional information.
*/
package gocql
import (
"context"
"sync"
"sync/atomic"
"time"
)
// Deprecated: Will be removed in a future major release. Also Query and Batch no longer implement this interface.
//
// Please use Statement (for Query / Batch objects) or ExecutableStatement (in HostSelectionPolicy implementations) instead.
type ExecutableQuery = ExecutableStatement
// ExecutableStatement is an interface that represents a query or batch statement that
// exposes the correct functions for the HostSelectionPolicy to operate correctly.
type ExecutableStatement interface {
GetRoutingKey() ([]byte, error)
Keyspace() string
Table() string
IsIdempotent() bool
GetHostID() string
Statement() Statement
}
// Statement is an interface that represents a CQL statement that the driver can execute
// (currently Query and Batch via Session.Query and Session.Batch)
type Statement interface {
Iter() *Iter
IterContext(ctx context.Context) *Iter
Exec() error
ExecContext(ctx context.Context) error
}
type internalRequest interface {
execute(ctx context.Context, conn *Conn) *Iter
attempt(keyspace string, end, start time.Time, iter *Iter, host *HostInfo)
retryPolicy() RetryPolicy
speculativeExecutionPolicy() SpeculativeExecutionPolicy
getQueryMetrics() *queryMetrics
getRoutingInfo() *queryRoutingInfo
getKeyspaceFunc() func() string
RetryableQuery
ExecutableStatement
}
type queryExecutor struct {
pool *policyConnPool
policy HostSelectionPolicy
}
func (q *queryExecutor) attemptQuery(ctx context.Context, qry internalRequest, conn *Conn) *Iter {
start := time.Now()
iter := qry.execute(ctx, conn)
end := time.Now()
qry.attempt(q.pool.keyspace, end, start, iter, conn.host)
return iter
}
func (q *queryExecutor) speculate(ctx context.Context, qry internalRequest, sp SpeculativeExecutionPolicy,
hostIter NextHost, results chan *Iter) *Iter {
ticker := time.NewTicker(sp.Delay())
defer ticker.Stop()
for i := 0; i < sp.Attempts(); i++ {
select {
case <-ticker.C:
go q.run(ctx, qry, hostIter, results)
case <-ctx.Done():
return newErrIter(ctx.Err(), qry.getQueryMetrics(), qry.Keyspace(), qry.getRoutingInfo(), qry.getKeyspaceFunc())
case iter := <-results:
return iter
}
}
return nil
}
func (q *queryExecutor) executeQuery(qry internalRequest) (*Iter, error) {
var hostIter NextHost
// check if the host id is specified for the query,
// if it is, the query should be executed at the corresponding host.
if hostID := qry.GetHostID(); hostID != "" {
host, ok := q.pool.session.ring.getHost(hostID)
if !ok {
return nil, ErrNoConnections
}
var returnedHostOnce int32 = 0
hostIter = func() SelectedHost {
if atomic.CompareAndSwapInt32(&returnedHostOnce, 0, 1) {
return (*selectedHost)(host)
}
return nil
}
}
// if host is not specified for the query,
// then a host will be picked by HostSelectionPolicy
if hostIter == nil {
hostIter = q.policy.Pick(qry)
}
// check if the query is not marked as idempotent, if
// it is, we force the policy to NonSpeculative
sp := qry.speculativeExecutionPolicy()
if qry.GetHostID() != "" || !qry.IsIdempotent() || sp.Attempts() == 0 {
return q.do(qry.Context(), qry, hostIter), nil
}
// When speculative execution is enabled, we could be accessing the host iterator from multiple goroutines below.
// To ensure we don't call it concurrently, we wrap the returned NextHost function here to synchronize access to it.
var mu sync.Mutex
origHostIter := hostIter
hostIter = func() SelectedHost {
mu.Lock()
defer mu.Unlock()
return origHostIter()
}
ctx, cancel := context.WithCancel(qry.Context())
defer cancel()
results := make(chan *Iter, 1)
// Launch the main execution
go q.run(ctx, qry, hostIter, results)
// The speculative executions are launched _in addition_ to the main
// execution, on a timer. So Speculation{2} would make 3 executions running
// in total.
if iter := q.speculate(ctx, qry, sp, hostIter, results); iter != nil {
return iter, nil
}
select {
case iter := <-results:
return iter, nil
case <-ctx.Done():
return newErrIter(ctx.Err(), qry.getQueryMetrics(), qry.Keyspace(), qry.getRoutingInfo(), qry.getKeyspaceFunc()), nil
}
}
func (q *queryExecutor) do(ctx context.Context, qry internalRequest, hostIter NextHost) *Iter {
selectedHost := hostIter()
rt := qry.retryPolicy()
var lastErr error
var iter *Iter
for selectedHost != nil {
host := selectedHost.Info()
if host == nil || !host.IsUp() {
selectedHost = hostIter()
continue
}
pool, ok := q.pool.getPool(host)
if !ok {
selectedHost = hostIter()
continue
}
conn := pool.Pick()
if conn == nil {
selectedHost = hostIter()
continue
}
iter = q.attemptQuery(ctx, qry, conn)
iter.host = selectedHost.Info()
// Update host
switch iter.err {
case context.Canceled, context.DeadlineExceeded, ErrNotFound:
// those errors represents logical errors, they should not count
// toward removing a node from the pool
selectedHost.Mark(nil)
return iter
default:
selectedHost.Mark(iter.err)
}
// Exit if the query was successful
// or query is not idempotent or no retry policy defined
if iter.err == nil || !qry.IsIdempotent() || rt == nil {
return iter
}
attemptsReached := !rt.Attempt(qry)
retryType := rt.GetRetryType(iter.err)
var stopRetries bool
// If query is unsuccessful, check the error with RetryPolicy to retry
switch retryType {
case Retry:
// retry on the same host
case RetryNextHost:
// retry on the next host
selectedHost = hostIter()
case Ignore:
iter.err = nil
stopRetries = true
case Rethrow:
stopRetries = true
default:
// Undefined? Return nil and error, this will panic in the requester
return newErrIter(ErrUnknownRetryType, qry.getQueryMetrics(), qry.Keyspace(), qry.getRoutingInfo(), qry.getKeyspaceFunc())
}
if stopRetries || attemptsReached {
return iter
}
lastErr = iter.err
continue
}
if lastErr != nil {
return newErrIter(lastErr, qry.getQueryMetrics(), qry.Keyspace(), qry.getRoutingInfo(), qry.getKeyspaceFunc())
}
return newErrIter(ErrNoConnections, qry.getQueryMetrics(), qry.Keyspace(), qry.getRoutingInfo(), qry.getKeyspaceFunc())
}
func (q *queryExecutor) run(ctx context.Context, qry internalRequest, hostIter NextHost, results chan<- *Iter) {
select {
case results <- q.do(ctx, qry, hostIter):
case <-ctx.Done():
}
}
type queryOptions struct {
stmt string
// Paging
pageSize int
disableAutoPage bool
// Monitoring
trace Tracer
observer QueryObserver
// Parameters
values []interface{}
binding func(q *QueryInfo) ([]interface{}, error)
// Timestamp
defaultTimestamp bool
defaultTimestampValue int64
// Consistency
serialCons SerialConsistency
// Protocol flag
disableSkipMetadata bool
customPayload map[string][]byte
prefetch float64
rt RetryPolicy
spec SpeculativeExecutionPolicy
context context.Context
idempotent bool
keyspace string
skipPrepare bool
routingKey []byte
nowInSecondsValue *int
hostID string
// getKeyspace is field so that it can be overriden in tests
getKeyspace func() string
}
func newQueryOptions(q *Query, ctx context.Context) *queryOptions {
var newRoutingKey []byte
if q.routingKey != nil {
routingKey := q.routingKey
newRoutingKey = make([]byte, len(routingKey))
copy(newRoutingKey, routingKey)
}
if ctx == nil {
ctx = q.Context()
}
return &queryOptions{
stmt: q.stmt,
values: q.values,
pageSize: q.pageSize,
prefetch: q.prefetch,
trace: q.trace,
observer: q.observer,
rt: q.rt,
spec: q.spec,
binding: q.binding,
serialCons: q.serialCons,
defaultTimestamp: q.defaultTimestamp,
defaultTimestampValue: q.defaultTimestampValue,
disableSkipMetadata: q.disableSkipMetadata,
context: ctx,
idempotent: q.idempotent,
customPayload: q.customPayload,
disableAutoPage: q.disableAutoPage,
skipPrepare: q.skipPrepare,
routingKey: newRoutingKey,
getKeyspace: q.getKeyspace,
nowInSecondsValue: q.nowInSecondsValue,
keyspace: q.keyspace,
hostID: q.hostID,
}
}
type internalQuery struct {
originalQuery *Query
qryOpts *queryOptions
pageState []byte
conn *Conn
consistency uint32
session *Session
routingInfo *queryRoutingInfo
metrics *queryMetrics
hostMetricsManager hostMetricsManager
}
func newInternalQuery(q *Query, ctx context.Context) *internalQuery {
var newPageState []byte
if q.initialPageState != nil {
pageState := q.initialPageState
newPageState = make([]byte, len(pageState))
copy(newPageState, pageState)
}
var hostMetricsMgr hostMetricsManager
if q.observer != nil {
hostMetricsMgr = newHostMetricsManager()
} else {
hostMetricsMgr = emptyHostMetricsManager
}
return &internalQuery{
originalQuery: q,
qryOpts: newQueryOptions(q, ctx),
metrics: &queryMetrics{},
hostMetricsManager: hostMetricsMgr,
consistency: uint32(q.initialConsistency),
pageState: newPageState,
conn: nil,
session: q.session,
routingInfo: &queryRoutingInfo{},
}
}
// Attempts returns the number of times the query was executed.
func (q *internalQuery) Attempts() int {
return q.metrics.attempts()
}
func (q *internalQuery) attempt(keyspace string, end, start time.Time, iter *Iter, host *HostInfo) {
latency := end.Sub(start)
attempt := q.metrics.attempt(latency)
if q.qryOpts.observer != nil {
metricsForHost := q.hostMetricsManager.attempt(latency, host)
q.qryOpts.observer.ObserveQuery(q.qryOpts.context, ObservedQuery{
Keyspace: keyspace,
Statement: q.qryOpts.stmt,
Values: q.qryOpts.values,
Start: start,
End: end,
Rows: iter.numRows,
Host: host,
Metrics: metricsForHost,
Err: iter.err,
Attempt: attempt,
Query: q.originalQuery,
})
}
}
func (q *internalQuery) execute(ctx context.Context, conn *Conn) *Iter {
return conn.executeQuery(ctx, q)
}
func (q *internalQuery) retryPolicy() RetryPolicy {
return q.qryOpts.rt
}
func (q *internalQuery) speculativeExecutionPolicy() SpeculativeExecutionPolicy {
return q.qryOpts.spec
}
func (q *internalQuery) GetRoutingKey() ([]byte, error) {
if q.qryOpts.routingKey != nil {
return q.qryOpts.routingKey, nil
}
if q.qryOpts.binding != nil && len(q.qryOpts.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 nil, nil
}
// try to determine the routing key
meta, err := q.session.routingStatementMetadata(q.Context(), q.qryOpts.stmt, q.qryOpts.keyspace)
if err != nil {
return nil, err
}
if meta != nil {
q.routingInfo.mu.Lock()
q.routingInfo.keyspace = meta.Keyspace
q.routingInfo.table = meta.Table
q.routingInfo.mu.Unlock()
}
return createRoutingKey(meta, q.qryOpts.values)
}
func (q *internalQuery) Keyspace() string {
if q.qryOpts.getKeyspace != nil {
return q.qryOpts.getKeyspace()
}
qrKs := q.routingInfo.getKeyspace()
if qrKs != "" {
return qrKs
}
if q.qryOpts.keyspace != "" {
return q.qryOpts.keyspace
}
if q.session == nil {
return ""
}
// TODO(chbannis): this should be parsed from the query or we should let
// this be set by users.
return q.session.cfg.Keyspace
}
func (q *internalQuery) Table() string {
return q.routingInfo.getTable()
}
func (q *internalQuery) IsIdempotent() bool {
return q.qryOpts.idempotent
}
func (q *internalQuery) getQueryMetrics() *queryMetrics {
return q.metrics
}
func (q *internalQuery) SetConsistency(c Consistency) {
atomic.StoreUint32(&q.consistency, uint32(c))
}
func (q *internalQuery) GetConsistency() Consistency {
return Consistency(atomic.LoadUint32(&q.consistency))
}
func (q *internalQuery) Context() context.Context {
return q.qryOpts.context
}
func (q *internalQuery) Statement() Statement {
return q.originalQuery
}
func (q *internalQuery) GetHostID() string {
return q.qryOpts.hostID
}
func (q *internalQuery) getRoutingInfo() *queryRoutingInfo {
return q.routingInfo
}
func (q *internalQuery) getKeyspaceFunc() func() string {
return q.qryOpts.getKeyspace
}
type batchOptions struct {
trace Tracer
observer BatchObserver
bType BatchType
entries []BatchEntry
defaultTimestamp bool
defaultTimestampValue int64
serialCons SerialConsistency
customPayload map[string][]byte
rt RetryPolicy
spec SpeculativeExecutionPolicy
context context.Context
keyspace string
idempotent bool
routingKey []byte
nowInSeconds *int
}
func newBatchOptions(b *Batch, ctx context.Context) *batchOptions {
// make a new array so if user keeps appending entries on the Batch object it doesn't affect this execution
newEntries := make([]BatchEntry, len(b.Entries))
for i, e := range b.Entries {
newEntries[i] = e
}
var newRoutingKey []byte
if b.routingKey != nil {
routingKey := b.routingKey
newRoutingKey = make([]byte, len(routingKey))
copy(newRoutingKey, routingKey)
}
if ctx == nil {
ctx = b.Context()
}
return &batchOptions{
bType: b.Type,
entries: newEntries,
customPayload: b.CustomPayload,
rt: b.rt,
spec: b.spec,
trace: b.trace,
observer: b.observer,
serialCons: b.serialCons,
defaultTimestamp: b.defaultTimestamp,
defaultTimestampValue: b.defaultTimestampValue,
context: ctx,
keyspace: b.Keyspace(),
idempotent: b.IsIdempotent(),
routingKey: newRoutingKey,
nowInSeconds: b.nowInSeconds,
}
}
type internalBatch struct {
originalBatch *Batch
batchOpts *batchOptions
consistency uint32
routingInfo *queryRoutingInfo
session *Session
metrics *queryMetrics
hostMetricsManager hostMetricsManager
}
func newInternalBatch(batch *Batch, ctx context.Context) *internalBatch {
var hostMetricsMgr hostMetricsManager
if batch.observer != nil {
hostMetricsMgr = newHostMetricsManager()
} else {
hostMetricsMgr = emptyHostMetricsManager
}
return &internalBatch{
originalBatch: batch,
batchOpts: newBatchOptions(batch, ctx),
routingInfo: &queryRoutingInfo{},
session: batch.session,
consistency: uint32(batch.GetConsistency()),
metrics: &queryMetrics{},
hostMetricsManager: hostMetricsMgr,
}
}
// Attempts returns the number of attempts made to execute the batch.
func (b *internalBatch) Attempts() int {
return b.metrics.attempts()
}
func (b *internalBatch) attempt(keyspace string, end, start time.Time, iter *Iter, host *HostInfo) {
latency := end.Sub(start)
attempt := b.metrics.attempt(latency)
if b.batchOpts.observer == nil {
return
}
metricsForHost := b.hostMetricsManager.attempt(latency, host)
statements := make([]string, len(b.batchOpts.entries))
values := make([][]interface{}, len(b.batchOpts.entries))
for i, entry := range b.batchOpts.entries {
statements[i] = entry.Stmt
values[i] = entry.Args
}
b.batchOpts.observer.ObserveBatch(b.batchOpts.context, ObservedBatch{
Keyspace: keyspace,
Statements: statements,
Values: values,
Start: start,
End: end,
// Rows not used in batch observations // TODO - might be able to support it when using BatchCAS
Host: host,
Metrics: metricsForHost,
Err: iter.err,
Attempt: attempt,
Batch: b.originalBatch,
})
}
func (b *internalBatch) retryPolicy() RetryPolicy {
return b.batchOpts.rt
}
func (b *internalBatch) speculativeExecutionPolicy() SpeculativeExecutionPolicy {
return b.batchOpts.spec
}
func (b *internalBatch) GetRoutingKey() ([]byte, error) {
if b.batchOpts.routingKey != nil {
return b.batchOpts.routingKey, nil
}
if len(b.batchOpts.entries) == 0 {
return nil, nil
}
entry := b.batchOpts.entries[0]
if entry.binding != nil {
// bindings do not have the values let's skip it like Query does.
return nil, nil
}
// try to determine the routing key
meta, err := b.session.routingStatementMetadata(b.Context(), entry.Stmt, b.batchOpts.keyspace)
if err != nil {
return nil, err
}
if meta != nil {
b.routingInfo.mu.Lock()
b.routingInfo.keyspace = meta.Keyspace
b.routingInfo.table = meta.Table
b.routingInfo.mu.Unlock()
}
return createRoutingKey(meta, entry.Args)
}
func (b *internalBatch) Keyspace() string {
return b.batchOpts.keyspace
}
func (b *internalBatch) Table() string {
return b.routingInfo.getTable()
}
func (b *internalBatch) IsIdempotent() bool {
return b.batchOpts.idempotent
}
func (b *internalBatch) getQueryMetrics() *queryMetrics {
return b.metrics
}
func (b *internalBatch) SetConsistency(c Consistency) {
atomic.StoreUint32(&b.consistency, uint32(c))
}
func (b *internalBatch) GetConsistency() Consistency {
return Consistency(atomic.LoadUint32(&b.consistency))
}
func (b *internalBatch) Context() context.Context {
return b.batchOpts.context
}
func (b *internalBatch) Statement() Statement {
return b.originalBatch
}
func (b *internalBatch) GetHostID() string {
return ""
}
func (b *internalBatch) getRoutingInfo() *queryRoutingInfo {
return b.routingInfo
}
func (b *internalBatch) getKeyspaceFunc() func() string {
return nil
}
func (b *internalBatch) execute(ctx context.Context, conn *Conn) *Iter {
return conn.executeBatch(ctx, b)
}