conn.go 25 KB

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