conn.go 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445
  1. // Copyright (c) 2012 The gocql Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package gocql
  5. import (
  6. "bufio"
  7. "context"
  8. "crypto/tls"
  9. "errors"
  10. "fmt"
  11. "io"
  12. "io/ioutil"
  13. "net"
  14. "strconv"
  15. "strings"
  16. "sync"
  17. "sync/atomic"
  18. "time"
  19. "github.com/gocql/gocql/internal/lru"
  20. "github.com/gocql/gocql/internal/streams"
  21. )
  22. var (
  23. approvedAuthenticators = [...]string{
  24. "org.apache.cassandra.auth.PasswordAuthenticator",
  25. "com.instaclustr.cassandra.auth.SharedSecretAuthenticator",
  26. "com.datastax.bdp.cassandra.auth.DseAuthenticator",
  27. "io.aiven.cassandra.auth.AivenAuthenticator",
  28. }
  29. )
  30. func approve(authenticator string) bool {
  31. for _, s := range approvedAuthenticators {
  32. if authenticator == s {
  33. return true
  34. }
  35. }
  36. return false
  37. }
  38. //JoinHostPort is a utility to return a address string that can be used
  39. //gocql.Conn to form a connection with a host.
  40. func JoinHostPort(addr string, port int) string {
  41. addr = strings.TrimSpace(addr)
  42. if _, _, err := net.SplitHostPort(addr); err != nil {
  43. addr = net.JoinHostPort(addr, strconv.Itoa(port))
  44. }
  45. return addr
  46. }
  47. type Authenticator interface {
  48. Challenge(req []byte) (resp []byte, auth Authenticator, err error)
  49. Success(data []byte) error
  50. }
  51. type PasswordAuthenticator struct {
  52. Username string
  53. Password string
  54. }
  55. func (p PasswordAuthenticator) Challenge(req []byte) ([]byte, Authenticator, error) {
  56. if !approve(string(req)) {
  57. return nil, nil, fmt.Errorf("unexpected authenticator %q", req)
  58. }
  59. resp := make([]byte, 2+len(p.Username)+len(p.Password))
  60. resp[0] = 0
  61. copy(resp[1:], p.Username)
  62. resp[len(p.Username)+1] = 0
  63. copy(resp[2+len(p.Username):], p.Password)
  64. return resp, nil, nil
  65. }
  66. func (p PasswordAuthenticator) Success(data []byte) error {
  67. return nil
  68. }
  69. type SslOptions struct {
  70. *tls.Config
  71. // CertPath and KeyPath are optional depending on server
  72. // config, but both fields must be omitted to avoid using a
  73. // client certificate
  74. CertPath string
  75. KeyPath string
  76. CaPath string //optional depending on server config
  77. // If you want to verify the hostname and server cert (like a wildcard for cass cluster) then you should turn this on
  78. // This option is basically the inverse of InSecureSkipVerify
  79. // See InSecureSkipVerify in http://golang.org/pkg/crypto/tls/ for more info
  80. EnableHostVerification bool
  81. }
  82. type ConnConfig struct {
  83. ProtoVersion int
  84. CQLVersion string
  85. Timeout time.Duration
  86. ConnectTimeout time.Duration
  87. Compressor Compressor
  88. Authenticator Authenticator
  89. AuthProvider func(h *HostInfo) (Authenticator, error)
  90. Keepalive time.Duration
  91. tlsConfig *tls.Config
  92. disableCoalesce bool
  93. }
  94. type ConnErrorHandler interface {
  95. HandleError(conn *Conn, err error, closed bool)
  96. }
  97. type connErrorHandlerFn func(conn *Conn, err error, closed bool)
  98. func (fn connErrorHandlerFn) HandleError(conn *Conn, err error, closed bool) {
  99. fn(conn, err, closed)
  100. }
  101. // If not zero, how many timeouts we will allow to occur before the connection is closed
  102. // and restarted. This is to prevent a single query timeout from killing a connection
  103. // which may be serving more queries just fine.
  104. // Default is 0, should not be changed concurrently with queries.
  105. //
  106. // depreciated
  107. var TimeoutLimit int64 = 0
  108. // Conn is a single connection to a Cassandra node. It can be used to execute
  109. // queries, but users are usually advised to use a more reliable, higher
  110. // level API.
  111. type Conn struct {
  112. conn net.Conn
  113. r *bufio.Reader
  114. w io.Writer
  115. timeout time.Duration
  116. cfg *ConnConfig
  117. frameObserver FrameHeaderObserver
  118. headerBuf [maxFrameHeaderSize]byte
  119. streams *streams.IDGenerator
  120. mu sync.Mutex
  121. calls map[int]*callReq
  122. errorHandler ConnErrorHandler
  123. compressor Compressor
  124. auth Authenticator
  125. addr string
  126. version uint8
  127. currentKeyspace string
  128. host *HostInfo
  129. session *Session
  130. closed int32
  131. quit chan struct{}
  132. timeouts int64
  133. }
  134. // connect establishes a connection to a Cassandra node using session's connection config.
  135. func (s *Session) connect(host *HostInfo, errorHandler ConnErrorHandler) (*Conn, error) {
  136. return s.dial(host, s.connCfg, errorHandler)
  137. }
  138. // dial establishes a connection to a Cassandra node and notifies the session's connectObserver.
  139. func (s *Session) dial(host *HostInfo, connConfig *ConnConfig, errorHandler ConnErrorHandler) (*Conn, error) {
  140. var obs ObservedConnect
  141. if s.connectObserver != nil {
  142. obs.Host = host
  143. obs.Start = time.Now()
  144. }
  145. conn, err := s.dialWithoutObserver(host, connConfig, errorHandler)
  146. if s.connectObserver != nil {
  147. obs.End = time.Now()
  148. obs.Err = err
  149. s.connectObserver.ObserveConnect(obs)
  150. }
  151. return conn, err
  152. }
  153. // dialWithoutObserver establishes connection to a Cassandra node.
  154. //
  155. // dialWithoutObserver does not notify the connection observer, so you most probably want to call dial() instead.
  156. func (s *Session) dialWithoutObserver(host *HostInfo, cfg *ConnConfig, errorHandler ConnErrorHandler) (*Conn, error) {
  157. ip := host.ConnectAddress()
  158. port := host.port
  159. // TODO(zariel): remove these
  160. if 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.Lock()
  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.Unlock()
  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.Lock()
  539. call, ok := c.calls[head.stream]
  540. delete(c.calls, head.stream)
  541. c.mu.Unlock()
  542. if call == nil || call.framer == nil || !ok {
  543. Logger.Printf("gocql: received response for stream which has no handler: header=%v\n", head)
  544. return c.discardFrame(head)
  545. } else if head.stream != call.streamID {
  546. panic(fmt.Sprintf("call has incorrect streamID: got %d expected %d", call.streamID, head.stream))
  547. }
  548. err = call.framer.readFrame(&head)
  549. if err != nil {
  550. // only net errors should cause the connection to be closed. Though
  551. // cassandra returning corrupt frames will be returned here as well.
  552. if _, ok := err.(net.Error); ok {
  553. return err
  554. }
  555. }
  556. // we either, return a response to the caller, the caller timedout, or the
  557. // connection has closed. Either way we should never block indefinatly here
  558. select {
  559. case call.resp <- err:
  560. case <-call.timeout:
  561. c.releaseStream(call)
  562. case <-c.quit:
  563. }
  564. return nil
  565. }
  566. func (c *Conn) releaseStream(call *callReq) {
  567. if call.timer != nil {
  568. call.timer.Stop()
  569. }
  570. c.streams.Clear(call.streamID)
  571. }
  572. func (c *Conn) handleTimeout() {
  573. if TimeoutLimit > 0 && atomic.AddInt64(&c.timeouts, 1) > TimeoutLimit {
  574. c.closeWithError(ErrTooManyTimeouts)
  575. }
  576. }
  577. type callReq struct {
  578. // could use a waitgroup but this allows us to do timeouts on the read/send
  579. resp chan error
  580. framer *framer
  581. timeout chan struct{} // indicates to recv() that a call has timedout
  582. streamID int // current stream in use
  583. timer *time.Timer
  584. }
  585. type deadlineWriter struct {
  586. w interface {
  587. SetWriteDeadline(time.Time) error
  588. io.Writer
  589. }
  590. timeout time.Duration
  591. }
  592. func (c *deadlineWriter) Write(p []byte) (int, error) {
  593. if c.timeout > 0 {
  594. c.w.SetWriteDeadline(time.Now().Add(c.timeout))
  595. }
  596. return c.w.Write(p)
  597. }
  598. func newWriteCoalescer(conn net.Conn, timeout time.Duration, d time.Duration, quit <-chan struct{}) *writeCoalescer {
  599. wc := &writeCoalescer{
  600. writeCh: make(chan struct{}), // TODO: could this be sync?
  601. cond: sync.NewCond(&sync.Mutex{}),
  602. c: conn,
  603. quit: quit,
  604. timeout: timeout,
  605. }
  606. go wc.writeFlusher(d)
  607. return wc
  608. }
  609. type writeCoalescer struct {
  610. c net.Conn
  611. quit <-chan struct{}
  612. writeCh chan struct{}
  613. running bool
  614. // cond waits for the buffer to be flushed
  615. cond *sync.Cond
  616. buffers net.Buffers
  617. timeout time.Duration
  618. // result of the write
  619. err error
  620. }
  621. func (w *writeCoalescer) flushLocked() {
  622. w.running = false
  623. if len(w.buffers) == 0 {
  624. return
  625. }
  626. if w.timeout > 0 {
  627. w.c.SetWriteDeadline(time.Now().Add(w.timeout))
  628. }
  629. // Given we are going to do a fanout n is useless and according to
  630. // the docs WriteTo should return 0 and err or bytes written and
  631. // no error.
  632. _, w.err = w.buffers.WriteTo(w.c)
  633. if w.err != nil {
  634. w.buffers = nil
  635. }
  636. w.cond.Broadcast()
  637. }
  638. func (w *writeCoalescer) flush() {
  639. w.cond.L.Lock()
  640. w.flushLocked()
  641. w.cond.L.Unlock()
  642. }
  643. func (w *writeCoalescer) stop() {
  644. w.cond.L.Lock()
  645. defer w.cond.L.Unlock()
  646. w.flushLocked()
  647. // nil the channel out sends block forever on it
  648. // instead of closing which causes a send on closed channel
  649. // panic.
  650. w.writeCh = nil
  651. }
  652. func (w *writeCoalescer) Write(p []byte) (int, error) {
  653. w.cond.L.Lock()
  654. if !w.running {
  655. select {
  656. case w.writeCh <- struct{}{}:
  657. w.running = true
  658. case <-w.quit:
  659. w.cond.L.Unlock()
  660. return 0, io.EOF // TODO: better error here?
  661. }
  662. }
  663. w.buffers = append(w.buffers, p)
  664. for len(w.buffers) != 0 {
  665. w.cond.Wait()
  666. }
  667. err := w.err
  668. w.cond.L.Unlock()
  669. if err != nil {
  670. return 0, err
  671. }
  672. return len(p), nil
  673. }
  674. func (w *writeCoalescer) writeFlusher(interval time.Duration) {
  675. timer := time.NewTimer(interval)
  676. defer timer.Stop()
  677. defer w.stop()
  678. if !timer.Stop() {
  679. <-timer.C
  680. }
  681. for {
  682. // wait for a write to start the flush loop
  683. select {
  684. case <-w.writeCh:
  685. case <-w.quit:
  686. return
  687. }
  688. timer.Reset(interval)
  689. select {
  690. case <-w.quit:
  691. return
  692. case <-timer.C:
  693. }
  694. w.flush()
  695. }
  696. }
  697. func (c *Conn) exec(ctx context.Context, req frameWriter, tracer Tracer) (*framer, error) {
  698. // TODO: move tracer onto conn
  699. stream, ok := c.streams.GetStream()
  700. if !ok {
  701. return nil, ErrNoStreams
  702. }
  703. // resp is basically a waiting semaphore protecting the framer
  704. framer := newFramer(c, c, c.compressor, c.version)
  705. call := &callReq{
  706. framer: framer,
  707. timeout: make(chan struct{}),
  708. streamID: stream,
  709. resp: make(chan error),
  710. }
  711. c.mu.Lock()
  712. existingCall := c.calls[stream]
  713. if existingCall == nil {
  714. c.calls[stream] = call
  715. }
  716. c.mu.Unlock()
  717. if existingCall != nil {
  718. return nil, fmt.Errorf("attempting to use stream already in use: %d -> %d", stream, existingCall.streamID)
  719. }
  720. if tracer != nil {
  721. framer.trace()
  722. }
  723. err := req.writeFrame(framer, stream)
  724. if err != nil {
  725. // closeWithError will block waiting for this stream to either receive a response
  726. // or for us to timeout, close the timeout chan here. Im not entirely sure
  727. // but we should not get a response after an error on the write side.
  728. close(call.timeout)
  729. // I think this is the correct thing to do, im not entirely sure. It is not
  730. // ideal as readers might still get some data, but they probably wont.
  731. // Here we need to be careful as the stream is not available and if all
  732. // writes just timeout or fail then the pool might use this connection to
  733. // send a frame on, with all the streams used up and not returned.
  734. c.closeWithError(err)
  735. return nil, err
  736. }
  737. var timeoutCh <-chan time.Time
  738. if c.timeout > 0 {
  739. if call.timer == nil {
  740. call.timer = time.NewTimer(0)
  741. <-call.timer.C
  742. } else {
  743. if !call.timer.Stop() {
  744. select {
  745. case <-call.timer.C:
  746. default:
  747. }
  748. }
  749. }
  750. call.timer.Reset(c.timeout)
  751. timeoutCh = call.timer.C
  752. }
  753. var ctxDone <-chan struct{}
  754. if ctx != nil {
  755. ctxDone = ctx.Done()
  756. }
  757. select {
  758. case err := <-call.resp:
  759. close(call.timeout)
  760. if err != nil {
  761. if !c.Closed() {
  762. // if the connection is closed then we cant release the stream,
  763. // this is because the request is still outstanding and we have
  764. // been handed another error from another stream which caused the
  765. // connection to close.
  766. c.releaseStream(call)
  767. }
  768. return nil, err
  769. }
  770. case <-timeoutCh:
  771. close(call.timeout)
  772. c.handleTimeout()
  773. return nil, ErrTimeoutNoResponse
  774. case <-ctxDone:
  775. close(call.timeout)
  776. return nil, ctx.Err()
  777. case <-c.quit:
  778. return nil, ErrConnectionClosed
  779. }
  780. // dont release the stream if detect a timeout as another request can reuse
  781. // that stream and get a response for the old request, which we have no
  782. // easy way of detecting.
  783. //
  784. // Ensure that the stream is not released if there are potentially outstanding
  785. // requests on the stream to prevent nil pointer dereferences in recv().
  786. defer c.releaseStream(call)
  787. if v := framer.header.version.version(); v != c.version {
  788. return nil, NewErrProtocol("unexpected protocol version in response: got %d expected %d", v, c.version)
  789. }
  790. return framer, nil
  791. }
  792. type preparedStatment struct {
  793. id []byte
  794. request preparedMetadata
  795. response resultMetadata
  796. }
  797. type inflightPrepare struct {
  798. wg sync.WaitGroup
  799. err error
  800. preparedStatment *preparedStatment
  801. }
  802. func (c *Conn) prepareStatement(ctx context.Context, stmt string, tracer Tracer) (*preparedStatment, error) {
  803. stmtCacheKey := c.session.stmtsLRU.keyFor(c.addr, c.currentKeyspace, stmt)
  804. flight, ok := c.session.stmtsLRU.execIfMissing(stmtCacheKey, func(lru *lru.Cache) *inflightPrepare {
  805. flight := new(inflightPrepare)
  806. flight.wg.Add(1)
  807. lru.Add(stmtCacheKey, flight)
  808. return flight
  809. })
  810. if ok {
  811. flight.wg.Wait()
  812. return flight.preparedStatment, flight.err
  813. }
  814. prep := &writePrepareFrame{
  815. statement: stmt,
  816. }
  817. if c.version > protoVersion4 {
  818. prep.keyspace = c.currentKeyspace
  819. }
  820. framer, err := c.exec(ctx, prep, tracer)
  821. if err != nil {
  822. flight.err = err
  823. flight.wg.Done()
  824. c.session.stmtsLRU.remove(stmtCacheKey)
  825. return nil, err
  826. }
  827. frame, err := framer.parseFrame()
  828. if err != nil {
  829. flight.err = err
  830. flight.wg.Done()
  831. c.session.stmtsLRU.remove(stmtCacheKey)
  832. return nil, err
  833. }
  834. // TODO(zariel): tidy this up, simplify handling of frame parsing so its not duplicated
  835. // everytime we need to parse a frame.
  836. if len(framer.traceID) > 0 && tracer != nil {
  837. tracer.Trace(framer.traceID)
  838. }
  839. switch x := frame.(type) {
  840. case *resultPreparedFrame:
  841. flight.preparedStatment = &preparedStatment{
  842. // defensively copy as we will recycle the underlying buffer after we
  843. // return.
  844. id: copyBytes(x.preparedID),
  845. // the type info's should _not_ have a reference to the framers read buffer,
  846. // therefore we can just copy them directly.
  847. request: x.reqMeta,
  848. response: x.respMeta,
  849. }
  850. case error:
  851. flight.err = x
  852. default:
  853. flight.err = NewErrProtocol("Unknown type in response to prepare frame: %s", x)
  854. }
  855. flight.wg.Done()
  856. if flight.err != nil {
  857. c.session.stmtsLRU.remove(stmtCacheKey)
  858. }
  859. return flight.preparedStatment, flight.err
  860. }
  861. func marshalQueryValue(typ TypeInfo, value interface{}, dst *queryValues) error {
  862. if named, ok := value.(*namedValue); ok {
  863. dst.name = named.name
  864. value = named.value
  865. }
  866. if _, ok := value.(unsetColumn); !ok {
  867. val, err := Marshal(typ, value)
  868. if err != nil {
  869. return err
  870. }
  871. dst.value = val
  872. } else {
  873. dst.isUnset = true
  874. }
  875. return nil
  876. }
  877. func (c *Conn) executeQuery(ctx context.Context, qry *Query) *Iter {
  878. params := queryParams{
  879. consistency: qry.cons,
  880. }
  881. // frame checks that it is not 0
  882. params.serialConsistency = qry.serialCons
  883. params.defaultTimestamp = qry.defaultTimestamp
  884. params.defaultTimestampValue = qry.defaultTimestampValue
  885. if len(qry.pageState) > 0 {
  886. params.pagingState = qry.pageState
  887. }
  888. if qry.pageSize > 0 {
  889. params.pageSize = qry.pageSize
  890. }
  891. if c.version > protoVersion4 {
  892. params.keyspace = c.currentKeyspace
  893. }
  894. var (
  895. frame frameWriter
  896. info *preparedStatment
  897. )
  898. if qry.shouldPrepare() {
  899. // Prepare all DML queries. Other queries can not be prepared.
  900. var err error
  901. info, err = c.prepareStatement(ctx, qry.stmt, qry.trace)
  902. if err != nil {
  903. return &Iter{err: err}
  904. }
  905. var values []interface{}
  906. if qry.binding == nil {
  907. values = qry.values
  908. } else {
  909. values, err = qry.binding(&QueryInfo{
  910. Id: info.id,
  911. Args: info.request.columns,
  912. Rval: info.response.columns,
  913. PKeyColumns: info.request.pkeyColumns,
  914. })
  915. if err != nil {
  916. return &Iter{err: err}
  917. }
  918. }
  919. if len(values) != info.request.actualColCount {
  920. return &Iter{err: fmt.Errorf("gocql: expected %d values send got %d", info.request.actualColCount, len(values))}
  921. }
  922. params.values = make([]queryValues, len(values))
  923. for i := 0; i < len(values); i++ {
  924. v := &params.values[i]
  925. value := values[i]
  926. typ := info.request.columns[i].TypeInfo
  927. if err := marshalQueryValue(typ, value, v); err != nil {
  928. return &Iter{err: err}
  929. }
  930. }
  931. params.skipMeta = !(c.session.cfg.DisableSkipMetadata || qry.disableSkipMetadata)
  932. frame = &writeExecuteFrame{
  933. preparedID: info.id,
  934. params: params,
  935. customPayload: qry.customPayload,
  936. }
  937. } else {
  938. frame = &writeQueryFrame{
  939. statement: qry.stmt,
  940. params: params,
  941. customPayload: qry.customPayload,
  942. }
  943. }
  944. framer, err := c.exec(ctx, frame, qry.trace)
  945. if err != nil {
  946. return &Iter{err: err}
  947. }
  948. resp, err := framer.parseFrame()
  949. if err != nil {
  950. return &Iter{err: err}
  951. }
  952. if len(framer.traceID) > 0 && qry.trace != nil {
  953. qry.trace.Trace(framer.traceID)
  954. }
  955. switch x := resp.(type) {
  956. case *resultVoidFrame:
  957. return &Iter{framer: framer}
  958. case *resultRowsFrame:
  959. iter := &Iter{
  960. meta: x.meta,
  961. framer: framer,
  962. numRows: x.numRows,
  963. }
  964. if params.skipMeta {
  965. if info != nil {
  966. iter.meta = info.response
  967. iter.meta.pagingState = copyBytes(x.meta.pagingState)
  968. } else {
  969. return &Iter{framer: framer, err: errors.New("gocql: did not receive metadata but prepared info is nil")}
  970. }
  971. } else {
  972. iter.meta = x.meta
  973. }
  974. if x.meta.morePages() && !qry.disableAutoPage {
  975. iter.next = &nextIter{
  976. qry: qry,
  977. pos: int((1 - qry.prefetch) * float64(x.numRows)),
  978. }
  979. iter.next.qry.pageState = copyBytes(x.meta.pagingState)
  980. if iter.next.pos < 1 {
  981. iter.next.pos = 1
  982. }
  983. }
  984. return iter
  985. case *resultKeyspaceFrame:
  986. return &Iter{framer: framer}
  987. case *schemaChangeKeyspace, *schemaChangeTable, *schemaChangeFunction, *schemaChangeAggregate, *schemaChangeType:
  988. iter := &Iter{framer: framer}
  989. if err := c.awaitSchemaAgreement(ctx); err != nil {
  990. // TODO: should have this behind a flag
  991. Logger.Println(err)
  992. }
  993. // dont return an error from this, might be a good idea to give a warning
  994. // though. The impact of this returning an error would be that the cluster
  995. // is not consistent with regards to its schema.
  996. return iter
  997. case *RequestErrUnprepared:
  998. stmtCacheKey := c.session.stmtsLRU.keyFor(c.addr, c.currentKeyspace, qry.stmt)
  999. if c.session.stmtsLRU.remove(stmtCacheKey) {
  1000. return c.executeQuery(ctx, qry)
  1001. }
  1002. return &Iter{err: x, framer: framer}
  1003. case error:
  1004. return &Iter{err: x, framer: framer}
  1005. default:
  1006. return &Iter{
  1007. err: NewErrProtocol("Unknown type in response to execute query (%T): %s", x, x),
  1008. framer: framer,
  1009. }
  1010. }
  1011. }
  1012. func (c *Conn) Pick(qry *Query) *Conn {
  1013. if c.Closed() {
  1014. return nil
  1015. }
  1016. return c
  1017. }
  1018. func (c *Conn) Closed() bool {
  1019. return atomic.LoadInt32(&c.closed) == 1
  1020. }
  1021. func (c *Conn) Address() string {
  1022. return c.addr
  1023. }
  1024. func (c *Conn) AvailableStreams() int {
  1025. return c.streams.Available()
  1026. }
  1027. func (c *Conn) UseKeyspace(keyspace string) error {
  1028. q := &writeQueryFrame{statement: `USE "` + keyspace + `"`}
  1029. q.params.consistency = Any
  1030. framer, err := c.exec(context.Background(), q, nil)
  1031. if err != nil {
  1032. return err
  1033. }
  1034. resp, err := framer.parseFrame()
  1035. if err != nil {
  1036. return err
  1037. }
  1038. switch x := resp.(type) {
  1039. case *resultKeyspaceFrame:
  1040. case error:
  1041. return x
  1042. default:
  1043. return NewErrProtocol("unknown frame in response to USE: %v", x)
  1044. }
  1045. c.currentKeyspace = keyspace
  1046. return nil
  1047. }
  1048. func (c *Conn) executeBatch(ctx context.Context, batch *Batch) *Iter {
  1049. if c.version == protoVersion1 {
  1050. return &Iter{err: ErrUnsupported}
  1051. }
  1052. n := len(batch.Entries)
  1053. req := &writeBatchFrame{
  1054. typ: batch.Type,
  1055. statements: make([]batchStatment, n),
  1056. consistency: batch.Cons,
  1057. serialConsistency: batch.serialCons,
  1058. defaultTimestamp: batch.defaultTimestamp,
  1059. defaultTimestampValue: batch.defaultTimestampValue,
  1060. customPayload: batch.CustomPayload,
  1061. }
  1062. stmts := make(map[string]string, len(batch.Entries))
  1063. for i := 0; i < n; i++ {
  1064. entry := &batch.Entries[i]
  1065. b := &req.statements[i]
  1066. if len(entry.Args) > 0 || entry.binding != nil {
  1067. info, err := c.prepareStatement(batch.Context(), entry.Stmt, nil)
  1068. if err != nil {
  1069. return &Iter{err: err}
  1070. }
  1071. var values []interface{}
  1072. if entry.binding == nil {
  1073. values = entry.Args
  1074. } else {
  1075. values, err = entry.binding(&QueryInfo{
  1076. Id: info.id,
  1077. Args: info.request.columns,
  1078. Rval: info.response.columns,
  1079. PKeyColumns: info.request.pkeyColumns,
  1080. })
  1081. if err != nil {
  1082. return &Iter{err: err}
  1083. }
  1084. }
  1085. if len(values) != info.request.actualColCount {
  1086. return &Iter{err: fmt.Errorf("gocql: batch statement %d expected %d values send got %d", i, info.request.actualColCount, len(values))}
  1087. }
  1088. b.preparedID = info.id
  1089. stmts[string(info.id)] = entry.Stmt
  1090. b.values = make([]queryValues, info.request.actualColCount)
  1091. for j := 0; j < info.request.actualColCount; j++ {
  1092. v := &b.values[j]
  1093. value := values[j]
  1094. typ := info.request.columns[j].TypeInfo
  1095. if err := marshalQueryValue(typ, value, v); err != nil {
  1096. return &Iter{err: err}
  1097. }
  1098. }
  1099. } else {
  1100. b.statement = entry.Stmt
  1101. }
  1102. }
  1103. // TODO: should batch support tracing?
  1104. framer, err := c.exec(batch.Context(), req, nil)
  1105. if err != nil {
  1106. return &Iter{err: err}
  1107. }
  1108. resp, err := framer.parseFrame()
  1109. if err != nil {
  1110. return &Iter{err: err, framer: framer}
  1111. }
  1112. switch x := resp.(type) {
  1113. case *resultVoidFrame:
  1114. return &Iter{}
  1115. case *RequestErrUnprepared:
  1116. stmt, found := stmts[string(x.StatementId)]
  1117. if found {
  1118. key := c.session.stmtsLRU.keyFor(c.addr, c.currentKeyspace, stmt)
  1119. c.session.stmtsLRU.remove(key)
  1120. }
  1121. if found {
  1122. return c.executeBatch(ctx, batch)
  1123. } else {
  1124. return &Iter{err: x, framer: framer}
  1125. }
  1126. case *resultRowsFrame:
  1127. iter := &Iter{
  1128. meta: x.meta,
  1129. framer: framer,
  1130. numRows: x.numRows,
  1131. }
  1132. return iter
  1133. case error:
  1134. return &Iter{err: x, framer: framer}
  1135. default:
  1136. return &Iter{err: NewErrProtocol("Unknown type in response to batch statement: %s", x), framer: framer}
  1137. }
  1138. }
  1139. func (c *Conn) query(ctx context.Context, statement string, values ...interface{}) (iter *Iter) {
  1140. q := c.session.Query(statement, values...).Consistency(One)
  1141. q.trace = nil
  1142. return c.executeQuery(ctx, q)
  1143. }
  1144. func (c *Conn) awaitSchemaAgreement(ctx context.Context) (err error) {
  1145. const (
  1146. peerSchemas = "SELECT schema_version, peer FROM system.peers"
  1147. localSchemas = "SELECT schema_version FROM system.local WHERE key='local'"
  1148. )
  1149. var versions map[string]struct{}
  1150. endDeadline := time.Now().Add(c.session.cfg.MaxWaitSchemaAgreement)
  1151. for time.Now().Before(endDeadline) {
  1152. iter := c.query(ctx, peerSchemas)
  1153. versions = make(map[string]struct{})
  1154. var schemaVersion string
  1155. var peer string
  1156. for iter.Scan(&schemaVersion, &peer) {
  1157. if schemaVersion == "" {
  1158. Logger.Printf("skipping peer entry with empty schema_version: peer=%q", peer)
  1159. continue
  1160. }
  1161. versions[schemaVersion] = struct{}{}
  1162. schemaVersion = ""
  1163. }
  1164. if err = iter.Close(); err != nil {
  1165. goto cont
  1166. }
  1167. iter = c.query(ctx, localSchemas)
  1168. for iter.Scan(&schemaVersion) {
  1169. versions[schemaVersion] = struct{}{}
  1170. schemaVersion = ""
  1171. }
  1172. if err = iter.Close(); err != nil {
  1173. goto cont
  1174. }
  1175. if len(versions) <= 1 {
  1176. return nil
  1177. }
  1178. cont:
  1179. select {
  1180. case <-ctx.Done():
  1181. return ctx.Err()
  1182. case <-time.After(200 * time.Millisecond):
  1183. }
  1184. }
  1185. if err != nil {
  1186. return err
  1187. }
  1188. schemas := make([]string, 0, len(versions))
  1189. for schema := range versions {
  1190. schemas = append(schemas, schema)
  1191. }
  1192. // not exported
  1193. return fmt.Errorf("gocql: cluster schema versions not consistent: %+v", schemas)
  1194. }
  1195. func (c *Conn) localHostInfo(ctx context.Context) (*HostInfo, error) {
  1196. row, err := c.query(ctx, "SELECT * FROM system.local WHERE key='local'").rowMap()
  1197. if err != nil {
  1198. return nil, err
  1199. }
  1200. port := c.conn.RemoteAddr().(*net.TCPAddr).Port
  1201. // TODO(zariel): avoid doing this here
  1202. host, err := c.session.hostInfoFromMap(row, port)
  1203. if err != nil {
  1204. return nil, err
  1205. }
  1206. return c.session.ring.addOrUpdate(host), nil
  1207. }
  1208. var (
  1209. ErrQueryArgLength = errors.New("gocql: query argument length mismatch")
  1210. ErrTimeoutNoResponse = errors.New("gocql: no response received from cassandra within timeout period")
  1211. ErrTooManyTimeouts = errors.New("gocql: too many query timeouts on the connection")
  1212. ErrConnectionClosed = errors.New("gocql: connection closed waiting for response")
  1213. ErrNoStreams = errors.New("gocql: no streams available on connection")
  1214. )