conn.go 15 KB

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