conn_test.go 24 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001
  1. // Copyright (c) 2012 The gocql Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // +build all unit
  5. package gocql
  6. import (
  7. "bufio"
  8. "bytes"
  9. "context"
  10. "crypto/tls"
  11. "crypto/x509"
  12. "fmt"
  13. "io"
  14. "io/ioutil"
  15. "net"
  16. "os"
  17. "strings"
  18. "sync"
  19. "sync/atomic"
  20. "testing"
  21. "time"
  22. "github.com/gocql/gocql/internal/streams"
  23. )
  24. const (
  25. defaultProto = protoVersion2
  26. )
  27. func TestApprove(t *testing.T) {
  28. tests := map[bool]bool{
  29. approve("org.apache.cassandra.auth.PasswordAuthenticator"): true,
  30. approve("com.instaclustr.cassandra.auth.SharedSecretAuthenticator"): true,
  31. approve("com.datastax.bdp.cassandra.auth.DseAuthenticator"): true,
  32. approve("com.apache.cassandra.auth.FakeAuthenticator"): false,
  33. }
  34. for k, v := range tests {
  35. if k != v {
  36. t.Fatalf("expected '%v', got '%v'", k, v)
  37. }
  38. }
  39. }
  40. func TestJoinHostPort(t *testing.T) {
  41. tests := map[string]string{
  42. "127.0.0.1:0": JoinHostPort("127.0.0.1", 0),
  43. "127.0.0.1:1": JoinHostPort("127.0.0.1:1", 9142),
  44. "[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:0": JoinHostPort("2001:0db8:85a3:0000:0000:8a2e:0370:7334", 0),
  45. "[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:1": JoinHostPort("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:1", 9142),
  46. }
  47. for k, v := range tests {
  48. if k != v {
  49. t.Fatalf("expected '%v', got '%v'", k, v)
  50. }
  51. }
  52. }
  53. func testCluster(addr string, proto protoVersion) *ClusterConfig {
  54. cluster := NewCluster(addr)
  55. cluster.ProtoVersion = int(proto)
  56. cluster.disableControlConn = true
  57. return cluster
  58. }
  59. func TestSimple(t *testing.T) {
  60. srv := NewTestServer(t, defaultProto, context.Background())
  61. defer srv.Stop()
  62. cluster := testCluster(srv.Address, defaultProto)
  63. db, err := cluster.CreateSession()
  64. if err != nil {
  65. t.Fatalf("0x%x: NewCluster: %v", defaultProto, err)
  66. }
  67. if err := db.Query("void").Exec(); err != nil {
  68. t.Fatalf("0x%x: %v", defaultProto, err)
  69. }
  70. }
  71. func TestSSLSimple(t *testing.T) {
  72. srv := NewSSLTestServer(t, defaultProto, context.Background())
  73. defer srv.Stop()
  74. db, err := createTestSslCluster(srv.Address, defaultProto, true).CreateSession()
  75. if err != nil {
  76. t.Fatalf("0x%x: NewCluster: %v", defaultProto, err)
  77. }
  78. if err := db.Query("void").Exec(); err != nil {
  79. t.Fatalf("0x%x: %v", defaultProto, err)
  80. }
  81. }
  82. func TestSSLSimpleNoClientCert(t *testing.T) {
  83. srv := NewSSLTestServer(t, defaultProto, context.Background())
  84. defer srv.Stop()
  85. db, err := createTestSslCluster(srv.Address, defaultProto, false).CreateSession()
  86. if err != nil {
  87. t.Fatalf("0x%x: NewCluster: %v", defaultProto, err)
  88. }
  89. if err := db.Query("void").Exec(); err != nil {
  90. t.Fatalf("0x%x: %v", defaultProto, err)
  91. }
  92. }
  93. func createTestSslCluster(addr string, proto protoVersion, useClientCert bool) *ClusterConfig {
  94. cluster := testCluster(addr, proto)
  95. sslOpts := &SslOptions{
  96. CaPath: "testdata/pki/ca.crt",
  97. EnableHostVerification: false,
  98. }
  99. if useClientCert {
  100. sslOpts.CertPath = "testdata/pki/gocql.crt"
  101. sslOpts.KeyPath = "testdata/pki/gocql.key"
  102. }
  103. cluster.SslOpts = sslOpts
  104. return cluster
  105. }
  106. func TestClosed(t *testing.T) {
  107. t.Skip("Skipping the execution of TestClosed for now to try to concentrate on more important test failures on Travis")
  108. srv := NewTestServer(t, defaultProto, context.Background())
  109. defer srv.Stop()
  110. session, err := newTestSession(srv.Address, defaultProto)
  111. if err != nil {
  112. t.Fatalf("0x%x: NewCluster: %v", defaultProto, err)
  113. }
  114. session.Close()
  115. if err := session.Query("void").Exec(); err != ErrSessionClosed {
  116. t.Fatalf("0x%x: expected %#v, got %#v", defaultProto, ErrSessionClosed, err)
  117. }
  118. }
  119. func newTestSession(addr string, proto protoVersion) (*Session, error) {
  120. return testCluster(addr, proto).CreateSession()
  121. }
  122. func TestDNSLookupConnected(t *testing.T) {
  123. log := &testLogger{}
  124. Logger = log
  125. defer func() {
  126. Logger = &defaultLogger{}
  127. }()
  128. srv := NewTestServer(t, defaultProto, context.Background())
  129. defer srv.Stop()
  130. cluster := NewCluster("cassandra1.invalid", srv.Address, "cassandra2.invalid")
  131. cluster.ProtoVersion = int(defaultProto)
  132. cluster.disableControlConn = true
  133. // CreateSession() should attempt to resolve the DNS name "cassandraX.invalid"
  134. // and fail, but continue to connect via srv.Address
  135. _, err := cluster.CreateSession()
  136. if err != nil {
  137. t.Fatal("CreateSession() should have connected")
  138. }
  139. if !strings.Contains(log.String(), "gocql: dns error") {
  140. t.Fatalf("Expected to receive dns error log message - got '%s' instead", log.String())
  141. }
  142. }
  143. func TestDNSLookupError(t *testing.T) {
  144. log := &testLogger{}
  145. Logger = log
  146. defer func() {
  147. Logger = &defaultLogger{}
  148. }()
  149. srv := NewTestServer(t, defaultProto, context.Background())
  150. defer srv.Stop()
  151. cluster := NewCluster("cassandra1.invalid", "cassandra2.invalid")
  152. cluster.ProtoVersion = int(defaultProto)
  153. cluster.disableControlConn = true
  154. // CreateSession() should attempt to resolve each DNS name "cassandraX.invalid"
  155. // and fail since it could not resolve any dns entries
  156. _, err := cluster.CreateSession()
  157. if err == nil {
  158. t.Fatal("CreateSession() should have returned an error")
  159. }
  160. if !strings.Contains(log.String(), "gocql: dns error") {
  161. t.Fatalf("Expected to receive dns error log message - got '%s' instead", log.String())
  162. }
  163. if err.Error() != "gocql: unable to create session: failed to resolve any of the provided hostnames" {
  164. t.Fatalf("Expected CreateSession() to fail with message - got '%s' instead", err.Error())
  165. }
  166. }
  167. func TestStartupTimeout(t *testing.T) {
  168. ctx, cancel := context.WithCancel(context.Background())
  169. log := &testLogger{}
  170. Logger = log
  171. defer func() {
  172. Logger = &defaultLogger{}
  173. }()
  174. srv := NewTestServer(t, defaultProto, ctx)
  175. defer srv.Stop()
  176. // Tell the server to never respond to Startup frame
  177. atomic.StoreInt32(&srv.TimeoutOnStartup, 1)
  178. startTime := time.Now()
  179. cluster := NewCluster(srv.Address)
  180. cluster.ProtoVersion = int(defaultProto)
  181. cluster.disableControlConn = true
  182. // Set very long query connection timeout
  183. // so we know CreateSession() is using the ConnectTimeout
  184. cluster.Timeout = time.Second * 5
  185. // Create session should timeout during connect attempt
  186. _, err := cluster.CreateSession()
  187. if err == nil {
  188. t.Fatal("CreateSession() should have returned a timeout error")
  189. }
  190. elapsed := time.Since(startTime)
  191. if elapsed > time.Second*5 {
  192. t.Fatal("ConnectTimeout is not respected")
  193. }
  194. if !strings.Contains(err.Error(), "no connections were made when creating the session") {
  195. t.Fatalf("Expected to receive no connections error - got '%s'", err)
  196. }
  197. if !strings.Contains(log.String(), "no response to connection startup within timeout") {
  198. t.Fatalf("Expected to receive timeout log message - got '%s'", log.String())
  199. }
  200. cancel()
  201. }
  202. func TestTimeout(t *testing.T) {
  203. ctx, cancel := context.WithCancel(context.Background())
  204. srv := NewTestServer(t, defaultProto, ctx)
  205. defer srv.Stop()
  206. db, err := newTestSession(srv.Address, defaultProto)
  207. if err != nil {
  208. t.Fatalf("NewCluster: %v", err)
  209. }
  210. defer db.Close()
  211. var wg sync.WaitGroup
  212. wg.Add(1)
  213. go func() {
  214. defer wg.Done()
  215. select {
  216. case <-time.After(5 * time.Second):
  217. t.Errorf("no timeout")
  218. case <-ctx.Done():
  219. }
  220. }()
  221. if err := db.Query("kill").WithContext(ctx).Exec(); err == nil {
  222. t.Fatal("expected error got nil")
  223. }
  224. cancel()
  225. wg.Wait()
  226. }
  227. type testRetryPolicy struct {
  228. numRetries int // maximum number of times to retry a query
  229. attemptTimeout time.Duration
  230. t *testing.T
  231. }
  232. // Attempt tells gocql to attempt the query again based on query.Attempts being less
  233. // than the NumRetries defined in the policy.
  234. func (s *testRetryPolicy) Attempt(q RetryableQuery) bool {
  235. return q.Attempts() <= s.numRetries
  236. }
  237. func (s *testRetryPolicy) GetRetryType(err error) RetryType {
  238. return Retry
  239. }
  240. // AttemptTimeout satisfies the optional RetryPolicyWithAttemptTimeout interface.
  241. func (s *testRetryPolicy) AttemptTimeout() time.Duration {
  242. return s.attemptTimeout
  243. }
  244. type testQueryObserver struct{}
  245. func (o *testQueryObserver) ObserveQuery(ctx context.Context, q ObservedQuery) {
  246. Logger.Printf("Observed query %q. Returned %v rows, took %v on host %q. Error: %q\n", q.Statement, q.Rows, q.End.Sub(q.Start), q.Host.ConnectAddress().String(), q.Err)
  247. }
  248. // TestQueryRetry will test to make sure that gocql will execute
  249. // the exact amount of retry queries designated by the user.
  250. func TestQueryRetry(t *testing.T) {
  251. ctx, cancel := context.WithCancel(context.Background())
  252. defer cancel()
  253. log := &testLogger{}
  254. Logger = log
  255. defer func() {
  256. Logger = &defaultLogger{}
  257. os.Stdout.WriteString(log.String())
  258. }()
  259. srv := NewTestServer(t, defaultProto, ctx)
  260. defer srv.Stop()
  261. db, err := newTestSession(srv.Address, defaultProto)
  262. if err != nil {
  263. t.Fatalf("NewCluster: %v", err)
  264. }
  265. defer db.Close()
  266. go func() {
  267. select {
  268. case <-ctx.Done():
  269. return
  270. case <-time.After(5 * time.Second):
  271. t.Errorf("no timeout")
  272. }
  273. }()
  274. rt := &testRetryPolicy{numRetries: 2, t: t, attemptTimeout: time.Millisecond * 25}
  275. queryCtx, cancel := context.WithTimeout(context.Background(), time.Millisecond*90)
  276. defer cancel()
  277. qry := db.Query("slow").RetryPolicy(rt).Observer(&testQueryObserver{}).WithContext(queryCtx)
  278. if err := qry.Exec(); err == nil {
  279. t.Fatalf("expected error")
  280. }
  281. // wait for the last slow query to finish
  282. // this prevents the test from flaking because of writing to a connection that's been closed
  283. time.Sleep(100 * time.Millisecond)
  284. numQueries := atomic.LoadUint64(&srv.nQueries)
  285. // the 90ms timeout allows at most 4 retries but the maximum is 2 as per the retry policy
  286. // the number of queries therefore needs to be 3 (initial query + 2 retries)
  287. if numQueries != 3 {
  288. t.Fatalf("Number of queries should be 3 but query executed %v times", numQueries)
  289. }
  290. }
  291. func TestStreams_Protocol1(t *testing.T) {
  292. srv := NewTestServer(t, protoVersion1, context.Background())
  293. defer srv.Stop()
  294. // TODO: these are more like session tests and should instead operate
  295. // on a single Conn
  296. cluster := testCluster(srv.Address, protoVersion1)
  297. cluster.NumConns = 1
  298. cluster.ProtoVersion = 1
  299. db, err := cluster.CreateSession()
  300. if err != nil {
  301. t.Fatal(err)
  302. }
  303. defer db.Close()
  304. var wg sync.WaitGroup
  305. for i := 1; i < 128; i++ {
  306. // here were just validating that if we send NumStream request we get
  307. // a response for every stream and the lengths for the queries are set
  308. // correctly.
  309. wg.Add(1)
  310. go func() {
  311. defer wg.Done()
  312. if err := db.Query("void").Exec(); err != nil {
  313. t.Error(err)
  314. }
  315. }()
  316. }
  317. wg.Wait()
  318. }
  319. func TestStreams_Protocol3(t *testing.T) {
  320. srv := NewTestServer(t, protoVersion3, context.Background())
  321. defer srv.Stop()
  322. // TODO: these are more like session tests and should instead operate
  323. // on a single Conn
  324. cluster := testCluster(srv.Address, protoVersion3)
  325. cluster.NumConns = 1
  326. cluster.ProtoVersion = 3
  327. db, err := cluster.CreateSession()
  328. if err != nil {
  329. t.Fatal(err)
  330. }
  331. defer db.Close()
  332. for i := 1; i < 32768; i++ {
  333. // the test server processes each conn synchronously
  334. // here were just validating that if we send NumStream request we get
  335. // a response for every stream and the lengths for the queries are set
  336. // correctly.
  337. if err = db.Query("void").Exec(); err != nil {
  338. t.Fatal(err)
  339. }
  340. }
  341. }
  342. func BenchmarkProtocolV3(b *testing.B) {
  343. srv := NewTestServer(b, protoVersion3, context.Background())
  344. defer srv.Stop()
  345. // TODO: these are more like session tests and should instead operate
  346. // on a single Conn
  347. cluster := NewCluster(srv.Address)
  348. cluster.NumConns = 1
  349. cluster.ProtoVersion = 3
  350. db, err := cluster.CreateSession()
  351. if err != nil {
  352. b.Fatal(err)
  353. }
  354. defer db.Close()
  355. b.ResetTimer()
  356. b.ReportAllocs()
  357. for i := 0; i < b.N; i++ {
  358. if err = db.Query("void").Exec(); err != nil {
  359. b.Fatal(err)
  360. }
  361. }
  362. }
  363. // This tests that the policy connection pool handles SSL correctly
  364. func TestPolicyConnPoolSSL(t *testing.T) {
  365. srv := NewSSLTestServer(t, defaultProto, context.Background())
  366. defer srv.Stop()
  367. cluster := createTestSslCluster(srv.Address, defaultProto, true)
  368. cluster.PoolConfig.HostSelectionPolicy = RoundRobinHostPolicy()
  369. db, err := cluster.CreateSession()
  370. if err != nil {
  371. t.Fatalf("failed to create new session: %v", err)
  372. }
  373. if err := db.Query("void").Exec(); err != nil {
  374. t.Fatalf("query failed due to error: %v", err)
  375. }
  376. db.Close()
  377. // wait for the pool to drain
  378. time.Sleep(100 * time.Millisecond)
  379. size := db.pool.Size()
  380. if size != 0 {
  381. t.Fatalf("connection pool did not drain, still contains %d connections", size)
  382. }
  383. }
  384. func TestQueryTimeout(t *testing.T) {
  385. srv := NewTestServer(t, defaultProto, context.Background())
  386. defer srv.Stop()
  387. cluster := testCluster(srv.Address, defaultProto)
  388. // Set the timeout arbitrarily low so that the query hits the timeout in a
  389. // timely manner.
  390. cluster.Timeout = 1 * time.Millisecond
  391. db, err := cluster.CreateSession()
  392. if err != nil {
  393. t.Fatalf("NewCluster: %v", err)
  394. }
  395. defer db.Close()
  396. ch := make(chan error, 1)
  397. go func() {
  398. err := db.Query("timeout").Exec()
  399. if err != nil {
  400. ch <- err
  401. return
  402. }
  403. t.Errorf("err was nil, expected to get a timeout after %v", db.cfg.Timeout)
  404. }()
  405. select {
  406. case err := <-ch:
  407. if err != ErrTimeoutNoResponse {
  408. t.Fatalf("expected to get %v for timeout got %v", ErrTimeoutNoResponse, err)
  409. }
  410. case <-time.After(10*time.Millisecond + db.cfg.Timeout):
  411. // ensure that the query goroutines have been scheduled
  412. t.Fatalf("query did not timeout after %v", db.cfg.Timeout)
  413. }
  414. }
  415. func BenchmarkSingleConn(b *testing.B) {
  416. srv := NewTestServer(b, 3, context.Background())
  417. defer srv.Stop()
  418. cluster := testCluster(srv.Address, 3)
  419. // Set the timeout arbitrarily low so that the query hits the timeout in a
  420. // timely manner.
  421. cluster.Timeout = 500 * time.Millisecond
  422. cluster.NumConns = 1
  423. db, err := cluster.CreateSession()
  424. if err != nil {
  425. b.Fatalf("NewCluster: %v", err)
  426. }
  427. defer db.Close()
  428. b.ResetTimer()
  429. b.RunParallel(func(pb *testing.PB) {
  430. for pb.Next() {
  431. err := db.Query("void").Exec()
  432. if err != nil {
  433. b.Error(err)
  434. return
  435. }
  436. }
  437. })
  438. }
  439. func TestQueryTimeoutReuseStream(t *testing.T) {
  440. t.Skip("no longer tests anything")
  441. // TODO(zariel): move this to conn test, we really just want to check what
  442. // happens when a conn is
  443. srv := NewTestServer(t, defaultProto, context.Background())
  444. defer srv.Stop()
  445. cluster := testCluster(srv.Address, defaultProto)
  446. // Set the timeout arbitrarily low so that the query hits the timeout in a
  447. // timely manner.
  448. cluster.Timeout = 1 * time.Millisecond
  449. cluster.NumConns = 1
  450. db, err := cluster.CreateSession()
  451. if err != nil {
  452. t.Fatalf("NewCluster: %v", err)
  453. }
  454. defer db.Close()
  455. db.Query("slow").Exec()
  456. err = db.Query("void").Exec()
  457. if err != nil {
  458. t.Fatal(err)
  459. }
  460. }
  461. func TestQueryTimeoutClose(t *testing.T) {
  462. srv := NewTestServer(t, defaultProto, context.Background())
  463. defer srv.Stop()
  464. cluster := testCluster(srv.Address, defaultProto)
  465. // Set the timeout arbitrarily low so that the query hits the timeout in a
  466. // timely manner.
  467. cluster.Timeout = 1000 * time.Millisecond
  468. cluster.NumConns = 1
  469. db, err := cluster.CreateSession()
  470. if err != nil {
  471. t.Fatalf("NewCluster: %v", err)
  472. }
  473. ch := make(chan error)
  474. go func() {
  475. err := db.Query("timeout").Exec()
  476. ch <- err
  477. }()
  478. // ensure that the above goroutine gets sheduled
  479. time.Sleep(50 * time.Millisecond)
  480. db.Close()
  481. select {
  482. case err = <-ch:
  483. case <-time.After(1 * time.Second):
  484. t.Fatal("timedout waiting to get a response once cluster is closed")
  485. }
  486. if err != ErrConnectionClosed {
  487. t.Fatalf("expected to get %v got %v", ErrConnectionClosed, err)
  488. }
  489. }
  490. func TestStream0(t *testing.T) {
  491. // TODO: replace this with type check
  492. const expErr = "gocql: received unexpected frame on stream 0"
  493. var buf bytes.Buffer
  494. f := newFramer(nil, &buf, nil, protoVersion4)
  495. f.writeHeader(0, opResult, 0)
  496. f.writeInt(resultKindVoid)
  497. f.wbuf[0] |= 0x80
  498. if err := f.finishWrite(); err != nil {
  499. t.Fatal(err)
  500. }
  501. conn := &Conn{
  502. r: bufio.NewReader(&buf),
  503. streams: streams.New(protoVersion4),
  504. }
  505. err := conn.recv()
  506. if err == nil {
  507. t.Fatal("expected to get an error on stream 0")
  508. } else if !strings.HasPrefix(err.Error(), expErr) {
  509. t.Fatalf("expected to get error prefix %q got %q", expErr, err.Error())
  510. }
  511. }
  512. func TestConnClosedBlocked(t *testing.T) {
  513. t.Skip("FLAKE: skipping test flake see https://github.com/gocql/gocql/issues/1088")
  514. // issue 664
  515. const proto = 3
  516. srv := NewTestServer(t, proto, context.Background())
  517. defer srv.Stop()
  518. errorHandler := connErrorHandlerFn(func(conn *Conn, err error, closed bool) {
  519. t.Log(err)
  520. })
  521. s, err := srv.session()
  522. if err != nil {
  523. t.Fatal(err)
  524. }
  525. defer s.Close()
  526. conn, err := s.connect(srv.host(), errorHandler)
  527. if err != nil {
  528. t.Fatal(err)
  529. }
  530. if err := conn.conn.Close(); err != nil {
  531. t.Fatal(err)
  532. }
  533. // This will block indefintaly if #664 is not fixed
  534. err = conn.executeQuery(&Query{stmt: "void"}).Close()
  535. if !strings.HasSuffix(err.Error(), "use of closed network connection") {
  536. t.Fatalf("expected to get use of closed networking connection error got: %v\n", err)
  537. }
  538. }
  539. func TestContext_Timeout(t *testing.T) {
  540. srv := NewTestServer(t, defaultProto, context.Background())
  541. defer srv.Stop()
  542. cluster := testCluster(srv.Address, defaultProto)
  543. cluster.Timeout = 5 * time.Second
  544. db, err := cluster.CreateSession()
  545. if err != nil {
  546. t.Fatal(err)
  547. }
  548. defer db.Close()
  549. ctx, cancel := context.WithCancel(context.Background())
  550. cancel()
  551. err = db.Query("timeout").WithContext(ctx).Exec()
  552. if err != context.Canceled {
  553. t.Fatalf("expected to get context cancel error: %v got %v", context.Canceled, err)
  554. }
  555. }
  556. type recordingFrameHeaderObserver struct {
  557. t *testing.T
  558. mu sync.Mutex
  559. frames []ObservedFrameHeader
  560. }
  561. func (r *recordingFrameHeaderObserver) ObserveFrameHeader(ctx context.Context, frm ObservedFrameHeader) {
  562. r.mu.Lock()
  563. r.frames = append(r.frames, frm)
  564. r.mu.Unlock()
  565. }
  566. func (r *recordingFrameHeaderObserver) getFrames() []ObservedFrameHeader {
  567. r.mu.Lock()
  568. defer r.mu.Unlock()
  569. return r.frames
  570. }
  571. func TestFrameHeaderObserver(t *testing.T) {
  572. srv := NewTestServer(t, defaultProto, context.Background())
  573. defer srv.Stop()
  574. cluster := testCluster(srv.Address, defaultProto)
  575. cluster.NumConns = 1
  576. observer := &recordingFrameHeaderObserver{t: t}
  577. cluster.FrameHeaderObserver = observer
  578. db, err := cluster.CreateSession()
  579. if err != nil {
  580. t.Fatal(err)
  581. }
  582. if err := db.Query("void").Exec(); err != nil {
  583. t.Fatal(err)
  584. }
  585. frames := observer.getFrames()
  586. if len(frames) != 2 {
  587. t.Fatalf("Expected to receive 2 frames, instead received %d", len(frames))
  588. }
  589. readyFrame := frames[0]
  590. if readyFrame.Opcode != frameOp(opReady) {
  591. t.Fatalf("Expected to receive ready frame, instead received frame of opcode %d", readyFrame.Opcode)
  592. }
  593. voidResultFrame := frames[1]
  594. if voidResultFrame.Opcode != frameOp(opResult) {
  595. t.Fatalf("Expected to receive result frame, instead received frame of opcode %d", voidResultFrame.Opcode)
  596. }
  597. if voidResultFrame.Length != int32(4) {
  598. t.Fatalf("Expected to receive frame with body length 4, instead received body length %d", voidResultFrame.Length)
  599. }
  600. }
  601. func NewTestServer(t testing.TB, protocol uint8, ctx context.Context) *TestServer {
  602. laddr, err := net.ResolveTCPAddr("tcp", "127.0.0.1:0")
  603. if err != nil {
  604. t.Fatal(err)
  605. }
  606. listen, err := net.ListenTCP("tcp", laddr)
  607. if err != nil {
  608. t.Fatal(err)
  609. }
  610. headerSize := 8
  611. if protocol > protoVersion2 {
  612. headerSize = 9
  613. }
  614. ctx, cancel := context.WithCancel(ctx)
  615. srv := &TestServer{
  616. Address: listen.Addr().String(),
  617. listen: listen,
  618. t: t,
  619. protocol: protocol,
  620. headerSize: headerSize,
  621. ctx: ctx,
  622. cancel: cancel,
  623. }
  624. go srv.closeWatch()
  625. go srv.serve()
  626. return srv
  627. }
  628. func NewSSLTestServer(t testing.TB, protocol uint8, ctx context.Context) *TestServer {
  629. pem, err := ioutil.ReadFile("testdata/pki/ca.crt")
  630. certPool := x509.NewCertPool()
  631. if !certPool.AppendCertsFromPEM(pem) {
  632. t.Fatalf("Failed parsing or appending certs")
  633. }
  634. mycert, err := tls.LoadX509KeyPair("testdata/pki/cassandra.crt", "testdata/pki/cassandra.key")
  635. if err != nil {
  636. t.Fatalf("could not load cert")
  637. }
  638. config := &tls.Config{
  639. Certificates: []tls.Certificate{mycert},
  640. RootCAs: certPool,
  641. }
  642. listen, err := tls.Listen("tcp", "127.0.0.1:0", config)
  643. if err != nil {
  644. t.Fatal(err)
  645. }
  646. headerSize := 8
  647. if protocol > protoVersion2 {
  648. headerSize = 9
  649. }
  650. ctx, cancel := context.WithCancel(ctx)
  651. srv := &TestServer{
  652. Address: listen.Addr().String(),
  653. listen: listen,
  654. t: t,
  655. protocol: protocol,
  656. headerSize: headerSize,
  657. ctx: ctx,
  658. cancel: cancel,
  659. }
  660. go srv.closeWatch()
  661. go srv.serve()
  662. return srv
  663. }
  664. type TestServer struct {
  665. Address string
  666. TimeoutOnStartup int32
  667. t testing.TB
  668. nreq uint64
  669. listen net.Listener
  670. nKillReq int64
  671. nQueries uint64
  672. compressor Compressor
  673. protocol byte
  674. headerSize int
  675. ctx context.Context
  676. cancel context.CancelFunc
  677. quit chan struct{}
  678. mu sync.Mutex
  679. closed bool
  680. }
  681. func (srv *TestServer) session() (*Session, error) {
  682. return testCluster(srv.Address, protoVersion(srv.protocol)).CreateSession()
  683. }
  684. func (srv *TestServer) host() *HostInfo {
  685. hosts, err := hostInfo(srv.Address, 9042)
  686. if err != nil {
  687. srv.t.Fatal(err)
  688. }
  689. return hosts[0]
  690. }
  691. func (srv *TestServer) closeWatch() {
  692. <-srv.ctx.Done()
  693. srv.mu.Lock()
  694. defer srv.mu.Unlock()
  695. srv.closeLocked()
  696. }
  697. func (srv *TestServer) serve() {
  698. defer srv.listen.Close()
  699. for !srv.isClosed() {
  700. conn, err := srv.listen.Accept()
  701. if err != nil {
  702. break
  703. }
  704. go func(conn net.Conn) {
  705. defer conn.Close()
  706. for !srv.isClosed() {
  707. framer, err := srv.readFrame(conn)
  708. if err != nil {
  709. if err == io.EOF {
  710. return
  711. }
  712. srv.errorLocked(err)
  713. return
  714. }
  715. atomic.AddUint64(&srv.nreq, 1)
  716. go srv.process(framer)
  717. }
  718. }(conn)
  719. }
  720. }
  721. func (srv *TestServer) isClosed() bool {
  722. srv.mu.Lock()
  723. defer srv.mu.Unlock()
  724. return srv.closed
  725. }
  726. func (srv *TestServer) closeLocked() {
  727. if srv.closed {
  728. return
  729. }
  730. srv.closed = true
  731. srv.listen.Close()
  732. srv.cancel()
  733. }
  734. func (srv *TestServer) Stop() {
  735. srv.mu.Lock()
  736. defer srv.mu.Unlock()
  737. srv.closeLocked()
  738. }
  739. func (srv *TestServer) errorLocked(err interface{}) {
  740. srv.mu.Lock()
  741. defer srv.mu.Unlock()
  742. if srv.closed {
  743. return
  744. }
  745. srv.t.Error(err)
  746. }
  747. func (srv *TestServer) process(f *framer) {
  748. head := f.header
  749. if head == nil {
  750. srv.errorLocked("process frame with a nil header")
  751. return
  752. }
  753. switch head.op {
  754. case opStartup:
  755. if atomic.LoadInt32(&srv.TimeoutOnStartup) > 0 {
  756. // Do not respond to startup command
  757. // wait until we get a cancel signal
  758. select {
  759. case <-srv.ctx.Done():
  760. return
  761. }
  762. }
  763. f.writeHeader(0, opReady, head.stream)
  764. case opOptions:
  765. f.writeHeader(0, opSupported, head.stream)
  766. f.writeShort(0)
  767. case opQuery:
  768. atomic.AddUint64(&srv.nQueries, 1)
  769. query := f.readLongString()
  770. first := query
  771. if n := strings.Index(query, " "); n > 0 {
  772. first = first[:n]
  773. }
  774. switch strings.ToLower(first) {
  775. case "kill":
  776. atomic.AddInt64(&srv.nKillReq, 1)
  777. f.writeHeader(0, opError, head.stream)
  778. f.writeInt(0x1001)
  779. f.writeString("query killed")
  780. case "use":
  781. f.writeInt(resultKindKeyspace)
  782. f.writeString(strings.TrimSpace(query[3:]))
  783. case "void":
  784. f.writeHeader(0, opResult, head.stream)
  785. f.writeInt(resultKindVoid)
  786. case "timeout":
  787. <-srv.ctx.Done()
  788. return
  789. case "slow":
  790. go func() {
  791. f.writeHeader(0, opResult, head.stream)
  792. f.writeInt(resultKindVoid)
  793. f.wbuf[0] = srv.protocol | 0x80
  794. select {
  795. case <-srv.ctx.Done():
  796. return
  797. case <-time.After(50 * time.Millisecond):
  798. f.finishWrite()
  799. }
  800. }()
  801. return
  802. default:
  803. f.writeHeader(0, opResult, head.stream)
  804. f.writeInt(resultKindVoid)
  805. }
  806. case opError:
  807. f.writeHeader(0, opError, head.stream)
  808. f.wbuf = append(f.wbuf, f.rbuf...)
  809. default:
  810. f.writeHeader(0, opError, head.stream)
  811. f.writeInt(0)
  812. f.writeString("not supported")
  813. }
  814. f.wbuf[0] = srv.protocol | 0x80
  815. if err := f.finishWrite(); err != nil {
  816. srv.errorLocked(err)
  817. }
  818. }
  819. func (srv *TestServer) readFrame(conn net.Conn) (*framer, error) {
  820. buf := make([]byte, srv.headerSize)
  821. head, err := readHeader(conn, buf)
  822. if err != nil {
  823. return nil, err
  824. }
  825. framer := newFramer(conn, conn, nil, srv.protocol)
  826. err = framer.readFrame(&head)
  827. if err != nil {
  828. return nil, err
  829. }
  830. // should be a request frame
  831. if head.version.response() {
  832. return nil, fmt.Errorf("expected to read a request frame got version: %v", head.version)
  833. } else if head.version.version() != srv.protocol {
  834. return nil, fmt.Errorf("expected to read protocol version 0x%x got 0x%x", srv.protocol, head.version.version())
  835. }
  836. return framer, nil
  837. }