conn.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958
  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. framer, err := c.exec(&writeStartupFrame{opts: m}, nil)
  202. if err != nil {
  203. return err
  204. }
  205. frame, err := framer.parseFrame()
  206. if err != nil {
  207. return err
  208. }
  209. switch v := frame.(type) {
  210. case error:
  211. return v
  212. case *readyFrame:
  213. return nil
  214. case *authenticateFrame:
  215. return c.authenticateHandshake(v)
  216. default:
  217. return NewErrProtocol("Unknown type of response to startup frame: %s", v)
  218. }
  219. }
  220. func (c *Conn) authenticateHandshake(authFrame *authenticateFrame) error {
  221. if c.auth == nil {
  222. return fmt.Errorf("authentication required (using %q)", authFrame.class)
  223. }
  224. resp, challenger, err := c.auth.Challenge([]byte(authFrame.class))
  225. if err != nil {
  226. return err
  227. }
  228. req := &writeAuthResponseFrame{data: resp}
  229. for {
  230. framer, err := c.exec(req, nil)
  231. if err != nil {
  232. return err
  233. }
  234. frame, err := framer.parseFrame()
  235. if err != nil {
  236. return err
  237. }
  238. switch v := frame.(type) {
  239. case error:
  240. return v
  241. case *authSuccessFrame:
  242. if challenger != nil {
  243. return challenger.Success(v.data)
  244. }
  245. return nil
  246. case *authChallengeFrame:
  247. resp, challenger, err = challenger.Challenge(v.data)
  248. if err != nil {
  249. return err
  250. }
  251. req = &writeAuthResponseFrame{
  252. data: resp,
  253. }
  254. default:
  255. return fmt.Errorf("unknown frame response during authentication: %v", v)
  256. }
  257. framerPool.Put(framer)
  258. }
  259. }
  260. func (c *Conn) closeWithError(err error) {
  261. if !atomic.CompareAndSwapInt32(&c.closed, 0, 1) {
  262. return
  263. }
  264. if err != nil {
  265. // we should attempt to deliver the error back to the caller if it
  266. // exists
  267. for id := 0; id < len(c.calls); id++ {
  268. req := &c.calls[id]
  269. // we need to send the error to all waiting queries, put the state
  270. // of this conn into not active so that it can not execute any queries.
  271. if err != nil {
  272. select {
  273. case req.resp <- err:
  274. default:
  275. }
  276. }
  277. }
  278. }
  279. // if error was nil then unblock the quit channel
  280. close(c.quit)
  281. c.conn.Close()
  282. if c.started && err != nil {
  283. c.errorHandler.HandleError(c, err, true)
  284. }
  285. }
  286. func (c *Conn) Close() {
  287. c.closeWithError(nil)
  288. }
  289. // Serve starts the stream multiplexer for this connection, which is required
  290. // to execute any queries. This method runs as long as the connection is
  291. // open and is therefore usually called in a separate goroutine.
  292. func (c *Conn) serve() {
  293. var (
  294. err error
  295. )
  296. for {
  297. err = c.recv()
  298. if err != nil {
  299. break
  300. }
  301. }
  302. c.closeWithError(err)
  303. }
  304. func (c *Conn) discardFrame(head frameHeader) error {
  305. _, err := io.CopyN(ioutil.Discard, c, int64(head.length))
  306. if err != nil {
  307. return err
  308. }
  309. return nil
  310. }
  311. func (c *Conn) recv() error {
  312. // not safe for concurrent reads
  313. // read a full header, ignore timeouts, as this is being ran in a loop
  314. // TODO: TCP level deadlines? or just query level deadlines?
  315. if c.timeout > 0 {
  316. c.conn.SetReadDeadline(time.Time{})
  317. }
  318. // were just reading headers over and over and copy bodies
  319. head, err := readHeader(c.r, c.headerBuf)
  320. if err != nil {
  321. return err
  322. }
  323. if head.stream > len(c.calls) {
  324. return fmt.Errorf("gocql: frame header stream is beyond call exepected bounds: %d", head.stream)
  325. } else if head.stream == -1 {
  326. // TODO: handle cassandra event frames, we shouldnt get any currently
  327. return c.discardFrame(head)
  328. } else if head.stream <= 0 {
  329. // reserved stream that we dont use, probably due to a protocol error
  330. // or a bug in Cassandra, this should be an error, parse it and return.
  331. framer := newFramer(c, c, c.compressor, c.version)
  332. if err := framer.readFrame(&head); err != nil {
  333. return err
  334. }
  335. defer framerPool.Put(framer)
  336. frame, err := framer.parseFrame()
  337. if err != nil {
  338. return err
  339. }
  340. switch v := frame.(type) {
  341. case error:
  342. return fmt.Errorf("gocql: error on stream %d: %v", head.stream, v)
  343. default:
  344. return fmt.Errorf("gocql: received frame on stream %d: %v", head.stream, frame)
  345. }
  346. }
  347. call := &c.calls[head.stream]
  348. if call == nil || call.framer == nil {
  349. log.Printf("gocql: received response for stream which has no handler: header=%v\n", head)
  350. return c.discardFrame(head)
  351. }
  352. err = call.framer.readFrame(&head)
  353. if err != nil {
  354. // only net errors should cause the connection to be closed. Though
  355. // cassandra returning corrupt frames will be returned here as well.
  356. if _, ok := err.(net.Error); ok {
  357. return err
  358. }
  359. }
  360. // we either, return a response to the caller, the caller timedout, or the
  361. // connection has closed. Either way we should never block indefinatly here
  362. select {
  363. case call.resp <- err:
  364. case <-call.timeout:
  365. c.releaseStream(head.stream)
  366. case <-c.quit:
  367. }
  368. return nil
  369. }
  370. type callReq struct {
  371. // could use a waitgroup but this allows us to do timeouts on the read/send
  372. resp chan error
  373. framer *framer
  374. timeout chan struct{} // indicates to recv() that a call has timedout
  375. }
  376. func (c *Conn) releaseStream(stream int) {
  377. call := &c.calls[stream]
  378. call.framer = nil
  379. select {
  380. case c.uniq <- stream:
  381. case <-c.quit:
  382. }
  383. }
  384. func (c *Conn) handleTimeout() {
  385. if atomic.AddInt64(&c.timeouts, 1) > TimeoutLimit {
  386. c.closeWithError(ErrTooManyTimeouts)
  387. }
  388. }
  389. func (c *Conn) exec(req frameWriter, tracer Tracer) (*framer, error) {
  390. // TODO: move tracer onto conn
  391. var stream int
  392. select {
  393. case stream = <-c.uniq:
  394. case <-c.quit:
  395. return nil, ErrConnectionClosed
  396. }
  397. // resp is basically a waiting semaphore protecting the framer
  398. framer := newFramer(c, c, c.compressor, c.version)
  399. call := &c.calls[stream]
  400. call.framer = framer
  401. call.timeout = make(chan struct{})
  402. if tracer != nil {
  403. framer.trace()
  404. }
  405. err := req.writeFrame(framer, stream)
  406. if err != nil {
  407. // I think this is the correct thing to do, im not entirely sure. It is not
  408. // ideal as readers might still get some data, but they probably wont.
  409. // Here we need to be careful as the stream is not available and if all
  410. // writes just timeout or fail then the pool might use this connection to
  411. // send a frame on, with all the streams used up and not returned.
  412. c.closeWithError(err)
  413. return nil, err
  414. }
  415. select {
  416. case err := <-call.resp:
  417. if err != nil {
  418. if !c.Closed() {
  419. // if the connection is closed then we cant release the stream,
  420. // this is because the request is still outstanding and we have
  421. // been handed another error from another stream which caused the
  422. // connection to close.
  423. c.releaseStream(stream)
  424. }
  425. return nil, err
  426. }
  427. case <-time.After(c.timeout):
  428. close(call.timeout)
  429. c.handleTimeout()
  430. return nil, ErrTimeoutNoResponse
  431. case <-c.quit:
  432. return nil, ErrConnectionClosed
  433. }
  434. // dont release the stream if detect a timeout as another request can reuse
  435. // that stream and get a response for the old request, which we have no
  436. // easy way of detecting.
  437. //
  438. // Ensure that the stream is not released if there are potentially outstanding
  439. // requests on the stream to prevent nil pointer dereferences in recv().
  440. defer c.releaseStream(stream)
  441. if v := framer.header.version.version(); v != c.version {
  442. return nil, NewErrProtocol("unexpected protocol version in response: got %d expected %d", v, c.version)
  443. }
  444. return framer, nil
  445. }
  446. func (c *Conn) prepareStatement(stmt string, tracer Tracer) (*QueryInfo, error) {
  447. stmtsLRU.Lock()
  448. if stmtsLRU.lru == nil {
  449. initStmtsLRU(defaultMaxPreparedStmts)
  450. }
  451. stmtCacheKey := c.addr + c.currentKeyspace + stmt
  452. if val, ok := stmtsLRU.lru.Get(stmtCacheKey); ok {
  453. stmtsLRU.Unlock()
  454. flight := val.(*inflightPrepare)
  455. flight.wg.Wait()
  456. return &flight.info, flight.err
  457. }
  458. flight := new(inflightPrepare)
  459. flight.wg.Add(1)
  460. stmtsLRU.lru.Add(stmtCacheKey, flight)
  461. stmtsLRU.Unlock()
  462. prep := &writePrepareFrame{
  463. statement: stmt,
  464. }
  465. framer, err := c.exec(prep, tracer)
  466. if err != nil {
  467. flight.err = err
  468. flight.wg.Done()
  469. return nil, err
  470. }
  471. frame, err := framer.parseFrame()
  472. if err != nil {
  473. flight.err = err
  474. flight.wg.Done()
  475. return nil, err
  476. }
  477. // TODO(zariel): tidy this up, simplify handling of frame parsing so its not duplicated
  478. // everytime we need to parse a frame.
  479. if len(framer.traceID) > 0 {
  480. tracer.Trace(framer.traceID)
  481. }
  482. switch x := frame.(type) {
  483. case *resultPreparedFrame:
  484. // defensivly copy as we will recycle the underlying buffer after we
  485. // return.
  486. flight.info.Id = copyBytes(x.preparedID)
  487. // the type info's should _not_ have a reference to the framers read buffer,
  488. // therefore we can just copy them directly.
  489. flight.info.Args = x.reqMeta.columns
  490. flight.info.PKeyColumns = x.reqMeta.pkeyColumns
  491. flight.info.Rval = x.respMeta.columns
  492. case error:
  493. flight.err = x
  494. default:
  495. flight.err = NewErrProtocol("Unknown type in response to prepare frame: %s", x)
  496. }
  497. flight.wg.Done()
  498. if flight.err != nil {
  499. stmtsLRU.Lock()
  500. stmtsLRU.lru.Remove(stmtCacheKey)
  501. stmtsLRU.Unlock()
  502. }
  503. framerPool.Put(framer)
  504. return &flight.info, flight.err
  505. }
  506. func (c *Conn) executeQuery(qry *Query) *Iter {
  507. params := queryParams{
  508. consistency: qry.cons,
  509. }
  510. // frame checks that it is not 0
  511. params.serialConsistency = qry.serialCons
  512. params.defaultTimestamp = qry.defaultTimestamp
  513. if len(qry.pageState) > 0 {
  514. params.pagingState = qry.pageState
  515. }
  516. if qry.pageSize > 0 {
  517. params.pageSize = qry.pageSize
  518. }
  519. var frame frameWriter
  520. if qry.shouldPrepare() {
  521. // Prepare all DML queries. Other queries can not be prepared.
  522. info, err := c.prepareStatement(qry.stmt, qry.trace)
  523. if err != nil {
  524. return &Iter{err: err}
  525. }
  526. var values []interface{}
  527. if qry.binding == nil {
  528. values = qry.values
  529. } else {
  530. values, err = qry.binding(info)
  531. if err != nil {
  532. return &Iter{err: err}
  533. }
  534. }
  535. if len(values) != len(info.Args) {
  536. return &Iter{err: ErrQueryArgLength}
  537. }
  538. params.values = make([]queryValues, len(values))
  539. for i := 0; i < len(values); i++ {
  540. val, err := Marshal(info.Args[i].TypeInfo, values[i])
  541. if err != nil {
  542. return &Iter{err: err}
  543. }
  544. v := &params.values[i]
  545. v.value = val
  546. // TODO: handle query binding names
  547. }
  548. frame = &writeExecuteFrame{
  549. preparedID: info.Id,
  550. params: params,
  551. }
  552. } else {
  553. frame = &writeQueryFrame{
  554. statement: qry.stmt,
  555. params: params,
  556. }
  557. }
  558. framer, err := c.exec(frame, qry.trace)
  559. if err != nil {
  560. return &Iter{err: err}
  561. }
  562. resp, err := framer.parseFrame()
  563. if err != nil {
  564. return &Iter{err: err}
  565. }
  566. if len(framer.traceID) > 0 {
  567. qry.trace.Trace(framer.traceID)
  568. }
  569. switch x := resp.(type) {
  570. case *resultVoidFrame:
  571. return &Iter{framer: framer}
  572. case *resultRowsFrame:
  573. iter := &Iter{
  574. meta: x.meta,
  575. rows: x.rows,
  576. framer: framer,
  577. }
  578. if len(x.meta.pagingState) > 0 && !qry.disableAutoPage {
  579. iter.next = &nextIter{
  580. qry: *qry,
  581. pos: int((1 - qry.prefetch) * float64(len(iter.rows))),
  582. }
  583. iter.next.qry.pageState = x.meta.pagingState
  584. if iter.next.pos < 1 {
  585. iter.next.pos = 1
  586. }
  587. }
  588. return iter
  589. case *resultKeyspaceFrame, *resultSchemaChangeFrame, *schemaChangeKeyspace, *schemaChangeTable:
  590. return &Iter{framer: framer}
  591. case *RequestErrUnprepared:
  592. stmtsLRU.Lock()
  593. stmtCacheKey := c.addr + c.currentKeyspace + qry.stmt
  594. if _, ok := stmtsLRU.lru.Get(stmtCacheKey); ok {
  595. stmtsLRU.lru.Remove(stmtCacheKey)
  596. stmtsLRU.Unlock()
  597. return c.executeQuery(qry)
  598. }
  599. stmtsLRU.Unlock()
  600. return &Iter{err: x, framer: framer}
  601. case error:
  602. return &Iter{err: x, framer: framer}
  603. default:
  604. return &Iter{
  605. err: NewErrProtocol("Unknown type in response to execute query (%T): %s", x, x),
  606. framer: framer,
  607. }
  608. }
  609. }
  610. func (c *Conn) Pick(qry *Query) *Conn {
  611. if c.Closed() {
  612. return nil
  613. }
  614. return c
  615. }
  616. func (c *Conn) Closed() bool {
  617. return atomic.LoadInt32(&c.closed) == 1
  618. }
  619. func (c *Conn) Address() string {
  620. return c.addr
  621. }
  622. func (c *Conn) AvailableStreams() int {
  623. return len(c.uniq)
  624. }
  625. func (c *Conn) UseKeyspace(keyspace string) error {
  626. q := &writeQueryFrame{statement: `USE "` + keyspace + `"`}
  627. q.params.consistency = Any
  628. framer, err := c.exec(q, nil)
  629. if err != nil {
  630. return err
  631. }
  632. resp, err := framer.parseFrame()
  633. if err != nil {
  634. return err
  635. }
  636. switch x := resp.(type) {
  637. case *resultKeyspaceFrame:
  638. case error:
  639. return x
  640. default:
  641. return NewErrProtocol("unknown frame in response to USE: %v", x)
  642. }
  643. c.currentKeyspace = keyspace
  644. return nil
  645. }
  646. func (c *Conn) executeBatch(batch *Batch) (*Iter, error) {
  647. if c.version == protoVersion1 {
  648. return nil, ErrUnsupported
  649. }
  650. n := len(batch.Entries)
  651. req := &writeBatchFrame{
  652. typ: batch.Type,
  653. statements: make([]batchStatment, n),
  654. consistency: batch.Cons,
  655. serialConsistency: batch.serialCons,
  656. defaultTimestamp: batch.defaultTimestamp,
  657. }
  658. stmts := make(map[string]string)
  659. for i := 0; i < n; i++ {
  660. entry := &batch.Entries[i]
  661. b := &req.statements[i]
  662. if len(entry.Args) > 0 || entry.binding != nil {
  663. info, err := c.prepareStatement(entry.Stmt, nil)
  664. if err != nil {
  665. return nil, err
  666. }
  667. var args []interface{}
  668. if entry.binding == nil {
  669. args = entry.Args
  670. } else {
  671. args, err = entry.binding(info)
  672. if err != nil {
  673. return nil, err
  674. }
  675. }
  676. if len(args) != len(info.Args) {
  677. return nil, ErrQueryArgLength
  678. }
  679. b.preparedID = info.Id
  680. stmts[string(info.Id)] = entry.Stmt
  681. b.values = make([]queryValues, len(info.Args))
  682. for j := 0; j < len(info.Args); j++ {
  683. val, err := Marshal(info.Args[j].TypeInfo, args[j])
  684. if err != nil {
  685. return nil, err
  686. }
  687. b.values[j].value = val
  688. // TODO: add names
  689. }
  690. } else {
  691. b.statement = entry.Stmt
  692. }
  693. }
  694. // TODO: should batch support tracing?
  695. framer, err := c.exec(req, nil)
  696. if err != nil {
  697. return nil, err
  698. }
  699. resp, err := framer.parseFrame()
  700. if err != nil {
  701. return nil, err
  702. }
  703. switch x := resp.(type) {
  704. case *resultVoidFrame:
  705. framerPool.Put(framer)
  706. return nil, nil
  707. case *RequestErrUnprepared:
  708. stmt, found := stmts[string(x.StatementId)]
  709. if found {
  710. stmtsLRU.Lock()
  711. stmtsLRU.lru.Remove(c.addr + c.currentKeyspace + stmt)
  712. stmtsLRU.Unlock()
  713. }
  714. framerPool.Put(framer)
  715. if found {
  716. return c.executeBatch(batch)
  717. } else {
  718. return nil, x
  719. }
  720. case *resultRowsFrame:
  721. iter := &Iter{
  722. meta: x.meta,
  723. rows: x.rows,
  724. framer: framer,
  725. }
  726. return iter, nil
  727. case error:
  728. framerPool.Put(framer)
  729. return nil, x
  730. default:
  731. framerPool.Put(framer)
  732. return nil, NewErrProtocol("Unknown type in response to batch statement: %s", x)
  733. }
  734. }
  735. func (c *Conn) setKeepalive(d time.Duration) error {
  736. if tc, ok := c.conn.(*net.TCPConn); ok {
  737. err := tc.SetKeepAlivePeriod(d)
  738. if err != nil {
  739. return err
  740. }
  741. return tc.SetKeepAlive(true)
  742. }
  743. return nil
  744. }
  745. func (c *Conn) awaitSchemaAgreement() (err error) {
  746. const (
  747. // TODO(zariel): if we export this make this configurable
  748. maxWaitTime = 60 * time.Second
  749. peerSchemas = "SELECT schema_version FROM system.peers"
  750. localSchemas = "SELECT schema_version FROM system.local WHERE key='local'"
  751. )
  752. endDeadline := time.Now().Add(maxWaitTime)
  753. for time.Now().Before(endDeadline) {
  754. iter := c.executeQuery(&Query{
  755. stmt: peerSchemas,
  756. cons: One,
  757. })
  758. versions := make(map[string]struct{})
  759. var schemaVersion string
  760. for iter.Scan(&schemaVersion) {
  761. versions[schemaVersion] = struct{}{}
  762. schemaVersion = ""
  763. }
  764. if err = iter.Close(); err != nil {
  765. goto cont
  766. }
  767. iter = c.executeQuery(&Query{
  768. stmt: localSchemas,
  769. cons: One,
  770. })
  771. for iter.Scan(&schemaVersion) {
  772. versions[schemaVersion] = struct{}{}
  773. schemaVersion = ""
  774. }
  775. if err = iter.Close(); err != nil {
  776. goto cont
  777. }
  778. if len(versions) <= 1 {
  779. return nil
  780. }
  781. cont:
  782. time.Sleep(200 * time.Millisecond)
  783. }
  784. if err != nil {
  785. return
  786. }
  787. // not exported
  788. return errors.New("gocql: cluster schema versions not consistent")
  789. }
  790. type inflightPrepare struct {
  791. info QueryInfo
  792. err error
  793. wg sync.WaitGroup
  794. }
  795. var (
  796. ErrQueryArgLength = errors.New("gocql: query argument length mismatch")
  797. ErrTimeoutNoResponse = errors.New("gocql: no response received from cassandra within timeout period")
  798. ErrTooManyTimeouts = errors.New("gocql: too many query timeouts on the connection")
  799. ErrConnectionClosed = errors.New("gocql: connection closed waiting for response")
  800. )