conn.go 22 KB

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