conn.go 22 KB

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