conn.go 22 KB

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