conn.go 15 KB

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