conn.go 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232
  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. c.mu.Lock()
  529. call := c.calls[stream]
  530. if call != nil {
  531. c.mu.Unlock()
  532. return nil, fmt.Errorf("attempting to use stream already in use: %d -> %d", stream, call.streamID)
  533. } else {
  534. call = streamPool.Get().(*callReq)
  535. }
  536. c.calls[stream] = call
  537. call.framer = framer
  538. call.timeout = make(chan struct{})
  539. call.streamID = stream
  540. call.req = req
  541. c.mu.Unlock()
  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. close(call.timeout)
  604. c.handleTimeout()
  605. return ErrTimeoutNoResponse
  606. case <-ctxDone:
  607. close(call.timeout)
  608. return ctx.Err()
  609. case <-c.quit:
  610. return ErrConnectionClosed
  611. }
  612. }
  613. type preparedStatment struct {
  614. id []byte
  615. request preparedMetadata
  616. response resultMetadata
  617. }
  618. type inflightPrepare struct {
  619. wg sync.WaitGroup
  620. err error
  621. preparedStatment *preparedStatment
  622. }
  623. func (c *Conn) prepareStatement(ctx context.Context, stmt string, tracer Tracer) (*preparedStatment, error) {
  624. stmtCacheKey := c.session.stmtsLRU.keyFor(c.addr, c.currentKeyspace, stmt)
  625. flight, ok := c.session.stmtsLRU.execIfMissing(stmtCacheKey, func(lru *lru.Cache) *inflightPrepare {
  626. flight := new(inflightPrepare)
  627. flight.wg.Add(1)
  628. lru.Add(stmtCacheKey, flight)
  629. return flight
  630. })
  631. if ok {
  632. flight.wg.Wait()
  633. return flight.preparedStatment, flight.err
  634. }
  635. prep := &writePrepareFrame{
  636. statement: stmt,
  637. }
  638. framer, err := c.exec(ctx, prep, tracer)
  639. if err != nil {
  640. flight.err = err
  641. flight.wg.Done()
  642. c.session.stmtsLRU.remove(stmtCacheKey)
  643. return nil, err
  644. }
  645. frame, err := framer.parseFrame()
  646. if err != nil {
  647. flight.err = err
  648. flight.wg.Done()
  649. return nil, err
  650. }
  651. // TODO(zariel): tidy this up, simplify handling of frame parsing so its not duplicated
  652. // everytime we need to parse a frame.
  653. if len(framer.traceID) > 0 && tracer != nil {
  654. tracer.Trace(framer.traceID)
  655. }
  656. switch x := frame.(type) {
  657. case *resultPreparedFrame:
  658. flight.preparedStatment = &preparedStatment{
  659. // defensively copy as we will recycle the underlying buffer after we
  660. // return.
  661. id: copyBytes(x.preparedID),
  662. // the type info's should _not_ have a reference to the framers read buffer,
  663. // therefore we can just copy them directly.
  664. request: x.reqMeta,
  665. response: x.respMeta,
  666. }
  667. case error:
  668. flight.err = x
  669. default:
  670. flight.err = NewErrProtocol("Unknown type in response to prepare frame: %s", x)
  671. }
  672. flight.wg.Done()
  673. if flight.err != nil {
  674. c.session.stmtsLRU.remove(stmtCacheKey)
  675. }
  676. framerPool.Put(framer)
  677. return flight.preparedStatment, flight.err
  678. }
  679. func marshalQueryValue(typ TypeInfo, value interface{}, dst *queryValues) error {
  680. if named, ok := value.(*namedValue); ok {
  681. dst.name = named.name
  682. value = named.value
  683. }
  684. if _, ok := value.(unsetColumn); !ok {
  685. val, err := Marshal(typ, value)
  686. if err != nil {
  687. return err
  688. }
  689. dst.value = val
  690. } else {
  691. dst.isUnset = true
  692. }
  693. return nil
  694. }
  695. func (c *Conn) executeQuery(qry *Query) *Iter {
  696. params := queryParams{
  697. consistency: qry.cons,
  698. }
  699. // frame checks that it is not 0
  700. params.serialConsistency = qry.serialCons
  701. params.defaultTimestamp = qry.defaultTimestamp
  702. params.defaultTimestampValue = qry.defaultTimestampValue
  703. if len(qry.pageState) > 0 {
  704. params.pagingState = qry.pageState
  705. }
  706. if qry.pageSize > 0 {
  707. params.pageSize = qry.pageSize
  708. }
  709. var (
  710. frame frameWriter
  711. info *preparedStatment
  712. )
  713. if qry.shouldPrepare() {
  714. // Prepare all DML queries. Other queries can not be prepared.
  715. var err error
  716. info, err = c.prepareStatement(qry.context, qry.stmt, qry.trace)
  717. if err != nil {
  718. return &Iter{err: err}
  719. }
  720. var values []interface{}
  721. if qry.binding == nil {
  722. values = qry.values
  723. } else {
  724. values, err = qry.binding(&QueryInfo{
  725. Id: info.id,
  726. Args: info.request.columns,
  727. Rval: info.response.columns,
  728. PKeyColumns: info.request.pkeyColumns,
  729. })
  730. if err != nil {
  731. return &Iter{err: err}
  732. }
  733. }
  734. if len(values) != info.request.actualColCount {
  735. return &Iter{err: fmt.Errorf("gocql: expected %d values send got %d", info.request.actualColCount, len(values))}
  736. }
  737. params.values = make([]queryValues, len(values))
  738. for i := 0; i < len(values); i++ {
  739. v := &params.values[i]
  740. value := values[i]
  741. typ := info.request.columns[i].TypeInfo
  742. if err := marshalQueryValue(typ, value, v); err != nil {
  743. return &Iter{err: err}
  744. }
  745. }
  746. params.skipMeta = !(c.session.cfg.DisableSkipMetadata || qry.disableSkipMetadata)
  747. frame = &writeExecuteFrame{
  748. preparedID: info.id,
  749. params: params,
  750. }
  751. } else {
  752. frame = &writeQueryFrame{
  753. statement: qry.stmt,
  754. params: params,
  755. }
  756. }
  757. framer, err := c.exec(qry.context, frame, qry.trace)
  758. if err != nil {
  759. return &Iter{err: err}
  760. }
  761. resp, err := framer.parseFrame()
  762. if err != nil {
  763. return &Iter{err: err}
  764. }
  765. if len(framer.traceID) > 0 && qry.trace != nil {
  766. qry.trace.Trace(framer.traceID)
  767. }
  768. switch x := resp.(type) {
  769. case *resultVoidFrame:
  770. return &Iter{framer: framer}
  771. case *resultRowsFrame:
  772. iter := &Iter{
  773. meta: x.meta,
  774. framer: framer,
  775. numRows: x.numRows,
  776. }
  777. if params.skipMeta {
  778. if info != nil {
  779. iter.meta = info.response
  780. iter.meta.pagingState = x.meta.pagingState
  781. } else {
  782. return &Iter{framer: framer, err: errors.New("gocql: did not receive metadata but prepared info is nil")}
  783. }
  784. } else {
  785. iter.meta = x.meta
  786. }
  787. if len(x.meta.pagingState) > 0 && !qry.disableAutoPage {
  788. iter.next = &nextIter{
  789. qry: *qry,
  790. pos: int((1 - qry.prefetch) * float64(x.numRows)),
  791. conn: c,
  792. }
  793. iter.next.qry.pageState = copyBytes(x.meta.pagingState)
  794. if iter.next.pos < 1 {
  795. iter.next.pos = 1
  796. }
  797. }
  798. return iter
  799. case *resultKeyspaceFrame:
  800. return &Iter{framer: framer}
  801. case *schemaChangeKeyspace, *schemaChangeTable, *schemaChangeFunction, *schemaChangeAggregate, *schemaChangeType:
  802. iter := &Iter{framer: framer}
  803. if err := c.awaitSchemaAgreement(); err != nil {
  804. // TODO: should have this behind a flag
  805. Logger.Println(err)
  806. }
  807. // dont return an error from this, might be a good idea to give a warning
  808. // though. The impact of this returning an error would be that the cluster
  809. // is not consistent with regards to its schema.
  810. return iter
  811. case *RequestErrUnprepared:
  812. stmtCacheKey := c.session.stmtsLRU.keyFor(c.addr, c.currentKeyspace, qry.stmt)
  813. if c.session.stmtsLRU.remove(stmtCacheKey) {
  814. return c.executeQuery(qry)
  815. }
  816. return &Iter{err: x, framer: framer}
  817. case error:
  818. return &Iter{err: x, framer: framer}
  819. default:
  820. return &Iter{
  821. err: NewErrProtocol("Unknown type in response to execute query (%T): %s", x, x),
  822. framer: framer,
  823. }
  824. }
  825. }
  826. func (c *Conn) Pick(qry *Query) *Conn {
  827. if c.Closed() {
  828. return nil
  829. }
  830. return c
  831. }
  832. func (c *Conn) Closed() bool {
  833. return atomic.LoadInt32(&c.closed) == 1
  834. }
  835. func (c *Conn) Address() string {
  836. return c.addr
  837. }
  838. func (c *Conn) AvailableStreams() int {
  839. return c.streams.Available()
  840. }
  841. func (c *Conn) UseKeyspace(keyspace string) error {
  842. q := &writeQueryFrame{statement: `USE "` + keyspace + `"`}
  843. q.params.consistency = Any
  844. framer, err := c.exec(context.Background(), q, nil)
  845. if err != nil {
  846. return err
  847. }
  848. resp, err := framer.parseFrame()
  849. if err != nil {
  850. return err
  851. }
  852. switch x := resp.(type) {
  853. case *resultKeyspaceFrame:
  854. case error:
  855. return x
  856. default:
  857. return NewErrProtocol("unknown frame in response to USE: %v", x)
  858. }
  859. c.currentKeyspace = keyspace
  860. return nil
  861. }
  862. func (c *Conn) executeBatch(batch *Batch) *Iter {
  863. if c.version == protoVersion1 {
  864. return &Iter{err: ErrUnsupported}
  865. }
  866. n := len(batch.Entries)
  867. req := &writeBatchFrame{
  868. typ: batch.Type,
  869. statements: make([]batchStatment, n),
  870. consistency: batch.Cons,
  871. serialConsistency: batch.serialCons,
  872. defaultTimestamp: batch.defaultTimestamp,
  873. defaultTimestampValue: batch.defaultTimestampValue,
  874. }
  875. stmts := make(map[string]string, len(batch.Entries))
  876. for i := 0; i < n; i++ {
  877. entry := &batch.Entries[i]
  878. b := &req.statements[i]
  879. if len(entry.Args) > 0 || entry.binding != nil {
  880. info, err := c.prepareStatement(batch.context, entry.Stmt, nil)
  881. if err != nil {
  882. return &Iter{err: err}
  883. }
  884. var values []interface{}
  885. if entry.binding == nil {
  886. values = entry.Args
  887. } else {
  888. values, err = entry.binding(&QueryInfo{
  889. Id: info.id,
  890. Args: info.request.columns,
  891. Rval: info.response.columns,
  892. PKeyColumns: info.request.pkeyColumns,
  893. })
  894. if err != nil {
  895. return &Iter{err: err}
  896. }
  897. }
  898. if len(values) != info.request.actualColCount {
  899. return &Iter{err: fmt.Errorf("gocql: batch statement %d expected %d values send got %d", i, info.request.actualColCount, len(values))}
  900. }
  901. b.preparedID = info.id
  902. stmts[string(info.id)] = entry.Stmt
  903. b.values = make([]queryValues, info.request.actualColCount)
  904. for j := 0; j < info.request.actualColCount; j++ {
  905. v := &b.values[j]
  906. value := values[j]
  907. typ := info.request.columns[j].TypeInfo
  908. if err := marshalQueryValue(typ, value, v); err != nil {
  909. return &Iter{err: err}
  910. }
  911. }
  912. } else {
  913. b.statement = entry.Stmt
  914. }
  915. }
  916. // TODO: should batch support tracing?
  917. framer, err := c.exec(batch.context, req, nil)
  918. if err != nil {
  919. return &Iter{err: err}
  920. }
  921. resp, err := framer.parseFrame()
  922. if err != nil {
  923. return &Iter{err: err, framer: framer}
  924. }
  925. switch x := resp.(type) {
  926. case *resultVoidFrame:
  927. framerPool.Put(framer)
  928. return &Iter{}
  929. case *RequestErrUnprepared:
  930. stmt, found := stmts[string(x.StatementId)]
  931. if found {
  932. key := c.session.stmtsLRU.keyFor(c.addr, c.currentKeyspace, stmt)
  933. c.session.stmtsLRU.remove(key)
  934. }
  935. framerPool.Put(framer)
  936. if found {
  937. return c.executeBatch(batch)
  938. } else {
  939. return &Iter{err: x, framer: framer}
  940. }
  941. case *resultRowsFrame:
  942. iter := &Iter{
  943. meta: x.meta,
  944. framer: framer,
  945. numRows: x.numRows,
  946. }
  947. return iter
  948. case error:
  949. return &Iter{err: x, framer: framer}
  950. default:
  951. return &Iter{err: NewErrProtocol("Unknown type in response to batch statement: %s", x), framer: framer}
  952. }
  953. }
  954. func (c *Conn) setKeepalive(d time.Duration) error {
  955. if tc, ok := c.conn.(*net.TCPConn); ok {
  956. err := tc.SetKeepAlivePeriod(d)
  957. if err != nil {
  958. return err
  959. }
  960. return tc.SetKeepAlive(true)
  961. }
  962. return nil
  963. }
  964. func (c *Conn) query(statement string, values ...interface{}) (iter *Iter) {
  965. q := c.session.Query(statement, values...).Consistency(One)
  966. return c.executeQuery(q)
  967. }
  968. func (c *Conn) awaitSchemaAgreement() (err error) {
  969. const (
  970. peerSchemas = "SELECT schema_version, peer FROM system.peers"
  971. localSchemas = "SELECT schema_version FROM system.local WHERE key='local'"
  972. )
  973. var versions map[string]struct{}
  974. endDeadline := time.Now().Add(c.session.cfg.MaxWaitSchemaAgreement)
  975. for time.Now().Before(endDeadline) {
  976. iter := c.query(peerSchemas)
  977. versions = make(map[string]struct{})
  978. var schemaVersion string
  979. var peer string
  980. for iter.Scan(&schemaVersion, &peer) {
  981. if schemaVersion == "" {
  982. Logger.Printf("skipping peer entry with empty schema_version: peer=%q", peer)
  983. continue
  984. }
  985. versions[schemaVersion] = struct{}{}
  986. schemaVersion = ""
  987. }
  988. if err = iter.Close(); err != nil {
  989. goto cont
  990. }
  991. iter = c.query(localSchemas)
  992. for iter.Scan(&schemaVersion) {
  993. versions[schemaVersion] = struct{}{}
  994. schemaVersion = ""
  995. }
  996. if err = iter.Close(); err != nil {
  997. goto cont
  998. }
  999. if len(versions) <= 1 {
  1000. return nil
  1001. }
  1002. cont:
  1003. time.Sleep(200 * time.Millisecond)
  1004. }
  1005. if err != nil {
  1006. return
  1007. }
  1008. schemas := make([]string, 0, len(versions))
  1009. for schema := range versions {
  1010. schemas = append(schemas, schema)
  1011. }
  1012. // not exported
  1013. return fmt.Errorf("gocql: cluster schema versions not consistent: %+v", schemas)
  1014. }
  1015. const localHostInfo = "SELECT * FROM system.local WHERE key='local'"
  1016. func (c *Conn) localHostInfo() (*HostInfo, error) {
  1017. row, err := c.query(localHostInfo).rowMap()
  1018. if err != nil {
  1019. return nil, err
  1020. }
  1021. port := c.conn.RemoteAddr().(*net.TCPAddr).Port
  1022. // TODO(zariel): avoid doing this here
  1023. host, err := c.session.hostInfoFromMap(row, port)
  1024. if err != nil {
  1025. return nil, err
  1026. }
  1027. return c.session.ring.addOrUpdate(host), nil
  1028. }
  1029. var (
  1030. ErrQueryArgLength = errors.New("gocql: query argument length mismatch")
  1031. ErrTimeoutNoResponse = errors.New("gocql: no response received from cassandra within timeout period")
  1032. ErrTooManyTimeouts = errors.New("gocql: too many query timeouts on the connection")
  1033. ErrConnectionClosed = errors.New("gocql: connection closed waiting for response")
  1034. ErrNoStreams = errors.New("gocql: no streams available on connection")
  1035. )