conn_test.go 24 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004
  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: 10, 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
  286. if numQueries > 4 {
  287. t.Fatalf("Too many retries executed for query. Query executed %v times", numQueries)
  288. }
  289. // make sure query is retried to guard against regressions
  290. if numQueries < 2 {
  291. t.Fatalf("Not enough retries executed for query. Query executed %v times", numQueries)
  292. }
  293. }
  294. func TestStreams_Protocol1(t *testing.T) {
  295. srv := NewTestServer(t, protoVersion1, context.Background())
  296. defer srv.Stop()
  297. // TODO: these are more like session tests and should instead operate
  298. // on a single Conn
  299. cluster := testCluster(srv.Address, protoVersion1)
  300. cluster.NumConns = 1
  301. cluster.ProtoVersion = 1
  302. db, err := cluster.CreateSession()
  303. if err != nil {
  304. t.Fatal(err)
  305. }
  306. defer db.Close()
  307. var wg sync.WaitGroup
  308. for i := 1; i < 128; i++ {
  309. // here were just validating that if we send NumStream request we get
  310. // a response for every stream and the lengths for the queries are set
  311. // correctly.
  312. wg.Add(1)
  313. go func() {
  314. defer wg.Done()
  315. if err := db.Query("void").Exec(); err != nil {
  316. t.Error(err)
  317. }
  318. }()
  319. }
  320. wg.Wait()
  321. }
  322. func TestStreams_Protocol3(t *testing.T) {
  323. srv := NewTestServer(t, protoVersion3, context.Background())
  324. defer srv.Stop()
  325. // TODO: these are more like session tests and should instead operate
  326. // on a single Conn
  327. cluster := testCluster(srv.Address, protoVersion3)
  328. cluster.NumConns = 1
  329. cluster.ProtoVersion = 3
  330. db, err := cluster.CreateSession()
  331. if err != nil {
  332. t.Fatal(err)
  333. }
  334. defer db.Close()
  335. for i := 1; i < 32768; i++ {
  336. // the test server processes each conn synchronously
  337. // here were just validating that if we send NumStream request we get
  338. // a response for every stream and the lengths for the queries are set
  339. // correctly.
  340. if err = db.Query("void").Exec(); err != nil {
  341. t.Fatal(err)
  342. }
  343. }
  344. }
  345. func BenchmarkProtocolV3(b *testing.B) {
  346. srv := NewTestServer(b, protoVersion3, context.Background())
  347. defer srv.Stop()
  348. // TODO: these are more like session tests and should instead operate
  349. // on a single Conn
  350. cluster := NewCluster(srv.Address)
  351. cluster.NumConns = 1
  352. cluster.ProtoVersion = 3
  353. db, err := cluster.CreateSession()
  354. if err != nil {
  355. b.Fatal(err)
  356. }
  357. defer db.Close()
  358. b.ResetTimer()
  359. b.ReportAllocs()
  360. for i := 0; i < b.N; i++ {
  361. if err = db.Query("void").Exec(); err != nil {
  362. b.Fatal(err)
  363. }
  364. }
  365. }
  366. // This tests that the policy connection pool handles SSL correctly
  367. func TestPolicyConnPoolSSL(t *testing.T) {
  368. srv := NewSSLTestServer(t, defaultProto, context.Background())
  369. defer srv.Stop()
  370. cluster := createTestSslCluster(srv.Address, defaultProto, true)
  371. cluster.PoolConfig.HostSelectionPolicy = RoundRobinHostPolicy()
  372. db, err := cluster.CreateSession()
  373. if err != nil {
  374. t.Fatalf("failed to create new session: %v", err)
  375. }
  376. if err := db.Query("void").Exec(); err != nil {
  377. t.Fatalf("query failed due to error: %v", err)
  378. }
  379. db.Close()
  380. // wait for the pool to drain
  381. time.Sleep(100 * time.Millisecond)
  382. size := db.pool.Size()
  383. if size != 0 {
  384. t.Fatalf("connection pool did not drain, still contains %d connections", size)
  385. }
  386. }
  387. func TestQueryTimeout(t *testing.T) {
  388. srv := NewTestServer(t, defaultProto, context.Background())
  389. defer srv.Stop()
  390. cluster := testCluster(srv.Address, defaultProto)
  391. // Set the timeout arbitrarily low so that the query hits the timeout in a
  392. // timely manner.
  393. cluster.Timeout = 1 * time.Millisecond
  394. db, err := cluster.CreateSession()
  395. if err != nil {
  396. t.Fatalf("NewCluster: %v", err)
  397. }
  398. defer db.Close()
  399. ch := make(chan error, 1)
  400. go func() {
  401. err := db.Query("timeout").Exec()
  402. if err != nil {
  403. ch <- err
  404. return
  405. }
  406. t.Errorf("err was nil, expected to get a timeout after %v", db.cfg.Timeout)
  407. }()
  408. select {
  409. case err := <-ch:
  410. if err != ErrTimeoutNoResponse {
  411. t.Fatalf("expected to get %v for timeout got %v", ErrTimeoutNoResponse, err)
  412. }
  413. case <-time.After(10*time.Millisecond + db.cfg.Timeout):
  414. // ensure that the query goroutines have been scheduled
  415. t.Fatalf("query did not timeout after %v", db.cfg.Timeout)
  416. }
  417. }
  418. func BenchmarkSingleConn(b *testing.B) {
  419. srv := NewTestServer(b, 3, context.Background())
  420. defer srv.Stop()
  421. cluster := testCluster(srv.Address, 3)
  422. // Set the timeout arbitrarily low so that the query hits the timeout in a
  423. // timely manner.
  424. cluster.Timeout = 500 * time.Millisecond
  425. cluster.NumConns = 1
  426. db, err := cluster.CreateSession()
  427. if err != nil {
  428. b.Fatalf("NewCluster: %v", err)
  429. }
  430. defer db.Close()
  431. b.ResetTimer()
  432. b.RunParallel(func(pb *testing.PB) {
  433. for pb.Next() {
  434. err := db.Query("void").Exec()
  435. if err != nil {
  436. b.Error(err)
  437. return
  438. }
  439. }
  440. })
  441. }
  442. func TestQueryTimeoutReuseStream(t *testing.T) {
  443. t.Skip("no longer tests anything")
  444. // TODO(zariel): move this to conn test, we really just want to check what
  445. // happens when a conn is
  446. srv := NewTestServer(t, defaultProto, context.Background())
  447. defer srv.Stop()
  448. cluster := testCluster(srv.Address, defaultProto)
  449. // Set the timeout arbitrarily low so that the query hits the timeout in a
  450. // timely manner.
  451. cluster.Timeout = 1 * time.Millisecond
  452. cluster.NumConns = 1
  453. db, err := cluster.CreateSession()
  454. if err != nil {
  455. t.Fatalf("NewCluster: %v", err)
  456. }
  457. defer db.Close()
  458. db.Query("slow").Exec()
  459. err = db.Query("void").Exec()
  460. if err != nil {
  461. t.Fatal(err)
  462. }
  463. }
  464. func TestQueryTimeoutClose(t *testing.T) {
  465. srv := NewTestServer(t, defaultProto, context.Background())
  466. defer srv.Stop()
  467. cluster := testCluster(srv.Address, defaultProto)
  468. // Set the timeout arbitrarily low so that the query hits the timeout in a
  469. // timely manner.
  470. cluster.Timeout = 1000 * time.Millisecond
  471. cluster.NumConns = 1
  472. db, err := cluster.CreateSession()
  473. if err != nil {
  474. t.Fatalf("NewCluster: %v", err)
  475. }
  476. ch := make(chan error)
  477. go func() {
  478. err := db.Query("timeout").Exec()
  479. ch <- err
  480. }()
  481. // ensure that the above goroutine gets sheduled
  482. time.Sleep(50 * time.Millisecond)
  483. db.Close()
  484. select {
  485. case err = <-ch:
  486. case <-time.After(1 * time.Second):
  487. t.Fatal("timedout waiting to get a response once cluster is closed")
  488. }
  489. if err != ErrConnectionClosed {
  490. t.Fatalf("expected to get %v got %v", ErrConnectionClosed, err)
  491. }
  492. }
  493. func TestStream0(t *testing.T) {
  494. // TODO: replace this with type check
  495. const expErr = "gocql: received unexpected frame on stream 0"
  496. var buf bytes.Buffer
  497. f := newFramer(nil, &buf, nil, protoVersion4)
  498. f.writeHeader(0, opResult, 0)
  499. f.writeInt(resultKindVoid)
  500. f.wbuf[0] |= 0x80
  501. if err := f.finishWrite(); err != nil {
  502. t.Fatal(err)
  503. }
  504. conn := &Conn{
  505. r: bufio.NewReader(&buf),
  506. streams: streams.New(protoVersion4),
  507. }
  508. err := conn.recv()
  509. if err == nil {
  510. t.Fatal("expected to get an error on stream 0")
  511. } else if !strings.HasPrefix(err.Error(), expErr) {
  512. t.Fatalf("expected to get error prefix %q got %q", expErr, err.Error())
  513. }
  514. }
  515. func TestConnClosedBlocked(t *testing.T) {
  516. t.Skip("FLAKE: skipping test flake see https://github.com/gocql/gocql/issues/1088")
  517. // issue 664
  518. const proto = 3
  519. srv := NewTestServer(t, proto, context.Background())
  520. defer srv.Stop()
  521. errorHandler := connErrorHandlerFn(func(conn *Conn, err error, closed bool) {
  522. t.Log(err)
  523. })
  524. s, err := srv.session()
  525. if err != nil {
  526. t.Fatal(err)
  527. }
  528. defer s.Close()
  529. conn, err := s.connect(srv.host(), errorHandler)
  530. if err != nil {
  531. t.Fatal(err)
  532. }
  533. if err := conn.conn.Close(); err != nil {
  534. t.Fatal(err)
  535. }
  536. // This will block indefintaly if #664 is not fixed
  537. err = conn.executeQuery(&Query{stmt: "void"}).Close()
  538. if !strings.HasSuffix(err.Error(), "use of closed network connection") {
  539. t.Fatalf("expected to get use of closed networking connection error got: %v\n", err)
  540. }
  541. }
  542. func TestContext_Timeout(t *testing.T) {
  543. srv := NewTestServer(t, defaultProto, context.Background())
  544. defer srv.Stop()
  545. cluster := testCluster(srv.Address, defaultProto)
  546. cluster.Timeout = 5 * time.Second
  547. db, err := cluster.CreateSession()
  548. if err != nil {
  549. t.Fatal(err)
  550. }
  551. defer db.Close()
  552. ctx, cancel := context.WithCancel(context.Background())
  553. cancel()
  554. err = db.Query("timeout").WithContext(ctx).Exec()
  555. if err != context.Canceled {
  556. t.Fatalf("expected to get context cancel error: %v got %v", context.Canceled, err)
  557. }
  558. }
  559. type recordingFrameHeaderObserver struct {
  560. t *testing.T
  561. mu sync.Mutex
  562. frames []ObservedFrameHeader
  563. }
  564. func (r *recordingFrameHeaderObserver) ObserveFrameHeader(ctx context.Context, frm ObservedFrameHeader) {
  565. r.mu.Lock()
  566. r.frames = append(r.frames, frm)
  567. r.mu.Unlock()
  568. }
  569. func (r *recordingFrameHeaderObserver) getFrames() []ObservedFrameHeader {
  570. r.mu.Lock()
  571. defer r.mu.Unlock()
  572. return r.frames
  573. }
  574. func TestFrameHeaderObserver(t *testing.T) {
  575. srv := NewTestServer(t, defaultProto, context.Background())
  576. defer srv.Stop()
  577. cluster := testCluster(srv.Address, defaultProto)
  578. cluster.NumConns = 1
  579. observer := &recordingFrameHeaderObserver{t: t}
  580. cluster.FrameHeaderObserver = observer
  581. db, err := cluster.CreateSession()
  582. if err != nil {
  583. t.Fatal(err)
  584. }
  585. if err := db.Query("void").Exec(); err != nil {
  586. t.Fatal(err)
  587. }
  588. frames := observer.getFrames()
  589. if len(frames) != 2 {
  590. t.Fatalf("Expected to receive 2 frames, instead received %d", len(frames))
  591. }
  592. readyFrame := frames[0]
  593. if readyFrame.Opcode != frameOp(opReady) {
  594. t.Fatalf("Expected to receive ready frame, instead received frame of opcode %d", readyFrame.Opcode)
  595. }
  596. voidResultFrame := frames[1]
  597. if voidResultFrame.Opcode != frameOp(opResult) {
  598. t.Fatalf("Expected to receive result frame, instead received frame of opcode %d", voidResultFrame.Opcode)
  599. }
  600. if voidResultFrame.Length != int32(4) {
  601. t.Fatalf("Expected to receive frame with body length 4, instead received body length %d", voidResultFrame.Length)
  602. }
  603. }
  604. func NewTestServer(t testing.TB, protocol uint8, ctx context.Context) *TestServer {
  605. laddr, err := net.ResolveTCPAddr("tcp", "127.0.0.1:0")
  606. if err != nil {
  607. t.Fatal(err)
  608. }
  609. listen, err := net.ListenTCP("tcp", laddr)
  610. if err != nil {
  611. t.Fatal(err)
  612. }
  613. headerSize := 8
  614. if protocol > protoVersion2 {
  615. headerSize = 9
  616. }
  617. ctx, cancel := context.WithCancel(ctx)
  618. srv := &TestServer{
  619. Address: listen.Addr().String(),
  620. listen: listen,
  621. t: t,
  622. protocol: protocol,
  623. headerSize: headerSize,
  624. ctx: ctx,
  625. cancel: cancel,
  626. }
  627. go srv.closeWatch()
  628. go srv.serve()
  629. return srv
  630. }
  631. func NewSSLTestServer(t testing.TB, protocol uint8, ctx context.Context) *TestServer {
  632. pem, err := ioutil.ReadFile("testdata/pki/ca.crt")
  633. certPool := x509.NewCertPool()
  634. if !certPool.AppendCertsFromPEM(pem) {
  635. t.Fatalf("Failed parsing or appending certs")
  636. }
  637. mycert, err := tls.LoadX509KeyPair("testdata/pki/cassandra.crt", "testdata/pki/cassandra.key")
  638. if err != nil {
  639. t.Fatalf("could not load cert")
  640. }
  641. config := &tls.Config{
  642. Certificates: []tls.Certificate{mycert},
  643. RootCAs: certPool,
  644. }
  645. listen, err := tls.Listen("tcp", "127.0.0.1:0", config)
  646. if err != nil {
  647. t.Fatal(err)
  648. }
  649. headerSize := 8
  650. if protocol > protoVersion2 {
  651. headerSize = 9
  652. }
  653. ctx, cancel := context.WithCancel(ctx)
  654. srv := &TestServer{
  655. Address: listen.Addr().String(),
  656. listen: listen,
  657. t: t,
  658. protocol: protocol,
  659. headerSize: headerSize,
  660. ctx: ctx,
  661. cancel: cancel,
  662. }
  663. go srv.closeWatch()
  664. go srv.serve()
  665. return srv
  666. }
  667. type TestServer struct {
  668. Address string
  669. TimeoutOnStartup int32
  670. t testing.TB
  671. nreq uint64
  672. listen net.Listener
  673. nKillReq int64
  674. nQueries uint64
  675. compressor Compressor
  676. protocol byte
  677. headerSize int
  678. ctx context.Context
  679. cancel context.CancelFunc
  680. quit chan struct{}
  681. mu sync.Mutex
  682. closed bool
  683. }
  684. func (srv *TestServer) session() (*Session, error) {
  685. return testCluster(srv.Address, protoVersion(srv.protocol)).CreateSession()
  686. }
  687. func (srv *TestServer) host() *HostInfo {
  688. hosts, err := hostInfo(srv.Address, 9042)
  689. if err != nil {
  690. srv.t.Fatal(err)
  691. }
  692. return hosts[0]
  693. }
  694. func (srv *TestServer) closeWatch() {
  695. <-srv.ctx.Done()
  696. srv.mu.Lock()
  697. defer srv.mu.Unlock()
  698. srv.closeLocked()
  699. }
  700. func (srv *TestServer) serve() {
  701. defer srv.listen.Close()
  702. for !srv.isClosed() {
  703. conn, err := srv.listen.Accept()
  704. if err != nil {
  705. break
  706. }
  707. go func(conn net.Conn) {
  708. defer conn.Close()
  709. for !srv.isClosed() {
  710. framer, err := srv.readFrame(conn)
  711. if err != nil {
  712. if err == io.EOF {
  713. return
  714. }
  715. srv.errorLocked(err)
  716. return
  717. }
  718. atomic.AddUint64(&srv.nreq, 1)
  719. go srv.process(framer)
  720. }
  721. }(conn)
  722. }
  723. }
  724. func (srv *TestServer) isClosed() bool {
  725. srv.mu.Lock()
  726. defer srv.mu.Unlock()
  727. return srv.closed
  728. }
  729. func (srv *TestServer) closeLocked() {
  730. if srv.closed {
  731. return
  732. }
  733. srv.closed = true
  734. srv.listen.Close()
  735. srv.cancel()
  736. }
  737. func (srv *TestServer) Stop() {
  738. srv.mu.Lock()
  739. defer srv.mu.Unlock()
  740. srv.closeLocked()
  741. }
  742. func (srv *TestServer) errorLocked(err interface{}) {
  743. srv.mu.Lock()
  744. defer srv.mu.Unlock()
  745. if srv.closed {
  746. return
  747. }
  748. srv.t.Error(err)
  749. }
  750. func (srv *TestServer) process(f *framer) {
  751. head := f.header
  752. if head == nil {
  753. srv.errorLocked("process frame with a nil header")
  754. return
  755. }
  756. switch head.op {
  757. case opStartup:
  758. if atomic.LoadInt32(&srv.TimeoutOnStartup) > 0 {
  759. // Do not respond to startup command
  760. // wait until we get a cancel signal
  761. select {
  762. case <-srv.ctx.Done():
  763. return
  764. }
  765. }
  766. f.writeHeader(0, opReady, head.stream)
  767. case opOptions:
  768. f.writeHeader(0, opSupported, head.stream)
  769. f.writeShort(0)
  770. case opQuery:
  771. atomic.AddUint64(&srv.nQueries, 1)
  772. query := f.readLongString()
  773. first := query
  774. if n := strings.Index(query, " "); n > 0 {
  775. first = first[:n]
  776. }
  777. switch strings.ToLower(first) {
  778. case "kill":
  779. atomic.AddInt64(&srv.nKillReq, 1)
  780. f.writeHeader(0, opError, head.stream)
  781. f.writeInt(0x1001)
  782. f.writeString("query killed")
  783. case "use":
  784. f.writeInt(resultKindKeyspace)
  785. f.writeString(strings.TrimSpace(query[3:]))
  786. case "void":
  787. f.writeHeader(0, opResult, head.stream)
  788. f.writeInt(resultKindVoid)
  789. case "timeout":
  790. <-srv.ctx.Done()
  791. return
  792. case "slow":
  793. go func() {
  794. f.writeHeader(0, opResult, head.stream)
  795. f.writeInt(resultKindVoid)
  796. f.wbuf[0] = srv.protocol | 0x80
  797. select {
  798. case <-srv.ctx.Done():
  799. return
  800. case <-time.After(50 * time.Millisecond):
  801. f.finishWrite()
  802. }
  803. }()
  804. return
  805. default:
  806. f.writeHeader(0, opResult, head.stream)
  807. f.writeInt(resultKindVoid)
  808. }
  809. case opError:
  810. f.writeHeader(0, opError, head.stream)
  811. f.wbuf = append(f.wbuf, f.rbuf...)
  812. default:
  813. f.writeHeader(0, opError, head.stream)
  814. f.writeInt(0)
  815. f.writeString("not supported")
  816. }
  817. f.wbuf[0] = srv.protocol | 0x80
  818. if err := f.finishWrite(); err != nil {
  819. srv.errorLocked(err)
  820. }
  821. }
  822. func (srv *TestServer) readFrame(conn net.Conn) (*framer, error) {
  823. buf := make([]byte, srv.headerSize)
  824. head, err := readHeader(conn, buf)
  825. if err != nil {
  826. return nil, err
  827. }
  828. framer := newFramer(conn, conn, nil, srv.protocol)
  829. err = framer.readFrame(&head)
  830. if err != nil {
  831. return nil, err
  832. }
  833. // should be a request frame
  834. if head.version.response() {
  835. return nil, fmt.Errorf("expected to read a request frame got version: %v", head.version)
  836. } else if head.version.version() != srv.protocol {
  837. return nil, fmt.Errorf("expected to read protocol version 0x%x got 0x%x", srv.protocol, head.version.version())
  838. }
  839. return framer, nil
  840. }