conn.go 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235
  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. session *Session
  122. closed int32
  123. quit chan struct{}
  124. timeouts int64
  125. frameWriteArgChan chan *callReq
  126. }
  127. // Connect establishes a connection to a Cassandra node.
  128. func (s *Session) dial(ip net.IP, port int, cfg *ConnConfig, errorHandler ConnErrorHandler) (*Conn, error) {
  129. // TODO(zariel): remove these
  130. if len(ip) == 0 || ip.IsUnspecified() {
  131. panic(fmt.Sprintf("host missing connect ip address: %v", ip))
  132. } else if port == 0 {
  133. panic(fmt.Sprintf("host missing port: %v", port))
  134. }
  135. var (
  136. err error
  137. conn net.Conn
  138. )
  139. dialer := &net.Dialer{
  140. Timeout: cfg.ConnectTimeout,
  141. }
  142. // TODO(zariel): handle ipv6 zone
  143. addr := (&net.TCPAddr{IP: ip, Port: port}).String()
  144. if cfg.tlsConfig != nil {
  145. // the TLS config is safe to be reused by connections but it must not
  146. // be modified after being used.
  147. conn, err = tls.DialWithDialer(dialer, "tcp", addr, cfg.tlsConfig)
  148. } else {
  149. conn, err = dialer.Dial("tcp", addr)
  150. }
  151. if err != nil {
  152. return nil, err
  153. }
  154. c := &Conn{
  155. conn: conn,
  156. r: bufio.NewReader(conn),
  157. cfg: cfg,
  158. calls: make(map[int]*callReq),
  159. timeout: cfg.Timeout,
  160. version: uint8(cfg.ProtoVersion),
  161. addr: conn.RemoteAddr().String(),
  162. errorHandler: errorHandler,
  163. compressor: cfg.Compressor,
  164. auth: cfg.Authenticator,
  165. quit: make(chan struct{}),
  166. session: s,
  167. streams: streams.New(cfg.ProtoVersion),
  168. frameWriteArgChan: make(chan *callReq),
  169. }
  170. if cfg.Keepalive > 0 {
  171. c.setKeepalive(cfg.Keepalive)
  172. }
  173. var (
  174. ctx context.Context
  175. cancel func()
  176. )
  177. if cfg.ConnectTimeout > 0 {
  178. ctx, cancel = context.WithTimeout(context.Background(), cfg.ConnectTimeout)
  179. } else {
  180. ctx, cancel = context.WithCancel(context.Background())
  181. }
  182. defer cancel()
  183. frameTicker := make(chan struct{}, 1)
  184. startupErr := make(chan error)
  185. go c.writeToConn()
  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. 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. // writeToConn() processes writing to the connection, which is required before any write
  371. // to Conn and is usually called in a separate goroutine.
  372. func (c *Conn) writeToConn() {
  373. for {
  374. select {
  375. case call := <-c.frameWriteArgChan:
  376. if err := call.req.writeFrame(call.framer, call.streamID); err != nil {
  377. // I think this is the correct thing to do, im not entirely sure. It is not
  378. // ideal as readers might still get some data, but they probably wont.
  379. // Here we need to be careful as the stream is not available and if all
  380. // writes just timeout or fail then the pool might use this connection to
  381. // send a frame on, with all the streams used up and not returned.
  382. c.closeWithError(err)
  383. return
  384. }
  385. case <-c.quit:
  386. return
  387. }
  388. }
  389. }
  390. type protocolError struct {
  391. frame frame
  392. }
  393. func (p *protocolError) Error() string {
  394. if err, ok := p.frame.(error); ok {
  395. return err.Error()
  396. }
  397. return fmt.Sprintf("gocql: received unexpected frame on stream %d: %v", p.frame.Header().stream, p.frame)
  398. }
  399. func (c *Conn) recv() error {
  400. // not safe for concurrent reads
  401. // read a full header, ignore timeouts, as this is being ran in a loop
  402. // TODO: TCP level deadlines? or just query level deadlines?
  403. if c.timeout > 0 {
  404. c.conn.SetReadDeadline(time.Time{})
  405. }
  406. // were just reading headers over and over and copy bodies
  407. head, err := readHeader(c.r, c.headerBuf[:])
  408. if err != nil {
  409. return err
  410. }
  411. if head.stream > c.streams.NumStreams {
  412. return fmt.Errorf("gocql: frame header stream is beyond call exepected bounds: %d", head.stream)
  413. } else if head.stream == -1 {
  414. // TODO: handle cassandra event frames, we shouldnt get any currently
  415. framer := newFramer(c, c, c.compressor, c.version)
  416. if err := framer.readFrame(&head); err != nil {
  417. return err
  418. }
  419. go c.session.handleEvent(framer)
  420. return nil
  421. } else if head.stream <= 0 {
  422. // reserved stream that we dont use, probably due to a protocol error
  423. // or a bug in Cassandra, this should be an error, parse it and return.
  424. framer := newFramer(c, c, c.compressor, c.version)
  425. if err := framer.readFrame(&head); err != nil {
  426. return err
  427. }
  428. defer framerPool.Put(framer)
  429. frame, err := framer.parseFrame()
  430. if err != nil {
  431. return err
  432. }
  433. return &protocolError{
  434. frame: frame,
  435. }
  436. }
  437. c.mu.RLock()
  438. call, ok := c.calls[head.stream]
  439. c.mu.RUnlock()
  440. if call == nil || call.framer == nil || !ok {
  441. Logger.Printf("gocql: received response for stream which has no handler: header=%v\n", head)
  442. return c.discardFrame(head)
  443. }
  444. err = call.framer.readFrame(&head)
  445. if err != nil {
  446. // only net errors should cause the connection to be closed. Though
  447. // cassandra returning corrupt frames will be returned here as well.
  448. if _, ok := err.(net.Error); ok {
  449. return err
  450. }
  451. }
  452. // we either, return a response to the caller, the caller timedout, or the
  453. // connection has closed. Either way we should never block indefinatly here
  454. select {
  455. case call.resp <- err:
  456. case <-call.timeout:
  457. c.releaseStream(head.stream)
  458. case <-c.quit:
  459. }
  460. return nil
  461. }
  462. func (c *Conn) releaseStream(stream int) {
  463. c.mu.Lock()
  464. call := c.calls[stream]
  465. if call != nil && stream != call.streamID {
  466. panic(fmt.Sprintf("attempt to release streamID with ivalid stream: %d -> %+v\n", stream, call))
  467. } else if call == nil {
  468. panic(fmt.Sprintf("releasing a stream not in use: %d", stream))
  469. }
  470. delete(c.calls, stream)
  471. c.mu.Unlock()
  472. if call.timer != nil {
  473. call.timer.Stop()
  474. }
  475. streamPool.Put(call)
  476. c.streams.Clear(stream)
  477. }
  478. func (c *Conn) handleTimeout() {
  479. if TimeoutLimit > 0 && atomic.AddInt64(&c.timeouts, 1) > TimeoutLimit {
  480. c.closeWithError(ErrTooManyTimeouts)
  481. }
  482. }
  483. var (
  484. streamPool = sync.Pool{
  485. New: func() interface{} {
  486. return &callReq{
  487. resp: make(chan error),
  488. }
  489. },
  490. }
  491. )
  492. type callReq struct {
  493. // could use a waitgroup but this allows us to do timeouts on the read/send
  494. resp chan error
  495. framer *framer
  496. timeout chan struct{} // indicates to recv() that a call has timedout
  497. streamID int // current stream in use
  498. req frameWriter
  499. timer *time.Timer
  500. }
  501. func (c *callReq) resetTimeout(timeout time.Duration) <-chan time.Time {
  502. var timeoutCh <-chan time.Time
  503. if timeout > 0 {
  504. if c.timer == nil {
  505. c.timer = time.NewTimer(0)
  506. <-c.timer.C
  507. } else {
  508. if !c.timer.Stop() {
  509. select {
  510. case <-c.timer.C:
  511. default:
  512. }
  513. }
  514. }
  515. c.timer.Reset(timeout)
  516. timeoutCh = c.timer.C
  517. }
  518. return timeoutCh
  519. }
  520. func (c *Conn) exec(ctx context.Context, req frameWriter, tracer Tracer) (*framer, error) {
  521. // TODO: move tracer onto conn
  522. stream, ok := c.streams.GetStream()
  523. if !ok {
  524. return nil, ErrNoStreams
  525. }
  526. // resp is basically a waiting semaphore protecting the framer
  527. framer := newFramer(c, c, c.compressor, c.version)
  528. call := streamPool.Get().(*callReq)
  529. call.framer = framer
  530. call.timeout = make(chan struct{})
  531. call.streamID = stream
  532. call.req = req
  533. c.mu.Lock()
  534. existingCall := c.calls[stream]
  535. if existingCall == nil {
  536. c.calls[stream] = call
  537. }
  538. c.mu.Unlock()
  539. if existingCall != nil {
  540. return nil, fmt.Errorf("attempting to use stream already in use: %d -> %d", stream, existingCall.streamID)
  541. }
  542. if tracer != nil {
  543. framer.trace()
  544. }
  545. timeoutCh := call.resetTimeout(c.timeout)
  546. if err := c.sendFrame(ctx, call, timeoutCh); err != nil {
  547. return nil, err
  548. }
  549. if err := c.getResp(ctx, call, timeoutCh); err != nil {
  550. return nil, err
  551. }
  552. // dont release the stream if detect a timeout as another request can reuse
  553. // that stream and get a response for the old request, which we have no
  554. // easy way of detecting.
  555. //
  556. // Ensure that the stream is not released if there are potentially outstanding
  557. // requests on the stream to prevent nil pointer dereferences in recv().
  558. defer c.releaseStream(stream)
  559. if v := framer.header.version.version(); v != c.version {
  560. return nil, NewErrProtocol("unexpected protocol version in response: got %d expected %d", v, c.version)
  561. }
  562. return framer, nil
  563. }
  564. func (c *Conn) getResp(ctx context.Context, call *callReq, timeoutCh <-chan time.Time) error {
  565. var ctxDone <-chan struct{}
  566. if ctx != nil {
  567. ctxDone = ctx.Done()
  568. }
  569. select {
  570. case err := <-call.resp:
  571. close(call.timeout)
  572. if err != nil {
  573. if !c.Closed() {
  574. // if the connection is closed then we cant release the stream,
  575. // this is because the request is still outstanding and we have
  576. // been handed another error from another stream which caused the
  577. // connection to close.
  578. c.releaseStream(call.streamID)
  579. }
  580. return err
  581. }
  582. return nil
  583. case <-timeoutCh:
  584. close(call.timeout)
  585. c.handleTimeout()
  586. return ErrTimeoutNoResponse
  587. case <-ctxDone:
  588. close(call.timeout)
  589. return ctx.Err()
  590. case <-c.quit:
  591. return ErrConnectionClosed
  592. }
  593. }
  594. func (c *Conn) sendFrame(ctx context.Context, call *callReq, timeoutCh <-chan time.Time) error {
  595. var ctxDone <-chan struct{}
  596. if ctx != nil {
  597. ctxDone = ctx.Done()
  598. }
  599. select {
  600. case c.frameWriteArgChan <- call:
  601. return nil
  602. case <-timeoutCh:
  603. c.releaseStream(call.streamID)
  604. close(call.timeout)
  605. c.handleTimeout()
  606. return ErrTimeoutNoResponse
  607. case <-ctxDone:
  608. c.releaseStream(call.streamID)
  609. close(call.timeout)
  610. return ctx.Err()
  611. case <-c.quit:
  612. return ErrConnectionClosed
  613. }
  614. }
  615. type preparedStatment struct {
  616. id []byte
  617. request preparedMetadata
  618. response resultMetadata
  619. }
  620. type inflightPrepare struct {
  621. wg sync.WaitGroup
  622. err error
  623. preparedStatment *preparedStatment
  624. }
  625. func (c *Conn) prepareStatement(ctx context.Context, stmt string, tracer Tracer) (*preparedStatment, error) {
  626. stmtCacheKey := c.session.stmtsLRU.keyFor(c.addr, c.currentKeyspace, stmt)
  627. flight, ok := c.session.stmtsLRU.execIfMissing(stmtCacheKey, func(lru *lru.Cache) *inflightPrepare {
  628. flight := new(inflightPrepare)
  629. flight.wg.Add(1)
  630. lru.Add(stmtCacheKey, flight)
  631. return flight
  632. })
  633. if ok {
  634. flight.wg.Wait()
  635. return flight.preparedStatment, flight.err
  636. }
  637. prep := &writePrepareFrame{
  638. statement: stmt,
  639. }
  640. framer, err := c.exec(ctx, prep, tracer)
  641. if err != nil {
  642. flight.err = err
  643. flight.wg.Done()
  644. c.session.stmtsLRU.remove(stmtCacheKey)
  645. return nil, err
  646. }
  647. frame, err := framer.parseFrame()
  648. if err != nil {
  649. flight.err = err
  650. flight.wg.Done()
  651. c.session.stmtsLRU.remove(stmtCacheKey)
  652. return nil, err
  653. }
  654. // TODO(zariel): tidy this up, simplify handling of frame parsing so its not duplicated
  655. // everytime we need to parse a frame.
  656. if len(framer.traceID) > 0 && tracer != nil {
  657. tracer.Trace(framer.traceID)
  658. }
  659. switch x := frame.(type) {
  660. case *resultPreparedFrame:
  661. flight.preparedStatment = &preparedStatment{
  662. // defensively copy as we will recycle the underlying buffer after we
  663. // return.
  664. id: copyBytes(x.preparedID),
  665. // the type info's should _not_ have a reference to the framers read buffer,
  666. // therefore we can just copy them directly.
  667. request: x.reqMeta,
  668. response: x.respMeta,
  669. }
  670. case error:
  671. flight.err = x
  672. default:
  673. flight.err = NewErrProtocol("Unknown type in response to prepare frame: %s", x)
  674. }
  675. flight.wg.Done()
  676. if flight.err != nil {
  677. c.session.stmtsLRU.remove(stmtCacheKey)
  678. }
  679. framerPool.Put(framer)
  680. return flight.preparedStatment, flight.err
  681. }
  682. func marshalQueryValue(typ TypeInfo, value interface{}, dst *queryValues) error {
  683. if named, ok := value.(*namedValue); ok {
  684. dst.name = named.name
  685. value = named.value
  686. }
  687. if _, ok := value.(unsetColumn); !ok {
  688. val, err := Marshal(typ, value)
  689. if err != nil {
  690. return err
  691. }
  692. dst.value = val
  693. } else {
  694. dst.isUnset = true
  695. }
  696. return nil
  697. }
  698. func (c *Conn) executeQuery(qry *Query) *Iter {
  699. params := queryParams{
  700. consistency: qry.cons,
  701. }
  702. // frame checks that it is not 0
  703. params.serialConsistency = qry.serialCons
  704. params.defaultTimestamp = qry.defaultTimestamp
  705. params.defaultTimestampValue = qry.defaultTimestampValue
  706. if len(qry.pageState) > 0 {
  707. params.pagingState = qry.pageState
  708. }
  709. if qry.pageSize > 0 {
  710. params.pageSize = qry.pageSize
  711. }
  712. var (
  713. frame frameWriter
  714. info *preparedStatment
  715. )
  716. if qry.shouldPrepare() {
  717. // Prepare all DML queries. Other queries can not be prepared.
  718. var err error
  719. info, err = c.prepareStatement(qry.context, qry.stmt, qry.trace)
  720. if err != nil {
  721. return &Iter{err: err}
  722. }
  723. var values []interface{}
  724. if qry.binding == nil {
  725. values = qry.values
  726. } else {
  727. values, err = qry.binding(&QueryInfo{
  728. Id: info.id,
  729. Args: info.request.columns,
  730. Rval: info.response.columns,
  731. PKeyColumns: info.request.pkeyColumns,
  732. })
  733. if err != nil {
  734. return &Iter{err: err}
  735. }
  736. }
  737. if len(values) != info.request.actualColCount {
  738. return &Iter{err: fmt.Errorf("gocql: expected %d values send got %d", info.request.actualColCount, len(values))}
  739. }
  740. params.values = make([]queryValues, len(values))
  741. for i := 0; i < len(values); i++ {
  742. v := &params.values[i]
  743. value := values[i]
  744. typ := info.request.columns[i].TypeInfo
  745. if err := marshalQueryValue(typ, value, v); err != nil {
  746. return &Iter{err: err}
  747. }
  748. }
  749. params.skipMeta = !(c.session.cfg.DisableSkipMetadata || qry.disableSkipMetadata)
  750. frame = &writeExecuteFrame{
  751. preparedID: info.id,
  752. params: params,
  753. }
  754. } else {
  755. frame = &writeQueryFrame{
  756. statement: qry.stmt,
  757. params: params,
  758. }
  759. }
  760. framer, err := c.exec(qry.context, frame, qry.trace)
  761. if err != nil {
  762. return &Iter{err: err}
  763. }
  764. resp, err := framer.parseFrame()
  765. if err != nil {
  766. return &Iter{err: err}
  767. }
  768. if len(framer.traceID) > 0 && qry.trace != nil {
  769. qry.trace.Trace(framer.traceID)
  770. }
  771. switch x := resp.(type) {
  772. case *resultVoidFrame:
  773. return &Iter{framer: framer}
  774. case *resultRowsFrame:
  775. iter := &Iter{
  776. meta: x.meta,
  777. framer: framer,
  778. numRows: x.numRows,
  779. }
  780. if params.skipMeta {
  781. if info != nil {
  782. iter.meta = info.response
  783. iter.meta.pagingState = x.meta.pagingState
  784. } else {
  785. return &Iter{framer: framer, err: errors.New("gocql: did not receive metadata but prepared info is nil")}
  786. }
  787. } else {
  788. iter.meta = x.meta
  789. }
  790. if len(x.meta.pagingState) > 0 && !qry.disableAutoPage {
  791. iter.next = &nextIter{
  792. qry: *qry,
  793. pos: int((1 - qry.prefetch) * float64(x.numRows)),
  794. conn: c,
  795. }
  796. iter.next.qry.pageState = copyBytes(x.meta.pagingState)
  797. if iter.next.pos < 1 {
  798. iter.next.pos = 1
  799. }
  800. }
  801. return iter
  802. case *resultKeyspaceFrame:
  803. return &Iter{framer: framer}
  804. case *schemaChangeKeyspace, *schemaChangeTable, *schemaChangeFunction, *schemaChangeAggregate, *schemaChangeType:
  805. iter := &Iter{framer: framer}
  806. if err := c.awaitSchemaAgreement(); err != nil {
  807. // TODO: should have this behind a flag
  808. Logger.Println(err)
  809. }
  810. // dont return an error from this, might be a good idea to give a warning
  811. // though. The impact of this returning an error would be that the cluster
  812. // is not consistent with regards to its schema.
  813. return iter
  814. case *RequestErrUnprepared:
  815. stmtCacheKey := c.session.stmtsLRU.keyFor(c.addr, c.currentKeyspace, qry.stmt)
  816. if c.session.stmtsLRU.remove(stmtCacheKey) {
  817. return c.executeQuery(qry)
  818. }
  819. return &Iter{err: x, framer: framer}
  820. case error:
  821. return &Iter{err: x, framer: framer}
  822. default:
  823. return &Iter{
  824. err: NewErrProtocol("Unknown type in response to execute query (%T): %s", x, x),
  825. framer: framer,
  826. }
  827. }
  828. }
  829. func (c *Conn) Pick(qry *Query) *Conn {
  830. if c.Closed() {
  831. return nil
  832. }
  833. return c
  834. }
  835. func (c *Conn) Closed() bool {
  836. return atomic.LoadInt32(&c.closed) == 1
  837. }
  838. func (c *Conn) Address() string {
  839. return c.addr
  840. }
  841. func (c *Conn) AvailableStreams() int {
  842. return c.streams.Available()
  843. }
  844. func (c *Conn) UseKeyspace(keyspace string) error {
  845. q := &writeQueryFrame{statement: `USE "` + keyspace + `"`}
  846. q.params.consistency = Any
  847. framer, err := c.exec(context.Background(), q, nil)
  848. if err != nil {
  849. return err
  850. }
  851. resp, err := framer.parseFrame()
  852. if err != nil {
  853. return err
  854. }
  855. switch x := resp.(type) {
  856. case *resultKeyspaceFrame:
  857. case error:
  858. return x
  859. default:
  860. return NewErrProtocol("unknown frame in response to USE: %v", x)
  861. }
  862. c.currentKeyspace = keyspace
  863. return nil
  864. }
  865. func (c *Conn) executeBatch(batch *Batch) *Iter {
  866. if c.version == protoVersion1 {
  867. return &Iter{err: ErrUnsupported}
  868. }
  869. n := len(batch.Entries)
  870. req := &writeBatchFrame{
  871. typ: batch.Type,
  872. statements: make([]batchStatment, n),
  873. consistency: batch.Cons,
  874. serialConsistency: batch.serialCons,
  875. defaultTimestamp: batch.defaultTimestamp,
  876. defaultTimestampValue: batch.defaultTimestampValue,
  877. }
  878. stmts := make(map[string]string, len(batch.Entries))
  879. for i := 0; i < n; i++ {
  880. entry := &batch.Entries[i]
  881. b := &req.statements[i]
  882. if len(entry.Args) > 0 || entry.binding != nil {
  883. info, err := c.prepareStatement(batch.context, entry.Stmt, nil)
  884. if err != nil {
  885. return &Iter{err: err}
  886. }
  887. var values []interface{}
  888. if entry.binding == nil {
  889. values = entry.Args
  890. } else {
  891. values, err = entry.binding(&QueryInfo{
  892. Id: info.id,
  893. Args: info.request.columns,
  894. Rval: info.response.columns,
  895. PKeyColumns: info.request.pkeyColumns,
  896. })
  897. if err != nil {
  898. return &Iter{err: err}
  899. }
  900. }
  901. if len(values) != info.request.actualColCount {
  902. return &Iter{err: fmt.Errorf("gocql: batch statement %d expected %d values send got %d", i, info.request.actualColCount, len(values))}
  903. }
  904. b.preparedID = info.id
  905. stmts[string(info.id)] = entry.Stmt
  906. b.values = make([]queryValues, info.request.actualColCount)
  907. for j := 0; j < info.request.actualColCount; j++ {
  908. v := &b.values[j]
  909. value := values[j]
  910. typ := info.request.columns[j].TypeInfo
  911. if err := marshalQueryValue(typ, value, v); err != nil {
  912. return &Iter{err: err}
  913. }
  914. }
  915. } else {
  916. b.statement = entry.Stmt
  917. }
  918. }
  919. // TODO: should batch support tracing?
  920. framer, err := c.exec(batch.context, req, nil)
  921. if err != nil {
  922. return &Iter{err: err}
  923. }
  924. resp, err := framer.parseFrame()
  925. if err != nil {
  926. return &Iter{err: err, framer: framer}
  927. }
  928. switch x := resp.(type) {
  929. case *resultVoidFrame:
  930. framerPool.Put(framer)
  931. return &Iter{}
  932. case *RequestErrUnprepared:
  933. stmt, found := stmts[string(x.StatementId)]
  934. if found {
  935. key := c.session.stmtsLRU.keyFor(c.addr, c.currentKeyspace, stmt)
  936. c.session.stmtsLRU.remove(key)
  937. }
  938. if found {
  939. framerPool.Put(framer)
  940. return c.executeBatch(batch)
  941. } else {
  942. return &Iter{err: x, framer: framer}
  943. }
  944. case *resultRowsFrame:
  945. iter := &Iter{
  946. meta: x.meta,
  947. framer: framer,
  948. numRows: x.numRows,
  949. }
  950. return iter
  951. case error:
  952. return &Iter{err: x, framer: framer}
  953. default:
  954. return &Iter{err: NewErrProtocol("Unknown type in response to batch statement: %s", x), framer: framer}
  955. }
  956. }
  957. func (c *Conn) setKeepalive(d time.Duration) error {
  958. if tc, ok := c.conn.(*net.TCPConn); ok {
  959. err := tc.SetKeepAlivePeriod(d)
  960. if err != nil {
  961. return err
  962. }
  963. return tc.SetKeepAlive(true)
  964. }
  965. return nil
  966. }
  967. func (c *Conn) query(statement string, values ...interface{}) (iter *Iter) {
  968. q := c.session.Query(statement, values...).Consistency(One)
  969. return c.executeQuery(q)
  970. }
  971. func (c *Conn) awaitSchemaAgreement() (err error) {
  972. const (
  973. peerSchemas = "SELECT schema_version, peer FROM system.peers"
  974. localSchemas = "SELECT schema_version FROM system.local WHERE key='local'"
  975. )
  976. var versions map[string]struct{}
  977. endDeadline := time.Now().Add(c.session.cfg.MaxWaitSchemaAgreement)
  978. for time.Now().Before(endDeadline) {
  979. iter := c.query(peerSchemas)
  980. versions = make(map[string]struct{})
  981. var schemaVersion string
  982. var peer string
  983. for iter.Scan(&schemaVersion, &peer) {
  984. if schemaVersion == "" {
  985. Logger.Printf("skipping peer entry with empty schema_version: peer=%q", peer)
  986. continue
  987. }
  988. versions[schemaVersion] = struct{}{}
  989. schemaVersion = ""
  990. }
  991. if err = iter.Close(); err != nil {
  992. goto cont
  993. }
  994. iter = c.query(localSchemas)
  995. for iter.Scan(&schemaVersion) {
  996. versions[schemaVersion] = struct{}{}
  997. schemaVersion = ""
  998. }
  999. if err = iter.Close(); err != nil {
  1000. goto cont
  1001. }
  1002. if len(versions) <= 1 {
  1003. return nil
  1004. }
  1005. cont:
  1006. time.Sleep(200 * time.Millisecond)
  1007. }
  1008. if err != nil {
  1009. return
  1010. }
  1011. schemas := make([]string, 0, len(versions))
  1012. for schema := range versions {
  1013. schemas = append(schemas, schema)
  1014. }
  1015. // not exported
  1016. return fmt.Errorf("gocql: cluster schema versions not consistent: %+v", schemas)
  1017. }
  1018. const localHostInfo = "SELECT * FROM system.local WHERE key='local'"
  1019. func (c *Conn) localHostInfo() (*HostInfo, error) {
  1020. row, err := c.query(localHostInfo).rowMap()
  1021. if err != nil {
  1022. return nil, err
  1023. }
  1024. port := c.conn.RemoteAddr().(*net.TCPAddr).Port
  1025. // TODO(zariel): avoid doing this here
  1026. host, err := c.session.hostInfoFromMap(row, port)
  1027. if err != nil {
  1028. return nil, err
  1029. }
  1030. return c.session.ring.addOrUpdate(host), nil
  1031. }
  1032. var (
  1033. ErrQueryArgLength = errors.New("gocql: query argument length mismatch")
  1034. ErrTimeoutNoResponse = errors.New("gocql: no response received from cassandra within timeout period")
  1035. ErrTooManyTimeouts = errors.New("gocql: too many query timeouts on the connection")
  1036. ErrConnectionClosed = errors.New("gocql: connection closed waiting for response")
  1037. ErrNoStreams = errors.New("gocql: no streams available on connection")
  1038. )