forked from apache/cassandra-gocql-driver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
session.go
2232 lines (1902 loc) · 61.5 KB
/
session.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
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
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 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.
package gocql
import (
"bytes"
"context"
"encoding/binary"
"errors"
"fmt"
"io"
"net"
"strings"
"sync"
"sync/atomic"
"time"
"unicode"
"github.com/gocql/gocql/internal/lru"
)
// Session is the interface used by users to interact with the database.
//
// It's safe for concurrent use by multiple goroutines and a typical usage
// scenario is to have one global session object to interact with the
// whole Cassandra cluster.
//
// This type extends the Node interface by adding a convenient query builder
// and automatically sets a default consistency level on all operations
// that do not have a consistency level set.
type Session struct {
cons Consistency
pageSize int
prefetch float64
routingKeyInfoCache routingKeyInfoLRU
schemaDescriber *schemaDescriber
trace Tracer
queryObserver QueryObserver
batchObserver BatchObserver
connectObserver ConnectObserver
frameObserver FrameHeaderObserver
streamObserver StreamObserver
hostSource *ringDescriber
ringRefresher *refreshDebouncer
stmtsLRU *preparedLRU
connCfg *ConnConfig
executor *queryExecutor
pool *policyConnPool
policy HostSelectionPolicy
ring ring
metadata clusterMetadata
mu sync.RWMutex
control *controlConn
// event handlers
nodeEvents *eventDebouncer
schemaEvents *eventDebouncer
// ring metadata
useSystemSchema bool
hasAggregatesAndFunctions bool
cfg ClusterConfig
ctx context.Context
cancel context.CancelFunc
// sessionStateMu protects isClosed and isInitialized.
sessionStateMu sync.RWMutex
// isClosed is true once Session.Close is finished.
isClosed bool
// isClosing bool is true once Session.Close is started.
isClosing bool
// isInitialized is true once Session.init succeeds.
// you can use initialized() to read the value.
isInitialized bool
logger StdLogger
}
var queryPool = &sync.Pool{
New: func() interface{} {
return &Query{refCount: 1}
},
}
func addrsToHosts(addrs []string, defaultPort int, logger StdLogger) ([]*HostInfo, error) {
var hosts []*HostInfo
for _, hostport := range addrs {
resolvedHosts, err := hostInfo(hostport, defaultPort)
if err != nil {
// Try other hosts if unable to resolve DNS name
if _, ok := err.(*net.DNSError); ok {
logger.Printf("gocql: dns error: %v\n", err)
continue
}
return nil, err
}
hosts = append(hosts, resolvedHosts...)
}
if len(hosts) == 0 {
return nil, errors.New("failed to resolve any of the provided hostnames")
}
return hosts, nil
}
// NewSession wraps an existing Node.
func NewSession(cfg ClusterConfig) (*Session, error) {
// Check that hosts in the ClusterConfig is not empty
if len(cfg.Hosts) < 1 {
return nil, ErrNoHosts
}
// Check that either Authenticator is set or AuthProvider, not both
if cfg.Authenticator != nil && cfg.AuthProvider != nil {
return nil, errors.New("Can't use both Authenticator and AuthProvider in cluster config.")
}
// TODO: we should take a context in here at some point
ctx, cancel := context.WithCancel(context.TODO())
s := &Session{
cons: cfg.Consistency,
prefetch: 0.25,
cfg: cfg,
pageSize: cfg.PageSize,
stmtsLRU: &preparedLRU{lru: lru.New(cfg.MaxPreparedStmts)},
connectObserver: cfg.ConnectObserver,
ctx: ctx,
cancel: cancel,
logger: cfg.logger(),
}
s.schemaDescriber = newSchemaDescriber(s)
s.nodeEvents = newEventDebouncer("NodeEvents", s.handleNodeEvent, s.logger)
s.schemaEvents = newEventDebouncer("SchemaEvents", s.handleSchemaEvent, s.logger)
s.routingKeyInfoCache.lru = lru.New(cfg.MaxRoutingKeyInfo)
s.hostSource = &ringDescriber{session: s}
s.ringRefresher = newRefreshDebouncer(ringRefreshDebounceTime, func() error { return refreshRing(s.hostSource) })
if cfg.PoolConfig.HostSelectionPolicy == nil {
cfg.PoolConfig.HostSelectionPolicy = RoundRobinHostPolicy()
}
s.pool = cfg.PoolConfig.buildPool(s)
s.policy = cfg.PoolConfig.HostSelectionPolicy
s.policy.Init(s)
s.executor = &queryExecutor{
pool: s.pool,
policy: cfg.PoolConfig.HostSelectionPolicy,
}
s.queryObserver = cfg.QueryObserver
s.batchObserver = cfg.BatchObserver
s.connectObserver = cfg.ConnectObserver
s.frameObserver = cfg.FrameHeaderObserver
s.streamObserver = cfg.StreamObserver
//Check the TLS Config before trying to connect to anything external
connCfg, err := connConfig(&s.cfg)
if err != nil {
//TODO: Return a typed error
return nil, fmt.Errorf("gocql: unable to create session: %v", err)
}
s.connCfg = connCfg
if err := s.init(); err != nil {
s.Close()
if err == ErrNoConnectionsStarted {
//This error used to be generated inside NewSession & returned directly
//Forward it on up to be backwards compatible
return nil, ErrNoConnectionsStarted
} else {
// TODO(zariel): dont wrap this error in fmt.Errorf, return a typed error
return nil, fmt.Errorf("gocql: unable to create session: %v", err)
}
}
return s, nil
}
func (s *Session) init() error {
hosts, err := addrsToHosts(s.cfg.Hosts, s.cfg.Port, s.logger)
if err != nil {
return err
}
s.ring.endpoints = hosts
if !s.cfg.disableControlConn {
s.control = createControlConn(s)
if s.cfg.ProtoVersion == 0 {
proto, err := s.control.discoverProtocol(hosts)
if err != nil {
return fmt.Errorf("unable to discover protocol version: %v", err)
} else if proto == 0 {
return errors.New("unable to discovery protocol version")
}
// TODO(zariel): we really only need this in 1 place
s.cfg.ProtoVersion = proto
s.connCfg.ProtoVersion = proto
}
if err := s.control.connect(hosts); err != nil {
return err
}
if !s.cfg.DisableInitialHostLookup {
var partitioner string
newHosts, partitioner, err := s.hostSource.GetHosts()
if err != nil {
return err
}
s.policy.SetPartitioner(partitioner)
filteredHosts := make([]*HostInfo, 0, len(newHosts))
for _, host := range newHosts {
if !s.cfg.filterHost(host) {
filteredHosts = append(filteredHosts, host)
}
}
hosts = filteredHosts
}
}
for _, host := range hosts {
// In case when host lookup is disabled and when we are in unit tests,
// host are not discovered, and we are missing host ID information used
// by internal logic.
// Associate random UUIDs here with all hosts missing this information.
if len(host.HostID()) == 0 {
host.SetHostID(MustRandomUUID().String())
}
}
hostMap := make(map[string]*HostInfo, len(hosts))
for _, host := range hosts {
hostMap[host.HostID()] = host
}
hosts = hosts[:0]
// each host will increment left and decrement it after connecting and once
// there's none left, we'll close hostCh
var left int64
// we will receive up to len(hostMap) of messages so create a buffer so we
// don't end up stuck in a goroutine if we stopped listening
connectedCh := make(chan struct{}, len(hostMap))
// we add one here because we don't want to end up closing hostCh until we're
// done looping and the decerement code might be reached before we've looped
// again
atomic.AddInt64(&left, 1)
for _, host := range hostMap {
host := s.ring.addOrUpdate(host)
if s.cfg.filterHost(host) {
continue
}
atomic.AddInt64(&left, 1)
go func() {
s.pool.addHost(host)
connectedCh <- struct{}{}
// if there are no hosts left, then close the hostCh to unblock the loop
// below if its still waiting
if atomic.AddInt64(&left, -1) == 0 {
close(connectedCh)
}
}()
hosts = append(hosts, host)
}
// once we're done looping we subtract the one we initially added and check
// to see if we should close
if atomic.AddInt64(&left, -1) == 0 {
close(connectedCh)
}
// before waiting for them to connect, add them all to the policy so we can
// utilize efficiencies by calling AddHosts if the policy supports it
type bulkAddHosts interface {
AddHosts([]*HostInfo)
}
if v, ok := s.policy.(bulkAddHosts); ok {
v.AddHosts(hosts)
} else {
for _, host := range hosts {
s.policy.AddHost(host)
}
}
readyPolicy, _ := s.policy.(ReadyPolicy)
// now loop over connectedCh until it's closed (meaning we've connected to all)
// or until the policy says we're ready
for range connectedCh {
if readyPolicy != nil && readyPolicy.Ready() {
break
}
}
// TODO(zariel): we probably dont need this any more as we verify that we
// can connect to one of the endpoints supplied by using the control conn.
// See if there are any connections in the pool
if s.cfg.ReconnectInterval > 0 {
go s.reconnectDownedHosts(s.cfg.ReconnectInterval)
}
// If we disable the initial host lookup, we need to still check if the
// cluster is using the newer system schema or not... however, if control
// connection is disable, we really have no choice, so we just make our
// best guess...
if !s.cfg.disableControlConn && s.cfg.DisableInitialHostLookup {
newer, _ := checkSystemSchema(s.control)
s.useSystemSchema = newer
} else {
version := s.ring.rrHost().Version()
s.useSystemSchema = version.AtLeast(3, 0, 0)
s.hasAggregatesAndFunctions = version.AtLeast(2, 2, 0)
}
if s.pool.Size() == 0 {
return ErrNoConnectionsStarted
}
// Invoke KeyspaceChanged to let the policy cache the session keyspace
// parameters. This is used by tokenAwareHostPolicy to discover replicas.
if !s.cfg.disableControlConn && s.cfg.Keyspace != "" {
s.policy.KeyspaceChanged(KeyspaceUpdateEvent{Keyspace: s.cfg.Keyspace})
}
s.sessionStateMu.Lock()
s.isInitialized = true
s.sessionStateMu.Unlock()
return nil
}
// AwaitSchemaAgreement will wait until schema versions across all nodes in the
// cluster are the same (as seen from the point of view of the control connection).
// The maximum amount of time this takes is governed
// by the MaxWaitSchemaAgreement setting in the configuration (default: 60s).
// AwaitSchemaAgreement returns an error in case schema versions are not the same
// after the timeout specified in MaxWaitSchemaAgreement elapses.
func (s *Session) AwaitSchemaAgreement(ctx context.Context) error {
if s.cfg.disableControlConn {
return errNoControl
}
return s.control.withConn(func(conn *Conn) *Iter {
return &Iter{err: conn.awaitSchemaAgreement(ctx)}
}).err
}
func (s *Session) reconnectDownedHosts(intv time.Duration) {
reconnectTicker := time.NewTicker(intv)
defer reconnectTicker.Stop()
for {
select {
case <-reconnectTicker.C:
hosts := s.ring.allHosts()
// Print session.ring for debug.
if gocqlDebug {
buf := bytes.NewBufferString("Session.ring:")
for _, h := range hosts {
buf.WriteString("[" + h.ConnectAddress().String() + ":" + h.State().String() + "]")
}
s.logger.Println(buf.String())
}
for _, h := range hosts {
if h.IsUp() {
continue
}
// we let the pool call handleNodeConnected to change the host state
s.pool.addHost(h)
}
case <-s.ctx.Done():
return
}
}
}
// SetConsistency sets the default consistency level for this session. This
// setting can also be changed on a per-query basis and the default value
// is Quorum.
func (s *Session) SetConsistency(cons Consistency) {
s.mu.Lock()
s.cons = cons
s.mu.Unlock()
}
// SetPageSize sets the default page size for this session. A value <= 0 will
// disable paging. This setting can also be changed on a per-query basis.
func (s *Session) SetPageSize(n int) {
s.mu.Lock()
s.pageSize = n
s.mu.Unlock()
}
// SetPrefetch sets the default threshold for pre-fetching new pages. If
// there are only p*pageSize rows remaining, the next page will be requested
// automatically. This value can also be changed on a per-query basis and
// the default value is 0.25.
func (s *Session) SetPrefetch(p float64) {
s.mu.Lock()
s.prefetch = p
s.mu.Unlock()
}
// SetTrace sets the default tracer for this session. This setting can also
// be changed on a per-query basis.
func (s *Session) SetTrace(trace Tracer) {
s.mu.Lock()
s.trace = trace
s.mu.Unlock()
}
// Query generates a new query object for interacting with the database.
// Further details of the query may be tweaked using the resulting query
// value before the query is executed. Query is automatically prepared
// if it has not previously been executed.
func (s *Session) Query(stmt string, values ...interface{}) *Query {
qry := queryPool.Get().(*Query)
qry.session = s
qry.stmt = stmt
qry.values = values
qry.defaultsFromSession()
return qry
}
type QueryInfo struct {
Id []byte
Args []ColumnInfo
Rval []ColumnInfo
PKeyColumns []int
}
// Bind generates a new query object based on the query statement passed in.
// The query is automatically prepared if it has not previously been executed.
// The binding callback allows the application to define which query argument
// values will be marshalled as part of the query execution.
// During execution, the meta data of the prepared query will be routed to the
// binding callback, which is responsible for producing the query argument values.
func (s *Session) Bind(stmt string, b func(q *QueryInfo) ([]interface{}, error)) *Query {
qry := queryPool.Get().(*Query)
qry.session = s
qry.stmt = stmt
qry.binding = b
qry.defaultsFromSession()
return qry
}
// Close closes all connections. The session is unusable after this
// operation.
func (s *Session) Close() {
s.sessionStateMu.Lock()
if s.isClosing {
s.sessionStateMu.Unlock()
return
}
s.isClosing = true
s.sessionStateMu.Unlock()
if s.pool != nil {
s.pool.Close()
}
if s.control != nil {
s.control.close()
}
if s.nodeEvents != nil {
s.nodeEvents.stop()
}
if s.schemaEvents != nil {
s.schemaEvents.stop()
}
if s.ringRefresher != nil {
s.ringRefresher.stop()
}
if s.cancel != nil {
s.cancel()
}
s.sessionStateMu.Lock()
s.isClosed = true
s.sessionStateMu.Unlock()
}
func (s *Session) Closed() bool {
s.sessionStateMu.RLock()
closed := s.isClosed
s.sessionStateMu.RUnlock()
return closed
}
func (s *Session) initialized() bool {
s.sessionStateMu.RLock()
initialized := s.isInitialized
s.sessionStateMu.RUnlock()
return initialized
}
func (s *Session) executeQuery(qry *Query) (it *Iter) {
// fail fast
if s.Closed() {
return &Iter{err: ErrSessionClosed}
}
iter, err := s.executor.executeQuery(qry)
if err != nil {
return &Iter{err: err}
}
if iter == nil {
panic("nil iter")
}
return iter
}
func (s *Session) removeHost(h *HostInfo) {
s.policy.RemoveHost(h)
hostID := h.HostID()
s.pool.removeHost(hostID)
s.ring.removeHost(hostID)
}
// KeyspaceMetadata returns the schema metadata for the keyspace specified. Returns an error if the keyspace does not exist.
func (s *Session) KeyspaceMetadata(keyspace string) (*KeyspaceMetadata, error) {
// fail fast
if s.Closed() {
return nil, ErrSessionClosed
} else if keyspace == "" {
return nil, ErrNoKeyspace
}
return s.schemaDescriber.getSchema(keyspace)
}
func (s *Session) getConn() *Conn {
hosts := s.ring.allHosts()
for _, host := range hosts {
if !host.IsUp() {
continue
}
pool, ok := s.pool.getPool(host)
if !ok {
continue
} else if conn := pool.Pick(); conn != nil {
return conn
}
}
return nil
}
// returns routing key indexes and type info
func (s *Session) routingKeyInfo(ctx context.Context, stmt string) (*routingKeyInfo, error) {
s.routingKeyInfoCache.mu.Lock()
entry, cached := s.routingKeyInfoCache.lru.Get(stmt)
if cached {
// done accessing the cache
s.routingKeyInfoCache.mu.Unlock()
// the entry is an inflight struct similar to that used by
// Conn to prepare statements
inflight := entry.(*inflightCachedEntry)
// wait for any inflight work
inflight.wg.Wait()
if inflight.err != nil {
return nil, inflight.err
}
key, _ := inflight.value.(*routingKeyInfo)
return key, nil
}
// create a new inflight entry while the data is created
inflight := new(inflightCachedEntry)
inflight.wg.Add(1)
defer inflight.wg.Done()
s.routingKeyInfoCache.lru.Add(stmt, inflight)
s.routingKeyInfoCache.mu.Unlock()
var (
info *preparedStatment
partitionKey []*ColumnMetadata
)
conn := s.getConn()
if conn == nil {
// TODO: better error?
inflight.err = errors.New("gocql: unable to fetch prepared info: no connection available")
return nil, inflight.err
}
// get the query info for the statement
info, inflight.err = conn.prepareStatement(ctx, stmt, nil)
if inflight.err != nil {
// don't cache this error
s.routingKeyInfoCache.Remove(stmt)
return nil, inflight.err
}
// TODO: it would be nice to mark hosts here but as we are not using the policies
// to fetch hosts we cant
if info.request.colCount == 0 {
// no arguments, no routing key, and no error
return nil, nil
}
if len(info.request.pkeyColumns) > 0 {
// proto v4 dont need to calculate primary key columns
types := make([]TypeInfo, len(info.request.pkeyColumns))
for i, col := range info.request.pkeyColumns {
types[i] = info.request.columns[col].TypeInfo
}
routingKeyInfo := &routingKeyInfo{
indexes: info.request.pkeyColumns,
types: types,
}
inflight.value = routingKeyInfo
return routingKeyInfo, nil
}
// get the table metadata
table := info.request.columns[0].Table
var keyspaceMetadata *KeyspaceMetadata
keyspaceMetadata, inflight.err = s.KeyspaceMetadata(info.request.columns[0].Keyspace)
if inflight.err != nil {
// don't cache this error
s.routingKeyInfoCache.Remove(stmt)
return nil, inflight.err
}
tableMetadata, found := keyspaceMetadata.Tables[table]
if !found {
// unlikely that the statement could be prepared and the metadata for
// the table couldn't be found, but this may indicate either a bug
// in the metadata code, or that the table was just dropped.
inflight.err = ErrNoMetadata
// don't cache this error
s.routingKeyInfoCache.Remove(stmt)
return nil, inflight.err
}
partitionKey = tableMetadata.PartitionKey
size := len(partitionKey)
routingKeyInfo := &routingKeyInfo{
indexes: make([]int, size),
types: make([]TypeInfo, size),
}
for keyIndex, keyColumn := range partitionKey {
// set an indicator for checking if the mapping is missing
routingKeyInfo.indexes[keyIndex] = -1
// find the column in the query info
for argIndex, boundColumn := range info.request.columns {
if keyColumn.Name == boundColumn.Name {
// there may be many such bound columns, pick the first
routingKeyInfo.indexes[keyIndex] = argIndex
routingKeyInfo.types[keyIndex] = boundColumn.TypeInfo
break
}
}
if routingKeyInfo.indexes[keyIndex] == -1 {
// missing a routing key column mapping
// no routing key, and no error
return nil, nil
}
}
// cache this result
inflight.value = routingKeyInfo
return routingKeyInfo, nil
}
func (b *Batch) execute(ctx context.Context, conn *Conn) *Iter {
return conn.executeBatch(ctx, b)
}
func (s *Session) executeBatch(batch *Batch) *Iter {
// fail fast
if s.Closed() {
return &Iter{err: ErrSessionClosed}
}
// Prevent the execution of the batch if greater than the limit
// Currently batches have a limit of 65536 queries.
// https://datastax-oss.atlassian.net/browse/JAVA-229
if batch.Size() > BatchSizeMaximum {
return &Iter{err: ErrTooManyStmts}
}
iter, err := s.executor.executeQuery(batch)
if err != nil {
return &Iter{err: err}
}
return iter
}
// ExecuteBatch executes a batch operation and returns nil if successful
// otherwise an error is returned describing the failure.
func (s *Session) ExecuteBatch(batch *Batch) error {
iter := s.executeBatch(batch)
return iter.Close()
}
// ExecuteBatchCAS executes a batch operation and returns true if successful and
// an iterator (to scan additional rows if more than one conditional statement)
// was sent.
// Further scans on the interator must also remember to include
// the applied boolean as the first argument to *Iter.Scan
func (s *Session) ExecuteBatchCAS(batch *Batch, dest ...interface{}) (applied bool, iter *Iter, err error) {
iter = s.executeBatch(batch)
if err := iter.checkErrAndNotFound(); err != nil {
iter.Close()
return false, nil, err
}
if len(iter.Columns()) > 1 {
dest = append([]interface{}{&applied}, dest...)
iter.Scan(dest...)
} else {
iter.Scan(&applied)
}
return applied, iter, nil
}
// MapExecuteBatchCAS executes a batch operation much like ExecuteBatchCAS,
// however it accepts a map rather than a list of arguments for the initial
// scan.
func (s *Session) MapExecuteBatchCAS(batch *Batch, dest map[string]interface{}) (applied bool, iter *Iter, err error) {
iter = s.executeBatch(batch)
if err := iter.checkErrAndNotFound(); err != nil {
iter.Close()
return false, nil, err
}
iter.MapScan(dest)
applied = dest["[applied]"].(bool)
delete(dest, "[applied]")
// we usually close here, but instead of closing, just returin an error
// if MapScan failed. Although Close just returns err, using Close
// here might be confusing as we are not actually closing the iter
return applied, iter, iter.err
}
type hostMetrics struct {
// Attempts is count of how many times this query has been attempted for this host.
// An attempt is either a retry or fetching next page of results.
Attempts int
// TotalLatency is the sum of attempt latencies for this host in nanoseconds.
TotalLatency int64
}
type queryMetrics struct {
l sync.RWMutex
m map[string]*hostMetrics
// totalAttempts is total number of attempts.
// Equal to sum of all hostMetrics' Attempts.
totalAttempts int
}
// preFilledQueryMetrics initializes new queryMetrics based on per-host supplied data.
func preFilledQueryMetrics(m map[string]*hostMetrics) *queryMetrics {
qm := &queryMetrics{m: m}
for _, hm := range qm.m {
qm.totalAttempts += hm.Attempts
}
return qm
}
// hostMetrics returns a snapshot of metrics for given host.
// If the metrics for host don't exist, they are created.
func (qm *queryMetrics) hostMetrics(host *HostInfo) *hostMetrics {
qm.l.Lock()
metrics := qm.hostMetricsLocked(host)
copied := new(hostMetrics)
*copied = *metrics
qm.l.Unlock()
return copied
}
// hostMetricsLocked gets or creates host metrics for given host.
// It must be called only while holding qm.l lock.
func (qm *queryMetrics) hostMetricsLocked(host *HostInfo) *hostMetrics {
metrics, exists := qm.m[host.ConnectAddress().String()]
if !exists {
// if the host is not in the map, it means it's been accessed for the first time
metrics = &hostMetrics{}
qm.m[host.ConnectAddress().String()] = metrics
}
return metrics
}
// attempts returns the number of times the query was executed.
func (qm *queryMetrics) attempts() int {
qm.l.Lock()
attempts := qm.totalAttempts
qm.l.Unlock()
return attempts
}
func (qm *queryMetrics) latency() int64 {
qm.l.Lock()
var (
attempts int
latency int64
)
for _, metric := range qm.m {
attempts += metric.Attempts
latency += metric.TotalLatency
}
qm.l.Unlock()
if attempts > 0 {
return latency / int64(attempts)
}
return 0
}
// attempt adds given number of attempts and latency for given host.
// It returns previous total attempts.
// If needsHostMetrics is true, a copy of updated hostMetrics is returned.
func (qm *queryMetrics) attempt(addAttempts int, addLatency time.Duration,
host *HostInfo, needsHostMetrics bool) (int, *hostMetrics) {
qm.l.Lock()
totalAttempts := qm.totalAttempts
qm.totalAttempts += addAttempts
updateHostMetrics := qm.hostMetricsLocked(host)
updateHostMetrics.Attempts += addAttempts
updateHostMetrics.TotalLatency += addLatency.Nanoseconds()
var hostMetricsCopy *hostMetrics
if needsHostMetrics {
hostMetricsCopy = new(hostMetrics)
*hostMetricsCopy = *updateHostMetrics
}
qm.l.Unlock()
return totalAttempts, hostMetricsCopy
}
// Query represents a CQL statement that can be executed.
type Query struct {
stmt string
values []interface{}
cons Consistency
pageSize int
routingKey []byte
pageState []byte
prefetch float64
trace Tracer
observer QueryObserver
session *Session
conn *Conn
rt RetryPolicy
spec SpeculativeExecutionPolicy
binding func(q *QueryInfo) ([]interface{}, error)
serialCons SerialConsistency
defaultTimestamp bool
defaultTimestampValue int64
disableSkipMetadata bool
context context.Context
idempotent bool
customPayload map[string][]byte
metrics *queryMetrics
refCount uint32
disableAutoPage bool
// getKeyspace is field so that it can be overriden in tests
getKeyspace func() string
// used by control conn queries to prevent triggering a write to systems
// tables in AWS MCS see
skipPrepare bool
}
func (q *Query) defaultsFromSession() {
s := q.session
s.mu.RLock()
q.cons = s.cons
q.pageSize = s.pageSize
q.trace = s.trace
q.observer = s.queryObserver
q.prefetch = s.prefetch
q.rt = s.cfg.RetryPolicy
q.serialCons = s.cfg.SerialConsistency
q.defaultTimestamp = s.cfg.DefaultTimestamp
q.idempotent = s.cfg.DefaultIdempotence
q.metrics = &queryMetrics{m: make(map[string]*hostMetrics)}
q.spec = &NonSpeculativeExecution{}
s.mu.RUnlock()
}
// Statement returns the statement that was used to generate this query.
func (q Query) Statement() string {
return q.stmt
}
// String implements the stringer interface.
func (q Query) String() string {
return fmt.Sprintf("[query statement=%q values=%+v consistency=%s]", q.stmt, q.values, q.cons)
}
// Attempts returns the number of times the query was executed.
func (q *Query) Attempts() int {
return q.metrics.attempts()
}
func (q *Query) AddAttempts(i int, host *HostInfo) {
q.metrics.attempt(i, 0, host, false)
}
// Latency returns the average amount of nanoseconds per attempt of the query.
func (q *Query) Latency() int64 {
return q.metrics.latency()
}
func (q *Query) AddLatency(l int64, host *HostInfo) {
q.metrics.attempt(0, time.Duration(l)*time.Nanosecond, host, false)
}
// Consistency sets the consistency level for this query. If no consistency
// level have been set, the default consistency level of the cluster
// is used.
func (q *Query) Consistency(c Consistency) *Query {
q.cons = c
return q
}
// GetConsistency returns the currently configured consistency level for
// the query.
func (q *Query) GetConsistency() Consistency {
return q.cons
}
// Same as Consistency but without a return value
func (q *Query) SetConsistency(c Consistency) {
q.cons = c
}
// CustomPayload sets the custom payload level for this query.
func (q *Query) CustomPayload(customPayload map[string][]byte) *Query {
q.customPayload = customPayload
return q
}
func (q *Query) Context() context.Context {
if q.context == nil {
return context.Background()
}
return q.context
}
// Trace enables tracing of this query. Look at the documentation of the
// Tracer interface to learn more about tracing.
func (q *Query) Trace(trace Tracer) *Query {
q.trace = trace
return q
}
// Observer enables query-level observer on this query.