conn.go 15 KB

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