conn.go 15 KB

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