conn.go 34 KB

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