forked from apache/cassandra-gocql-driver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
conn_test.go
673 lines (571 loc) · 15.5 KB
/
conn_test.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
// 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.
// +build all unit
package gocql
import (
"crypto/tls"
"crypto/x509"
"fmt"
"io"
"io/ioutil"
"net"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
)
const (
defaultProto = protoVersion2
)
func TestApprove(t *testing.T) {
tests := map[bool]bool{
approve("org.apache.cassandra.auth.PasswordAuthenticator"): true,
approve("com.instaclustr.cassandra.auth.SharedSecretAuthenticator"): true,
approve("com.apache.cassandra.auth.FakeAuthenticator"): false,
}
for k, v := range tests {
if k != v {
t.Fatalf("expected '%v', got '%v'", k, v)
}
}
}
func TestJoinHostPort(t *testing.T) {
tests := map[string]string{
"127.0.0.1:0": JoinHostPort("127.0.0.1", 0),
"127.0.0.1:1": JoinHostPort("127.0.0.1:1", 9142),
"[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:0": JoinHostPort("2001:0db8:85a3:0000:0000:8a2e:0370:7334", 0),
"[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:1": JoinHostPort("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:1", 9142),
}
for k, v := range tests {
if k != v {
t.Fatalf("expected '%v', got '%v'", k, v)
}
}
}
func TestSimple(t *testing.T) {
srv := NewTestServer(t, defaultProto)
defer srv.Stop()
cluster := NewCluster(srv.Address)
cluster.ProtoVersion = int(defaultProto)
db, err := cluster.CreateSession()
if err != nil {
t.Fatalf("0x%x: NewCluster: %v", defaultProto, err)
}
if err := db.Query("void").Exec(); err != nil {
t.Fatalf("0x%x: %v", defaultProto, err)
}
}
func TestSSLSimple(t *testing.T) {
srv := NewSSLTestServer(t, defaultProto)
defer srv.Stop()
db, err := createTestSslCluster(srv.Address, defaultProto, true).CreateSession()
if err != nil {
t.Fatalf("0x%x: NewCluster: %v", defaultProto, err)
}
if err := db.Query("void").Exec(); err != nil {
t.Fatalf("0x%x: %v", defaultProto, err)
}
}
func TestSSLSimpleNoClientCert(t *testing.T) {
srv := NewSSLTestServer(t, defaultProto)
defer srv.Stop()
db, err := createTestSslCluster(srv.Address, defaultProto, false).CreateSession()
if err != nil {
t.Fatalf("0x%x: NewCluster: %v", defaultProto, err)
}
if err := db.Query("void").Exec(); err != nil {
t.Fatalf("0x%x: %v", defaultProto, err)
}
}
func createTestSslCluster(hosts string, proto uint8, useClientCert bool) *ClusterConfig {
cluster := NewCluster(hosts)
sslOpts := &SslOptions{
CaPath: "testdata/pki/ca.crt",
EnableHostVerification: false,
}
if useClientCert {
sslOpts.CertPath = "testdata/pki/gocql.crt"
sslOpts.KeyPath = "testdata/pki/gocql.key"
}
cluster.SslOpts = sslOpts
cluster.ProtoVersion = int(proto)
return cluster
}
func TestClosed(t *testing.T) {
t.Skip("Skipping the execution of TestClosed for now to try to concentrate on more important test failures on Travis")
srv := NewTestServer(t, defaultProto)
defer srv.Stop()
cluster := NewCluster(srv.Address)
cluster.ProtoVersion = int(defaultProto)
session, err := cluster.CreateSession()
defer session.Close()
if err != nil {
t.Fatalf("0x%x: NewCluster: %v", defaultProto, err)
}
if err := session.Query("void").Exec(); err != ErrSessionClosed {
t.Fatalf("0x%x: expected %#v, got %#v", defaultProto, ErrSessionClosed, err)
}
}
func newTestSession(addr string, proto uint8) (*Session, error) {
cluster := NewCluster(addr)
cluster.ProtoVersion = int(proto)
return cluster.CreateSession()
}
func TestTimeout(t *testing.T) {
srv := NewTestServer(t, defaultProto)
defer srv.Stop()
db, err := newTestSession(srv.Address, defaultProto)
if err != nil {
t.Fatalf("NewCluster: %v", err)
}
defer db.Close()
go func() {
<-time.After(2 * time.Second)
t.Errorf("no timeout")
}()
if err := db.Query("kill").Exec(); err == nil {
t.Errorf("expected error")
}
}
// TestQueryRetry will test to make sure that gocql will execute
// the exact amount of retry queries designated by the user.
func TestQueryRetry(t *testing.T) {
srv := NewTestServer(t, defaultProto)
defer srv.Stop()
db, err := newTestSession(srv.Address, defaultProto)
if err != nil {
t.Fatalf("NewCluster: %v", err)
}
defer db.Close()
go func() {
<-time.After(5 * time.Second)
t.Fatalf("no timeout")
}()
rt := &SimpleRetryPolicy{NumRetries: 1}
qry := db.Query("kill").RetryPolicy(rt)
if err := qry.Exec(); err == nil {
t.Fatalf("expected error")
}
requests := atomic.LoadInt64(&srv.nKillReq)
attempts := qry.Attempts()
if requests != int64(attempts) {
t.Fatalf("expected requests %v to match query attemps %v", requests, attempts)
}
//Minus 1 from the requests variable since there is the initial query attempt
if requests-1 != int64(rt.NumRetries) {
t.Fatalf("failed to retry the query %v time(s). Query executed %v times", rt.NumRetries, requests-1)
}
}
func TestStreams_Protocol1(t *testing.T) {
srv := NewTestServer(t, protoVersion1)
defer srv.Stop()
// TODO: these are more like session tests and should instead operate
// on a single Conn
cluster := NewCluster(srv.Address)
cluster.NumConns = 1
cluster.ProtoVersion = 1
db, err := cluster.CreateSession()
if err != nil {
t.Fatal(err)
}
defer db.Close()
var wg sync.WaitGroup
for i := 1; i < 128; i++ {
// here were just validating that if we send NumStream request we get
// a response for every stream and the lengths for the queries are set
// correctly.
wg.Add(1)
go func() {
defer wg.Done()
if err := db.Query("void").Exec(); err != nil {
t.Error(err)
}
}()
}
wg.Wait()
}
func TestStreams_Protocol3(t *testing.T) {
srv := NewTestServer(t, protoVersion3)
defer srv.Stop()
// TODO: these are more like session tests and should instead operate
// on a single Conn
cluster := NewCluster(srv.Address)
cluster.NumConns = 1
cluster.ProtoVersion = 3
db, err := cluster.CreateSession()
if err != nil {
t.Fatal(err)
}
defer db.Close()
for i := 1; i < 32768; i++ {
// the test server processes each conn synchronously
// here were just validating that if we send NumStream request we get
// a response for every stream and the lengths for the queries are set
// correctly.
if err = db.Query("void").Exec(); err != nil {
t.Fatal(err)
}
}
}
func BenchmarkProtocolV3(b *testing.B) {
srv := NewTestServer(b, protoVersion3)
defer srv.Stop()
// TODO: these are more like session tests and should instead operate
// on a single Conn
cluster := NewCluster(srv.Address)
cluster.NumConns = 1
cluster.ProtoVersion = 3
db, err := cluster.CreateSession()
if err != nil {
b.Fatal(err)
}
defer db.Close()
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
if err = db.Query("void").Exec(); err != nil {
b.Fatal(err)
}
}
}
func TestRoundRobinConnPoolRoundRobin(t *testing.T) {
// create 5 test servers
servers := make([]*TestServer, 5)
addrs := make([]string, len(servers))
for n := 0; n < len(servers); n++ {
servers[n] = NewTestServer(t, defaultProto)
addrs[n] = servers[n].Address
defer servers[n].Stop()
}
// create a new cluster using the policy-based round robin conn pool
cluster := NewCluster(addrs...)
cluster.PoolConfig.HostSelectionPolicy = RoundRobinHostPolicy()
cluster.PoolConfig.ConnSelectionPolicy = RoundRobinConnPolicy()
cluster.disableControlConn = true
db, err := cluster.CreateSession()
if err != nil {
t.Fatalf("failed to create a new session: %v", err)
}
// Sleep to allow the pool to fill
time.Sleep(100 * time.Millisecond)
// run concurrent queries against the pool, server usage should
// be even
var wg sync.WaitGroup
wg.Add(5)
for n := 0; n < 5; n++ {
go func() {
defer wg.Done()
for j := 0; j < 5; j++ {
if err := db.Query("void").Exec(); err != nil {
t.Errorf("Query failed with error: %v", err)
return
}
}
}()
}
wg.Wait()
db.Close()
// wait for the pool to drain
time.Sleep(100 * time.Millisecond)
size := db.pool.Size()
if size != 0 {
t.Errorf("connection pool did not drain, still contains %d connections", size)
}
// verify that server usage is even
diff := 0
for n := 1; n < len(servers); n++ {
d := 0
if servers[n].nreq > servers[n-1].nreq {
d = int(servers[n].nreq - servers[n-1].nreq)
} else {
d = int(servers[n-1].nreq - servers[n].nreq)
}
if d > diff {
diff = d
}
}
if diff > 0 {
t.Fatalf("expected 0 difference in usage but was %d", diff)
}
}
// This tests that the policy connection pool handles SSL correctly
func TestPolicyConnPoolSSL(t *testing.T) {
srv := NewSSLTestServer(t, defaultProto)
defer srv.Stop()
cluster := createTestSslCluster(srv.Address, defaultProto, true)
cluster.PoolConfig.HostSelectionPolicy = RoundRobinHostPolicy()
cluster.PoolConfig.ConnSelectionPolicy = RoundRobinConnPolicy()
db, err := cluster.CreateSession()
if err != nil {
db.Close()
t.Fatalf("failed to create new session: %v", err)
}
if err := db.Query("void").Exec(); err != nil {
t.Fatalf("query failed due to error: %v", err)
}
db.Close()
// wait for the pool to drain
time.Sleep(100 * time.Millisecond)
size := db.pool.Size()
if size != 0 {
t.Fatalf("connection pool did not drain, still contains %d connections", size)
}
}
func TestQueryTimeout(t *testing.T) {
srv := NewTestServer(t, defaultProto)
defer srv.Stop()
cluster := NewCluster(srv.Address)
// Set the timeout arbitrarily low so that the query hits the timeout in a
// timely manner.
cluster.Timeout = 1 * time.Millisecond
db, err := cluster.CreateSession()
if err != nil {
t.Fatalf("NewCluster: %v", err)
}
defer db.Close()
ch := make(chan error, 1)
go func() {
err := db.Query("timeout").Exec()
if err != nil {
ch <- err
return
}
t.Errorf("err was nil, expected to get a timeout after %v", db.cfg.Timeout)
}()
select {
case err := <-ch:
if err != ErrTimeoutNoResponse {
t.Fatalf("expected to get %v for timeout got %v", ErrTimeoutNoResponse, err)
}
case <-time.After(10*time.Millisecond + db.cfg.Timeout):
// ensure that the query goroutines have been scheduled
t.Fatalf("query did not timeout after %v", db.cfg.Timeout)
}
}
func TestQueryTimeoutReuseStream(t *testing.T) {
t.Skip("no longer tests anything")
// TODO(zariel): move this to conn test, we really just want to check what
// happens when a conn is
srv := NewTestServer(t, defaultProto)
defer srv.Stop()
cluster := NewCluster(srv.Address)
// Set the timeout arbitrarily low so that the query hits the timeout in a
// timely manner.
cluster.Timeout = 1 * time.Millisecond
cluster.NumConns = 1
db, err := cluster.CreateSession()
if err != nil {
t.Fatalf("NewCluster: %v", err)
}
defer db.Close()
db.Query("slow").Exec()
err = db.Query("void").Exec()
if err != nil {
t.Fatal(err)
}
}
func TestQueryTimeoutClose(t *testing.T) {
srv := NewTestServer(t, defaultProto)
defer srv.Stop()
cluster := NewCluster(srv.Address)
// Set the timeout arbitrarily low so that the query hits the timeout in a
// timely manner.
cluster.Timeout = 1000 * time.Millisecond
cluster.NumConns = 1
db, err := cluster.CreateSession()
if err != nil {
t.Fatalf("NewCluster: %v", err)
}
ch := make(chan error)
go func() {
err := db.Query("timeout").Exec()
ch <- err
}()
// ensure that the above goroutine gets sheduled
time.Sleep(50 * time.Millisecond)
db.Close()
select {
case err = <-ch:
case <-time.After(1 * time.Second):
t.Fatal("timedout waiting to get a response once cluster is closed")
}
if err != ErrConnectionClosed {
t.Fatalf("expected to get %v got %v", ErrConnectionClosed, err)
}
}
func NewTestServer(t testing.TB, protocol uint8) *TestServer {
laddr, err := net.ResolveTCPAddr("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
listen, err := net.ListenTCP("tcp", laddr)
if err != nil {
t.Fatal(err)
}
headerSize := 8
if protocol > protoVersion2 {
headerSize = 9
}
srv := &TestServer{
Address: listen.Addr().String(),
listen: listen,
t: t,
protocol: protocol,
headerSize: headerSize,
quit: make(chan struct{}),
}
go srv.serve()
return srv
}
func NewSSLTestServer(t testing.TB, protocol uint8) *TestServer {
pem, err := ioutil.ReadFile("testdata/pki/ca.crt")
certPool := x509.NewCertPool()
if !certPool.AppendCertsFromPEM(pem) {
t.Fatalf("Failed parsing or appending certs")
}
mycert, err := tls.LoadX509KeyPair("testdata/pki/cassandra.crt", "testdata/pki/cassandra.key")
if err != nil {
t.Fatalf("could not load cert")
}
config := &tls.Config{
Certificates: []tls.Certificate{mycert},
RootCAs: certPool,
}
listen, err := tls.Listen("tcp", "127.0.0.1:0", config)
if err != nil {
t.Fatal(err)
}
headerSize := 8
if protocol > protoVersion2 {
headerSize = 9
}
srv := &TestServer{
Address: listen.Addr().String(),
listen: listen,
t: t,
protocol: protocol,
headerSize: headerSize,
quit: make(chan struct{}),
}
go srv.serve()
return srv
}
type TestServer struct {
Address string
t testing.TB
nreq uint64
listen net.Listener
nKillReq int64
compressor Compressor
protocol byte
headerSize int
quit chan struct{}
}
func (srv *TestServer) serve() {
defer srv.listen.Close()
for {
conn, err := srv.listen.Accept()
if err != nil {
break
}
go func(conn net.Conn) {
defer conn.Close()
for {
framer, err := srv.readFrame(conn)
if err != nil {
if err == io.EOF {
return
}
srv.t.Error(err)
return
}
atomic.AddUint64(&srv.nreq, 1)
go srv.process(framer)
}
}(conn)
}
}
func (srv *TestServer) Stop() {
srv.listen.Close()
close(srv.quit)
}
func (srv *TestServer) process(f *framer) {
head := f.header
if head == nil {
srv.t.Error("process frame with a nil header")
return
}
switch head.op {
case opStartup:
f.writeHeader(0, opReady, head.stream)
case opOptions:
f.writeHeader(0, opSupported, head.stream)
f.writeShort(0)
case opQuery:
query := f.readLongString()
first := query
if n := strings.Index(query, " "); n > 0 {
first = first[:n]
}
switch strings.ToLower(first) {
case "kill":
atomic.AddInt64(&srv.nKillReq, 1)
f.writeHeader(0, opError, head.stream)
f.writeInt(0x1001)
f.writeString("query killed")
case "use":
f.writeInt(resultKindKeyspace)
f.writeString(strings.TrimSpace(query[3:]))
case "void":
f.writeHeader(0, opResult, head.stream)
f.writeInt(resultKindVoid)
case "timeout":
<-srv.quit
return
case "slow":
go func() {
f.writeHeader(0, opResult, head.stream)
f.writeInt(resultKindVoid)
f.wbuf[0] = srv.protocol | 0x80
select {
case <-srv.quit:
case <-time.After(50 * time.Millisecond):
f.finishWrite()
}
}()
return
default:
f.writeHeader(0, opResult, head.stream)
f.writeInt(resultKindVoid)
}
default:
f.writeHeader(0, opError, head.stream)
f.writeInt(0)
f.writeString("not supported")
}
f.wbuf[0] = srv.protocol | 0x80
if err := f.finishWrite(); err != nil {
srv.t.Error(err)
}
}
func (srv *TestServer) readFrame(conn net.Conn) (*framer, error) {
buf := make([]byte, srv.headerSize)
head, err := readHeader(conn, buf)
if err != nil {
return nil, err
}
framer := newFramer(conn, conn, nil, srv.protocol)
err = framer.readFrame(&head)
if err != nil {
return nil, err
}
// should be a request frame
if head.version.response() {
return nil, fmt.Errorf("expected to read a request frame got version: %v", head.version)
} else if head.version.version() != srv.protocol {
return nil, fmt.Errorf("expected to read protocol version 0x%x got 0x%x", srv.protocol, head.version.version())
}
return framer, nil
}