conn.go 25 KB

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