conn.go 31 KB

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