conn.go 26 KB

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