conn.go 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451
  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. quit chan struct{}
  133. timeouts int64
  134. }
  135. // connect establishes a connection to a Cassandra node using session's connection config.
  136. func (s *Session) connect(host *HostInfo, errorHandler ConnErrorHandler) (*Conn, error) {
  137. return s.dial(host, s.connCfg, errorHandler)
  138. }
  139. // dial establishes a connection to a Cassandra node and notifies the session's connectObserver.
  140. func (s *Session) dial(host *HostInfo, connConfig *ConnConfig, errorHandler ConnErrorHandler) (*Conn, error) {
  141. var obs ObservedConnect
  142. if s.connectObserver != nil {
  143. obs.Host = host
  144. obs.Start = time.Now()
  145. }
  146. conn, err := s.dialWithoutObserver(host, connConfig, errorHandler)
  147. if s.connectObserver != nil {
  148. obs.End = time.Now()
  149. obs.Err = err
  150. s.connectObserver.ObserveConnect(obs)
  151. }
  152. return conn, err
  153. }
  154. // dialWithoutObserver establishes connection to a Cassandra node.
  155. //
  156. // dialWithoutObserver does not notify the connection observer, so you most probably want to call dial() instead.
  157. func (s *Session) dialWithoutObserver(host *HostInfo, cfg *ConnConfig, errorHandler ConnErrorHandler) (*Conn, error) {
  158. ip := host.ConnectAddress()
  159. port := host.port
  160. // TODO(zariel): remove these
  161. if !validIpAddr(ip) {
  162. panic(fmt.Sprintf("host missing connect ip address: %v", ip))
  163. } else if port == 0 {
  164. panic(fmt.Sprintf("host missing port: %v", port))
  165. }
  166. var (
  167. err error
  168. conn net.Conn
  169. )
  170. dialer := &net.Dialer{
  171. Timeout: cfg.ConnectTimeout,
  172. }
  173. if cfg.Keepalive > 0 {
  174. dialer.KeepAlive = cfg.Keepalive
  175. }
  176. if cfg.tlsConfig != nil {
  177. // the TLS config is safe to be reused by connections but it must not
  178. // be modified after being used.
  179. conn, err = tls.DialWithDialer(dialer, "tcp", host.HostnameAndPort(), cfg.tlsConfig)
  180. } else {
  181. conn, err = dialer.Dial("tcp", host.HostnameAndPort())
  182. }
  183. if err != nil {
  184. return nil, err
  185. }
  186. c := &Conn{
  187. conn: conn,
  188. r: bufio.NewReader(conn),
  189. cfg: cfg,
  190. calls: make(map[int]*callReq),
  191. version: uint8(cfg.ProtoVersion),
  192. addr: conn.RemoteAddr().String(),
  193. errorHandler: errorHandler,
  194. compressor: cfg.Compressor,
  195. quit: make(chan struct{}),
  196. session: s,
  197. streams: streams.New(cfg.ProtoVersion),
  198. host: host,
  199. frameObserver: s.frameObserver,
  200. w: &deadlineWriter{
  201. w: conn,
  202. timeout: cfg.Timeout,
  203. },
  204. }
  205. if cfg.AuthProvider != nil {
  206. c.auth, err = cfg.AuthProvider(host)
  207. if err != nil {
  208. return nil, err
  209. }
  210. } else {
  211. c.auth = cfg.Authenticator
  212. }
  213. var (
  214. ctx context.Context
  215. cancel func()
  216. )
  217. if cfg.ConnectTimeout > 0 {
  218. ctx, cancel = context.WithTimeout(context.TODO(), cfg.ConnectTimeout)
  219. } else {
  220. ctx, cancel = context.WithCancel(context.TODO())
  221. }
  222. defer cancel()
  223. startup := &startupCoordinator{
  224. frameTicker: make(chan struct{}),
  225. conn: c,
  226. }
  227. c.timeout = cfg.ConnectTimeout
  228. if err := startup.setupConn(ctx); err != nil {
  229. c.close()
  230. return nil, err
  231. }
  232. c.timeout = cfg.Timeout
  233. // dont coalesce startup frames
  234. if s.cfg.WriteCoalesceWaitTime > 0 && !cfg.disableCoalesce {
  235. c.w = newWriteCoalescer(conn, c.timeout, s.cfg.WriteCoalesceWaitTime, c.quit)
  236. }
  237. go c.serve()
  238. go c.heartBeat()
  239. return c, nil
  240. }
  241. func (c *Conn) Write(p []byte) (n int, err error) {
  242. return c.w.Write(p)
  243. }
  244. func (c *Conn) Read(p []byte) (n int, err error) {
  245. const maxAttempts = 5
  246. for i := 0; i < maxAttempts; i++ {
  247. var nn int
  248. if c.timeout > 0 {
  249. c.conn.SetReadDeadline(time.Now().Add(c.timeout))
  250. }
  251. nn, err = io.ReadFull(c.r, p[n:])
  252. n += nn
  253. if err == nil {
  254. break
  255. }
  256. if verr, ok := err.(net.Error); !ok || !verr.Temporary() {
  257. break
  258. }
  259. }
  260. return
  261. }
  262. type startupCoordinator struct {
  263. conn *Conn
  264. frameTicker chan struct{}
  265. }
  266. func (s *startupCoordinator) setupConn(ctx context.Context) error {
  267. startupErr := make(chan error)
  268. go func() {
  269. for range s.frameTicker {
  270. err := s.conn.recv()
  271. if err != nil {
  272. select {
  273. case startupErr <- err:
  274. case <-ctx.Done():
  275. }
  276. return
  277. }
  278. }
  279. }()
  280. go func() {
  281. defer close(s.frameTicker)
  282. err := s.options(ctx)
  283. select {
  284. case startupErr <- err:
  285. case <-ctx.Done():
  286. }
  287. }()
  288. select {
  289. case err := <-startupErr:
  290. if err != nil {
  291. return err
  292. }
  293. case <-ctx.Done():
  294. return errors.New("gocql: no response to connection startup within timeout")
  295. }
  296. return nil
  297. }
  298. func (s *startupCoordinator) write(ctx context.Context, frame frameWriter) (frame, error) {
  299. select {
  300. case s.frameTicker <- struct{}{}:
  301. case <-ctx.Done():
  302. return nil, ctx.Err()
  303. }
  304. framer, err := s.conn.exec(ctx, frame, nil)
  305. if err != nil {
  306. return nil, err
  307. }
  308. return framer.parseFrame()
  309. }
  310. func (s *startupCoordinator) options(ctx context.Context) error {
  311. frame, err := s.write(ctx, &writeOptionsFrame{})
  312. if err != nil {
  313. return err
  314. }
  315. supported, ok := frame.(*supportedFrame)
  316. if !ok {
  317. return NewErrProtocol("Unknown type of response to startup frame: %T", frame)
  318. }
  319. return s.startup(ctx, supported.supported)
  320. }
  321. func (s *startupCoordinator) startup(ctx context.Context, supported map[string][]string) error {
  322. m := map[string]string{
  323. "CQL_VERSION": s.conn.cfg.CQLVersion,
  324. }
  325. if s.conn.compressor != nil {
  326. comp := supported["COMPRESSION"]
  327. name := s.conn.compressor.Name()
  328. for _, compressor := range comp {
  329. if compressor == name {
  330. m["COMPRESSION"] = compressor
  331. break
  332. }
  333. }
  334. if _, ok := m["COMPRESSION"]; !ok {
  335. s.conn.compressor = nil
  336. }
  337. }
  338. frame, err := s.write(ctx, &writeStartupFrame{opts: m})
  339. if err != nil {
  340. return err
  341. }
  342. switch v := frame.(type) {
  343. case error:
  344. return v
  345. case *readyFrame:
  346. return nil
  347. case *authenticateFrame:
  348. return s.authenticateHandshake(ctx, v)
  349. default:
  350. return NewErrProtocol("Unknown type of response to startup frame: %s", v)
  351. }
  352. }
  353. func (s *startupCoordinator) authenticateHandshake(ctx context.Context, authFrame *authenticateFrame) error {
  354. if s.conn.auth == nil {
  355. return fmt.Errorf("authentication required (using %q)", authFrame.class)
  356. }
  357. resp, challenger, err := s.conn.auth.Challenge([]byte(authFrame.class))
  358. if err != nil {
  359. return err
  360. }
  361. req := &writeAuthResponseFrame{data: resp}
  362. for {
  363. frame, err := s.write(ctx, req)
  364. if err != nil {
  365. return err
  366. }
  367. switch v := frame.(type) {
  368. case error:
  369. return v
  370. case *authSuccessFrame:
  371. if challenger != nil {
  372. return challenger.Success(v.data)
  373. }
  374. return nil
  375. case *authChallengeFrame:
  376. resp, challenger, err = challenger.Challenge(v.data)
  377. if err != nil {
  378. return err
  379. }
  380. req = &writeAuthResponseFrame{
  381. data: resp,
  382. }
  383. default:
  384. return fmt.Errorf("unknown frame response during authentication: %v", v)
  385. }
  386. }
  387. }
  388. func (c *Conn) closeWithError(err error) {
  389. if !atomic.CompareAndSwapInt32(&c.closed, 0, 1) {
  390. return
  391. }
  392. // we should attempt to deliver the error back to the caller if it
  393. // exists
  394. if err != nil {
  395. c.mu.Lock()
  396. for _, req := range c.calls {
  397. // we need to send the error to all waiting queries, put the state
  398. // of this conn into not active so that it can not execute any queries.
  399. select {
  400. case req.resp <- err:
  401. case <-req.timeout:
  402. }
  403. }
  404. c.mu.Unlock()
  405. }
  406. // if error was nil then unblock the quit channel
  407. close(c.quit)
  408. cerr := c.close()
  409. if err != nil {
  410. c.errorHandler.HandleError(c, err, true)
  411. } else if cerr != nil {
  412. // TODO(zariel): is it a good idea to do this?
  413. c.errorHandler.HandleError(c, cerr, true)
  414. }
  415. }
  416. func (c *Conn) close() error {
  417. return c.conn.Close()
  418. }
  419. func (c *Conn) Close() {
  420. c.closeWithError(nil)
  421. }
  422. // Serve starts the stream multiplexer for this connection, which is required
  423. // to execute any queries. This method runs as long as the connection is
  424. // open and is therefore usually called in a separate goroutine.
  425. func (c *Conn) serve() {
  426. var err error
  427. for err == nil {
  428. err = c.recv()
  429. }
  430. c.closeWithError(err)
  431. }
  432. func (c *Conn) discardFrame(head frameHeader) error {
  433. _, err := io.CopyN(ioutil.Discard, c, int64(head.length))
  434. if err != nil {
  435. return err
  436. }
  437. return nil
  438. }
  439. type protocolError struct {
  440. frame frame
  441. }
  442. func (p *protocolError) Error() string {
  443. if err, ok := p.frame.(error); ok {
  444. return err.Error()
  445. }
  446. return fmt.Sprintf("gocql: received unexpected frame on stream %d: %v", p.frame.Header().stream, p.frame)
  447. }
  448. func (c *Conn) heartBeat() {
  449. sleepTime := 1 * time.Second
  450. timer := time.NewTimer(sleepTime)
  451. defer timer.Stop()
  452. var failures int
  453. for {
  454. if failures > 5 {
  455. c.closeWithError(fmt.Errorf("gocql: heartbeat failed"))
  456. return
  457. }
  458. timer.Reset(sleepTime)
  459. select {
  460. case <-c.quit:
  461. return
  462. case <-timer.C:
  463. }
  464. framer, err := c.exec(context.Background(), &writeOptionsFrame{}, nil)
  465. if err != nil {
  466. failures++
  467. continue
  468. }
  469. resp, err := framer.parseFrame()
  470. if err != nil {
  471. // invalid frame
  472. failures++
  473. continue
  474. }
  475. switch resp.(type) {
  476. case *supportedFrame:
  477. // Everything ok
  478. sleepTime = 5 * time.Second
  479. failures = 0
  480. case error:
  481. // TODO: should we do something here?
  482. default:
  483. panic(fmt.Sprintf("gocql: unknown frame in response to options: %T", resp))
  484. }
  485. }
  486. }
  487. func (c *Conn) recv() error {
  488. // not safe for concurrent reads
  489. // read a full header, ignore timeouts, as this is being ran in a loop
  490. // TODO: TCP level deadlines? or just query level deadlines?
  491. if c.timeout > 0 {
  492. c.conn.SetReadDeadline(time.Time{})
  493. }
  494. headStartTime := time.Now()
  495. // were just reading headers over and over and copy bodies
  496. head, err := readHeader(c.r, c.headerBuf[:])
  497. headEndTime := time.Now()
  498. if err != nil {
  499. return err
  500. }
  501. if c.frameObserver != nil {
  502. c.frameObserver.ObserveFrameHeader(context.Background(), ObservedFrameHeader{
  503. Version: protoVersion(head.version),
  504. Flags: head.flags,
  505. Stream: int16(head.stream),
  506. Opcode: frameOp(head.op),
  507. Length: int32(head.length),
  508. Start: headStartTime,
  509. End: headEndTime,
  510. Host: c.host,
  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 * FROM system.peers"
  1147. localSchemas = "SELECT schema_version FROM system.local WHERE key='local'"
  1148. )
  1149. var versions map[string]struct{}
  1150. var schemaVersion string
  1151. endDeadline := time.Now().Add(c.session.cfg.MaxWaitSchemaAgreement)
  1152. for time.Now().Before(endDeadline) {
  1153. iter := c.query(ctx, peerSchemas)
  1154. versions = make(map[string]struct{})
  1155. rows, err := iter.SliceMap()
  1156. if err != nil {
  1157. goto cont
  1158. }
  1159. for _, row := range rows {
  1160. host, err := c.session.hostInfoFromMap(row, &HostInfo{connectAddress: c.host.ConnectAddress(), port: c.session.cfg.Port})
  1161. if err != nil {
  1162. goto cont
  1163. }
  1164. if !isValidPeer(host) || host.schemaVersion == "" {
  1165. Logger.Printf("invalid peer or peer with empty schema_version: peer=%q", host)
  1166. continue
  1167. }
  1168. versions[host.schemaVersion] = struct{}{}
  1169. }
  1170. if err = iter.Close(); err != nil {
  1171. goto cont
  1172. }
  1173. iter = c.query(ctx, localSchemas)
  1174. for iter.Scan(&schemaVersion) {
  1175. versions[schemaVersion] = struct{}{}
  1176. schemaVersion = ""
  1177. }
  1178. if err = iter.Close(); err != nil {
  1179. goto cont
  1180. }
  1181. if len(versions) <= 1 {
  1182. return nil
  1183. }
  1184. cont:
  1185. select {
  1186. case <-ctx.Done():
  1187. return ctx.Err()
  1188. case <-time.After(200 * time.Millisecond):
  1189. }
  1190. }
  1191. if err != nil {
  1192. return err
  1193. }
  1194. schemas := make([]string, 0, len(versions))
  1195. for schema := range versions {
  1196. schemas = append(schemas, schema)
  1197. }
  1198. // not exported
  1199. return fmt.Errorf("gocql: cluster schema versions not consistent: %+v", schemas)
  1200. }
  1201. func (c *Conn) localHostInfo(ctx context.Context) (*HostInfo, error) {
  1202. row, err := c.query(ctx, "SELECT * FROM system.local WHERE key='local'").rowMap()
  1203. if err != nil {
  1204. return nil, err
  1205. }
  1206. port := c.conn.RemoteAddr().(*net.TCPAddr).Port
  1207. // TODO(zariel): avoid doing this here
  1208. host, err := c.session.hostInfoFromMap(row, &HostInfo{connectAddress: c.host.connectAddress, port: port})
  1209. if err != nil {
  1210. return nil, err
  1211. }
  1212. return c.session.ring.addOrUpdate(host), nil
  1213. }
  1214. var (
  1215. ErrQueryArgLength = errors.New("gocql: query argument length mismatch")
  1216. ErrTimeoutNoResponse = errors.New("gocql: no response received from cassandra within timeout period")
  1217. ErrTooManyTimeouts = errors.New("gocql: too many query timeouts on the connection")
  1218. ErrConnectionClosed = errors.New("gocql: connection closed waiting for response")
  1219. ErrNoStreams = errors.New("gocql: no streams available on connection")
  1220. )