conn.go 31 KB

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