conn.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  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)
  167. }
  168. func (c *Conn) exec(op operation) (interface{}, error) {
  169. //fmt.Printf("exec: %#v\n", op)
  170. req, err := op.encodeFrame(c.version, nil)
  171. if err != nil {
  172. return nil, err
  173. }
  174. if len(req) > headerSize && c.compressor != nil {
  175. body, err := c.compressor.Encode([]byte(req[headerSize:]))
  176. if err != nil {
  177. return nil, err
  178. }
  179. req = append(req[:headerSize], frame(body)...)
  180. req[1] |= flagCompress
  181. }
  182. req.setLength(len(req) - headerSize)
  183. id := <-c.uniq
  184. req[2] = id
  185. call := &c.calls[id]
  186. call.resp = make(chan callResp, 1)
  187. atomic.AddInt32(&c.nwait, 1)
  188. atomic.StoreInt32(&call.active, 1)
  189. if n, err := c.conn.Write(req); err != nil {
  190. c.conn.Close()
  191. if n > 0 {
  192. return nil, ErrProtocol
  193. }
  194. return nil, ErrUnavailable
  195. }
  196. reply := <-call.resp
  197. call.resp = nil
  198. c.uniq <- id
  199. if reply.err != nil {
  200. return nil, reply.err
  201. }
  202. return c.decodeFrame(reply.buf)
  203. }
  204. func (c *Conn) dispatch(resp frame) {
  205. id := int(resp[2])
  206. if id >= len(c.calls) {
  207. return
  208. }
  209. call := &c.calls[id]
  210. if !atomic.CompareAndSwapInt32(&call.active, 1, 0) {
  211. return
  212. }
  213. atomic.AddInt32(&c.nwait, -1)
  214. call.resp <- callResp{resp, nil}
  215. }
  216. func (c *Conn) ping() error {
  217. _, err := c.exec(&optionsFrame{})
  218. return err
  219. }
  220. func (c *Conn) prepareStatement(stmt string) (*queryInfo, error) {
  221. c.prepMu.Lock()
  222. info := c.prep[stmt]
  223. if info != nil {
  224. c.prepMu.Unlock()
  225. info.wg.Wait()
  226. return info, nil
  227. }
  228. info = new(queryInfo)
  229. info.wg.Add(1)
  230. c.prep[stmt] = info
  231. c.prepMu.Unlock()
  232. resp, err := c.exec(&prepareFrame{Stmt: stmt})
  233. if err != nil {
  234. return nil, err
  235. }
  236. switch x := resp.(type) {
  237. case resultPreparedFrame:
  238. info.id = x.PreparedId
  239. info.args = x.Values
  240. info.wg.Done()
  241. case error:
  242. return nil, x
  243. default:
  244. return nil, ErrProtocol
  245. }
  246. return info, nil
  247. }
  248. func (c *Conn) Pick(qry *Query) *Conn {
  249. return c
  250. }
  251. func (c *Conn) Close() {
  252. c.conn.Close()
  253. }
  254. func (c *Conn) Address() string {
  255. return c.addr
  256. }
  257. func (c *Conn) UseKeyspace(keyspace string) error {
  258. resp, err := c.exec(&queryFrame{Stmt: "USE " + keyspace, Cons: Any})
  259. if err != nil {
  260. return err
  261. }
  262. switch x := resp.(type) {
  263. case resultKeyspaceFrame:
  264. case error:
  265. return x
  266. default:
  267. return ErrProtocol
  268. }
  269. return nil
  270. }
  271. func (c *Conn) executeBatch(batch *Batch) error {
  272. if c.version == 1 {
  273. return ErrUnsupported
  274. }
  275. f := make(frame, headerSize, defaultFrameSize)
  276. f.setHeader(c.version, 0, 0, opBatch)
  277. f.writeByte(byte(batch.Type))
  278. f.writeShort(uint16(len(batch.Entries)))
  279. for i := 0; i < len(batch.Entries); i++ {
  280. entry := &batch.Entries[i]
  281. var info *queryInfo
  282. if len(entry.Args) > 0 {
  283. var err error
  284. info, err = c.prepareStatement(entry.Stmt)
  285. if err != nil {
  286. return err
  287. }
  288. f.writeByte(1)
  289. f.writeShortBytes(info.id)
  290. } else {
  291. f.writeByte(0)
  292. f.writeLongString(entry.Stmt)
  293. }
  294. f.writeShort(uint16(len(entry.Args)))
  295. for j := 0; j < len(entry.Args); j++ {
  296. val, err := Marshal(info.args[j].TypeInfo, entry.Args[j])
  297. if err != nil {
  298. return err
  299. }
  300. f.writeBytes(val)
  301. }
  302. }
  303. f.writeConsistency(batch.Cons)
  304. resp, err := c.exec(f)
  305. if err != nil {
  306. return err
  307. }
  308. switch x := resp.(type) {
  309. case resultVoidFrame:
  310. return nil
  311. case error:
  312. return x
  313. default:
  314. return ErrProtocol
  315. }
  316. }
  317. func (c *Conn) decodeFrame(f frame) (rval interface{}, err error) {
  318. defer func() {
  319. if r := recover(); r != nil {
  320. if e, ok := r.(error); ok && e == ErrProtocol {
  321. err = e
  322. return
  323. }
  324. panic(r)
  325. }
  326. }()
  327. if len(f) < headerSize || (f[0] != c.version|flagResponse) {
  328. return nil, ErrProtocol
  329. }
  330. flags, op, f := f[1], f[3], f[headerSize:]
  331. if flags&flagCompress != 0 && len(f) > 0 && c.compressor != nil {
  332. if buf, err := c.compressor.Decode([]byte(f)); err != nil {
  333. return nil, err
  334. } else {
  335. f = frame(buf)
  336. }
  337. }
  338. switch op {
  339. case opReady:
  340. return readyFrame{}, nil
  341. case opResult:
  342. switch kind := f.readInt(); kind {
  343. case resultKindVoid:
  344. return resultVoidFrame{}, nil
  345. case resultKindRows:
  346. columns, pageState := f.readMetaData()
  347. numRows := f.readInt()
  348. values := make([][]byte, numRows*len(columns))
  349. for i := 0; i < len(values); i++ {
  350. values[i] = f.readBytes()
  351. }
  352. rows := make([][][]byte, numRows)
  353. for i := 0; i < len(values); i += len(columns) {
  354. rows[i] = values[i : i+len(columns)]
  355. }
  356. return resultRowsFrame{columns, rows, pageState}, nil
  357. case resultKindKeyspace:
  358. keyspace := f.readString()
  359. return resultKeyspaceFrame{keyspace}, nil
  360. case resultKindPrepared:
  361. id := f.readShortBytes()
  362. values, _ := f.readMetaData()
  363. return resultPreparedFrame{id, values}, nil
  364. case resultKindSchemaChanged:
  365. return resultVoidFrame{}, nil
  366. default:
  367. return nil, ErrProtocol
  368. }
  369. case opError:
  370. code := f.readInt()
  371. msg := f.readString()
  372. return errorFrame{code, msg}, nil
  373. default:
  374. return nil, ErrProtocol
  375. }
  376. }
  377. type queryInfo struct {
  378. id []byte
  379. args []ColumnInfo
  380. rval []ColumnInfo
  381. wg sync.WaitGroup
  382. }
  383. type callReq struct {
  384. active int32
  385. resp chan callResp
  386. }
  387. type callResp struct {
  388. buf frame
  389. err error
  390. }
  391. type Compressor interface {
  392. Name() string
  393. Encode(data []byte) ([]byte, error)
  394. Decode(data []byte) ([]byte, error)
  395. }
  396. type SnappyCompressor struct{}
  397. func (s SnappyCompressor) Name() string {
  398. return "snappy"
  399. }
  400. func (s SnappyCompressor) Encode(data []byte) ([]byte, error) {
  401. return snappy.Encode(nil, data)
  402. }
  403. func (s SnappyCompressor) Decode(data []byte) ([]byte, error) {
  404. return snappy.Decode(nil, data)
  405. }