conn.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712
  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. c.uniq <- head.stream
  276. return nil
  277. }
  278. type callReq struct {
  279. // could use a waitgroup but this allows us to do timeouts on the read/send
  280. resp chan error
  281. framer *framer
  282. }
  283. func (c *Conn) exec(req frameWriter, tracer Tracer) (frame, error) {
  284. // TODO: move tracer onto conn
  285. stream := <-c.uniq
  286. call := &c.calls[stream]
  287. // resp is basically a waiting semaphore protecting the framer
  288. framer := newFramer(c, c, c.compressor, c.version)
  289. call.framer = framer
  290. if tracer != nil {
  291. framer.trace()
  292. }
  293. err := req.writeFrame(framer, stream)
  294. if err != nil {
  295. return nil, err
  296. }
  297. err = <-call.resp
  298. if err != nil {
  299. return nil, err
  300. }
  301. if v := framer.header.version.version(); v != c.version {
  302. return nil, NewErrProtocol("unexpected protocol version in response: got %d expected %d", v, c.version)
  303. }
  304. frame, err := framer.parseFrame()
  305. if err != nil {
  306. return nil, err
  307. }
  308. if len(framer.traceID) > 0 {
  309. tracer.Trace(framer.traceID)
  310. }
  311. framerPool.Put(framer)
  312. call.framer = nil
  313. return frame, nil
  314. }
  315. func (c *Conn) prepareStatement(stmt string, trace Tracer) (*resultPreparedFrame, error) {
  316. stmtsLRU.Lock()
  317. if stmtsLRU.lru == nil {
  318. initStmtsLRU(defaultMaxPreparedStmts)
  319. }
  320. stmtCacheKey := c.addr + c.currentKeyspace + stmt
  321. if val, ok := stmtsLRU.lru.Get(stmtCacheKey); ok {
  322. stmtsLRU.Unlock()
  323. flight := val.(*inflightPrepare)
  324. flight.wg.Wait()
  325. return flight.info, flight.err
  326. }
  327. flight := new(inflightPrepare)
  328. flight.wg.Add(1)
  329. stmtsLRU.lru.Add(stmtCacheKey, flight)
  330. stmtsLRU.Unlock()
  331. prep := &writePrepareFrame{
  332. statement: stmt,
  333. }
  334. resp, err := c.exec(prep, trace)
  335. if err != nil {
  336. flight.err = err
  337. flight.wg.Done()
  338. return nil, err
  339. }
  340. switch x := resp.(type) {
  341. case *resultPreparedFrame:
  342. flight.info = x
  343. case error:
  344. flight.err = x
  345. default:
  346. flight.err = NewErrProtocol("Unknown type in response to prepare frame: %s", x)
  347. }
  348. flight.wg.Done()
  349. if flight.err != nil {
  350. stmtsLRU.Lock()
  351. stmtsLRU.lru.Remove(stmtCacheKey)
  352. stmtsLRU.Unlock()
  353. }
  354. return flight.info, flight.err
  355. }
  356. func (c *Conn) executeQuery(qry *Query) *Iter {
  357. params := queryParams{
  358. consistency: qry.cons,
  359. }
  360. // frame checks that it is not 0
  361. params.serialConsistency = qry.serialCons
  362. // TODO: Add DefaultTimestamp
  363. if len(qry.pageState) > 0 {
  364. params.pagingState = qry.pageState
  365. }
  366. if qry.pageSize > 0 {
  367. params.pageSize = qry.pageSize
  368. }
  369. var frame frameWriter
  370. if qry.shouldPrepare() {
  371. // Prepare all DML queries. Other queries can not be prepared.
  372. info, err := c.prepareStatement(qry.stmt, qry.trace)
  373. if err != nil {
  374. return &Iter{err: err}
  375. }
  376. var values []interface{}
  377. if qry.binding == nil {
  378. values = qry.values
  379. } else {
  380. binding := &QueryInfo{
  381. Id: info.preparedID,
  382. Args: info.reqMeta.columns,
  383. Rval: info.respMeta.columns,
  384. }
  385. values, err = qry.binding(binding)
  386. if err != nil {
  387. return &Iter{err: err}
  388. }
  389. }
  390. if len(values) != len(info.reqMeta.columns) {
  391. return &Iter{err: ErrQueryArgLength}
  392. }
  393. params.values = make([]queryValues, len(values))
  394. for i := 0; i < len(values); i++ {
  395. val, err := Marshal(info.reqMeta.columns[i].TypeInfo, values[i])
  396. if err != nil {
  397. return &Iter{err: err}
  398. }
  399. v := &params.values[i]
  400. v.value = val
  401. // TODO: handle query binding names
  402. }
  403. frame = &writeExecuteFrame{
  404. preparedID: info.preparedID,
  405. params: params,
  406. }
  407. } else {
  408. frame = &writeQueryFrame{
  409. statement: qry.stmt,
  410. params: params,
  411. }
  412. }
  413. resp, err := c.exec(frame, qry.trace)
  414. if err != nil {
  415. return &Iter{err: err}
  416. }
  417. switch x := resp.(type) {
  418. case *resultVoidFrame:
  419. return &Iter{}
  420. case *resultRowsFrame:
  421. iter := &Iter{
  422. meta: x.meta,
  423. rows: x.rows,
  424. }
  425. if len(x.meta.pagingState) > 0 {
  426. iter.next = &nextIter{
  427. qry: *qry,
  428. pos: int((1 - qry.prefetch) * float64(len(iter.rows))),
  429. }
  430. iter.next.qry.pageState = x.meta.pagingState
  431. if iter.next.pos < 1 {
  432. iter.next.pos = 1
  433. }
  434. }
  435. return iter
  436. case *resultKeyspaceFrame, *resultSchemaChangeFrame:
  437. return &Iter{}
  438. case *RequestErrUnprepared:
  439. stmtsLRU.Lock()
  440. stmtCacheKey := c.addr + c.currentKeyspace + qry.stmt
  441. if _, ok := stmtsLRU.lru.Get(stmtCacheKey); ok {
  442. stmtsLRU.lru.Remove(stmtCacheKey)
  443. stmtsLRU.Unlock()
  444. return c.executeQuery(qry)
  445. }
  446. stmtsLRU.Unlock()
  447. return &Iter{err: x}
  448. case error:
  449. return &Iter{err: x}
  450. default:
  451. return &Iter{err: NewErrProtocol("Unknown type in response to execute query: %s", x)}
  452. }
  453. }
  454. func (c *Conn) Pick(qry *Query) *Conn {
  455. if c.Closed() {
  456. return nil
  457. }
  458. return c
  459. }
  460. func (c *Conn) Closed() bool {
  461. c.closedMu.RLock()
  462. closed := c.isClosed
  463. c.closedMu.RUnlock()
  464. return closed
  465. }
  466. func (c *Conn) Close() {
  467. c.closedMu.Lock()
  468. if c.isClosed {
  469. c.closedMu.Unlock()
  470. return
  471. }
  472. c.isClosed = true
  473. c.closedMu.Unlock()
  474. c.conn.Close()
  475. }
  476. func (c *Conn) Address() string {
  477. return c.addr
  478. }
  479. func (c *Conn) AvailableStreams() int {
  480. return len(c.uniq)
  481. }
  482. func (c *Conn) UseKeyspace(keyspace string) error {
  483. q := &writeQueryFrame{statement: `USE "` + keyspace + `"`}
  484. q.params.consistency = Any
  485. resp, err := c.exec(q, nil)
  486. if err != nil {
  487. return err
  488. }
  489. switch x := resp.(type) {
  490. case *resultKeyspaceFrame:
  491. case error:
  492. return x
  493. default:
  494. return NewErrProtocol("unknown frame in response to USE: %v", x)
  495. }
  496. c.currentKeyspace = keyspace
  497. return nil
  498. }
  499. func (c *Conn) executeBatch(batch *Batch) error {
  500. if c.version == protoVersion1 {
  501. return ErrUnsupported
  502. }
  503. n := len(batch.Entries)
  504. req := &writeBatchFrame{
  505. typ: batch.Type,
  506. statements: make([]batchStatment, n),
  507. consistency: batch.Cons,
  508. serialConsistency: batch.serialCons,
  509. }
  510. stmts := make(map[string]string)
  511. for i := 0; i < n; i++ {
  512. entry := &batch.Entries[i]
  513. b := &req.statements[i]
  514. if len(entry.Args) > 0 || entry.binding != nil {
  515. info, err := c.prepareStatement(entry.Stmt, nil)
  516. if err != nil {
  517. return err
  518. }
  519. var args []interface{}
  520. if entry.binding == nil {
  521. args = entry.Args
  522. } else {
  523. binding := &QueryInfo{
  524. Id: info.preparedID,
  525. Args: info.reqMeta.columns,
  526. Rval: info.respMeta.columns,
  527. }
  528. args, err = entry.binding(binding)
  529. if err != nil {
  530. return err
  531. }
  532. }
  533. if len(args) != len(info.reqMeta.columns) {
  534. return ErrQueryArgLength
  535. }
  536. b.preparedID = info.preparedID
  537. stmts[string(info.preparedID)] = entry.Stmt
  538. b.values = make([]queryValues, len(info.reqMeta.columns))
  539. for j := 0; j < len(info.reqMeta.columns); j++ {
  540. val, err := Marshal(info.reqMeta.columns[j].TypeInfo, args[j])
  541. if err != nil {
  542. return err
  543. }
  544. b.values[j].value = val
  545. // TODO: add names
  546. }
  547. } else {
  548. b.statement = entry.Stmt
  549. }
  550. }
  551. // TODO: should batch support tracing?
  552. resp, err := c.exec(req, nil)
  553. if err != nil {
  554. return err
  555. }
  556. switch x := resp.(type) {
  557. case *resultVoidFrame:
  558. return nil
  559. case *RequestErrUnprepared:
  560. stmt, found := stmts[string(x.StatementId)]
  561. if found {
  562. stmtsLRU.Lock()
  563. stmtsLRU.lru.Remove(c.addr + c.currentKeyspace + stmt)
  564. stmtsLRU.Unlock()
  565. }
  566. if found {
  567. return c.executeBatch(batch)
  568. } else {
  569. return x
  570. }
  571. case error:
  572. return x
  573. default:
  574. return NewErrProtocol("Unknown type in response to batch statement: %s", x)
  575. }
  576. }
  577. func (c *Conn) setKeepalive(d time.Duration) error {
  578. if tc, ok := c.conn.(*net.TCPConn); ok {
  579. err := tc.SetKeepAlivePeriod(d)
  580. if err != nil {
  581. return err
  582. }
  583. return tc.SetKeepAlive(true)
  584. }
  585. return nil
  586. }
  587. type inflightPrepare struct {
  588. info *resultPreparedFrame
  589. err error
  590. wg sync.WaitGroup
  591. }
  592. var (
  593. ErrQueryArgLength = errors.New("query argument length mismatch")
  594. )