conn.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  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. "net"
  7. "sync"
  8. "sync/atomic"
  9. "time"
  10. "code.google.com/p/snappy-go/snappy"
  11. )
  12. const defaultFrameSize = 4096
  13. const flagResponse = 0x80
  14. const maskVersion = 0x7F
  15. type Cluster interface {
  16. //HandleAuth(addr, method string) ([]byte, Challenger, error)
  17. HandleError(conn *Conn, err error, closed bool)
  18. HandleKeyspace(conn *Conn, keyspace string)
  19. // Authenticate(addr string)
  20. }
  21. /* type Challenger interface {
  22. Challenge(data []byte) ([]byte, error)
  23. } */
  24. type ConnConfig struct {
  25. ProtoVersion int
  26. CQLVersion string
  27. Timeout time.Duration
  28. NumStreams int
  29. Compressor Compressor
  30. }
  31. // Conn is a single connection to a Cassandra node. It can be used to execute
  32. // queries, but users are usually advised to use a more reliable, higher
  33. // level API.
  34. type Conn struct {
  35. conn net.Conn
  36. timeout time.Duration
  37. uniq chan uint8
  38. calls []callReq
  39. nwait int32
  40. prepMu sync.Mutex
  41. prep map[string]*queryInfo
  42. cluster Cluster
  43. compressor Compressor
  44. addr string
  45. version uint8
  46. }
  47. // Connect establishes a connection to a Cassandra node.
  48. // You must also call the Serve method before you can execute any queries.
  49. func Connect(addr string, cfg ConnConfig, cluster Cluster) (*Conn, error) {
  50. conn, err := net.DialTimeout("tcp", addr, cfg.Timeout)
  51. if err != nil {
  52. return nil, err
  53. }
  54. if cfg.NumStreams <= 0 || cfg.NumStreams > 128 {
  55. cfg.NumStreams = 128
  56. }
  57. if cfg.ProtoVersion != 1 && cfg.ProtoVersion != 2 {
  58. cfg.ProtoVersion = 2
  59. }
  60. c := &Conn{
  61. conn: conn,
  62. uniq: make(chan uint8, cfg.NumStreams),
  63. calls: make([]callReq, cfg.NumStreams),
  64. prep: make(map[string]*queryInfo),
  65. timeout: cfg.Timeout,
  66. version: uint8(cfg.ProtoVersion),
  67. addr: conn.RemoteAddr().String(),
  68. cluster: cluster,
  69. compressor: cfg.Compressor,
  70. }
  71. for i := 0; i < cap(c.uniq); i++ {
  72. c.uniq <- uint8(i)
  73. }
  74. if err := c.startup(&cfg); err != nil {
  75. return nil, err
  76. }
  77. go c.serve()
  78. return c, nil
  79. }
  80. func (c *Conn) startup(cfg *ConnConfig) error {
  81. req := &startupFrame{
  82. CQLVersion: cfg.CQLVersion,
  83. }
  84. if c.compressor != nil {
  85. req.Compression = c.compressor.Name()
  86. }
  87. resp, err := c.execSimple(req)
  88. if err != nil {
  89. return err
  90. }
  91. switch x := resp.(type) {
  92. case readyFrame:
  93. case error:
  94. return x
  95. default:
  96. return ErrProtocol
  97. }
  98. return nil
  99. }
  100. // Serve starts the stream multiplexer for this connection, which is required
  101. // to execute any queries. This method runs as long as the connection is
  102. // open and is therefore usually called in a separate goroutine.
  103. func (c *Conn) serve() {
  104. for {
  105. resp, err := c.recv()
  106. if err != nil {
  107. break
  108. }
  109. c.dispatch(resp)
  110. }
  111. c.conn.Close()
  112. for id := 0; id < len(c.calls); id++ {
  113. req := &c.calls[id]
  114. if atomic.LoadInt32(&req.active) == 1 {
  115. req.resp <- callResp{nil, ErrProtocol}
  116. }
  117. }
  118. c.cluster.HandleError(c, ErrProtocol, true)
  119. }
  120. func (c *Conn) recv() (frame, error) {
  121. resp := make(frame, headerSize, headerSize+512)
  122. c.conn.SetReadDeadline(time.Now().Add(c.timeout))
  123. n, last, pinged := 0, 0, false
  124. for n < len(resp) {
  125. nn, err := c.conn.Read(resp[n:])
  126. n += nn
  127. if err != nil {
  128. if nerr, ok := err.(net.Error); ok && nerr.Timeout() {
  129. if n > last {
  130. // we hit the deadline but we made progress.
  131. // simply extend the deadline
  132. c.conn.SetReadDeadline(time.Now().Add(c.timeout))
  133. last = n
  134. } else if n == 0 && !pinged {
  135. c.conn.SetReadDeadline(time.Now().Add(c.timeout))
  136. if atomic.LoadInt32(&c.nwait) > 0 {
  137. go c.ping()
  138. pinged = true
  139. }
  140. } else {
  141. return nil, err
  142. }
  143. } else {
  144. return nil, err
  145. }
  146. }
  147. if n == headerSize && len(resp) == headerSize {
  148. if resp[0] != c.version|flagResponse {
  149. return nil, ErrProtocol
  150. }
  151. resp.grow(resp.Length())
  152. }
  153. }
  154. return resp, nil
  155. }
  156. func (c *Conn) execSimple(op operation) (interface{}, error) {
  157. f, err := op.encodeFrame(c.version, nil)
  158. f.setLength(len(f) - headerSize)
  159. if _, err := c.conn.Write([]byte(f)); err != nil {
  160. c.conn.Close()
  161. return nil, err
  162. }
  163. if f, err = c.recv(); err != nil {
  164. return nil, err
  165. }
  166. return c.decodeFrame(f, nil)
  167. }
  168. func (c *Conn) exec(op operation, trace Tracer) (interface{}, error) {
  169. req, err := op.encodeFrame(c.version, nil)
  170. if err != nil {
  171. return nil, err
  172. }
  173. if trace != nil {
  174. req[1] |= flagTrace
  175. }
  176. if len(req) > headerSize && c.compressor != nil {
  177. body, err := c.compressor.Encode([]byte(req[headerSize:]))
  178. if err != nil {
  179. return nil, err
  180. }
  181. req = append(req[:headerSize], frame(body)...)
  182. req[1] |= flagCompress
  183. }
  184. req.setLength(len(req) - headerSize)
  185. id := <-c.uniq
  186. req[2] = id
  187. call := &c.calls[id]
  188. call.resp = make(chan callResp, 1)
  189. atomic.AddInt32(&c.nwait, 1)
  190. atomic.StoreInt32(&call.active, 1)
  191. if n, err := c.conn.Write(req); err != nil {
  192. c.conn.Close()
  193. if n > 0 {
  194. return nil, ErrProtocol
  195. }
  196. return nil, ErrUnavailable
  197. }
  198. reply := <-call.resp
  199. call.resp = nil
  200. c.uniq <- id
  201. if reply.err != nil {
  202. return nil, reply.err
  203. }
  204. return c.decodeFrame(reply.buf, trace)
  205. }
  206. func (c *Conn) dispatch(resp frame) {
  207. id := int(resp[2])
  208. if id >= len(c.calls) {
  209. return
  210. }
  211. call := &c.calls[id]
  212. if !atomic.CompareAndSwapInt32(&call.active, 1, 0) {
  213. return
  214. }
  215. atomic.AddInt32(&c.nwait, -1)
  216. call.resp <- callResp{resp, nil}
  217. }
  218. func (c *Conn) ping() error {
  219. _, err := c.exec(&optionsFrame{}, nil)
  220. return err
  221. }
  222. func (c *Conn) prepareStatement(stmt string, trace Tracer) (*queryInfo, error) {
  223. c.prepMu.Lock()
  224. info := c.prep[stmt]
  225. if info != nil {
  226. c.prepMu.Unlock()
  227. info.wg.Wait()
  228. return info, nil
  229. }
  230. info = new(queryInfo)
  231. info.wg.Add(1)
  232. c.prep[stmt] = info
  233. c.prepMu.Unlock()
  234. resp, err := c.exec(&prepareFrame{Stmt: stmt}, trace)
  235. if err != nil {
  236. return nil, err
  237. }
  238. switch x := resp.(type) {
  239. case resultPreparedFrame:
  240. info.id = x.PreparedId
  241. info.args = x.Values
  242. info.wg.Done()
  243. case error:
  244. return nil, x
  245. default:
  246. return nil, ErrProtocol
  247. }
  248. return info, nil
  249. }
  250. func (c *Conn) executeQuery(qry *Query) *Iter {
  251. op := &queryFrame{
  252. Stmt: qry.stmt,
  253. Cons: qry.cons,
  254. PageSize: qry.pageSize,
  255. PageState: qry.pageState,
  256. }
  257. if len(qry.values) > 0 {
  258. info, err := c.prepareStatement(qry.stmt, qry.trace)
  259. if err != nil {
  260. return &Iter{err: err}
  261. }
  262. op.Prepared = info.id
  263. op.Values = make([][]byte, len(qry.values))
  264. for i := 0; i < len(qry.values); i++ {
  265. val, err := Marshal(info.args[i].TypeInfo, qry.values[i])
  266. if err != nil {
  267. return &Iter{err: err}
  268. }
  269. op.Values[i] = val
  270. }
  271. }
  272. resp, err := c.exec(op, qry.trace)
  273. if err != nil {
  274. return &Iter{qry: qry, err: err}
  275. }
  276. switch x := resp.(type) {
  277. case resultVoidFrame:
  278. return &Iter{qry: qry}
  279. case resultRowsFrame:
  280. return &Iter{qry: qry, columns: x.Columns, rows: x.Rows, pageState: x.PagingState}
  281. case resultKeyspaceFrame:
  282. c.cluster.HandleKeyspace(c, x.Keyspace)
  283. return &Iter{qry: qry}
  284. case error:
  285. return &Iter{qry: qry, err: x}
  286. default:
  287. return &Iter{qry: qry, err: ErrProtocol}
  288. }
  289. }
  290. func (c *Conn) Pick(qry *Query) *Conn {
  291. return c
  292. }
  293. func (c *Conn) Close() {
  294. c.conn.Close()
  295. }
  296. func (c *Conn) Address() string {
  297. return c.addr
  298. }
  299. func (c *Conn) UseKeyspace(keyspace string) error {
  300. resp, err := c.exec(&queryFrame{Stmt: "USE " + keyspace, Cons: Any}, nil)
  301. if err != nil {
  302. return err
  303. }
  304. switch x := resp.(type) {
  305. case resultKeyspaceFrame:
  306. case error:
  307. return x
  308. default:
  309. return ErrProtocol
  310. }
  311. return nil
  312. }
  313. func (c *Conn) executeBatch(batch *Batch) error {
  314. if c.version == 1 {
  315. return ErrUnsupported
  316. }
  317. f := make(frame, headerSize, defaultFrameSize)
  318. f.setHeader(c.version, 0, 0, opBatch)
  319. f.writeByte(byte(batch.Type))
  320. f.writeShort(uint16(len(batch.Entries)))
  321. for i := 0; i < len(batch.Entries); i++ {
  322. entry := &batch.Entries[i]
  323. var info *queryInfo
  324. if len(entry.Args) > 0 {
  325. var err error
  326. info, err = c.prepareStatement(entry.Stmt, nil)
  327. if err != nil {
  328. return err
  329. }
  330. f.writeByte(1)
  331. f.writeShortBytes(info.id)
  332. } else {
  333. f.writeByte(0)
  334. f.writeLongString(entry.Stmt)
  335. }
  336. f.writeShort(uint16(len(entry.Args)))
  337. for j := 0; j < len(entry.Args); j++ {
  338. val, err := Marshal(info.args[j].TypeInfo, entry.Args[j])
  339. if err != nil {
  340. return err
  341. }
  342. f.writeBytes(val)
  343. }
  344. }
  345. f.writeConsistency(batch.Cons)
  346. resp, err := c.exec(f, nil)
  347. if err != nil {
  348. return err
  349. }
  350. switch x := resp.(type) {
  351. case resultVoidFrame:
  352. return nil
  353. case error:
  354. return x
  355. default:
  356. return ErrProtocol
  357. }
  358. }
  359. func (c *Conn) decodeFrame(f frame, trace Tracer) (rval interface{}, err error) {
  360. defer func() {
  361. if r := recover(); r != nil {
  362. if e, ok := r.(error); ok && e == ErrProtocol {
  363. err = e
  364. return
  365. }
  366. panic(r)
  367. }
  368. }()
  369. if len(f) < headerSize || (f[0] != c.version|flagResponse) {
  370. return nil, ErrProtocol
  371. }
  372. flags, op, f := f[1], f[3], f[headerSize:]
  373. if flags&flagCompress != 0 && len(f) > 0 && c.compressor != nil {
  374. if buf, err := c.compressor.Decode([]byte(f)); err != nil {
  375. return nil, err
  376. } else {
  377. f = frame(buf)
  378. }
  379. }
  380. if flags&flagTrace != 0 {
  381. if len(f) < 16 {
  382. return nil, ErrProtocol
  383. }
  384. traceId := []byte(f[:16])
  385. f = f[16:]
  386. trace.Trace(traceId)
  387. }
  388. switch op {
  389. case opReady:
  390. return readyFrame{}, nil
  391. case opResult:
  392. switch kind := f.readInt(); kind {
  393. case resultKindVoid:
  394. return resultVoidFrame{}, nil
  395. case resultKindRows:
  396. columns, pageState := f.readMetaData()
  397. numRows := f.readInt()
  398. values := make([][]byte, numRows*len(columns))
  399. for i := 0; i < len(values); i++ {
  400. values[i] = f.readBytes()
  401. }
  402. rows := make([][][]byte, numRows)
  403. for i := 0; i < numRows; i++ {
  404. rows[i], values = values[:len(columns)], values[len(columns):]
  405. }
  406. return resultRowsFrame{columns, rows, pageState}, nil
  407. case resultKindKeyspace:
  408. keyspace := f.readString()
  409. return resultKeyspaceFrame{keyspace}, nil
  410. case resultKindPrepared:
  411. id := f.readShortBytes()
  412. values, _ := f.readMetaData()
  413. return resultPreparedFrame{id, values}, nil
  414. case resultKindSchemaChanged:
  415. return resultVoidFrame{}, nil
  416. default:
  417. return nil, ErrProtocol
  418. }
  419. case opError:
  420. code := f.readInt()
  421. msg := f.readString()
  422. return errorFrame{code, msg}, nil
  423. default:
  424. return nil, ErrProtocol
  425. }
  426. }
  427. type queryInfo struct {
  428. id []byte
  429. args []ColumnInfo
  430. rval []ColumnInfo
  431. wg sync.WaitGroup
  432. }
  433. type callReq struct {
  434. active int32
  435. resp chan callResp
  436. }
  437. type callResp struct {
  438. buf frame
  439. err error
  440. }
  441. type Compressor interface {
  442. Name() string
  443. Encode(data []byte) ([]byte, error)
  444. Decode(data []byte) ([]byte, error)
  445. }
  446. type SnappyCompressor struct{}
  447. func (s SnappyCompressor) Name() string {
  448. return "snappy"
  449. }
  450. func (s SnappyCompressor) Encode(data []byte) ([]byte, error) {
  451. return snappy.Encode(nil, data)
  452. }
  453. func (s SnappyCompressor) Decode(data []byte) ([]byte, error) {
  454. return snappy.Decode(nil, data)
  455. }