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