conn.go 27 KB

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