conn.go 34 KB

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