conn.go 31 KB

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