conn.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913
  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. )
  20. //JoinHostPort is a utility to return a address string that can be used
  21. //gocql.Conn to form a connection with a host.
  22. func JoinHostPort(addr string, port int) string {
  23. addr = strings.TrimSpace(addr)
  24. if _, _, err := net.SplitHostPort(addr); err != nil {
  25. addr = net.JoinHostPort(addr, strconv.Itoa(port))
  26. }
  27. return addr
  28. }
  29. type Authenticator interface {
  30. Challenge(req []byte) (resp []byte, auth Authenticator, err error)
  31. Success(data []byte) error
  32. }
  33. type PasswordAuthenticator struct {
  34. Username string
  35. Password string
  36. }
  37. func (p PasswordAuthenticator) Challenge(req []byte) ([]byte, Authenticator, error) {
  38. if string(req) != "org.apache.cassandra.auth.PasswordAuthenticator" {
  39. return nil, nil, fmt.Errorf("unexpected authenticator %q", req)
  40. }
  41. resp := make([]byte, 2+len(p.Username)+len(p.Password))
  42. resp[0] = 0
  43. copy(resp[1:], p.Username)
  44. resp[len(p.Username)+1] = 0
  45. copy(resp[2+len(p.Username):], p.Password)
  46. return resp, nil, nil
  47. }
  48. func (p PasswordAuthenticator) Success(data []byte) error {
  49. return nil
  50. }
  51. type SslOptions struct {
  52. tls.Config
  53. // CertPath and KeyPath are optional depending on server
  54. // config, but both fields must be omitted to avoid using a
  55. // client certificate
  56. CertPath string
  57. KeyPath string
  58. CaPath string //optional depending on server config
  59. // If you want to verify the hostname and server cert (like a wildcard for cass cluster) then you should turn this on
  60. // This option is basically the inverse of InSecureSkipVerify
  61. // See InSecureSkipVerify in http://golang.org/pkg/crypto/tls/ for more info
  62. EnableHostVerification bool
  63. }
  64. type ConnConfig struct {
  65. ProtoVersion int
  66. CQLVersion string
  67. Timeout time.Duration
  68. NumStreams int
  69. Compressor Compressor
  70. Authenticator Authenticator
  71. Keepalive time.Duration
  72. tlsConfig *tls.Config
  73. }
  74. type ConnErrorHandler interface {
  75. HandleError(conn *Conn, err error, closed bool)
  76. }
  77. // How many timeouts we will allow to occur before the connection is closed
  78. // and restarted. This is to prevent a single query timeout from killing a connection
  79. // which may be serving more queries just fine.
  80. // Default is 10, should not be changed concurrently with queries.
  81. var TimeoutLimit int64 = 10
  82. // Conn is a single connection to a Cassandra node. It can be used to execute
  83. // queries, but users are usually advised to use a more reliable, higher
  84. // level API.
  85. type Conn struct {
  86. conn net.Conn
  87. r *bufio.Reader
  88. timeout time.Duration
  89. headerBuf []byte
  90. uniq chan int
  91. calls []callReq
  92. errorHandler ConnErrorHandler
  93. compressor Compressor
  94. auth Authenticator
  95. addr string
  96. version uint8
  97. currentKeyspace string
  98. started bool
  99. closed int32
  100. quit chan struct{}
  101. timeouts int64
  102. }
  103. // Connect establishes a connection to a Cassandra node.
  104. // You must also call the Serve method before you can execute any queries.
  105. func Connect(addr string, cfg ConnConfig, errorHandler ConnErrorHandler) (*Conn, error) {
  106. var (
  107. err error
  108. conn net.Conn
  109. )
  110. dialer := &net.Dialer{
  111. Timeout: cfg.Timeout,
  112. }
  113. if cfg.tlsConfig != nil {
  114. // the TLS config is safe to be reused by connections but it must not
  115. // be modified after being used.
  116. conn, err = tls.DialWithDialer(dialer, "tcp", addr, cfg.tlsConfig)
  117. } else {
  118. conn, err = dialer.Dial("tcp", addr)
  119. }
  120. if err != nil {
  121. return nil, err
  122. }
  123. // going to default to proto 2
  124. if cfg.ProtoVersion < protoVersion1 || cfg.ProtoVersion > protoVersion4 {
  125. log.Printf("unsupported protocol version: %d using 2\n", cfg.ProtoVersion)
  126. cfg.ProtoVersion = 2
  127. }
  128. headerSize := 8
  129. maxStreams := 128
  130. if cfg.ProtoVersion > protoVersion2 {
  131. maxStreams = 32768
  132. headerSize = 9
  133. }
  134. if cfg.NumStreams <= 0 || cfg.NumStreams >= maxStreams {
  135. cfg.NumStreams = maxStreams
  136. } else {
  137. cfg.NumStreams++
  138. }
  139. c := &Conn{
  140. conn: conn,
  141. r: bufio.NewReader(conn),
  142. uniq: make(chan int, cfg.NumStreams),
  143. calls: make([]callReq, cfg.NumStreams),
  144. timeout: cfg.Timeout,
  145. version: uint8(cfg.ProtoVersion),
  146. addr: conn.RemoteAddr().String(),
  147. errorHandler: errorHandler,
  148. compressor: cfg.Compressor,
  149. auth: cfg.Authenticator,
  150. headerBuf: make([]byte, headerSize),
  151. quit: make(chan struct{}),
  152. }
  153. if cfg.Keepalive > 0 {
  154. c.setKeepalive(cfg.Keepalive)
  155. }
  156. // reserve stream 0 incase cassandra returns an error on it without us sending
  157. // a request.
  158. for i := 1; i < cfg.NumStreams; i++ {
  159. c.calls[i].resp = make(chan error)
  160. c.uniq <- i
  161. }
  162. go c.serve()
  163. if err := c.startup(&cfg); err != nil {
  164. conn.Close()
  165. return nil, err
  166. }
  167. c.started = true
  168. return c, nil
  169. }
  170. func (c *Conn) Write(p []byte) (int, error) {
  171. if c.timeout > 0 {
  172. c.conn.SetWriteDeadline(time.Now().Add(c.timeout))
  173. }
  174. return c.conn.Write(p)
  175. }
  176. func (c *Conn) Read(p []byte) (n int, err error) {
  177. const maxAttempts = 5
  178. for i := 0; i < maxAttempts; i++ {
  179. var nn int
  180. if c.timeout > 0 {
  181. c.conn.SetReadDeadline(time.Now().Add(c.timeout))
  182. }
  183. nn, err = io.ReadFull(c.r, p[n:])
  184. n += nn
  185. if err == nil {
  186. break
  187. }
  188. if verr, ok := err.(net.Error); !ok || !verr.Temporary() {
  189. break
  190. }
  191. }
  192. return
  193. }
  194. func (c *Conn) startup(cfg *ConnConfig) error {
  195. m := map[string]string{
  196. "CQL_VERSION": cfg.CQLVersion,
  197. }
  198. if c.compressor != nil {
  199. m["COMPRESSION"] = c.compressor.Name()
  200. }
  201. frame, err := c.exec(&writeStartupFrame{opts: m}, nil)
  202. if err != nil {
  203. return err
  204. }
  205. switch v := frame.(type) {
  206. case error:
  207. return v
  208. case *readyFrame:
  209. return nil
  210. case *authenticateFrame:
  211. return c.authenticateHandshake(v)
  212. default:
  213. return NewErrProtocol("Unknown type of response to startup frame: %s", v)
  214. }
  215. }
  216. func (c *Conn) authenticateHandshake(authFrame *authenticateFrame) error {
  217. if c.auth == nil {
  218. return fmt.Errorf("authentication required (using %q)", authFrame.class)
  219. }
  220. resp, challenger, err := c.auth.Challenge([]byte(authFrame.class))
  221. if err != nil {
  222. return err
  223. }
  224. req := &writeAuthResponseFrame{data: resp}
  225. for {
  226. frame, err := c.exec(req, nil)
  227. if err != nil {
  228. return err
  229. }
  230. switch v := frame.(type) {
  231. case error:
  232. return v
  233. case *authSuccessFrame:
  234. if challenger != nil {
  235. return challenger.Success(v.data)
  236. }
  237. return nil
  238. case *authChallengeFrame:
  239. resp, challenger, err = challenger.Challenge(v.data)
  240. if err != nil {
  241. return err
  242. }
  243. req = &writeAuthResponseFrame{
  244. data: resp,
  245. }
  246. default:
  247. return fmt.Errorf("unknown frame response during authentication: %v", v)
  248. }
  249. }
  250. }
  251. func (c *Conn) closeWithError(err error) {
  252. if !atomic.CompareAndSwapInt32(&c.closed, 0, 1) {
  253. return
  254. }
  255. if err != nil {
  256. // we should attempt to deliver the error back to the caller if it
  257. // exists
  258. for id := 0; id < len(c.calls); id++ {
  259. req := &c.calls[id]
  260. // we need to send the error to all waiting queries, put the state
  261. // of this conn into not active so that it can not execute any queries.
  262. if err != nil {
  263. select {
  264. case req.resp <- err:
  265. default:
  266. }
  267. }
  268. }
  269. }
  270. // if error was nil then unblock the quit channel
  271. close(c.quit)
  272. c.conn.Close()
  273. if c.started && err != nil {
  274. c.errorHandler.HandleError(c, err, true)
  275. }
  276. }
  277. func (c *Conn) Close() {
  278. c.closeWithError(nil)
  279. }
  280. // Serve starts the stream multiplexer for this connection, which is required
  281. // to execute any queries. This method runs as long as the connection is
  282. // open and is therefore usually called in a separate goroutine.
  283. func (c *Conn) serve() {
  284. var (
  285. err error
  286. )
  287. for {
  288. err = c.recv()
  289. if err != nil {
  290. break
  291. }
  292. }
  293. c.closeWithError(err)
  294. }
  295. func (c *Conn) discardFrame(head frameHeader) error {
  296. _, err := io.CopyN(ioutil.Discard, c, int64(head.length))
  297. if err != nil {
  298. return err
  299. }
  300. return nil
  301. }
  302. func (c *Conn) recv() error {
  303. // not safe for concurrent reads
  304. // read a full header, ignore timeouts, as this is being ran in a loop
  305. // TODO: TCP level deadlines? or just query level deadlines?
  306. if c.timeout > 0 {
  307. c.conn.SetReadDeadline(time.Time{})
  308. }
  309. // were just reading headers over and over and copy bodies
  310. head, err := readHeader(c.r, c.headerBuf)
  311. if err != nil {
  312. return err
  313. }
  314. if head.stream > len(c.calls) {
  315. return fmt.Errorf("gocql: frame header stream is beyond call exepected bounds: %d", head.stream)
  316. } else if head.stream == -1 {
  317. // TODO: handle cassandra event frames, we shouldnt get any currently
  318. return c.discardFrame(head)
  319. } else if head.stream <= 0 {
  320. // reserved stream that we dont use, probably due to a protocol error
  321. // or a bug in Cassandra, this should be an error, parse it and return.
  322. framer := newFramer(c, c, c.compressor, c.version)
  323. if err := framer.readFrame(&head); err != nil {
  324. return err
  325. }
  326. frame, err := framer.parseFrame()
  327. if err != nil {
  328. return err
  329. }
  330. switch v := frame.(type) {
  331. case error:
  332. return fmt.Errorf("gocql: error on stream %d: %v", head.stream, v)
  333. default:
  334. return fmt.Errorf("gocql: received frame on stream %d: %v", head.stream, frame)
  335. }
  336. }
  337. call := &c.calls[head.stream]
  338. if call == nil || call.framer == nil {
  339. log.Printf("gocql: received response for stream which has no handler: header=%v\n", head)
  340. return c.discardFrame(head)
  341. }
  342. err = call.framer.readFrame(&head)
  343. if err != nil {
  344. // only net errors should cause the connection to be closed. Though
  345. // cassandra returning corrupt frames will be returned here as well.
  346. if _, ok := err.(net.Error); ok {
  347. return err
  348. }
  349. }
  350. // we either, return a response to the caller, the caller timedout, or the
  351. // connection has closed. Either way we should never block indefinatly here
  352. select {
  353. case call.resp <- err:
  354. case <-call.timeout:
  355. c.releaseStream(head.stream)
  356. case <-c.quit:
  357. }
  358. return nil
  359. }
  360. type callReq struct {
  361. // could use a waitgroup but this allows us to do timeouts on the read/send
  362. resp chan error
  363. framer *framer
  364. timeout chan struct{} // indicates to recv() that a call has timedout
  365. }
  366. func (c *Conn) releaseStream(stream int) {
  367. call := &c.calls[stream]
  368. framerPool.Put(call.framer)
  369. call.framer = nil
  370. select {
  371. case c.uniq <- stream:
  372. case <-c.quit:
  373. }
  374. }
  375. func (c *Conn) handleTimeout() {
  376. if atomic.AddInt64(&c.timeouts, 1) > TimeoutLimit {
  377. c.closeWithError(ErrTooManyTimeouts)
  378. }
  379. }
  380. func (c *Conn) exec(req frameWriter, tracer Tracer) (frame, error) {
  381. // TODO: move tracer onto conn
  382. var stream int
  383. select {
  384. case stream = <-c.uniq:
  385. case <-c.quit:
  386. return nil, ErrConnectionClosed
  387. }
  388. // resp is basically a waiting semaphore protecting the framer
  389. framer := newFramer(c, c, c.compressor, c.version)
  390. call := &c.calls[stream]
  391. call.framer = framer
  392. call.timeout = make(chan struct{})
  393. if tracer != nil {
  394. framer.trace()
  395. }
  396. err := req.writeFrame(framer, stream)
  397. if err != nil {
  398. // I think this is the correct thing to do, im not entirely sure. It is not
  399. // ideal as readers might still get some data, but they probably wont.
  400. // Here we need to be careful as the stream is not available and if all
  401. // writes just timeout or fail then the pool might use this connection to
  402. // send a frame on, with all the streams used up and not returned.
  403. c.closeWithError(err)
  404. return nil, err
  405. }
  406. select {
  407. case err := <-call.resp:
  408. if err != nil {
  409. if !c.Closed() {
  410. // if the connection is closed then we cant release the stream,
  411. // this is because the request is still outstanding and we have
  412. // been handed another error from another stream which caused the
  413. // connection to close.
  414. c.releaseStream(stream)
  415. }
  416. return nil, err
  417. }
  418. case <-time.After(c.timeout):
  419. close(call.timeout)
  420. c.handleTimeout()
  421. return nil, ErrTimeoutNoResponse
  422. case <-c.quit:
  423. return nil, ErrConnectionClosed
  424. }
  425. // dont release the stream if detect a timeout as another request can reuse
  426. // that stream and get a response for the old request, which we have no
  427. // easy way of detecting.
  428. //
  429. // Ensure that the stream is not released if there are potentially outstanding
  430. // requests on the stream to prevent nil pointer dereferences in recv().
  431. defer c.releaseStream(stream)
  432. if v := framer.header.version.version(); v != c.version {
  433. return nil, NewErrProtocol("unexpected protocol version in response: got %d expected %d", v, c.version)
  434. }
  435. frame, err := framer.parseFrame()
  436. if err != nil {
  437. return nil, err
  438. }
  439. if len(framer.traceID) > 0 {
  440. tracer.Trace(framer.traceID)
  441. }
  442. return frame, nil
  443. }
  444. func (c *Conn) prepareStatement(stmt string, trace Tracer) (*resultPreparedFrame, error) {
  445. stmtsLRU.Lock()
  446. if stmtsLRU.lru == nil {
  447. initStmtsLRU(defaultMaxPreparedStmts)
  448. }
  449. stmtCacheKey := c.addr + c.currentKeyspace + stmt
  450. if val, ok := stmtsLRU.lru.Get(stmtCacheKey); ok {
  451. stmtsLRU.Unlock()
  452. flight := val.(*inflightPrepare)
  453. flight.wg.Wait()
  454. return flight.info, flight.err
  455. }
  456. flight := new(inflightPrepare)
  457. flight.wg.Add(1)
  458. stmtsLRU.lru.Add(stmtCacheKey, flight)
  459. stmtsLRU.Unlock()
  460. prep := &writePrepareFrame{
  461. statement: stmt,
  462. }
  463. resp, err := c.exec(prep, trace)
  464. if err != nil {
  465. flight.err = err
  466. flight.wg.Done()
  467. return nil, err
  468. }
  469. switch x := resp.(type) {
  470. case *resultPreparedFrame:
  471. flight.info = x
  472. case error:
  473. flight.err = x
  474. default:
  475. flight.err = NewErrProtocol("Unknown type in response to prepare frame: %s", x)
  476. }
  477. flight.wg.Done()
  478. if flight.err != nil {
  479. stmtsLRU.Lock()
  480. stmtsLRU.lru.Remove(stmtCacheKey)
  481. stmtsLRU.Unlock()
  482. }
  483. return flight.info, flight.err
  484. }
  485. func (c *Conn) executeQuery(qry *Query) *Iter {
  486. params := queryParams{
  487. consistency: qry.cons,
  488. }
  489. // frame checks that it is not 0
  490. params.serialConsistency = qry.serialCons
  491. params.defaultTimestamp = qry.defaultTimestamp
  492. if len(qry.pageState) > 0 {
  493. params.pagingState = qry.pageState
  494. }
  495. if qry.pageSize > 0 {
  496. params.pageSize = qry.pageSize
  497. }
  498. var frame frameWriter
  499. if qry.shouldPrepare() {
  500. // Prepare all DML queries. Other queries can not be prepared.
  501. info, err := c.prepareStatement(qry.stmt, qry.trace)
  502. if err != nil {
  503. return &Iter{err: err}
  504. }
  505. var values []interface{}
  506. if qry.binding == nil {
  507. values = qry.values
  508. } else {
  509. binding := &QueryInfo{
  510. Id: info.preparedID,
  511. Args: info.reqMeta.columns,
  512. Rval: info.respMeta.columns,
  513. }
  514. values, err = qry.binding(binding)
  515. if err != nil {
  516. return &Iter{err: err}
  517. }
  518. }
  519. if len(values) != len(info.reqMeta.columns) {
  520. return &Iter{err: ErrQueryArgLength}
  521. }
  522. params.values = make([]queryValues, len(values))
  523. for i := 0; i < len(values); i++ {
  524. val, err := Marshal(info.reqMeta.columns[i].TypeInfo, values[i])
  525. if err != nil {
  526. return &Iter{err: err}
  527. }
  528. v := &params.values[i]
  529. v.value = val
  530. // TODO: handle query binding names
  531. }
  532. frame = &writeExecuteFrame{
  533. preparedID: info.preparedID,
  534. params: params,
  535. }
  536. } else {
  537. frame = &writeQueryFrame{
  538. statement: qry.stmt,
  539. params: params,
  540. }
  541. }
  542. resp, err := c.exec(frame, qry.trace)
  543. if err != nil {
  544. return &Iter{err: err}
  545. }
  546. switch x := resp.(type) {
  547. case *resultVoidFrame:
  548. return &Iter{}
  549. case *resultRowsFrame:
  550. iter := &Iter{
  551. meta: x.meta,
  552. rows: x.rows,
  553. }
  554. if len(x.meta.pagingState) > 0 && !qry.disableAutoPage {
  555. iter.next = &nextIter{
  556. qry: *qry,
  557. pos: int((1 - qry.prefetch) * float64(len(iter.rows))),
  558. }
  559. iter.next.qry.pageState = x.meta.pagingState
  560. if iter.next.pos < 1 {
  561. iter.next.pos = 1
  562. }
  563. }
  564. return iter
  565. case *resultKeyspaceFrame, *resultSchemaChangeFrame, *schemaChangeKeyspace, *schemaChangeTable:
  566. return &Iter{}
  567. case *RequestErrUnprepared:
  568. stmtsLRU.Lock()
  569. stmtCacheKey := c.addr + c.currentKeyspace + qry.stmt
  570. if _, ok := stmtsLRU.lru.Get(stmtCacheKey); ok {
  571. stmtsLRU.lru.Remove(stmtCacheKey)
  572. stmtsLRU.Unlock()
  573. return c.executeQuery(qry)
  574. }
  575. stmtsLRU.Unlock()
  576. return &Iter{err: x}
  577. case error:
  578. return &Iter{err: x}
  579. default:
  580. return &Iter{err: NewErrProtocol("Unknown type in response to execute query (%T): %s", x, x)}
  581. }
  582. }
  583. func (c *Conn) Pick(qry *Query) *Conn {
  584. if c.Closed() {
  585. return nil
  586. }
  587. return c
  588. }
  589. func (c *Conn) Closed() bool {
  590. return atomic.LoadInt32(&c.closed) == 1
  591. }
  592. func (c *Conn) Address() string {
  593. return c.addr
  594. }
  595. func (c *Conn) AvailableStreams() int {
  596. return len(c.uniq)
  597. }
  598. func (c *Conn) UseKeyspace(keyspace string) error {
  599. q := &writeQueryFrame{statement: `USE "` + keyspace + `"`}
  600. q.params.consistency = Any
  601. resp, err := c.exec(q, nil)
  602. if err != nil {
  603. return err
  604. }
  605. switch x := resp.(type) {
  606. case *resultKeyspaceFrame:
  607. case error:
  608. return x
  609. default:
  610. return NewErrProtocol("unknown frame in response to USE: %v", x)
  611. }
  612. c.currentKeyspace = keyspace
  613. return nil
  614. }
  615. func (c *Conn) executeBatch(batch *Batch) (*Iter, error) {
  616. if c.version == protoVersion1 {
  617. return nil, ErrUnsupported
  618. }
  619. n := len(batch.Entries)
  620. req := &writeBatchFrame{
  621. typ: batch.Type,
  622. statements: make([]batchStatment, n),
  623. consistency: batch.Cons,
  624. serialConsistency: batch.serialCons,
  625. defaultTimestamp: batch.defaultTimestamp,
  626. }
  627. stmts := make(map[string]string)
  628. for i := 0; i < n; i++ {
  629. entry := &batch.Entries[i]
  630. b := &req.statements[i]
  631. if len(entry.Args) > 0 || entry.binding != nil {
  632. info, err := c.prepareStatement(entry.Stmt, nil)
  633. if err != nil {
  634. return nil, err
  635. }
  636. var args []interface{}
  637. if entry.binding == nil {
  638. args = entry.Args
  639. } else {
  640. binding := &QueryInfo{
  641. Id: info.preparedID,
  642. Args: info.reqMeta.columns,
  643. Rval: info.respMeta.columns,
  644. }
  645. args, err = entry.binding(binding)
  646. if err != nil {
  647. return nil, err
  648. }
  649. }
  650. if len(args) != len(info.reqMeta.columns) {
  651. return nil, ErrQueryArgLength
  652. }
  653. b.preparedID = info.preparedID
  654. stmts[string(info.preparedID)] = entry.Stmt
  655. b.values = make([]queryValues, len(info.reqMeta.columns))
  656. for j := 0; j < len(info.reqMeta.columns); j++ {
  657. val, err := Marshal(info.reqMeta.columns[j].TypeInfo, args[j])
  658. if err != nil {
  659. return nil, err
  660. }
  661. b.values[j].value = val
  662. // TODO: add names
  663. }
  664. } else {
  665. b.statement = entry.Stmt
  666. }
  667. }
  668. // TODO: should batch support tracing?
  669. resp, err := c.exec(req, nil)
  670. if err != nil {
  671. return nil, err
  672. }
  673. switch x := resp.(type) {
  674. case *resultVoidFrame:
  675. return nil, nil
  676. case *RequestErrUnprepared:
  677. stmt, found := stmts[string(x.StatementId)]
  678. if found {
  679. stmtsLRU.Lock()
  680. stmtsLRU.lru.Remove(c.addr + c.currentKeyspace + stmt)
  681. stmtsLRU.Unlock()
  682. }
  683. if found {
  684. return c.executeBatch(batch)
  685. } else {
  686. return nil, x
  687. }
  688. case *resultRowsFrame:
  689. iter := &Iter{
  690. meta: x.meta,
  691. rows: x.rows,
  692. }
  693. return iter, nil
  694. case error:
  695. return nil, x
  696. default:
  697. return nil, NewErrProtocol("Unknown type in response to batch statement: %s", x)
  698. }
  699. }
  700. func (c *Conn) setKeepalive(d time.Duration) error {
  701. if tc, ok := c.conn.(*net.TCPConn); ok {
  702. err := tc.SetKeepAlivePeriod(d)
  703. if err != nil {
  704. return err
  705. }
  706. return tc.SetKeepAlive(true)
  707. }
  708. return nil
  709. }
  710. func (c *Conn) awaitSchemaAgreement() (err error) {
  711. const (
  712. // TODO(zariel): if we export this make this configurable
  713. maxWaitTime = 60 * time.Second
  714. peerSchemas = "SELECT schema_version FROM system.peers"
  715. localSchemas = "SELECT schema_version FROM system.local WHERE key='local'"
  716. )
  717. endDeadline := time.Now().Add(maxWaitTime)
  718. for time.Now().Before(endDeadline) {
  719. iter := c.executeQuery(&Query{
  720. stmt: peerSchemas,
  721. cons: One,
  722. })
  723. versions := make(map[string]struct{})
  724. var schemaVersion string
  725. for iter.Scan(&schemaVersion) {
  726. versions[schemaVersion] = struct{}{}
  727. schemaVersion = ""
  728. }
  729. if err = iter.Close(); err != nil {
  730. goto cont
  731. }
  732. iter = c.executeQuery(&Query{
  733. stmt: localSchemas,
  734. cons: One,
  735. })
  736. for iter.Scan(&schemaVersion) {
  737. versions[schemaVersion] = struct{}{}
  738. schemaVersion = ""
  739. }
  740. if err = iter.Close(); err != nil {
  741. goto cont
  742. }
  743. if len(versions) <= 1 {
  744. return nil
  745. }
  746. cont:
  747. time.Sleep(200 * time.Millisecond)
  748. }
  749. if err != nil {
  750. return
  751. }
  752. // not exported
  753. return errors.New("gocql: cluster schema versions not consistent")
  754. }
  755. type inflightPrepare struct {
  756. info *resultPreparedFrame
  757. err error
  758. wg sync.WaitGroup
  759. }
  760. var (
  761. ErrQueryArgLength = errors.New("gocql: query argument length mismatch")
  762. ErrTimeoutNoResponse = errors.New("gocql: no response received from cassandra within timeout period")
  763. ErrTooManyTimeouts = errors.New("gocql: too many query timeouts on the connection")
  764. ErrConnectionClosed = errors.New("gocql: connection closed waiting for response")
  765. )