conn.go 8.8 KB

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