conn.go 27 KB

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