conn.go 7.4 KB

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