conn.go 34 KB

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