conn.go 14 KB

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