conn.go 26 KB

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