conn.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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) prepareStatement(stmt string) (*queryInfo, error) {
  171. c.prepMu.Lock()
  172. info := c.prep[stmt]
  173. if info != nil {
  174. c.prepMu.Unlock()
  175. info.wg.Wait()
  176. return info, nil
  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, err
  189. }
  190. if frame[3] == opError {
  191. return nil, frame.readErrorFrame()
  192. }
  193. frame.skipHeader()
  194. frame.readInt() // kind
  195. info.id = frame.readShortBytes()
  196. info.args = frame.readMetaData()
  197. info.rval = frame.readMetaData()
  198. info.wg.Done()
  199. return info, nil
  200. }
  201. func (c *Conn) ExecuteQuery(qry *Query) (*Iter, error) {
  202. frame, err := c.executeQuery(qry)
  203. if err != nil {
  204. return nil, err
  205. }
  206. if frame[3] == opError {
  207. return nil, frame.readErrorFrame()
  208. } else if frame[3] == opResult {
  209. iter := new(Iter)
  210. iter.readFrame(frame)
  211. return iter, nil
  212. }
  213. return nil, nil
  214. }
  215. func (c *Conn) ExecuteBatch(batch *Batch) error {
  216. frame := make(frame, headerSize, defaultFrameSize)
  217. frame.setHeader(protoRequest, 0, 0, opBatch)
  218. frame.writeByte(byte(batch.Type))
  219. frame.writeShort(uint16(len(batch.Entries)))
  220. for i := 0; i < len(batch.Entries); i++ {
  221. entry := &batch.Entries[i]
  222. var info *queryInfo
  223. if len(entry.Args) > 0 {
  224. info, err := c.prepareStatement(entry.Stmt)
  225. if err != nil {
  226. return err
  227. }
  228. frame.writeByte(1)
  229. frame.writeShortBytes(info.id)
  230. } else {
  231. frame.writeByte(0)
  232. frame.writeLongString(entry.Stmt)
  233. }
  234. frame.writeShort(uint16(len(entry.Args)))
  235. for j := 0; j < len(entry.Args); j++ {
  236. val, err := Marshal(info.args[j].TypeInfo, entry.Args[i])
  237. if err != nil {
  238. return err
  239. }
  240. frame.writeBytes(val)
  241. }
  242. }
  243. frame.writeShort(uint16(batch.Cons))
  244. frame, err := c.call(frame)
  245. if err != nil {
  246. return err
  247. }
  248. if frame[3] == opError {
  249. return frame.readErrorFrame()
  250. }
  251. return nil
  252. }
  253. func (c *Conn) Close() {
  254. c.conn.Close()
  255. }
  256. func (c *Conn) executeQuery(query *Query) (frame, error) {
  257. var info *queryInfo
  258. if len(query.Args) > 0 {
  259. var err error
  260. info, err = c.prepareStatement(query.Stmt)
  261. if err != nil {
  262. return nil, err
  263. }
  264. }
  265. frame := make(frame, headerSize, headerSize+512)
  266. if info == nil {
  267. frame.setHeader(protoRequest, 0, 0, opQuery)
  268. frame.writeLongString(query.Stmt)
  269. } else {
  270. frame.setHeader(protoRequest, 0, 0, opExecute)
  271. frame.writeShortBytes(info.id)
  272. }
  273. frame.writeShort(uint16(query.Cons))
  274. flags := uint8(0)
  275. if len(query.Args) > 0 {
  276. flags |= flagQueryValues
  277. }
  278. frame.writeByte(flags)
  279. if len(query.Args) > 0 {
  280. frame.writeShort(uint16(len(query.Args)))
  281. for i := 0; i < len(query.Args); i++ {
  282. val, err := Marshal(info.args[i].TypeInfo, query.Args[i])
  283. if err != nil {
  284. return nil, err
  285. }
  286. frame.writeBytes(val)
  287. }
  288. }
  289. frame.setLength(len(frame) - headerSize)
  290. frame, err := c.call(frame)
  291. if err != nil {
  292. return nil, err
  293. }
  294. if frame[3] == opError {
  295. frame.skipHeader()
  296. code := frame.readInt()
  297. desc := frame.readString()
  298. return nil, Error{code, desc}
  299. }
  300. return frame, nil
  301. }
  302. type queryInfo struct {
  303. id []byte
  304. args []ColumnInfo
  305. rval []ColumnInfo
  306. wg sync.WaitGroup
  307. }
  308. type callReq struct {
  309. active int32
  310. resp chan callResp
  311. }
  312. type callResp struct {
  313. buf frame
  314. err error
  315. }