conn.go 25 KB

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