forked from apache/cassandra-gocql-driver
-
Notifications
You must be signed in to change notification settings - Fork 1
/
conn.go
619 lines (565 loc) · 13.6 KB
/
conn.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
// 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 (
"bufio"
"fmt"
"net"
"strings"
"sync"
"sync/atomic"
"time"
"unicode"
"code.google.com/p/snappy-go/snappy"
)
const defaultFrameSize = 4096
const flagResponse = 0x80
const maskVersion = 0x7F
type Cluster interface {
HandleError(conn *Conn, err error, closed bool)
HandleKeyspace(conn *Conn, keyspace string)
}
type Authenticator interface {
Challenge(req []byte) (resp []byte, auth Authenticator, err error)
Success(data []byte) error
}
type PasswordAuthenticator struct {
Username string
Password string
}
func (p PasswordAuthenticator) Challenge(req []byte) ([]byte, Authenticator, error) {
if string(req) != "org.apache.cassandra.auth.PasswordAuthenticator" {
return nil, nil, fmt.Errorf("unexpected authenticator %q", req)
}
resp := make([]byte, 2+len(p.Username)+len(p.Password))
resp[0] = 0
copy(resp[1:], p.Username)
resp[len(p.Username)+1] = 0
copy(resp[2+len(p.Username):], p.Password)
return resp, nil, nil
}
func (p PasswordAuthenticator) Success(data []byte) error {
return nil
}
type ConnConfig struct {
ProtoVersion int
CQLVersion string
Timeout time.Duration
NumStreams int
Compressor Compressor
Authenticator Authenticator
}
// Conn is a single connection to a Cassandra node. It can be used to execute
// queries, but users are usually advised to use a more reliable, higher
// level API.
type Conn struct {
conn net.Conn
r *bufio.Reader
timeout time.Duration
uniq chan uint8
calls []callReq
nwait int32
prepMu sync.Mutex
prep map[string]*inflightPrepare
cluster Cluster
compressor Compressor
auth Authenticator
addr string
version uint8
}
// Connect establishes a connection to a Cassandra node.
// You must also call the Serve method before you can execute any queries.
func Connect(addr string, cfg ConnConfig, cluster Cluster) (*Conn, error) {
conn, err := net.DialTimeout("tcp", addr, cfg.Timeout)
if err != nil {
return nil, err
}
if cfg.NumStreams <= 0 || cfg.NumStreams > 128 {
cfg.NumStreams = 128
}
if cfg.ProtoVersion != 1 && cfg.ProtoVersion != 2 {
cfg.ProtoVersion = 2
}
c := &Conn{
conn: conn,
r: bufio.NewReader(conn),
uniq: make(chan uint8, cfg.NumStreams),
calls: make([]callReq, cfg.NumStreams),
prep: make(map[string]*inflightPrepare),
timeout: cfg.Timeout,
version: uint8(cfg.ProtoVersion),
addr: conn.RemoteAddr().String(),
cluster: cluster,
compressor: cfg.Compressor,
auth: cfg.Authenticator,
}
for i := 0; i < cap(c.uniq); i++ {
c.uniq <- uint8(i)
}
if err := c.startup(&cfg); err != nil {
return nil, err
}
go c.serve()
return c, nil
}
func (c *Conn) startup(cfg *ConnConfig) error {
compression := ""
if c.compressor != nil {
compression = c.compressor.Name()
}
var req operation = &startupFrame{
CQLVersion: cfg.CQLVersion,
Compression: compression,
}
var challenger Authenticator
for {
resp, err := c.execSimple(req)
if err != nil {
return err
}
switch x := resp.(type) {
case readyFrame:
return nil
case error:
return x
case authenticateFrame:
if c.auth == nil {
return fmt.Errorf("authentication required (using %q)", x.Authenticator)
}
var resp []byte
resp, challenger, err = c.auth.Challenge([]byte(x.Authenticator))
if err != nil {
return err
}
req = &authResponseFrame{resp}
case authChallengeFrame:
if challenger == nil {
return fmt.Errorf("authentication error (invalid challenge)")
}
var resp []byte
resp, challenger, err = challenger.Challenge(x.Data)
if err != nil {
return err
}
req = &authResponseFrame{resp}
case authSuccessFrame:
if challenger != nil {
return challenger.Success(x.Data)
}
return nil
default:
return ErrProtocol
}
}
}
// Serve starts the stream multiplexer for this connection, which is required
// to execute any queries. This method runs as long as the connection is
// open and is therefore usually called in a separate goroutine.
func (c *Conn) serve() {
for {
resp, err := c.recv()
if err != nil {
break
}
c.dispatch(resp)
}
c.conn.Close()
for id := 0; id < len(c.calls); id++ {
req := &c.calls[id]
if atomic.LoadInt32(&req.active) == 1 {
req.resp <- callResp{nil, ErrProtocol}
}
}
c.cluster.HandleError(c, ErrProtocol, true)
}
func (c *Conn) recv() (frame, error) {
resp := make(frame, headerSize, headerSize+512)
c.conn.SetReadDeadline(time.Now().Add(c.timeout))
n, last, pinged := 0, 0, false
for n < len(resp) {
nn, err := c.r.Read(resp[n:])
n += nn
if err != nil {
if nerr, ok := err.(net.Error); ok && nerr.Timeout() {
if n > last {
// we hit the deadline but we made progress.
// simply extend the deadline
c.conn.SetReadDeadline(time.Now().Add(c.timeout))
last = n
} else if n == 0 && !pinged {
c.conn.SetReadDeadline(time.Now().Add(c.timeout))
if atomic.LoadInt32(&c.nwait) > 0 {
go c.ping()
pinged = true
}
} else {
return nil, err
}
} else {
return nil, err
}
}
if n == headerSize && len(resp) == headerSize {
if resp[0] != c.version|flagResponse {
return nil, ErrProtocol
}
resp.grow(resp.Length())
}
}
return resp, nil
}
func (c *Conn) execSimple(op operation) (interface{}, error) {
f, err := op.encodeFrame(c.version, nil)
f.setLength(len(f) - headerSize)
if _, err := c.conn.Write([]byte(f)); err != nil {
c.conn.Close()
return nil, err
}
if f, err = c.recv(); err != nil {
return nil, err
}
return c.decodeFrame(f, nil)
}
func (c *Conn) exec(op operation, trace Tracer) (interface{}, error) {
req, err := op.encodeFrame(c.version, nil)
if err != nil {
return nil, err
}
if trace != nil {
req[1] |= flagTrace
}
if len(req) > headerSize && c.compressor != nil {
body, err := c.compressor.Encode([]byte(req[headerSize:]))
if err != nil {
return nil, err
}
req = append(req[:headerSize], frame(body)...)
req[1] |= flagCompress
}
req.setLength(len(req) - headerSize)
id := <-c.uniq
req[2] = id
call := &c.calls[id]
call.resp = make(chan callResp, 1)
atomic.AddInt32(&c.nwait, 1)
atomic.StoreInt32(&call.active, 1)
if n, err := c.conn.Write(req); err != nil {
c.conn.Close()
c.uniq <- id
if n > 0 {
return nil, ErrProtocol
}
return nil, ErrUnavailable
}
reply := <-call.resp
call.resp = nil
c.uniq <- id
if reply.err != nil {
return nil, reply.err
}
return c.decodeFrame(reply.buf, trace)
}
func (c *Conn) dispatch(resp frame) {
id := int(resp[2])
if id >= len(c.calls) {
return
}
call := &c.calls[id]
if !atomic.CompareAndSwapInt32(&call.active, 1, 0) {
return
}
atomic.AddInt32(&c.nwait, -1)
call.resp <- callResp{resp, nil}
}
func (c *Conn) ping() error {
_, err := c.exec(&optionsFrame{}, nil)
return err
}
func (c *Conn) prepareStatement(stmt string, trace Tracer) (*queryInfo, error) {
c.prepMu.Lock()
flight := c.prep[stmt]
if flight != nil {
c.prepMu.Unlock()
flight.wg.Wait()
return flight.info, flight.err
}
flight = new(inflightPrepare)
flight.wg.Add(1)
c.prep[stmt] = flight
c.prepMu.Unlock()
resp, err := c.exec(&prepareFrame{Stmt: stmt}, trace)
if err != nil {
flight.err = err
} else {
switch x := resp.(type) {
case resultPreparedFrame:
flight.info = &queryInfo{
id: x.PreparedId,
args: x.Values,
}
case error:
flight.err = x
default:
flight.err = ErrProtocol
}
}
flight.wg.Done()
if err != nil {
c.prepMu.Lock()
delete(c.prep, stmt)
c.prepMu.Unlock()
}
return flight.info, flight.err
}
func (c *Conn) executeQuery(qry *Query) *Iter {
op := &queryFrame{
Stmt: strings.TrimSpace(qry.stmt),
Cons: qry.cons,
PageSize: qry.pageSize,
PageState: qry.pageState,
}
stmtType := op.Stmt
if n := strings.IndexFunc(stmtType, unicode.IsSpace); n >= 0 {
stmtType = strings.ToLower(stmtType[:n])
}
switch stmtType {
case "select", "insert", "update", "delete":
// Prepare all DML queries. Other queries can not be prepared.
info, err := c.prepareStatement(qry.stmt, qry.trace)
if err != nil {
return &Iter{err: err}
}
op.Prepared = info.id
op.Values = make([][]byte, len(qry.values))
for i := 0; i < len(qry.values); i++ {
val, err := Marshal(info.args[i].TypeInfo, qry.values[i])
if err != nil {
return &Iter{err: err}
}
op.Values[i] = val
}
}
resp, err := c.exec(op, qry.trace)
if err != nil {
return &Iter{err: err}
}
switch x := resp.(type) {
case resultVoidFrame:
return &Iter{}
case resultRowsFrame:
iter := &Iter{columns: x.Columns, rows: x.Rows}
if len(x.PagingState) > 0 {
iter.next = &nextIter{
qry: *qry,
pos: int((1 - qry.prefetch) * float64(len(iter.rows))),
}
iter.next.qry.pageState = x.PagingState
if iter.next.pos < 1 {
iter.next.pos = 1
}
}
return iter
case resultKeyspaceFrame:
c.cluster.HandleKeyspace(c, x.Keyspace)
return &Iter{}
case errorFrame:
if x.Code == errUnprepared && len(qry.values) > 0 {
c.prepMu.Lock()
if val, ok := c.prep[qry.stmt]; ok && val != nil {
delete(c.prep, qry.stmt)
c.prepMu.Unlock()
return c.executeQuery(qry)
}
c.prepMu.Unlock()
return &Iter{err: x}
} else {
return &Iter{err: x}
}
case error:
return &Iter{err: x}
default:
return &Iter{err: ErrProtocol}
}
}
func (c *Conn) Pick(qry *Query) *Conn {
return c
}
func (c *Conn) Close() {
c.conn.Close()
}
func (c *Conn) Address() string {
return c.addr
}
func (c *Conn) UseKeyspace(keyspace string) error {
resp, err := c.exec(&queryFrame{Stmt: `USE "` + keyspace + `"`, Cons: Any}, nil)
if err != nil {
return err
}
switch x := resp.(type) {
case resultKeyspaceFrame:
case error:
return x
default:
return ErrProtocol
}
return nil
}
func (c *Conn) executeBatch(batch *Batch) error {
if c.version == 1 {
return ErrUnsupported
}
f := make(frame, headerSize, defaultFrameSize)
f.setHeader(c.version, 0, 0, opBatch)
f.writeByte(byte(batch.Type))
f.writeShort(uint16(len(batch.Entries)))
for i := 0; i < len(batch.Entries); i++ {
entry := &batch.Entries[i]
var info *queryInfo
if len(entry.Args) > 0 {
var err error
info, err = c.prepareStatement(entry.Stmt, nil)
if err != nil {
return err
}
f.writeByte(1)
f.writeShortBytes(info.id)
} else {
f.writeByte(0)
f.writeLongString(entry.Stmt)
}
f.writeShort(uint16(len(entry.Args)))
for j := 0; j < len(entry.Args); j++ {
val, err := Marshal(info.args[j].TypeInfo, entry.Args[j])
if err != nil {
return err
}
f.writeBytes(val)
}
}
f.writeConsistency(batch.Cons)
resp, err := c.exec(f, nil)
if err != nil {
return err
}
switch x := resp.(type) {
case resultVoidFrame:
return nil
case error:
return x
default:
return ErrProtocol
}
}
func (c *Conn) decodeFrame(f frame, trace Tracer) (rval interface{}, err error) {
defer func() {
if r := recover(); r != nil {
if e, ok := r.(error); ok && e == ErrProtocol {
err = e
return
}
panic(r)
}
}()
if len(f) < headerSize || (f[0] != c.version|flagResponse) {
return nil, ErrProtocol
}
flags, op, f := f[1], f[3], f[headerSize:]
if flags&flagCompress != 0 && len(f) > 0 && c.compressor != nil {
if buf, err := c.compressor.Decode([]byte(f)); err != nil {
return nil, err
} else {
f = frame(buf)
}
}
if flags&flagTrace != 0 {
if len(f) < 16 {
return nil, ErrProtocol
}
traceId := []byte(f[:16])
f = f[16:]
trace.Trace(traceId)
}
switch op {
case opReady:
return readyFrame{}, nil
case opResult:
switch kind := f.readInt(); kind {
case resultKindVoid:
return resultVoidFrame{}, nil
case resultKindRows:
columns, pageState := f.readMetaData()
numRows := f.readInt()
values := make([][]byte, numRows*len(columns))
for i := 0; i < len(values); i++ {
values[i] = f.readBytes()
}
rows := make([][][]byte, numRows)
for i := 0; i < numRows; i++ {
rows[i], values = values[:len(columns)], values[len(columns):]
}
return resultRowsFrame{columns, rows, pageState}, nil
case resultKindKeyspace:
keyspace := f.readString()
return resultKeyspaceFrame{keyspace}, nil
case resultKindPrepared:
id := f.readShortBytes()
values, _ := f.readMetaData()
return resultPreparedFrame{id, values}, nil
case resultKindSchemaChanged:
return resultVoidFrame{}, nil
default:
return nil, ErrProtocol
}
case opAuthenticate:
return authenticateFrame{f.readString()}, nil
case opAuthChallenge:
return authChallengeFrame{f.readBytes()}, nil
case opAuthSuccess:
return authSuccessFrame{f.readBytes()}, nil
case opSupported:
return supportedFrame{}, nil
case opError:
code := f.readInt()
msg := f.readString()
return errorFrame{code, msg}, nil
default:
return nil, ErrProtocol
}
}
type queryInfo struct {
id []byte
args []ColumnInfo
rval []ColumnInfo
}
type callReq struct {
active int32
resp chan callResp
}
type callResp struct {
buf frame
err error
}
type Compressor interface {
Name() string
Encode(data []byte) ([]byte, error)
Decode(data []byte) ([]byte, error)
}
type inflightPrepare struct {
info *queryInfo
err error
wg sync.WaitGroup
}
// SnappyCompressor implements the Compressor interface and can be used to
// compress incoming and outgoing frames. The snappy compression algorithm
// aims for very high speeds and reasonable compression.
type SnappyCompressor struct{}
func (s SnappyCompressor) Name() string {
return "snappy"
}
func (s SnappyCompressor) Encode(data []byte) ([]byte, error) {
return snappy.Encode(nil, data)
}
func (s SnappyCompressor) Decode(data []byte) ([]byte, error) {
return snappy.Decode(nil, data)
}