conn.go 32 KB

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