conn.go 20 KB

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