conn.go 14 KB

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