conn.go 34 KB

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