conn.go 23 KB

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