conn.go 23 KB

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