conn.go 24 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054
  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. type preparedStatment struct {
  492. id []byte
  493. request preparedMetadata
  494. response resultMetadata
  495. }
  496. type inflightPrepare struct {
  497. wg sync.WaitGroup
  498. err error
  499. preparedStatment *preparedStatment
  500. }
  501. func (c *Conn) prepareStatement(stmt string, tracer Tracer) (*preparedStatment, error) {
  502. c.session.stmtsLRU.Lock()
  503. stmtCacheKey := c.addr + c.currentKeyspace + stmt
  504. if val, ok := c.session.stmtsLRU.lru.Get(stmtCacheKey); ok {
  505. c.session.stmtsLRU.Unlock()
  506. flight := val.(*inflightPrepare)
  507. flight.wg.Wait()
  508. return flight.preparedStatment, flight.err
  509. }
  510. flight := new(inflightPrepare)
  511. flight.wg.Add(1)
  512. c.session.stmtsLRU.lru.Add(stmtCacheKey, flight)
  513. c.session.stmtsLRU.Unlock()
  514. prep := &writePrepareFrame{
  515. statement: stmt,
  516. }
  517. framer, err := c.exec(prep, tracer)
  518. if err != nil {
  519. flight.err = err
  520. flight.wg.Done()
  521. return nil, err
  522. }
  523. frame, err := framer.parseFrame()
  524. if err != nil {
  525. flight.err = err
  526. flight.wg.Done()
  527. return nil, err
  528. }
  529. // TODO(zariel): tidy this up, simplify handling of frame parsing so its not duplicated
  530. // everytime we need to parse a frame.
  531. if len(framer.traceID) > 0 {
  532. tracer.Trace(framer.traceID)
  533. }
  534. switch x := frame.(type) {
  535. case *resultPreparedFrame:
  536. flight.preparedStatment = &preparedStatment{
  537. // defensivly copy as we will recycle the underlying buffer after we
  538. // return.
  539. id: copyBytes(x.preparedID),
  540. // the type info's should _not_ have a reference to the framers read buffer,
  541. // therefore we can just copy them directly.
  542. request: x.reqMeta,
  543. response: x.respMeta,
  544. }
  545. case error:
  546. flight.err = x
  547. default:
  548. flight.err = NewErrProtocol("Unknown type in response to prepare frame: %s", x)
  549. }
  550. flight.wg.Done()
  551. if flight.err != nil {
  552. c.session.stmtsLRU.Lock()
  553. c.session.stmtsLRU.lru.Remove(stmtCacheKey)
  554. c.session.stmtsLRU.Unlock()
  555. }
  556. framerPool.Put(framer)
  557. return flight.preparedStatment, flight.err
  558. }
  559. func (c *Conn) executeQuery(qry *Query) *Iter {
  560. params := queryParams{
  561. consistency: qry.cons,
  562. }
  563. // frame checks that it is not 0
  564. params.serialConsistency = qry.serialCons
  565. params.defaultTimestamp = qry.defaultTimestamp
  566. if len(qry.pageState) > 0 {
  567. params.pagingState = qry.pageState
  568. }
  569. if qry.pageSize > 0 {
  570. params.pageSize = qry.pageSize
  571. }
  572. var (
  573. frame frameWriter
  574. info *preparedStatment
  575. )
  576. if qry.shouldPrepare() {
  577. // Prepare all DML queries. Other queries can not be prepared.
  578. var err error
  579. info, err = c.prepareStatement(qry.stmt, qry.trace)
  580. if err != nil {
  581. return &Iter{err: err}
  582. }
  583. var values []interface{}
  584. if qry.binding == nil {
  585. values = qry.values
  586. } else {
  587. values, err = qry.binding(&QueryInfo{
  588. Id: info.id,
  589. Args: info.request.columns,
  590. Rval: info.response.columns,
  591. PKeyColumns: info.request.pkeyColumns,
  592. })
  593. if err != nil {
  594. return &Iter{err: err}
  595. }
  596. }
  597. if len(values) != info.request.actualColCount {
  598. return &Iter{err: fmt.Errorf("gocql: expected %d values send got %d", info.request.actualColCount, len(values))}
  599. }
  600. params.values = make([]queryValues, len(values))
  601. for i := 0; i < len(values); i++ {
  602. val, err := Marshal(info.request.columns[i].TypeInfo, values[i])
  603. if err != nil {
  604. return &Iter{err: err}
  605. }
  606. v := &params.values[i]
  607. v.value = val
  608. // TODO: handle query binding names
  609. }
  610. params.skipMeta = !qry.isCAS
  611. frame = &writeExecuteFrame{
  612. preparedID: info.id,
  613. params: params,
  614. }
  615. } else {
  616. frame = &writeQueryFrame{
  617. statement: qry.stmt,
  618. params: params,
  619. }
  620. }
  621. framer, err := c.exec(frame, qry.trace)
  622. if err != nil {
  623. return &Iter{err: err}
  624. }
  625. resp, err := framer.parseFrame()
  626. if err != nil {
  627. return &Iter{err: err}
  628. }
  629. if len(framer.traceID) > 0 {
  630. qry.trace.Trace(framer.traceID)
  631. }
  632. switch x := resp.(type) {
  633. case *resultVoidFrame:
  634. return &Iter{framer: framer}
  635. case *resultRowsFrame:
  636. iter := &Iter{
  637. rows: x.rows,
  638. framer: framer,
  639. }
  640. if params.skipMeta {
  641. if info != nil {
  642. iter.meta = info.response
  643. iter.meta.pagingState = x.meta.pagingState
  644. } else {
  645. return &Iter{framer: framer, err: errors.New("gocql: did not receive metadata but prepared info is nil")}
  646. }
  647. } else {
  648. iter.meta = x.meta
  649. }
  650. if len(x.meta.pagingState) > 0 && !qry.disableAutoPage {
  651. iter.next = &nextIter{
  652. qry: *qry,
  653. pos: int((1 - qry.prefetch) * float64(len(iter.rows))),
  654. }
  655. iter.next.qry.pageState = copyBytes(x.meta.pagingState)
  656. if iter.next.pos < 1 {
  657. iter.next.pos = 1
  658. }
  659. }
  660. return iter
  661. case *resultKeyspaceFrame:
  662. return &Iter{framer: framer}
  663. case *schemaChangeKeyspace, *schemaChangeTable, *schemaChangeFunction:
  664. // Clear the statments cache so that we dont use stale table info for requests.
  665. // TODO: only reset a specific table/keyapce and only when it is changed.
  666. c.session.stmtsLRU.clear()
  667. iter := &Iter{framer: framer}
  668. if err := c.awaitSchemaAgreement(); err != nil {
  669. // TODO: should have this behind a flag
  670. log.Println(err)
  671. }
  672. // dont return an error from this, might be a good idea to give a warning
  673. // though. The impact of this returning an error would be that the cluster
  674. // is not consistent with regards to its schema.
  675. return iter
  676. case *RequestErrUnprepared:
  677. c.session.stmtsLRU.Lock()
  678. stmtCacheKey := c.addr + c.currentKeyspace + qry.stmt
  679. if _, ok := c.session.stmtsLRU.lru.Get(stmtCacheKey); ok {
  680. c.session.stmtsLRU.lru.Remove(stmtCacheKey)
  681. c.session.stmtsLRU.Unlock()
  682. return c.executeQuery(qry)
  683. }
  684. c.session.stmtsLRU.Unlock()
  685. return &Iter{err: x, framer: framer}
  686. case error:
  687. return &Iter{err: x, framer: framer}
  688. default:
  689. return &Iter{
  690. err: NewErrProtocol("Unknown type in response to execute query (%T): %s", x, x),
  691. framer: framer,
  692. }
  693. }
  694. }
  695. func (c *Conn) Pick(qry *Query) *Conn {
  696. if c.Closed() {
  697. return nil
  698. }
  699. return c
  700. }
  701. func (c *Conn) Closed() bool {
  702. return atomic.LoadInt32(&c.closed) == 1
  703. }
  704. func (c *Conn) Address() string {
  705. return c.addr
  706. }
  707. func (c *Conn) AvailableStreams() int {
  708. return c.streams.Available()
  709. }
  710. func (c *Conn) UseKeyspace(keyspace string) error {
  711. q := &writeQueryFrame{statement: `USE "` + keyspace + `"`}
  712. q.params.consistency = Any
  713. framer, err := c.exec(q, nil)
  714. if err != nil {
  715. return err
  716. }
  717. resp, err := framer.parseFrame()
  718. if err != nil {
  719. return err
  720. }
  721. switch x := resp.(type) {
  722. case *resultKeyspaceFrame:
  723. case error:
  724. return x
  725. default:
  726. return NewErrProtocol("unknown frame in response to USE: %v", x)
  727. }
  728. c.currentKeyspace = keyspace
  729. return nil
  730. }
  731. func (c *Conn) executeBatch(batch *Batch) *Iter {
  732. if c.version == protoVersion1 {
  733. return &Iter{err: ErrUnsupported}
  734. }
  735. n := len(batch.Entries)
  736. req := &writeBatchFrame{
  737. typ: batch.Type,
  738. statements: make([]batchStatment, n),
  739. consistency: batch.Cons,
  740. serialConsistency: batch.serialCons,
  741. defaultTimestamp: batch.defaultTimestamp,
  742. }
  743. stmts := make(map[string]string, len(batch.Entries))
  744. for i := 0; i < n; i++ {
  745. entry := &batch.Entries[i]
  746. b := &req.statements[i]
  747. if len(entry.Args) > 0 || entry.binding != nil {
  748. info, err := c.prepareStatement(entry.Stmt, nil)
  749. if err != nil {
  750. return &Iter{err: err}
  751. }
  752. var values []interface{}
  753. if entry.binding == nil {
  754. values = entry.Args
  755. } else {
  756. values, err = entry.binding(&QueryInfo{
  757. Id: info.id,
  758. Args: info.request.columns,
  759. Rval: info.response.columns,
  760. PKeyColumns: info.request.pkeyColumns,
  761. })
  762. if err != nil {
  763. return &Iter{err: err}
  764. }
  765. }
  766. if len(values) != info.request.actualColCount {
  767. return &Iter{err: fmt.Errorf("gocql: batch statment %d expected %d values send got %d", i, info.request.actualColCount, len(values))}
  768. }
  769. b.preparedID = info.id
  770. stmts[string(info.id)] = entry.Stmt
  771. b.values = make([]queryValues, info.request.actualColCount)
  772. for j := 0; j < info.request.actualColCount; j++ {
  773. val, err := Marshal(info.request.columns[j].TypeInfo, values[j])
  774. if err != nil {
  775. return &Iter{err: err}
  776. }
  777. b.values[j].value = val
  778. // TODO: add names
  779. }
  780. } else {
  781. b.statement = entry.Stmt
  782. }
  783. }
  784. // TODO: should batch support tracing?
  785. framer, err := c.exec(req, nil)
  786. if err != nil {
  787. return &Iter{err: err}
  788. }
  789. resp, err := framer.parseFrame()
  790. if err != nil {
  791. return &Iter{err: err, framer: framer}
  792. }
  793. switch x := resp.(type) {
  794. case *resultVoidFrame:
  795. framerPool.Put(framer)
  796. return &Iter{}
  797. case *RequestErrUnprepared:
  798. stmt, found := stmts[string(x.StatementId)]
  799. if found {
  800. c.session.stmtsLRU.Lock()
  801. c.session.stmtsLRU.lru.Remove(c.addr + c.currentKeyspace + stmt)
  802. c.session.stmtsLRU.Unlock()
  803. }
  804. framerPool.Put(framer)
  805. if found {
  806. return c.executeBatch(batch)
  807. } else {
  808. return &Iter{err: err, framer: framer}
  809. }
  810. case *resultRowsFrame:
  811. iter := &Iter{
  812. meta: x.meta,
  813. rows: x.rows,
  814. framer: framer,
  815. }
  816. return iter
  817. case error:
  818. return &Iter{err: err, framer: framer}
  819. default:
  820. return &Iter{err: NewErrProtocol("Unknown type in response to batch statement: %s", x), framer: framer}
  821. }
  822. }
  823. func (c *Conn) setKeepalive(d time.Duration) error {
  824. if tc, ok := c.conn.(*net.TCPConn); ok {
  825. err := tc.SetKeepAlivePeriod(d)
  826. if err != nil {
  827. return err
  828. }
  829. return tc.SetKeepAlive(true)
  830. }
  831. return nil
  832. }
  833. func (c *Conn) query(statement string, values ...interface{}) (iter *Iter) {
  834. q := c.session.Query(statement, values...).Consistency(One)
  835. return c.executeQuery(q)
  836. }
  837. func (c *Conn) awaitSchemaAgreement() (err error) {
  838. const (
  839. peerSchemas = "SELECT schema_version FROM system.peers"
  840. localSchemas = "SELECT schema_version FROM system.local WHERE key='local'"
  841. )
  842. var versions map[string]struct{}
  843. endDeadline := time.Now().Add(c.session.cfg.MaxWaitSchemaAgreement)
  844. for time.Now().Before(endDeadline) {
  845. iter := c.query(peerSchemas)
  846. versions = make(map[string]struct{})
  847. var schemaVersion string
  848. for iter.Scan(&schemaVersion) {
  849. versions[schemaVersion] = struct{}{}
  850. schemaVersion = ""
  851. }
  852. if err = iter.Close(); err != nil {
  853. goto cont
  854. }
  855. iter = c.query(localSchemas)
  856. for iter.Scan(&schemaVersion) {
  857. versions[schemaVersion] = struct{}{}
  858. schemaVersion = ""
  859. }
  860. if err = iter.Close(); err != nil {
  861. goto cont
  862. }
  863. if len(versions) <= 1 {
  864. return nil
  865. }
  866. cont:
  867. time.Sleep(200 * time.Millisecond)
  868. }
  869. if err != nil {
  870. return
  871. }
  872. schemas := make([]string, 0, len(versions))
  873. for schema := range versions {
  874. schemas = append(schemas, schema)
  875. }
  876. // not exported
  877. return fmt.Errorf("gocql: cluster schema versions not consistent: %+v", schemas)
  878. }
  879. var (
  880. ErrQueryArgLength = errors.New("gocql: query argument length mismatch")
  881. ErrTimeoutNoResponse = errors.New("gocql: no response received from cassandra within timeout period")
  882. ErrTooManyTimeouts = errors.New("gocql: too many query timeouts on the connection")
  883. ErrConnectionClosed = errors.New("gocql: connection closed waiting for response")
  884. ErrNoStreams = errors.New("gocql: no streams available on connection")
  885. )