conn.go 28 KB

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