conn.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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. )
  11. const defaultFrameSize = 4096
  12. // Conn is a single connection to a Cassandra node. It can be used to execute
  13. // queries, but users are usually advised to use a more reliable, higher
  14. // level API.
  15. type Conn struct {
  16. conn net.Conn
  17. timeout time.Duration
  18. uniq chan uint8
  19. calls []callReq
  20. nwait int32
  21. prepMu sync.Mutex
  22. prep map[string]*queryInfo
  23. }
  24. // Connect establishes a connection to a Cassandra node.
  25. // You must also call the Serve method before you can execute any queries.
  26. func Connect(addr string, cfg *Config) (*Conn, error) {
  27. conn, err := net.DialTimeout("tcp", addr, cfg.Timeout)
  28. if err != nil {
  29. return nil, err
  30. }
  31. c := &Conn{
  32. conn: conn,
  33. uniq: make(chan uint8, 128),
  34. calls: make([]callReq, 128),
  35. prep: make(map[string]*queryInfo),
  36. timeout: cfg.Timeout,
  37. }
  38. for i := 0; i < cap(c.uniq); i++ {
  39. c.uniq <- uint8(i)
  40. }
  41. if err := c.init(cfg); err != nil {
  42. return nil, err
  43. }
  44. return c, nil
  45. }
  46. func (c *Conn) init(cfg *Config) error {
  47. req := make(frame, headerSize, defaultFrameSize)
  48. req.setHeader(protoRequest, 0, 0, opStartup)
  49. req.writeStringMap(map[string]string{
  50. "CQL_VERSION": cfg.CQLVersion,
  51. })
  52. resp, err := c.callSimple(req)
  53. if err != nil {
  54. return err
  55. } else if resp[3] == opError {
  56. return resp.readErrorFrame()
  57. } else if resp[3] != opReady {
  58. return ErrProtocol
  59. }
  60. /* if cfg.Keyspace != "" {
  61. qry := &Query{stmt: "USE " + cfg.Keyspace}
  62. frame, err = c.executeQuery(qry)
  63. if err != nil {
  64. return err
  65. }
  66. } */
  67. return nil
  68. }
  69. // Serve starts the stream multiplexer for this connection, which is required
  70. // to execute any queries. This method runs as long as the connection is
  71. // open and is therefore usually called in a separate goroutine.
  72. func (c *Conn) Serve() error {
  73. var err error
  74. for {
  75. var frame frame
  76. frame, err = c.recv()
  77. if err != nil {
  78. break
  79. }
  80. c.dispatch(frame)
  81. }
  82. c.conn.Close()
  83. for id := 0; id < len(c.calls); id++ {
  84. req := &c.calls[id]
  85. if atomic.LoadInt32(&req.active) == 1 {
  86. req.resp <- callResp{nil, err}
  87. }
  88. }
  89. return err
  90. }
  91. func (c *Conn) recv() (frame, error) {
  92. resp := make(frame, headerSize, headerSize+512)
  93. c.conn.SetReadDeadline(time.Now().Add(c.timeout))
  94. n, last, pinged := 0, 0, false
  95. for n < len(resp) {
  96. nn, err := c.conn.Read(resp[n:])
  97. n += nn
  98. if err != nil {
  99. if err, ok := err.(net.Error); ok && err.Timeout() {
  100. if n > last {
  101. // we hit the deadline but we made progress.
  102. // simply extend the deadline
  103. c.conn.SetReadDeadline(time.Now().Add(c.timeout))
  104. last = n
  105. } else if n == 0 && !pinged {
  106. c.conn.SetReadDeadline(time.Now().Add(c.timeout))
  107. if atomic.LoadInt32(&c.nwait) > 0 {
  108. go c.ping()
  109. pinged = true
  110. }
  111. } else {
  112. return nil, err
  113. }
  114. } else {
  115. return nil, err
  116. }
  117. }
  118. if n == headerSize && len(resp) == headerSize {
  119. if resp[0] != protoResponse {
  120. return nil, ErrProtocol
  121. }
  122. resp.grow(resp.Length())
  123. }
  124. }
  125. return resp, nil
  126. }
  127. func (c *Conn) callSimple(req frame) (frame, error) {
  128. req.setLength(len(req) - headerSize)
  129. if _, err := c.conn.Write(req); err != nil {
  130. c.conn.Close()
  131. return nil, err
  132. }
  133. return c.recv()
  134. }
  135. func (c *Conn) call(req frame) (frame, error) {
  136. id := <-c.uniq
  137. req[2] = id
  138. call := &c.calls[id]
  139. call.resp = make(chan callResp, 1)
  140. atomic.AddInt32(&c.nwait, 1)
  141. atomic.StoreInt32(&call.active, 1)
  142. req.setLength(len(req) - headerSize)
  143. if _, err := c.conn.Write(req); err != nil {
  144. c.conn.Close()
  145. return nil, err
  146. }
  147. reply := <-call.resp
  148. call.resp = nil
  149. c.uniq <- id
  150. return reply.buf, reply.err
  151. }
  152. func (c *Conn) dispatch(resp frame) {
  153. id := int(resp[2])
  154. if id >= len(c.calls) {
  155. return
  156. }
  157. call := &c.calls[id]
  158. if !atomic.CompareAndSwapInt32(&call.active, 1, 0) {
  159. return
  160. }
  161. atomic.AddInt32(&c.nwait, -1)
  162. call.resp <- callResp{resp, nil}
  163. }
  164. func (c *Conn) ping() error {
  165. req := make(frame, headerSize)
  166. req.setHeader(protoRequest, 0, 0, opOptions)
  167. _, err := c.call(req)
  168. return err
  169. }
  170. func (c *Conn) prepareQuery(stmt string) *queryInfo {
  171. c.prepMu.Lock()
  172. info := c.prep[stmt]
  173. if info != nil {
  174. c.prepMu.Unlock()
  175. info.wg.Wait()
  176. return info
  177. }
  178. info = new(queryInfo)
  179. info.wg.Add(1)
  180. c.prep[stmt] = info
  181. c.prepMu.Unlock()
  182. frame := make(frame, headerSize, headerSize+512)
  183. frame.setHeader(protoRequest, 0, 0, opPrepare)
  184. frame.writeLongString(stmt)
  185. frame.setLength(len(frame) - headerSize)
  186. frame, err := c.call(frame)
  187. if err != nil {
  188. return nil
  189. }
  190. frame.skipHeader()
  191. frame.readInt() // kind
  192. info.id = frame.readShortBytes()
  193. info.args = frame.readMetaData()
  194. info.rval = frame.readMetaData()
  195. info.wg.Done()
  196. return info
  197. }
  198. func (c *Conn) ExecuteQuery(qry *Query) (*Iter, error) {
  199. frame, err := c.executeQuery(qry)
  200. if err != nil {
  201. return nil, err
  202. }
  203. if frame[3] == opError {
  204. return nil, frame.readErrorFrame()
  205. } else if frame[3] == opResult {
  206. iter := new(Iter)
  207. iter.readFrame(frame)
  208. return iter, nil
  209. }
  210. return nil, nil
  211. }
  212. func (c *Conn) ExecuteBatch(batch *Batch) error {
  213. return nil
  214. }
  215. func (c *Conn) Close() {
  216. c.conn.Close()
  217. }
  218. func (c *Conn) executeQuery(query *Query) (frame, error) {
  219. var info *queryInfo
  220. if len(query.Args) > 0 {
  221. info = c.prepareQuery(query.Stmt)
  222. }
  223. frame := make(frame, headerSize, headerSize+512)
  224. if info == nil {
  225. frame.setHeader(protoRequest, 0, 0, opQuery)
  226. frame.writeLongString(query.Stmt)
  227. } else {
  228. frame.setHeader(protoRequest, 0, 0, opExecute)
  229. frame.writeShortBytes(info.id)
  230. }
  231. frame.writeShort(uint16(query.Cons))
  232. flags := uint8(0)
  233. if len(query.Args) > 0 {
  234. flags |= flagQueryValues
  235. }
  236. frame.writeByte(flags)
  237. if len(query.Args) > 0 {
  238. frame.writeShort(uint16(len(query.Args)))
  239. for i := 0; i < len(query.Args); i++ {
  240. val, err := Marshal(info.args[i].TypeInfo, query.Args[i])
  241. if err != nil {
  242. return nil, err
  243. }
  244. frame.writeBytes(val)
  245. }
  246. }
  247. frame.setLength(len(frame) - headerSize)
  248. frame, err := c.call(frame)
  249. if err != nil {
  250. return nil, err
  251. }
  252. if frame[3] == opError {
  253. frame.skipHeader()
  254. code := frame.readInt()
  255. desc := frame.readString()
  256. return nil, Error{code, desc}
  257. }
  258. return frame, nil
  259. }
  260. type queryInfo struct {
  261. id []byte
  262. args []ColumnInfo
  263. rval []ColumnInfo
  264. wg sync.WaitGroup
  265. }
  266. type callReq struct {
  267. active int32
  268. resp chan callResp
  269. }
  270. type callResp struct {
  271. buf frame
  272. err error
  273. }