conn.go 34 KB

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