conn.go 30 KB

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