conn.go 15 KB

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