conn.go 29 KB

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