conn.go 26 KB

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