conn.go 33 KB

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