conn.go 26 KB

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