conn.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149
  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. package gocql
  5. import (
  6. "bufio"
  7. "crypto/tls"
  8. "errors"
  9. "fmt"
  10. "io"
  11. "io/ioutil"
  12. "net"
  13. "strconv"
  14. "strings"
  15. "sync"
  16. "sync/atomic"
  17. "time"
  18. "golang.org/x/net/context"
  19. "github.com/gocql/gocql/internal/lru"
  20. "github.com/gocql/gocql/internal/streams"
  21. )
  22. var (
  23. approvedAuthenticators = [...]string{
  24. "org.apache.cassandra.auth.PasswordAuthenticator",
  25. "com.instaclustr.cassandra.auth.SharedSecretAuthenticator",
  26. }
  27. )
  28. func approve(authenticator string) bool {
  29. for _, s := range approvedAuthenticators {
  30. if authenticator == s {
  31. return true
  32. }
  33. }
  34. return false
  35. }
  36. //JoinHostPort is a utility to return a address string that can be used
  37. //gocql.Conn to form a connection with a host.
  38. func JoinHostPort(addr string, port int) string {
  39. addr = strings.TrimSpace(addr)
  40. if _, _, err := net.SplitHostPort(addr); err != nil {
  41. addr = net.JoinHostPort(addr, strconv.Itoa(port))
  42. }
  43. return addr
  44. }
  45. type Authenticator interface {
  46. Challenge(req []byte) (resp []byte, auth Authenticator, err error)
  47. Success(data []byte) error
  48. }
  49. type PasswordAuthenticator struct {
  50. Username string
  51. Password string
  52. }
  53. func (p PasswordAuthenticator) Challenge(req []byte) ([]byte, Authenticator, error) {
  54. if !approve(string(req)) {
  55. return nil, nil, fmt.Errorf("unexpected authenticator %q", req)
  56. }
  57. resp := make([]byte, 2+len(p.Username)+len(p.Password))
  58. resp[0] = 0
  59. copy(resp[1:], p.Username)
  60. resp[len(p.Username)+1] = 0
  61. copy(resp[2+len(p.Username):], p.Password)
  62. return resp, nil, nil
  63. }
  64. func (p PasswordAuthenticator) Success(data []byte) error {
  65. return nil
  66. }
  67. type SslOptions struct {
  68. tls.Config
  69. // CertPath and KeyPath are optional depending on server
  70. // config, but both fields must be omitted to avoid using a
  71. // client certificate
  72. CertPath string
  73. KeyPath string
  74. CaPath string //optional depending on server config
  75. // If you want to verify the hostname and server cert (like a wildcard for cass cluster) then you should turn this on
  76. // This option is basically the inverse of InSecureSkipVerify
  77. // See InSecureSkipVerify in http://golang.org/pkg/crypto/tls/ for more info
  78. EnableHostVerification bool
  79. }
  80. type ConnConfig struct {
  81. ProtoVersion int
  82. CQLVersion string
  83. Timeout time.Duration
  84. ConnectTimeout time.Duration
  85. Compressor Compressor
  86. Authenticator Authenticator
  87. Keepalive time.Duration
  88. tlsConfig *tls.Config
  89. }
  90. type ConnErrorHandler interface {
  91. HandleError(conn *Conn, err error, closed bool)
  92. }
  93. type connErrorHandlerFn func(conn *Conn, err error, closed bool)
  94. func (fn connErrorHandlerFn) HandleError(conn *Conn, err error, closed bool) {
  95. fn(conn, err, closed)
  96. }
  97. // If not zero, how many timeouts we will allow to occur before the connection is closed
  98. // and restarted. This is to prevent a single query timeout from killing a connection
  99. // which may be serving more queries just fine.
  100. // Default is 10, should not be changed concurrently with queries.
  101. var TimeoutLimit int64 = 10
  102. // Conn is a single connection to a Cassandra node. It can be used to execute
  103. // queries, but users are usually advised to use a more reliable, higher
  104. // level API.
  105. type Conn struct {
  106. conn net.Conn
  107. r *bufio.Reader
  108. timeout time.Duration
  109. cfg *ConnConfig
  110. headerBuf [maxFrameHeaderSize]byte
  111. streams *streams.IDGenerator
  112. mu sync.RWMutex
  113. calls map[int]*callReq
  114. errorHandler ConnErrorHandler
  115. compressor Compressor
  116. auth Authenticator
  117. addr string
  118. version uint8
  119. currentKeyspace string
  120. host *HostInfo
  121. session *Session
  122. closed int32
  123. quit chan struct{}
  124. timeouts int64
  125. }
  126. // Connect establishes a connection to a Cassandra node.
  127. func Connect(host *HostInfo, cfg *ConnConfig, errorHandler ConnErrorHandler, session *Session) (*Conn, error) {
  128. // TODO(zariel): remove these
  129. if host == nil {
  130. panic("host is nil")
  131. } else if len(host.Peer()) == 0 {
  132. panic("host missing peer ip address")
  133. } else if host.Port() == 0 {
  134. panic("host missing port")
  135. }
  136. var (
  137. err error
  138. conn net.Conn
  139. )
  140. dialer := &net.Dialer{
  141. Timeout: cfg.ConnectTimeout,
  142. }
  143. // TODO(zariel): handle ipv6 zone
  144. translatedPeer, translatedPort := session.cfg.translateAddressPort(host.Peer(), host.Port())
  145. addr := (&net.TCPAddr{IP: translatedPeer, Port: translatedPort}).String()
  146. //addr := (&net.TCPAddr{IP: host.Peer(), Port: host.Port()}).String()
  147. if cfg.tlsConfig != nil {
  148. // the TLS config is safe to be reused by connections but it must not
  149. // be modified after being used.
  150. conn, err = tls.DialWithDialer(dialer, "tcp", addr, cfg.tlsConfig)
  151. } else {
  152. conn, err = dialer.Dial("tcp", addr)
  153. }
  154. if err != nil {
  155. return nil, err
  156. }
  157. c := &Conn{
  158. conn: conn,
  159. r: bufio.NewReader(conn),
  160. cfg: cfg,
  161. calls: make(map[int]*callReq),
  162. timeout: cfg.Timeout,
  163. version: uint8(cfg.ProtoVersion),
  164. addr: conn.RemoteAddr().String(),
  165. errorHandler: errorHandler,
  166. compressor: cfg.Compressor,
  167. auth: cfg.Authenticator,
  168. quit: make(chan struct{}),
  169. session: session,
  170. streams: streams.New(cfg.ProtoVersion),
  171. host: host,
  172. }
  173. if cfg.Keepalive > 0 {
  174. c.setKeepalive(cfg.Keepalive)
  175. }
  176. var (
  177. ctx context.Context
  178. cancel func()
  179. )
  180. if cfg.ConnectTimeout > 0 {
  181. ctx, cancel = context.WithTimeout(context.Background(), cfg.ConnectTimeout)
  182. } else {
  183. ctx, cancel = context.WithCancel(context.Background())
  184. }
  185. defer cancel()
  186. frameTicker := make(chan struct{}, 1)
  187. startupErr := make(chan error)
  188. go func() {
  189. for range frameTicker {
  190. err := c.recv()
  191. if err != nil {
  192. select {
  193. case startupErr <- err:
  194. case <-ctx.Done():
  195. }
  196. return
  197. }
  198. }
  199. }()
  200. go func() {
  201. defer close(frameTicker)
  202. err := c.startup(ctx, frameTicker)
  203. select {
  204. case startupErr <- err:
  205. case <-ctx.Done():
  206. }
  207. }()
  208. select {
  209. case err := <-startupErr:
  210. if err != nil {
  211. c.Close()
  212. return nil, err
  213. }
  214. case <-ctx.Done():
  215. c.Close()
  216. return nil, errors.New("gocql: no response to connection startup within timeout")
  217. }
  218. go c.serve()
  219. return c, nil
  220. }
  221. func (c *Conn) Write(p []byte) (int, error) {
  222. if c.timeout > 0 {
  223. c.conn.SetWriteDeadline(time.Now().Add(c.timeout))
  224. }
  225. return c.conn.Write(p)
  226. }
  227. func (c *Conn) Read(p []byte) (n int, err error) {
  228. const maxAttempts = 5
  229. for i := 0; i < maxAttempts; i++ {
  230. var nn int
  231. if c.timeout > 0 {
  232. c.conn.SetReadDeadline(time.Now().Add(c.timeout))
  233. }
  234. nn, err = io.ReadFull(c.r, p[n:])
  235. n += nn
  236. if err == nil {
  237. break
  238. }
  239. if verr, ok := err.(net.Error); !ok || !verr.Temporary() {
  240. break
  241. }
  242. }
  243. return
  244. }
  245. func (c *Conn) startup(ctx context.Context, frameTicker chan struct{}) error {
  246. m := map[string]string{
  247. "CQL_VERSION": c.cfg.CQLVersion,
  248. }
  249. if c.compressor != nil {
  250. m["COMPRESSION"] = c.compressor.Name()
  251. }
  252. select {
  253. case frameTicker <- struct{}{}:
  254. case <-ctx.Done():
  255. return ctx.Err()
  256. }
  257. framer, err := c.exec(ctx, &writeStartupFrame{opts: m}, nil)
  258. if err != nil {
  259. return err
  260. }
  261. frame, err := framer.parseFrame()
  262. if err != nil {
  263. return err
  264. }
  265. switch v := frame.(type) {
  266. case error:
  267. return v
  268. case *readyFrame:
  269. return nil
  270. case *authenticateFrame:
  271. return c.authenticateHandshake(ctx, v, frameTicker)
  272. default:
  273. return NewErrProtocol("Unknown type of response to startup frame: %s", v)
  274. }
  275. }
  276. func (c *Conn) authenticateHandshake(ctx context.Context, authFrame *authenticateFrame, frameTicker chan struct{}) error {
  277. if c.auth == nil {
  278. return fmt.Errorf("authentication required (using %q)", authFrame.class)
  279. }
  280. resp, challenger, err := c.auth.Challenge([]byte(authFrame.class))
  281. if err != nil {
  282. return err
  283. }
  284. req := &writeAuthResponseFrame{data: resp}
  285. for {
  286. select {
  287. case frameTicker <- struct{}{}:
  288. case <-ctx.Done():
  289. return ctx.Err()
  290. }
  291. framer, err := c.exec(ctx, req, nil)
  292. if err != nil {
  293. return err
  294. }
  295. frame, err := framer.parseFrame()
  296. if err != nil {
  297. return err
  298. }
  299. switch v := frame.(type) {
  300. case error:
  301. return v
  302. case *authSuccessFrame:
  303. if challenger != nil {
  304. return challenger.Success(v.data)
  305. }
  306. return nil
  307. case *authChallengeFrame:
  308. resp, challenger, err = challenger.Challenge(v.data)
  309. if err != nil {
  310. return err
  311. }
  312. req = &writeAuthResponseFrame{
  313. data: resp,
  314. }
  315. default:
  316. return fmt.Errorf("unknown frame response during authentication: %v", v)
  317. }
  318. framerPool.Put(framer)
  319. }
  320. }
  321. func (c *Conn) closeWithError(err error) {
  322. if !atomic.CompareAndSwapInt32(&c.closed, 0, 1) {
  323. return
  324. }
  325. // we should attempt to deliver the error back to the caller if it
  326. // exists
  327. if err != nil {
  328. c.mu.RLock()
  329. for _, req := range c.calls {
  330. // we need to send the error to all waiting queries, put the state
  331. // of this conn into not active so that it can not execute any queries.
  332. select {
  333. case req.resp <- err:
  334. case <-req.timeout:
  335. }
  336. }
  337. c.mu.RUnlock()
  338. }
  339. // if error was nil then unblock the quit channel
  340. close(c.quit)
  341. c.conn.Close()
  342. if err != nil {
  343. c.errorHandler.HandleError(c, err, true)
  344. }
  345. }
  346. func (c *Conn) Close() {
  347. c.closeWithError(nil)
  348. }
  349. // Serve starts the stream multiplexer for this connection, which is required
  350. // to execute any queries. This method runs as long as the connection is
  351. // open and is therefore usually called in a separate goroutine.
  352. func (c *Conn) serve() {
  353. var (
  354. err error
  355. )
  356. for {
  357. err = c.recv()
  358. if err != nil {
  359. break
  360. }
  361. }
  362. c.closeWithError(err)
  363. }
  364. func (c *Conn) discardFrame(head frameHeader) error {
  365. _, err := io.CopyN(ioutil.Discard, c, int64(head.length))
  366. if err != nil {
  367. return err
  368. }
  369. return nil
  370. }
  371. type protocolError struct {
  372. frame frame
  373. }
  374. func (p *protocolError) Error() string {
  375. if err, ok := p.frame.(error); ok {
  376. return err.Error()
  377. }
  378. return fmt.Sprintf("gocql: received unexpected frame on stream %d: %v", p.frame.Header().stream, p.frame)
  379. }
  380. func (c *Conn) recv() error {
  381. // not safe for concurrent reads
  382. // read a full header, ignore timeouts, as this is being ran in a loop
  383. // TODO: TCP level deadlines? or just query level deadlines?
  384. if c.timeout > 0 {
  385. c.conn.SetReadDeadline(time.Time{})
  386. }
  387. // were just reading headers over and over and copy bodies
  388. head, err := readHeader(c.r, c.headerBuf[:])
  389. if err != nil {
  390. return err
  391. }
  392. if head.stream > c.streams.NumStreams {
  393. return fmt.Errorf("gocql: frame header stream is beyond call exepected bounds: %d", head.stream)
  394. } else if head.stream == -1 {
  395. // TODO: handle cassandra event frames, we shouldnt get any currently
  396. framer := newFramer(c, c, c.compressor, c.version)
  397. if err := framer.readFrame(&head); err != nil {
  398. return err
  399. }
  400. go c.session.handleEvent(framer)
  401. return nil
  402. } else if head.stream <= 0 {
  403. // reserved stream that we dont use, probably due to a protocol error
  404. // or a bug in Cassandra, this should be an error, parse it and return.
  405. framer := newFramer(c, c, c.compressor, c.version)
  406. if err := framer.readFrame(&head); err != nil {
  407. return err
  408. }
  409. defer framerPool.Put(framer)
  410. frame, err := framer.parseFrame()
  411. if err != nil {
  412. return err
  413. }
  414. return &protocolError{
  415. frame: frame,
  416. }
  417. }
  418. c.mu.RLock()
  419. call, ok := c.calls[head.stream]
  420. c.mu.RUnlock()
  421. if call == nil || call.framer == nil || !ok {
  422. Logger.Printf("gocql: received response for stream which has no handler: header=%v\n", head)
  423. return c.discardFrame(head)
  424. }
  425. err = call.framer.readFrame(&head)
  426. if err != nil {
  427. // only net errors should cause the connection to be closed. Though
  428. // cassandra returning corrupt frames will be returned here as well.
  429. if _, ok := err.(net.Error); ok {
  430. return err
  431. }
  432. }
  433. // we either, return a response to the caller, the caller timedout, or the
  434. // connection has closed. Either way we should never block indefinatly here
  435. select {
  436. case call.resp <- err:
  437. case <-call.timeout:
  438. c.releaseStream(head.stream)
  439. case <-c.quit:
  440. }
  441. return nil
  442. }
  443. func (c *Conn) releaseStream(stream int) {
  444. c.mu.Lock()
  445. call := c.calls[stream]
  446. if call != nil && stream != call.streamID {
  447. panic(fmt.Sprintf("attempt to release streamID with ivalid stream: %d -> %+v\n", stream, call))
  448. } else if call == nil {
  449. panic(fmt.Sprintf("releasing a stream not in use: %d", stream))
  450. }
  451. delete(c.calls, stream)
  452. c.mu.Unlock()
  453. if call.timer != nil {
  454. call.timer.Stop()
  455. }
  456. streamPool.Put(call)
  457. c.streams.Clear(stream)
  458. }
  459. func (c *Conn) handleTimeout() {
  460. if TimeoutLimit > 0 && atomic.AddInt64(&c.timeouts, 1) > TimeoutLimit {
  461. c.closeWithError(ErrTooManyTimeouts)
  462. }
  463. }
  464. var (
  465. streamPool = sync.Pool{
  466. New: func() interface{} {
  467. return &callReq{
  468. resp: make(chan error),
  469. }
  470. },
  471. }
  472. )
  473. type callReq struct {
  474. // could use a waitgroup but this allows us to do timeouts on the read/send
  475. resp chan error
  476. framer *framer
  477. timeout chan struct{} // indicates to recv() that a call has timedout
  478. streamID int // current stream in use
  479. timer *time.Timer
  480. }
  481. func (c *Conn) exec(ctx context.Context, req frameWriter, tracer Tracer) (*framer, error) {
  482. // TODO: move tracer onto conn
  483. stream, ok := c.streams.GetStream()
  484. if !ok {
  485. return nil, ErrNoStreams
  486. }
  487. // resp is basically a waiting semaphore protecting the framer
  488. framer := newFramer(c, c, c.compressor, c.version)
  489. c.mu.Lock()
  490. call := c.calls[stream]
  491. if call != nil {
  492. c.mu.Unlock()
  493. return nil, fmt.Errorf("attempting to use stream already in use: %d -> %d", stream, call.streamID)
  494. } else {
  495. call = streamPool.Get().(*callReq)
  496. }
  497. c.calls[stream] = call
  498. c.mu.Unlock()
  499. call.framer = framer
  500. call.timeout = make(chan struct{})
  501. call.streamID = stream
  502. if tracer != nil {
  503. framer.trace()
  504. }
  505. err := req.writeFrame(framer, stream)
  506. if err != nil {
  507. // closeWithError will block waiting for this stream to either receive a response
  508. // or for us to timeout, close the timeout chan here. Im not entirely sure
  509. // but we should not get a response after an error on the write side.
  510. close(call.timeout)
  511. // I think this is the correct thing to do, im not entirely sure. It is not
  512. // ideal as readers might still get some data, but they probably wont.
  513. // Here we need to be careful as the stream is not available and if all
  514. // writes just timeout or fail then the pool might use this connection to
  515. // send a frame on, with all the streams used up and not returned.
  516. c.closeWithError(err)
  517. return nil, err
  518. }
  519. var timeoutCh <-chan time.Time
  520. if c.timeout > 0 {
  521. if call.timer == nil {
  522. call.timer = time.NewTimer(0)
  523. <-call.timer.C
  524. } else {
  525. if !call.timer.Stop() {
  526. select {
  527. case <-call.timer.C:
  528. default:
  529. }
  530. }
  531. }
  532. call.timer.Reset(c.timeout)
  533. timeoutCh = call.timer.C
  534. }
  535. var ctxDone <-chan struct{}
  536. if ctx != nil {
  537. ctxDone = ctx.Done()
  538. }
  539. select {
  540. case err := <-call.resp:
  541. close(call.timeout)
  542. if err != nil {
  543. if !c.Closed() {
  544. // if the connection is closed then we cant release the stream,
  545. // this is because the request is still outstanding and we have
  546. // been handed another error from another stream which caused the
  547. // connection to close.
  548. c.releaseStream(stream)
  549. }
  550. return nil, err
  551. }
  552. case <-timeoutCh:
  553. close(call.timeout)
  554. c.handleTimeout()
  555. return nil, ErrTimeoutNoResponse
  556. case <-ctxDone:
  557. close(call.timeout)
  558. return nil, ctx.Err()
  559. case <-c.quit:
  560. return nil, ErrConnectionClosed
  561. }
  562. // dont release the stream if detect a timeout as another request can reuse
  563. // that stream and get a response for the old request, which we have no
  564. // easy way of detecting.
  565. //
  566. // Ensure that the stream is not released if there are potentially outstanding
  567. // requests on the stream to prevent nil pointer dereferences in recv().
  568. defer c.releaseStream(stream)
  569. if v := framer.header.version.version(); v != c.version {
  570. return nil, NewErrProtocol("unexpected protocol version in response: got %d expected %d", v, c.version)
  571. }
  572. return framer, nil
  573. }
  574. type preparedStatment struct {
  575. id []byte
  576. request preparedMetadata
  577. response resultMetadata
  578. }
  579. type inflightPrepare struct {
  580. wg sync.WaitGroup
  581. err error
  582. preparedStatment *preparedStatment
  583. }
  584. func (c *Conn) prepareStatement(ctx context.Context, stmt string, tracer Tracer) (*preparedStatment, error) {
  585. stmtCacheKey := c.session.stmtsLRU.keyFor(c.addr, c.currentKeyspace, stmt)
  586. flight, ok := c.session.stmtsLRU.execIfMissing(stmtCacheKey, func(lru *lru.Cache) *inflightPrepare {
  587. flight := new(inflightPrepare)
  588. flight.wg.Add(1)
  589. lru.Add(stmtCacheKey, flight)
  590. return flight
  591. })
  592. if ok {
  593. flight.wg.Wait()
  594. return flight.preparedStatment, flight.err
  595. }
  596. prep := &writePrepareFrame{
  597. statement: stmt,
  598. }
  599. framer, err := c.exec(ctx, prep, tracer)
  600. if err != nil {
  601. flight.err = err
  602. flight.wg.Done()
  603. return nil, err
  604. }
  605. frame, err := framer.parseFrame()
  606. if err != nil {
  607. flight.err = err
  608. flight.wg.Done()
  609. return nil, err
  610. }
  611. // TODO(zariel): tidy this up, simplify handling of frame parsing so its not duplicated
  612. // everytime we need to parse a frame.
  613. if len(framer.traceID) > 0 {
  614. tracer.Trace(framer.traceID)
  615. }
  616. switch x := frame.(type) {
  617. case *resultPreparedFrame:
  618. flight.preparedStatment = &preparedStatment{
  619. // defensively copy as we will recycle the underlying buffer after we
  620. // return.
  621. id: copyBytes(x.preparedID),
  622. // the type info's should _not_ have a reference to the framers read buffer,
  623. // therefore we can just copy them directly.
  624. request: x.reqMeta,
  625. response: x.respMeta,
  626. }
  627. case error:
  628. flight.err = x
  629. default:
  630. flight.err = NewErrProtocol("Unknown type in response to prepare frame: %s", x)
  631. }
  632. flight.wg.Done()
  633. if flight.err != nil {
  634. c.session.stmtsLRU.remove(stmtCacheKey)
  635. }
  636. framerPool.Put(framer)
  637. return flight.preparedStatment, flight.err
  638. }
  639. func (c *Conn) executeQuery(qry *Query) *Iter {
  640. params := queryParams{
  641. consistency: qry.cons,
  642. }
  643. // frame checks that it is not 0
  644. params.serialConsistency = qry.serialCons
  645. params.defaultTimestamp = qry.defaultTimestamp
  646. params.defaultTimestampValue = qry.defaultTimestampValue
  647. if len(qry.pageState) > 0 {
  648. params.pagingState = qry.pageState
  649. }
  650. if qry.pageSize > 0 {
  651. params.pageSize = qry.pageSize
  652. }
  653. var (
  654. frame frameWriter
  655. info *preparedStatment
  656. )
  657. if qry.shouldPrepare() {
  658. // Prepare all DML queries. Other queries can not be prepared.
  659. var err error
  660. info, err = c.prepareStatement(qry.context, qry.stmt, qry.trace)
  661. if err != nil {
  662. return &Iter{err: err}
  663. }
  664. var values []interface{}
  665. if qry.binding == nil {
  666. values = qry.values
  667. } else {
  668. values, err = qry.binding(&QueryInfo{
  669. Id: info.id,
  670. Args: info.request.columns,
  671. Rval: info.response.columns,
  672. PKeyColumns: info.request.pkeyColumns,
  673. })
  674. if err != nil {
  675. return &Iter{err: err}
  676. }
  677. }
  678. if len(values) != info.request.actualColCount {
  679. return &Iter{err: fmt.Errorf("gocql: expected %d values send got %d", info.request.actualColCount, len(values))}
  680. }
  681. params.values = make([]queryValues, len(values))
  682. for i := 0; i < len(values); i++ {
  683. val, err := Marshal(info.request.columns[i].TypeInfo, values[i])
  684. if err != nil {
  685. return &Iter{err: err}
  686. }
  687. v := &params.values[i]
  688. v.value = val
  689. // TODO: handle query binding names
  690. }
  691. params.skipMeta = !(c.session.cfg.DisableSkipMetadata || qry.disableSkipMetadata)
  692. frame = &writeExecuteFrame{
  693. preparedID: info.id,
  694. params: params,
  695. }
  696. } else {
  697. frame = &writeQueryFrame{
  698. statement: qry.stmt,
  699. params: params,
  700. }
  701. }
  702. framer, err := c.exec(qry.context, frame, qry.trace)
  703. if err != nil {
  704. return &Iter{err: err}
  705. }
  706. resp, err := framer.parseFrame()
  707. if err != nil {
  708. return &Iter{err: err}
  709. }
  710. if len(framer.traceID) > 0 {
  711. qry.trace.Trace(framer.traceID)
  712. }
  713. switch x := resp.(type) {
  714. case *resultVoidFrame:
  715. return &Iter{framer: framer}
  716. case *resultRowsFrame:
  717. iter := &Iter{
  718. meta: x.meta,
  719. framer: framer,
  720. numRows: x.numRows,
  721. }
  722. if params.skipMeta {
  723. if info != nil {
  724. iter.meta = info.response
  725. iter.meta.pagingState = x.meta.pagingState
  726. } else {
  727. return &Iter{framer: framer, err: errors.New("gocql: did not receive metadata but prepared info is nil")}
  728. }
  729. } else {
  730. iter.meta = x.meta
  731. }
  732. if len(x.meta.pagingState) > 0 && !qry.disableAutoPage {
  733. iter.next = &nextIter{
  734. qry: *qry,
  735. pos: int((1 - qry.prefetch) * float64(x.numRows)),
  736. }
  737. iter.next.qry.pageState = copyBytes(x.meta.pagingState)
  738. if iter.next.pos < 1 {
  739. iter.next.pos = 1
  740. }
  741. }
  742. return iter
  743. case *resultKeyspaceFrame:
  744. return &Iter{framer: framer}
  745. case *schemaChangeKeyspace, *schemaChangeTable, *schemaChangeFunction:
  746. iter := &Iter{framer: framer}
  747. if err := c.awaitSchemaAgreement(); err != nil {
  748. // TODO: should have this behind a flag
  749. Logger.Println(err)
  750. }
  751. // dont return an error from this, might be a good idea to give a warning
  752. // though. The impact of this returning an error would be that the cluster
  753. // is not consistent with regards to its schema.
  754. return iter
  755. case *RequestErrUnprepared:
  756. stmtCacheKey := c.session.stmtsLRU.keyFor(c.addr, c.currentKeyspace, qry.stmt)
  757. if c.session.stmtsLRU.remove(stmtCacheKey) {
  758. return c.executeQuery(qry)
  759. }
  760. return &Iter{err: x, framer: framer}
  761. case error:
  762. return &Iter{err: x, framer: framer}
  763. default:
  764. return &Iter{
  765. err: NewErrProtocol("Unknown type in response to execute query (%T): %s", x, x),
  766. framer: framer,
  767. }
  768. }
  769. }
  770. func (c *Conn) Pick(qry *Query) *Conn {
  771. if c.Closed() {
  772. return nil
  773. }
  774. return c
  775. }
  776. func (c *Conn) Closed() bool {
  777. return atomic.LoadInt32(&c.closed) == 1
  778. }
  779. func (c *Conn) Address() string {
  780. return c.addr
  781. }
  782. func (c *Conn) AvailableStreams() int {
  783. return c.streams.Available()
  784. }
  785. func (c *Conn) UseKeyspace(keyspace string) error {
  786. q := &writeQueryFrame{statement: `USE "` + keyspace + `"`}
  787. q.params.consistency = Any
  788. framer, err := c.exec(context.Background(), q, nil)
  789. if err != nil {
  790. return err
  791. }
  792. resp, err := framer.parseFrame()
  793. if err != nil {
  794. return err
  795. }
  796. switch x := resp.(type) {
  797. case *resultKeyspaceFrame:
  798. case error:
  799. return x
  800. default:
  801. return NewErrProtocol("unknown frame in response to USE: %v", x)
  802. }
  803. c.currentKeyspace = keyspace
  804. return nil
  805. }
  806. func (c *Conn) executeBatch(batch *Batch) *Iter {
  807. if c.version == protoVersion1 {
  808. return &Iter{err: ErrUnsupported}
  809. }
  810. n := len(batch.Entries)
  811. req := &writeBatchFrame{
  812. typ: batch.Type,
  813. statements: make([]batchStatment, n),
  814. consistency: batch.Cons,
  815. serialConsistency: batch.serialCons,
  816. defaultTimestamp: batch.defaultTimestamp,
  817. defaultTimestampValue: batch.defaultTimestampValue,
  818. }
  819. stmts := make(map[string]string, len(batch.Entries))
  820. for i := 0; i < n; i++ {
  821. entry := &batch.Entries[i]
  822. b := &req.statements[i]
  823. if len(entry.Args) > 0 || entry.binding != nil {
  824. info, err := c.prepareStatement(batch.context, entry.Stmt, nil)
  825. if err != nil {
  826. return &Iter{err: err}
  827. }
  828. var values []interface{}
  829. if entry.binding == nil {
  830. values = entry.Args
  831. } else {
  832. values, err = entry.binding(&QueryInfo{
  833. Id: info.id,
  834. Args: info.request.columns,
  835. Rval: info.response.columns,
  836. PKeyColumns: info.request.pkeyColumns,
  837. })
  838. if err != nil {
  839. return &Iter{err: err}
  840. }
  841. }
  842. if len(values) != info.request.actualColCount {
  843. return &Iter{err: fmt.Errorf("gocql: batch statement %d expected %d values send got %d", i, info.request.actualColCount, len(values))}
  844. }
  845. b.preparedID = info.id
  846. stmts[string(info.id)] = entry.Stmt
  847. b.values = make([]queryValues, info.request.actualColCount)
  848. for j := 0; j < info.request.actualColCount; j++ {
  849. val, err := Marshal(info.request.columns[j].TypeInfo, values[j])
  850. if err != nil {
  851. return &Iter{err: err}
  852. }
  853. b.values[j].value = val
  854. // TODO: add names
  855. }
  856. } else {
  857. b.statement = entry.Stmt
  858. }
  859. }
  860. // TODO: should batch support tracing?
  861. framer, err := c.exec(batch.context, req, nil)
  862. if err != nil {
  863. return &Iter{err: err}
  864. }
  865. resp, err := framer.parseFrame()
  866. if err != nil {
  867. return &Iter{err: err, framer: framer}
  868. }
  869. switch x := resp.(type) {
  870. case *resultVoidFrame:
  871. framerPool.Put(framer)
  872. return &Iter{}
  873. case *RequestErrUnprepared:
  874. stmt, found := stmts[string(x.StatementId)]
  875. if found {
  876. key := c.session.stmtsLRU.keyFor(c.addr, c.currentKeyspace, stmt)
  877. c.session.stmtsLRU.remove(key)
  878. }
  879. framerPool.Put(framer)
  880. if found {
  881. return c.executeBatch(batch)
  882. } else {
  883. return &Iter{err: err, framer: framer}
  884. }
  885. case *resultRowsFrame:
  886. iter := &Iter{
  887. meta: x.meta,
  888. framer: framer,
  889. numRows: x.numRows,
  890. }
  891. return iter
  892. case error:
  893. return &Iter{err: x, framer: framer}
  894. default:
  895. return &Iter{err: NewErrProtocol("Unknown type in response to batch statement: %s", x), framer: framer}
  896. }
  897. }
  898. func (c *Conn) setKeepalive(d time.Duration) error {
  899. if tc, ok := c.conn.(*net.TCPConn); ok {
  900. err := tc.SetKeepAlivePeriod(d)
  901. if err != nil {
  902. return err
  903. }
  904. return tc.SetKeepAlive(true)
  905. }
  906. return nil
  907. }
  908. func (c *Conn) query(statement string, values ...interface{}) (iter *Iter) {
  909. q := c.session.Query(statement, values...).Consistency(One)
  910. return c.executeQuery(q)
  911. }
  912. func (c *Conn) awaitSchemaAgreement() (err error) {
  913. const (
  914. peerSchemas = "SELECT schema_version FROM system.peers"
  915. localSchemas = "SELECT schema_version FROM system.local WHERE key='local'"
  916. )
  917. var versions map[string]struct{}
  918. endDeadline := time.Now().Add(c.session.cfg.MaxWaitSchemaAgreement)
  919. for time.Now().Before(endDeadline) {
  920. iter := c.query(peerSchemas)
  921. versions = make(map[string]struct{})
  922. var schemaVersion string
  923. for iter.Scan(&schemaVersion) {
  924. if schemaVersion == "" {
  925. Logger.Println("skipping peer entry with empty schema_version")
  926. continue
  927. }
  928. versions[schemaVersion] = struct{}{}
  929. schemaVersion = ""
  930. }
  931. if err = iter.Close(); err != nil {
  932. goto cont
  933. }
  934. iter = c.query(localSchemas)
  935. for iter.Scan(&schemaVersion) {
  936. versions[schemaVersion] = struct{}{}
  937. schemaVersion = ""
  938. }
  939. if err = iter.Close(); err != nil {
  940. goto cont
  941. }
  942. if len(versions) <= 1 {
  943. return nil
  944. }
  945. cont:
  946. time.Sleep(200 * time.Millisecond)
  947. }
  948. if err != nil {
  949. return
  950. }
  951. schemas := make([]string, 0, len(versions))
  952. for schema := range versions {
  953. schemas = append(schemas, schema)
  954. }
  955. // not exported
  956. return fmt.Errorf("gocql: cluster schema versions not consistent: %+v", schemas)
  957. }
  958. var (
  959. ErrQueryArgLength = errors.New("gocql: query argument length mismatch")
  960. ErrTimeoutNoResponse = errors.New("gocql: no response received from cassandra within timeout period")
  961. ErrTooManyTimeouts = errors.New("gocql: too many query timeouts on the connection")
  962. ErrConnectionClosed = errors.New("gocql: connection closed waiting for response")
  963. ErrNoStreams = errors.New("gocql: no streams available on connection")
  964. )