conn.go 33 KB

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