conn.go 28 KB

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