conn.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643
  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. "fmt"
  8. "net"
  9. "strings"
  10. "sync"
  11. "sync/atomic"
  12. "time"
  13. "unicode"
  14. "code.google.com/p/snappy-go/snappy"
  15. )
  16. const defaultFrameSize = 4096
  17. const flagResponse = 0x80
  18. const maskVersion = 0x7F
  19. type Cluster interface {
  20. HandleError(conn *Conn, err error, closed bool)
  21. HandleKeyspace(conn *Conn, keyspace string)
  22. }
  23. type Authenticator interface {
  24. Challenge(req []byte) (resp []byte, auth Authenticator, err error)
  25. Success(data []byte) error
  26. }
  27. type PasswordAuthenticator struct {
  28. Username string
  29. Password string
  30. }
  31. func (p PasswordAuthenticator) Challenge(req []byte) ([]byte, Authenticator, error) {
  32. if string(req) != "org.apache.cassandra.auth.PasswordAuthenticator" {
  33. return nil, nil, fmt.Errorf("unexpected authenticator %q", req)
  34. }
  35. resp := make([]byte, 2+len(p.Username)+len(p.Password))
  36. resp[0] = 0
  37. copy(resp[1:], p.Username)
  38. resp[len(p.Username)+1] = 0
  39. copy(resp[2+len(p.Username):], p.Password)
  40. return resp, nil, nil
  41. }
  42. func (p PasswordAuthenticator) Success(data []byte) error {
  43. return nil
  44. }
  45. type ConnConfig struct {
  46. ProtoVersion int
  47. CQLVersion string
  48. Timeout time.Duration
  49. NumStreams int
  50. Compressor Compressor
  51. Authenticator Authenticator
  52. Keepalive time.Duration
  53. }
  54. // Conn is a single connection to a Cassandra node. It can be used to execute
  55. // queries, but users are usually advised to use a more reliable, higher
  56. // level API.
  57. type Conn struct {
  58. conn net.Conn
  59. r *bufio.Reader
  60. timeout time.Duration
  61. uniq chan uint8
  62. calls []callReq
  63. nwait int32
  64. prepMu sync.Mutex
  65. prep map[string]*inflightPrepare
  66. cluster Cluster
  67. compressor Compressor
  68. auth Authenticator
  69. addr string
  70. version uint8
  71. }
  72. // Connect establishes a connection to a Cassandra node.
  73. // You must also call the Serve method before you can execute any queries.
  74. func Connect(addr string, cfg ConnConfig, cluster Cluster) (*Conn, error) {
  75. conn, err := net.DialTimeout("tcp", addr, cfg.Timeout)
  76. if err != nil {
  77. return nil, err
  78. }
  79. if cfg.NumStreams <= 0 || cfg.NumStreams > 128 {
  80. cfg.NumStreams = 128
  81. }
  82. if cfg.ProtoVersion != 1 && cfg.ProtoVersion != 2 {
  83. cfg.ProtoVersion = 2
  84. }
  85. c := &Conn{
  86. conn: conn,
  87. r: bufio.NewReader(conn),
  88. uniq: make(chan uint8, cfg.NumStreams),
  89. calls: make([]callReq, cfg.NumStreams),
  90. prep: make(map[string]*inflightPrepare),
  91. timeout: cfg.Timeout,
  92. version: uint8(cfg.ProtoVersion),
  93. addr: conn.RemoteAddr().String(),
  94. cluster: cluster,
  95. compressor: cfg.Compressor,
  96. auth: cfg.Authenticator,
  97. }
  98. if cfg.Keepalive > 0 {
  99. c.setKeepalive(cfg.Keepalive)
  100. }
  101. for i := 0; i < cap(c.uniq); i++ {
  102. c.uniq <- uint8(i)
  103. }
  104. if err := c.startup(&cfg); err != nil {
  105. return nil, err
  106. }
  107. go c.serve()
  108. return c, nil
  109. }
  110. func (c *Conn) startup(cfg *ConnConfig) error {
  111. compression := ""
  112. if c.compressor != nil {
  113. compression = c.compressor.Name()
  114. }
  115. var req operation = &startupFrame{
  116. CQLVersion: cfg.CQLVersion,
  117. Compression: compression,
  118. }
  119. var challenger Authenticator
  120. for {
  121. resp, err := c.execSimple(req)
  122. if err != nil {
  123. return err
  124. }
  125. switch x := resp.(type) {
  126. case readyFrame:
  127. return nil
  128. case error:
  129. return x
  130. case authenticateFrame:
  131. if c.auth == nil {
  132. return fmt.Errorf("authentication required (using %q)", x.Authenticator)
  133. }
  134. var resp []byte
  135. resp, challenger, err = c.auth.Challenge([]byte(x.Authenticator))
  136. if err != nil {
  137. return err
  138. }
  139. req = &authResponseFrame{resp}
  140. case authChallengeFrame:
  141. if challenger == nil {
  142. return fmt.Errorf("authentication error (invalid challenge)")
  143. }
  144. var resp []byte
  145. resp, challenger, err = challenger.Challenge(x.Data)
  146. if err != nil {
  147. return err
  148. }
  149. req = &authResponseFrame{resp}
  150. case authSuccessFrame:
  151. if challenger != nil {
  152. return challenger.Success(x.Data)
  153. }
  154. return nil
  155. default:
  156. return ErrProtocol
  157. }
  158. }
  159. }
  160. // Serve starts the stream multiplexer for this connection, which is required
  161. // to execute any queries. This method runs as long as the connection is
  162. // open and is therefore usually called in a separate goroutine.
  163. func (c *Conn) serve() {
  164. var (
  165. err error
  166. resp frame
  167. )
  168. for {
  169. resp, err = c.recv()
  170. if err != nil {
  171. break
  172. }
  173. c.dispatch(resp)
  174. }
  175. c.conn.Close()
  176. for id := 0; id < len(c.calls); id++ {
  177. req := &c.calls[id]
  178. if atomic.LoadInt32(&req.active) == 1 {
  179. req.resp <- callResp{nil, err}
  180. }
  181. }
  182. c.cluster.HandleError(c, err, true)
  183. }
  184. func (c *Conn) recv() (frame, error) {
  185. resp := make(frame, headerSize, headerSize+512)
  186. c.conn.SetReadDeadline(time.Now().Add(c.timeout))
  187. n, last, pinged := 0, 0, false
  188. for n < len(resp) {
  189. nn, err := c.r.Read(resp[n:])
  190. n += nn
  191. if err != nil {
  192. if nerr, ok := err.(net.Error); ok && nerr.Timeout() {
  193. if n > last {
  194. // we hit the deadline but we made progress.
  195. // simply extend the deadline
  196. c.conn.SetReadDeadline(time.Now().Add(c.timeout))
  197. last = n
  198. } else if n == 0 && !pinged {
  199. c.conn.SetReadDeadline(time.Now().Add(c.timeout))
  200. if atomic.LoadInt32(&c.nwait) > 0 {
  201. go c.ping()
  202. pinged = true
  203. }
  204. } else {
  205. return nil, err
  206. }
  207. } else {
  208. return nil, err
  209. }
  210. }
  211. if n == headerSize && len(resp) == headerSize {
  212. if resp[0] != c.version|flagResponse {
  213. return nil, ErrProtocol
  214. }
  215. resp.grow(resp.Length())
  216. }
  217. }
  218. return resp, nil
  219. }
  220. func (c *Conn) execSimple(op operation) (interface{}, error) {
  221. f, err := op.encodeFrame(c.version, nil)
  222. f.setLength(len(f) - headerSize)
  223. if _, err := c.conn.Write([]byte(f)); err != nil {
  224. c.conn.Close()
  225. return nil, err
  226. }
  227. if f, err = c.recv(); err != nil {
  228. return nil, err
  229. }
  230. return c.decodeFrame(f, nil)
  231. }
  232. func (c *Conn) exec(op operation, trace Tracer) (interface{}, error) {
  233. req, err := op.encodeFrame(c.version, nil)
  234. if err != nil {
  235. return nil, err
  236. }
  237. if trace != nil {
  238. req[1] |= flagTrace
  239. }
  240. if len(req) > headerSize && c.compressor != nil {
  241. body, err := c.compressor.Encode([]byte(req[headerSize:]))
  242. if err != nil {
  243. return nil, err
  244. }
  245. req = append(req[:headerSize], frame(body)...)
  246. req[1] |= flagCompress
  247. }
  248. req.setLength(len(req) - headerSize)
  249. id := <-c.uniq
  250. req[2] = id
  251. call := &c.calls[id]
  252. call.resp = make(chan callResp, 1)
  253. atomic.AddInt32(&c.nwait, 1)
  254. atomic.StoreInt32(&call.active, 1)
  255. if n, err := c.conn.Write(req); err != nil {
  256. c.conn.Close()
  257. c.uniq <- id
  258. if n > 0 {
  259. return nil, ErrProtocol
  260. }
  261. return nil, ErrUnavailable
  262. }
  263. reply := <-call.resp
  264. call.resp = nil
  265. c.uniq <- id
  266. if reply.err != nil {
  267. return nil, reply.err
  268. }
  269. return c.decodeFrame(reply.buf, trace)
  270. }
  271. func (c *Conn) dispatch(resp frame) {
  272. id := int(resp[2])
  273. if id >= len(c.calls) {
  274. return
  275. }
  276. call := &c.calls[id]
  277. if !atomic.CompareAndSwapInt32(&call.active, 1, 0) {
  278. return
  279. }
  280. atomic.AddInt32(&c.nwait, -1)
  281. call.resp <- callResp{resp, nil}
  282. }
  283. func (c *Conn) ping() error {
  284. _, err := c.exec(&optionsFrame{}, nil)
  285. return err
  286. }
  287. func (c *Conn) prepareStatement(stmt string, trace Tracer) (*queryInfo, error) {
  288. c.prepMu.Lock()
  289. flight := c.prep[stmt]
  290. if flight != nil {
  291. c.prepMu.Unlock()
  292. flight.wg.Wait()
  293. return flight.info, flight.err
  294. }
  295. flight = new(inflightPrepare)
  296. flight.wg.Add(1)
  297. c.prep[stmt] = flight
  298. c.prepMu.Unlock()
  299. resp, err := c.exec(&prepareFrame{Stmt: stmt}, trace)
  300. if err != nil {
  301. flight.err = err
  302. } else {
  303. switch x := resp.(type) {
  304. case resultPreparedFrame:
  305. flight.info = &queryInfo{
  306. id: x.PreparedId,
  307. args: x.Values,
  308. }
  309. case error:
  310. flight.err = x
  311. default:
  312. flight.err = ErrProtocol
  313. }
  314. }
  315. flight.wg.Done()
  316. if err != nil {
  317. c.prepMu.Lock()
  318. delete(c.prep, stmt)
  319. c.prepMu.Unlock()
  320. }
  321. return flight.info, flight.err
  322. }
  323. func shouldPrepare(stmt string) bool {
  324. var stmtType string
  325. if n := strings.IndexFunc(stmt, unicode.IsSpace); n >= 0 {
  326. stmtType = strings.ToLower(stmt[:n])
  327. }
  328. if stmtType == "begin" {
  329. if n := strings.LastIndexFunc(stmt, unicode.IsSpace); n >= 0 {
  330. stmtType = strings.ToLower(stmt[n+1:])
  331. }
  332. }
  333. switch stmtType {
  334. case "select", "insert", "update", "delete", "batch":
  335. return true
  336. }
  337. return false
  338. }
  339. func (c *Conn) executeQuery(qry *Query) *Iter {
  340. op := &queryFrame{
  341. Stmt: strings.TrimSpace(qry.stmt),
  342. Cons: qry.cons,
  343. PageSize: qry.pageSize,
  344. PageState: qry.pageState,
  345. }
  346. if shouldPrepare(op.Stmt) {
  347. // Prepare all DML queries. Other queries can not be prepared.
  348. info, err := c.prepareStatement(qry.stmt, qry.trace)
  349. if err != nil {
  350. return &Iter{err: err}
  351. }
  352. op.Prepared = info.id
  353. op.Values = make([][]byte, len(qry.values))
  354. for i := 0; i < len(qry.values); i++ {
  355. val, err := Marshal(info.args[i].TypeInfo, qry.values[i])
  356. if err != nil {
  357. return &Iter{err: err}
  358. }
  359. op.Values[i] = val
  360. }
  361. }
  362. resp, err := c.exec(op, qry.trace)
  363. if err != nil {
  364. return &Iter{err: err}
  365. }
  366. switch x := resp.(type) {
  367. case resultVoidFrame:
  368. return &Iter{}
  369. case resultRowsFrame:
  370. iter := &Iter{columns: x.Columns, rows: x.Rows}
  371. if len(x.PagingState) > 0 {
  372. iter.next = &nextIter{
  373. qry: *qry,
  374. pos: int((1 - qry.prefetch) * float64(len(iter.rows))),
  375. }
  376. iter.next.qry.pageState = x.PagingState
  377. if iter.next.pos < 1 {
  378. iter.next.pos = 1
  379. }
  380. }
  381. return iter
  382. case resultKeyspaceFrame:
  383. c.cluster.HandleKeyspace(c, x.Keyspace)
  384. return &Iter{}
  385. case errorFrame:
  386. if x.Code == errUnprepared && len(qry.values) > 0 {
  387. c.prepMu.Lock()
  388. if val, ok := c.prep[qry.stmt]; ok && val != nil {
  389. delete(c.prep, qry.stmt)
  390. c.prepMu.Unlock()
  391. return c.executeQuery(qry)
  392. }
  393. c.prepMu.Unlock()
  394. return &Iter{err: x}
  395. } else {
  396. return &Iter{err: x}
  397. }
  398. case error:
  399. return &Iter{err: x}
  400. default:
  401. return &Iter{err: ErrProtocol}
  402. }
  403. }
  404. func (c *Conn) Pick(qry *Query) *Conn {
  405. return c
  406. }
  407. func (c *Conn) Close() {
  408. c.conn.Close()
  409. }
  410. func (c *Conn) Address() string {
  411. return c.addr
  412. }
  413. func (c *Conn) UseKeyspace(keyspace string) error {
  414. resp, err := c.exec(&queryFrame{Stmt: `USE "` + keyspace + `"`, Cons: Any}, nil)
  415. if err != nil {
  416. return err
  417. }
  418. switch x := resp.(type) {
  419. case resultKeyspaceFrame:
  420. case error:
  421. return x
  422. default:
  423. return ErrProtocol
  424. }
  425. return nil
  426. }
  427. func (c *Conn) executeBatch(batch *Batch) error {
  428. if c.version == 1 {
  429. return ErrUnsupported
  430. }
  431. f := make(frame, headerSize, defaultFrameSize)
  432. f.setHeader(c.version, 0, 0, opBatch)
  433. f.writeByte(byte(batch.Type))
  434. f.writeShort(uint16(len(batch.Entries)))
  435. for i := 0; i < len(batch.Entries); i++ {
  436. entry := &batch.Entries[i]
  437. var info *queryInfo
  438. if len(entry.Args) > 0 {
  439. var err error
  440. info, err = c.prepareStatement(entry.Stmt, nil)
  441. if err != nil {
  442. return err
  443. }
  444. f.writeByte(1)
  445. f.writeShortBytes(info.id)
  446. } else {
  447. f.writeByte(0)
  448. f.writeLongString(entry.Stmt)
  449. }
  450. f.writeShort(uint16(len(entry.Args)))
  451. for j := 0; j < len(entry.Args); j++ {
  452. val, err := Marshal(info.args[j].TypeInfo, entry.Args[j])
  453. if err != nil {
  454. return err
  455. }
  456. f.writeBytes(val)
  457. }
  458. }
  459. f.writeConsistency(batch.Cons)
  460. resp, err := c.exec(f, nil)
  461. if err != nil {
  462. return err
  463. }
  464. switch x := resp.(type) {
  465. case resultVoidFrame:
  466. return nil
  467. case error:
  468. return x
  469. default:
  470. return ErrProtocol
  471. }
  472. }
  473. func (c *Conn) decodeFrame(f frame, trace Tracer) (rval interface{}, err error) {
  474. defer func() {
  475. if r := recover(); r != nil {
  476. if e, ok := r.(error); ok && e == ErrProtocol {
  477. err = e
  478. return
  479. }
  480. panic(r)
  481. }
  482. }()
  483. if len(f) < headerSize || (f[0] != c.version|flagResponse) {
  484. return nil, ErrProtocol
  485. }
  486. flags, op, f := f[1], f[3], f[headerSize:]
  487. if flags&flagCompress != 0 && len(f) > 0 && c.compressor != nil {
  488. if buf, err := c.compressor.Decode([]byte(f)); err != nil {
  489. return nil, err
  490. } else {
  491. f = frame(buf)
  492. }
  493. }
  494. if flags&flagTrace != 0 {
  495. if len(f) < 16 {
  496. return nil, ErrProtocol
  497. }
  498. traceId := []byte(f[:16])
  499. f = f[16:]
  500. trace.Trace(traceId)
  501. }
  502. switch op {
  503. case opReady:
  504. return readyFrame{}, nil
  505. case opResult:
  506. switch kind := f.readInt(); kind {
  507. case resultKindVoid:
  508. return resultVoidFrame{}, nil
  509. case resultKindRows:
  510. columns, pageState := f.readMetaData()
  511. numRows := f.readInt()
  512. values := make([][]byte, numRows*len(columns))
  513. for i := 0; i < len(values); i++ {
  514. values[i] = f.readBytes()
  515. }
  516. rows := make([][][]byte, numRows)
  517. for i := 0; i < numRows; i++ {
  518. rows[i], values = values[:len(columns)], values[len(columns):]
  519. }
  520. return resultRowsFrame{columns, rows, pageState}, nil
  521. case resultKindKeyspace:
  522. keyspace := f.readString()
  523. return resultKeyspaceFrame{keyspace}, nil
  524. case resultKindPrepared:
  525. id := f.readShortBytes()
  526. values, _ := f.readMetaData()
  527. return resultPreparedFrame{id, values}, nil
  528. case resultKindSchemaChanged:
  529. return resultVoidFrame{}, nil
  530. default:
  531. return nil, ErrProtocol
  532. }
  533. case opAuthenticate:
  534. return authenticateFrame{f.readString()}, nil
  535. case opAuthChallenge:
  536. return authChallengeFrame{f.readBytes()}, nil
  537. case opAuthSuccess:
  538. return authSuccessFrame{f.readBytes()}, nil
  539. case opSupported:
  540. return supportedFrame{}, nil
  541. case opError:
  542. code := f.readInt()
  543. msg := f.readString()
  544. return errorFrame{code, msg}, nil
  545. default:
  546. return nil, ErrProtocol
  547. }
  548. }
  549. type queryInfo struct {
  550. id []byte
  551. args []ColumnInfo
  552. rval []ColumnInfo
  553. }
  554. type callReq struct {
  555. active int32
  556. resp chan callResp
  557. }
  558. type callResp struct {
  559. buf frame
  560. err error
  561. }
  562. type Compressor interface {
  563. Name() string
  564. Encode(data []byte) ([]byte, error)
  565. Decode(data []byte) ([]byte, error)
  566. }
  567. type inflightPrepare struct {
  568. info *queryInfo
  569. err error
  570. wg sync.WaitGroup
  571. }
  572. // SnappyCompressor implements the Compressor interface and can be used to
  573. // compress incoming and outgoing frames. The snappy compression algorithm
  574. // aims for very high speeds and reasonable compression.
  575. type SnappyCompressor struct{}
  576. func (s SnappyCompressor) Name() string {
  577. return "snappy"
  578. }
  579. func (s SnappyCompressor) Encode(data []byte) ([]byte, error) {
  580. return snappy.Encode(nil, data)
  581. }
  582. func (s SnappyCompressor) Decode(data []byte) ([]byte, error) {
  583. return snappy.Decode(nil, data)
  584. }