conn.go 30 KB

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