conn.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775
  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. "crypto/tls"
  8. "errors"
  9. "fmt"
  10. "io"
  11. "log"
  12. "net"
  13. "strconv"
  14. "strings"
  15. "sync"
  16. "sync/atomic"
  17. "time"
  18. )
  19. //JoinHostPort is a utility to return a address string that can be used
  20. //gocql.Conn to form a connection with a host.
  21. func JoinHostPort(addr string, port int) string {
  22. addr = strings.TrimSpace(addr)
  23. if _, _, err := net.SplitHostPort(addr); err != nil {
  24. addr = net.JoinHostPort(addr, strconv.Itoa(port))
  25. }
  26. return addr
  27. }
  28. type Authenticator interface {
  29. Challenge(req []byte) (resp []byte, auth Authenticator, err error)
  30. Success(data []byte) error
  31. }
  32. type PasswordAuthenticator struct {
  33. Username string
  34. Password string
  35. }
  36. func (p PasswordAuthenticator) Challenge(req []byte) ([]byte, Authenticator, error) {
  37. if string(req) != "org.apache.cassandra.auth.PasswordAuthenticator" {
  38. return nil, nil, fmt.Errorf("unexpected authenticator %q", req)
  39. }
  40. resp := make([]byte, 2+len(p.Username)+len(p.Password))
  41. resp[0] = 0
  42. copy(resp[1:], p.Username)
  43. resp[len(p.Username)+1] = 0
  44. copy(resp[2+len(p.Username):], p.Password)
  45. return resp, nil, nil
  46. }
  47. func (p PasswordAuthenticator) Success(data []byte) error {
  48. return nil
  49. }
  50. type SslOptions struct {
  51. tls.Config
  52. // CertPath and KeyPath are optional depending on server
  53. // config, but both fields must be omitted to avoid using a
  54. // client certificate
  55. CertPath string
  56. KeyPath string
  57. CaPath string //optional depending on server config
  58. // If you want to verify the hostname and server cert (like a wildcard for cass cluster) then you should turn this on
  59. // This option is basically the inverse of InSecureSkipVerify
  60. // See InSecureSkipVerify in http://golang.org/pkg/crypto/tls/ for more info
  61. EnableHostVerification bool
  62. }
  63. type ConnConfig struct {
  64. ProtoVersion int
  65. CQLVersion string
  66. Timeout time.Duration
  67. NumStreams int
  68. Compressor Compressor
  69. Authenticator Authenticator
  70. Keepalive time.Duration
  71. tlsConfig *tls.Config
  72. }
  73. type ConnErrorHandler interface {
  74. HandleError(conn *Conn, err error, closed bool)
  75. }
  76. // How many timeouts we will allow to occur before the connection is closed
  77. // and restarted. This is to prevent a single query timeout from killing a connection
  78. // which may be serving more queries just fine.
  79. // Default is 10, should not be changed concurrently with queries.
  80. var TimeoutLimit int64 = 10
  81. // Conn is a single connection to a Cassandra node. It can be used to execute
  82. // queries, but users are usually advised to use a more reliable, higher
  83. // level API.
  84. type Conn struct {
  85. conn net.Conn
  86. r *bufio.Reader
  87. timeout time.Duration
  88. headerBuf []byte
  89. uniq chan int
  90. calls []callReq
  91. errorHandler ConnErrorHandler
  92. compressor Compressor
  93. auth Authenticator
  94. addr string
  95. version uint8
  96. currentKeyspace string
  97. started bool
  98. closed int32
  99. timeouts int64
  100. }
  101. // Connect establishes a connection to a Cassandra node.
  102. // You must also call the Serve method before you can execute any queries.
  103. func Connect(addr string, cfg ConnConfig, errorHandler ConnErrorHandler) (*Conn, error) {
  104. var (
  105. err error
  106. conn net.Conn
  107. )
  108. dialer := &net.Dialer{
  109. Timeout: cfg.Timeout,
  110. }
  111. if cfg.tlsConfig != nil {
  112. // the TLS config is safe to be reused by connections but it must not
  113. // be modified after being used.
  114. conn, err = tls.DialWithDialer(dialer, "tcp", addr, cfg.tlsConfig)
  115. } else {
  116. conn, err = dialer.Dial("tcp", addr)
  117. }
  118. if err != nil {
  119. return nil, err
  120. }
  121. // going to default to proto 2
  122. if cfg.ProtoVersion < protoVersion1 || cfg.ProtoVersion > protoVersion3 {
  123. log.Printf("unsupported protocol version: %d using 2\n", cfg.ProtoVersion)
  124. cfg.ProtoVersion = 2
  125. }
  126. headerSize := 8
  127. maxStreams := 128
  128. if cfg.ProtoVersion > protoVersion2 {
  129. maxStreams = 32768
  130. headerSize = 9
  131. }
  132. if cfg.NumStreams <= 0 || cfg.NumStreams > maxStreams {
  133. cfg.NumStreams = maxStreams
  134. }
  135. c := &Conn{
  136. conn: conn,
  137. r: bufio.NewReader(conn),
  138. uniq: make(chan int, cfg.NumStreams),
  139. calls: make([]callReq, cfg.NumStreams),
  140. timeout: cfg.Timeout,
  141. version: uint8(cfg.ProtoVersion),
  142. addr: conn.RemoteAddr().String(),
  143. errorHandler: errorHandler,
  144. compressor: cfg.Compressor,
  145. auth: cfg.Authenticator,
  146. headerBuf: make([]byte, headerSize),
  147. }
  148. if cfg.Keepalive > 0 {
  149. c.setKeepalive(cfg.Keepalive)
  150. }
  151. for i := 0; i < cfg.NumStreams; i++ {
  152. c.calls[i].resp = make(chan error)
  153. c.uniq <- i
  154. }
  155. go c.serve()
  156. if err := c.startup(&cfg); err != nil {
  157. conn.Close()
  158. return nil, err
  159. }
  160. c.started = true
  161. return c, nil
  162. }
  163. func (c *Conn) Write(p []byte) (int, error) {
  164. if c.timeout > 0 {
  165. c.conn.SetWriteDeadline(time.Now().Add(c.timeout))
  166. }
  167. return c.conn.Write(p)
  168. }
  169. func (c *Conn) Read(p []byte) (n int, err error) {
  170. const maxAttempts = 5
  171. for i := 0; i < maxAttempts; i++ {
  172. var nn int
  173. if c.timeout > 0 {
  174. c.conn.SetReadDeadline(time.Now().Add(c.timeout))
  175. }
  176. nn, err = io.ReadFull(c.r, p[n:])
  177. n += nn
  178. if err == nil {
  179. break
  180. }
  181. if verr, ok := err.(net.Error); !ok || !verr.Temporary() {
  182. break
  183. }
  184. }
  185. return
  186. }
  187. func (c *Conn) startup(cfg *ConnConfig) error {
  188. m := map[string]string{
  189. "CQL_VERSION": cfg.CQLVersion,
  190. }
  191. if c.compressor != nil {
  192. m["COMPRESSION"] = c.compressor.Name()
  193. }
  194. frame, err := c.exec(&writeStartupFrame{opts: m}, nil)
  195. if err != nil {
  196. return err
  197. }
  198. switch v := frame.(type) {
  199. case error:
  200. return v
  201. case *readyFrame:
  202. return nil
  203. case *authenticateFrame:
  204. return c.authenticateHandshake(v)
  205. default:
  206. return NewErrProtocol("Unknown type of response to startup frame: %s", v)
  207. }
  208. }
  209. func (c *Conn) authenticateHandshake(authFrame *authenticateFrame) error {
  210. if c.auth == nil {
  211. return fmt.Errorf("authentication required (using %q)", authFrame.class)
  212. }
  213. resp, challenger, err := c.auth.Challenge([]byte(authFrame.class))
  214. if err != nil {
  215. return err
  216. }
  217. req := &writeAuthResponseFrame{data: resp}
  218. for {
  219. frame, err := c.exec(req, nil)
  220. if err != nil {
  221. return err
  222. }
  223. switch v := frame.(type) {
  224. case error:
  225. return v
  226. case *authSuccessFrame:
  227. if challenger != nil {
  228. return challenger.Success(v.data)
  229. }
  230. return nil
  231. case *authChallengeFrame:
  232. resp, challenger, err = challenger.Challenge(v.data)
  233. if err != nil {
  234. return err
  235. }
  236. req = &writeAuthResponseFrame{
  237. data: resp,
  238. }
  239. default:
  240. return fmt.Errorf("unknown frame response during authentication: %v", v)
  241. }
  242. }
  243. }
  244. // Serve starts the stream multiplexer for this connection, which is required
  245. // to execute any queries. This method runs as long as the connection is
  246. // open and is therefore usually called in a separate goroutine.
  247. func (c *Conn) serve() {
  248. var (
  249. err error
  250. )
  251. for {
  252. err = c.recv()
  253. if err != nil {
  254. break
  255. }
  256. }
  257. c.closeWithError(err)
  258. }
  259. func (c *Conn) recv() error {
  260. // not safe for concurrent reads
  261. // read a full header, ignore timeouts, as this is being ran in a loop
  262. // TODO: TCP level deadlines? or just query level deadlines?
  263. if c.timeout > 0 {
  264. c.conn.SetReadDeadline(time.Time{})
  265. }
  266. // were just reading headers over and over and copy bodies
  267. head, err := readHeader(c.r, c.headerBuf)
  268. if err != nil {
  269. return err
  270. }
  271. call := &c.calls[head.stream]
  272. err = call.framer.readFrame(&head)
  273. if err != nil {
  274. // only net errors should cause the connection to be closed. Though
  275. // cassandra returning corrupt frames will be returned here as well.
  276. if _, ok := err.(net.Error); ok {
  277. return err
  278. }
  279. }
  280. if !atomic.CompareAndSwapInt32(&call.waiting, 1, 0) {
  281. // the waiting thread timed out and is no longer waiting, the stream has
  282. // not yet been readded to the chan so it cant be used again,
  283. c.releaseStream(head.stream)
  284. return nil
  285. }
  286. select {
  287. case call.resp <- err:
  288. default:
  289. c.releaseStream(head.stream)
  290. }
  291. return nil
  292. }
  293. type callReq struct {
  294. // could use a waitgroup but this allows us to do timeouts on the read/send
  295. resp chan error
  296. framer *framer
  297. waiting int32
  298. }
  299. func (c *Conn) releaseStream(stream int) {
  300. call := &c.calls[stream]
  301. framerPool.Put(call.framer)
  302. call.framer = nil
  303. select {
  304. case c.uniq <- stream:
  305. default:
  306. }
  307. }
  308. func (c *Conn) handleTimeout() {
  309. if atomic.AddInt64(&c.timeouts, 1) > TimeoutLimit {
  310. c.closeWithError(ErrTooManyTimeouts)
  311. }
  312. }
  313. func (c *Conn) exec(req frameWriter, tracer Tracer) (frame, error) {
  314. // TODO: move tracer onto conn
  315. stream := <-c.uniq
  316. call := &c.calls[stream]
  317. // resp is basically a waiting semaphore protecting the framer
  318. framer := newFramer(c, c, c.compressor, c.version)
  319. call.framer = framer
  320. if tracer != nil {
  321. framer.trace()
  322. }
  323. atomic.StoreInt32(&call.waiting, 1)
  324. defer atomic.StoreInt32(&call.waiting, 0)
  325. err := req.writeFrame(framer, stream)
  326. if err != nil {
  327. return nil, err
  328. }
  329. select {
  330. case err := <-call.resp:
  331. // dont release the stream if detect a timeout as another request can reuse
  332. // that stream and get a response for the old request, which we have no
  333. // easy way of detecting.
  334. defer c.releaseStream(stream)
  335. if err != nil {
  336. return nil, err
  337. }
  338. case <-time.After(c.timeout):
  339. c.handleTimeout()
  340. return nil, ErrTimeoutNoResponse
  341. }
  342. if v := framer.header.version.version(); v != c.version {
  343. return nil, NewErrProtocol("unexpected protocol version in response: got %d expected %d", v, c.version)
  344. }
  345. frame, err := framer.parseFrame()
  346. if err != nil {
  347. return nil, err
  348. }
  349. if len(framer.traceID) > 0 {
  350. tracer.Trace(framer.traceID)
  351. }
  352. return frame, nil
  353. }
  354. func (c *Conn) prepareStatement(stmt string, trace Tracer) (*resultPreparedFrame, error) {
  355. stmtsLRU.Lock()
  356. if stmtsLRU.lru == nil {
  357. initStmtsLRU(defaultMaxPreparedStmts)
  358. }
  359. stmtCacheKey := c.addr + c.currentKeyspace + stmt
  360. if val, ok := stmtsLRU.lru.Get(stmtCacheKey); ok {
  361. stmtsLRU.Unlock()
  362. flight := val.(*inflightPrepare)
  363. flight.wg.Wait()
  364. return flight.info, flight.err
  365. }
  366. flight := new(inflightPrepare)
  367. flight.wg.Add(1)
  368. stmtsLRU.lru.Add(stmtCacheKey, flight)
  369. stmtsLRU.Unlock()
  370. prep := &writePrepareFrame{
  371. statement: stmt,
  372. }
  373. resp, err := c.exec(prep, trace)
  374. if err != nil {
  375. flight.err = err
  376. flight.wg.Done()
  377. return nil, err
  378. }
  379. switch x := resp.(type) {
  380. case *resultPreparedFrame:
  381. flight.info = x
  382. case error:
  383. flight.err = x
  384. default:
  385. flight.err = NewErrProtocol("Unknown type in response to prepare frame: %s", x)
  386. }
  387. flight.wg.Done()
  388. if flight.err != nil {
  389. stmtsLRU.Lock()
  390. stmtsLRU.lru.Remove(stmtCacheKey)
  391. stmtsLRU.Unlock()
  392. }
  393. return flight.info, flight.err
  394. }
  395. func (c *Conn) executeQuery(qry *Query) *Iter {
  396. params := queryParams{
  397. consistency: qry.cons,
  398. }
  399. // frame checks that it is not 0
  400. params.serialConsistency = qry.serialCons
  401. params.defaultTimestamp = qry.defaultTimestamp
  402. if len(qry.pageState) > 0 {
  403. params.pagingState = qry.pageState
  404. }
  405. if qry.pageSize > 0 {
  406. params.pageSize = qry.pageSize
  407. }
  408. var frame frameWriter
  409. if qry.shouldPrepare() {
  410. // Prepare all DML queries. Other queries can not be prepared.
  411. info, err := c.prepareStatement(qry.stmt, qry.trace)
  412. if err != nil {
  413. return &Iter{err: err}
  414. }
  415. var values []interface{}
  416. if qry.binding == nil {
  417. values = qry.values
  418. } else {
  419. binding := &QueryInfo{
  420. Id: info.preparedID,
  421. Args: info.reqMeta.columns,
  422. Rval: info.respMeta.columns,
  423. }
  424. values, err = qry.binding(binding)
  425. if err != nil {
  426. return &Iter{err: err}
  427. }
  428. }
  429. if len(values) != len(info.reqMeta.columns) {
  430. return &Iter{err: ErrQueryArgLength}
  431. }
  432. params.values = make([]queryValues, len(values))
  433. for i := 0; i < len(values); i++ {
  434. val, err := Marshal(info.reqMeta.columns[i].TypeInfo, values[i])
  435. if err != nil {
  436. return &Iter{err: err}
  437. }
  438. v := &params.values[i]
  439. v.value = val
  440. // TODO: handle query binding names
  441. }
  442. frame = &writeExecuteFrame{
  443. preparedID: info.preparedID,
  444. params: params,
  445. }
  446. } else {
  447. frame = &writeQueryFrame{
  448. statement: qry.stmt,
  449. params: params,
  450. }
  451. }
  452. resp, err := c.exec(frame, qry.trace)
  453. if err != nil {
  454. return &Iter{err: err}
  455. }
  456. switch x := resp.(type) {
  457. case *resultVoidFrame:
  458. return &Iter{}
  459. case *resultRowsFrame:
  460. iter := &Iter{
  461. meta: x.meta,
  462. rows: x.rows,
  463. }
  464. if len(x.meta.pagingState) > 0 {
  465. iter.next = &nextIter{
  466. qry: *qry,
  467. pos: int((1 - qry.prefetch) * float64(len(iter.rows))),
  468. }
  469. iter.next.qry.pageState = x.meta.pagingState
  470. if iter.next.pos < 1 {
  471. iter.next.pos = 1
  472. }
  473. }
  474. return iter
  475. case *resultKeyspaceFrame, *resultSchemaChangeFrame:
  476. return &Iter{}
  477. case *RequestErrUnprepared:
  478. stmtsLRU.Lock()
  479. stmtCacheKey := c.addr + c.currentKeyspace + qry.stmt
  480. if _, ok := stmtsLRU.lru.Get(stmtCacheKey); ok {
  481. stmtsLRU.lru.Remove(stmtCacheKey)
  482. stmtsLRU.Unlock()
  483. return c.executeQuery(qry)
  484. }
  485. stmtsLRU.Unlock()
  486. return &Iter{err: x}
  487. case error:
  488. return &Iter{err: x}
  489. default:
  490. return &Iter{err: NewErrProtocol("Unknown type in response to execute query: %s", x)}
  491. }
  492. }
  493. func (c *Conn) Pick(qry *Query) *Conn {
  494. if c.Closed() {
  495. return nil
  496. }
  497. return c
  498. }
  499. func (c *Conn) Closed() bool {
  500. return atomic.LoadInt32(&c.closed) == 1
  501. }
  502. func (c *Conn) closeWithError(err error) {
  503. if !atomic.CompareAndSwapInt32(&c.closed, 0, 1) {
  504. return
  505. }
  506. for id := 0; id < len(c.calls); id++ {
  507. req := &c.calls[id]
  508. // we need to send the error to all waiting queries, put the state
  509. // of this conn into not active so that it can not execute any queries.
  510. select {
  511. case req.resp <- err:
  512. default:
  513. }
  514. close(req.resp)
  515. }
  516. c.conn.Close()
  517. if c.started && err != nil {
  518. c.errorHandler.HandleError(c, err, true)
  519. }
  520. }
  521. func (c *Conn) Close() {
  522. c.closeWithError(nil)
  523. }
  524. func (c *Conn) Address() string {
  525. return c.addr
  526. }
  527. func (c *Conn) AvailableStreams() int {
  528. return len(c.uniq)
  529. }
  530. func (c *Conn) UseKeyspace(keyspace string) error {
  531. q := &writeQueryFrame{statement: `USE "` + keyspace + `"`}
  532. q.params.consistency = Any
  533. resp, err := c.exec(q, nil)
  534. if err != nil {
  535. return err
  536. }
  537. switch x := resp.(type) {
  538. case *resultKeyspaceFrame:
  539. case error:
  540. return x
  541. default:
  542. return NewErrProtocol("unknown frame in response to USE: %v", x)
  543. }
  544. c.currentKeyspace = keyspace
  545. return nil
  546. }
  547. func (c *Conn) executeBatch(batch *Batch) error {
  548. if c.version == protoVersion1 {
  549. return ErrUnsupported
  550. }
  551. n := len(batch.Entries)
  552. req := &writeBatchFrame{
  553. typ: batch.Type,
  554. statements: make([]batchStatment, n),
  555. consistency: batch.Cons,
  556. serialConsistency: batch.serialCons,
  557. defaultTimestamp: batch.defaultTimestamp,
  558. }
  559. stmts := make(map[string]string)
  560. for i := 0; i < n; i++ {
  561. entry := &batch.Entries[i]
  562. b := &req.statements[i]
  563. if len(entry.Args) > 0 || entry.binding != nil {
  564. info, err := c.prepareStatement(entry.Stmt, nil)
  565. if err != nil {
  566. return err
  567. }
  568. var args []interface{}
  569. if entry.binding == nil {
  570. args = entry.Args
  571. } else {
  572. binding := &QueryInfo{
  573. Id: info.preparedID,
  574. Args: info.reqMeta.columns,
  575. Rval: info.respMeta.columns,
  576. }
  577. args, err = entry.binding(binding)
  578. if err != nil {
  579. return err
  580. }
  581. }
  582. if len(args) != len(info.reqMeta.columns) {
  583. return ErrQueryArgLength
  584. }
  585. b.preparedID = info.preparedID
  586. stmts[string(info.preparedID)] = entry.Stmt
  587. b.values = make([]queryValues, len(info.reqMeta.columns))
  588. for j := 0; j < len(info.reqMeta.columns); j++ {
  589. val, err := Marshal(info.reqMeta.columns[j].TypeInfo, args[j])
  590. if err != nil {
  591. return err
  592. }
  593. b.values[j].value = val
  594. // TODO: add names
  595. }
  596. } else {
  597. b.statement = entry.Stmt
  598. }
  599. }
  600. // TODO: should batch support tracing?
  601. resp, err := c.exec(req, nil)
  602. if err != nil {
  603. return err
  604. }
  605. switch x := resp.(type) {
  606. case *resultVoidFrame:
  607. return nil
  608. case *RequestErrUnprepared:
  609. stmt, found := stmts[string(x.StatementId)]
  610. if found {
  611. stmtsLRU.Lock()
  612. stmtsLRU.lru.Remove(c.addr + c.currentKeyspace + stmt)
  613. stmtsLRU.Unlock()
  614. }
  615. if found {
  616. return c.executeBatch(batch)
  617. } else {
  618. return x
  619. }
  620. case error:
  621. return x
  622. default:
  623. return NewErrProtocol("Unknown type in response to batch statement: %s", x)
  624. }
  625. }
  626. func (c *Conn) setKeepalive(d time.Duration) error {
  627. if tc, ok := c.conn.(*net.TCPConn); ok {
  628. err := tc.SetKeepAlivePeriod(d)
  629. if err != nil {
  630. return err
  631. }
  632. return tc.SetKeepAlive(true)
  633. }
  634. return nil
  635. }
  636. type inflightPrepare struct {
  637. info *resultPreparedFrame
  638. err error
  639. wg sync.WaitGroup
  640. }
  641. var (
  642. ErrQueryArgLength = errors.New("query argument length mismatch")
  643. ErrTimeoutNoResponse = errors.New("gocql: no response recieved from cassandra within timeout period")
  644. ErrTooManyTimeouts = errors.New("gocql: too many query timeouts on the connection")
  645. )