control.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. package gocql
  2. import (
  3. "errors"
  4. "fmt"
  5. "log"
  6. "math/rand"
  7. "net"
  8. "sync"
  9. "sync/atomic"
  10. "time"
  11. )
  12. // Ensure that the atomic variable is aligned to a 64bit boundary
  13. // so that atomic operations can be applied on 32bit architectures.
  14. type controlConn struct {
  15. connecting uint64
  16. session *Session
  17. conn atomic.Value
  18. session *Session
  19. conn atomic.Value
  20. retry RetryPolicy
  21. closeWg sync.WaitGroup
  22. quit chan struct{}
  23. }
  24. func createControlConn(session *Session) *controlConn {
  25. control := &controlConn{
  26. session: session,
  27. quit: make(chan struct{}),
  28. retry: &SimpleRetryPolicy{NumRetries: 3},
  29. }
  30. control.conn.Store((*Conn)(nil))
  31. return control
  32. }
  33. func (c *controlConn) heartBeat() {
  34. defer c.closeWg.Done()
  35. for {
  36. select {
  37. case <-c.quit:
  38. return
  39. case <-time.After(5 * time.Second):
  40. }
  41. resp, err := c.writeFrame(&writeOptionsFrame{})
  42. if err != nil {
  43. goto reconn
  44. }
  45. switch resp.(type) {
  46. case *supportedFrame:
  47. continue
  48. case error:
  49. goto reconn
  50. default:
  51. panic(fmt.Sprintf("gocql: unknown frame in response to options: %T", resp))
  52. }
  53. reconn:
  54. c.reconnect(true)
  55. // time.Sleep(5 * time.Second)
  56. continue
  57. }
  58. }
  59. func (c *controlConn) connect(endpoints []string) error {
  60. // intial connection attmept, try to connect to each endpoint to get an initial
  61. // list of nodes.
  62. // shuffle endpoints so not all drivers will connect to the same initial
  63. // node.
  64. r := rand.New(rand.NewSource(time.Now().UnixNano()))
  65. perm := r.Perm(len(endpoints))
  66. shuffled := make([]string, len(endpoints))
  67. for i, endpoint := range endpoints {
  68. shuffled[perm[i]] = endpoint
  69. }
  70. // store that we are not connected so that reconnect wont happen if we error
  71. atomic.StoreInt64(&c.connecting, -1)
  72. var (
  73. conn *Conn
  74. )
  75. for _, addr := range shuffled {
  76. conn, err = Connect(JoinHostPort(addr, c.session.cfg.Port), connCfg, c, c.session)
  77. if err != nil {
  78. log.Printf("gocql: unable to dial %v: %v\n", addr, err)
  79. continue
  80. }
  81. if err = c.registerEvents(conn); err != nil {
  82. conn.Close()
  83. continue
  84. }
  85. // we should fetch the initial ring here and update initial host data. So that
  86. // when we return from here we have a ring topology ready to go.
  87. break
  88. }
  89. if conn == nil {
  90. // this is fatal, not going to connect a session
  91. return err
  92. }
  93. c.conn.Store(conn)
  94. atomic.StoreInt64(&c.connecting, 0)
  95. c.closeWg.Add(1)
  96. go c.heartBeat()
  97. return nil
  98. }
  99. func (c *controlConn) registerEvents(conn *Conn) error {
  100. framer, err := conn.exec(&writeRegisterFrame{
  101. events: []string{"TOPOLOGY_CHANGE", "STATUS_CHANGE", "STATUS_CHANGE"},
  102. }, nil)
  103. if err != nil {
  104. return err
  105. }
  106. frame, err := framer.parseFrame()
  107. if err != nil {
  108. return err
  109. } else if _, ok := frame.(*readyFrame); !ok {
  110. return fmt.Errorf("unexpected frame in response to register: got %T: %v\n", frame, frame)
  111. }
  112. return nil
  113. }
  114. func (c *controlConn) reconnect(refreshring bool) {
  115. if !atomic.CompareAndSwapInt64(&c.connecting, 0, 1) {
  116. return
  117. }
  118. success := false
  119. defer func() {
  120. // debounce reconnect a little
  121. if success {
  122. go func() {
  123. time.Sleep(500 * time.Millisecond)
  124. atomic.StoreInt64(&c.connecting, 0)
  125. }()
  126. } else {
  127. atomic.StoreInt64(&c.connecting, 0)
  128. }
  129. }()
  130. oldConn := c.conn.Load().(*Conn)
  131. // TODO: should have our own roundrobbin for hosts so that we can try each
  132. // in succession and guantee that we get a different host each time.
  133. host, conn := c.session.pool.Pick(nil)
  134. if conn == nil {
  135. return
  136. }
  137. newConn, err := Connect(conn.addr, c.connCfg, c, c.session)
  138. if err != nil {
  139. host.Mark(err)
  140. // TODO: add log handler for things like this
  141. return
  142. }
  143. if err := c.registerEvents(newConn); err != nil {
  144. host.Mark(err)
  145. // TODO: handle this case better
  146. newConn.Close()
  147. log.Printf("gocql: unable to register events: %v\n", err)
  148. return
  149. }
  150. c.conn.Store(newConn)
  151. host.Mark(nil)
  152. success = true
  153. if oldConn != nil {
  154. oldConn.Close()
  155. }
  156. if refreshring {
  157. c.session.hostSource.refreshRing()
  158. }
  159. }
  160. func (c *controlConn) HandleError(conn *Conn, err error, closed bool) {
  161. if !closed {
  162. return
  163. }
  164. oldConn := c.conn.Load().(*Conn)
  165. if oldConn != conn {
  166. return
  167. }
  168. c.reconnect(true)
  169. }
  170. func (c *controlConn) writeFrame(w frameWriter) (frame, error) {
  171. conn := c.conn.Load().(*Conn)
  172. if conn == nil {
  173. return nil, errNoControl
  174. }
  175. framer, err := conn.exec(w, nil)
  176. if err != nil {
  177. return nil, err
  178. }
  179. return framer.parseFrame()
  180. }
  181. func (c *controlConn) withConn(fn func(*Conn) *Iter) *Iter {
  182. const maxConnectAttempts = 5
  183. connectAttempts := 0
  184. for i := 0; i < maxConnectAttempts; i++ {
  185. conn := c.conn.Load().(*Conn)
  186. if conn == nil {
  187. if connectAttempts > maxConnectAttempts {
  188. break
  189. }
  190. connectAttempts++
  191. c.reconnect(false)
  192. continue
  193. }
  194. return fn(conn)
  195. }
  196. return &Iter{err: errNoControl}
  197. }
  198. // query will return nil if the connection is closed or nil
  199. func (c *controlConn) query(statement string, values ...interface{}) (iter *Iter) {
  200. q := c.session.Query(statement, values...).Consistency(One)
  201. for {
  202. iter = c.withConn(func(conn *Conn) *Iter {
  203. return conn.executeQuery(q)
  204. })
  205. q.attempts++
  206. if iter.err == nil || !c.retry.Attempt(q) {
  207. break
  208. }
  209. }
  210. return
  211. }
  212. func (c *controlConn) fetchHostInfo(addr net.IP, port int) (*HostInfo, error) {
  213. // TODO(zariel): we should probably move this into host_source or atleast
  214. // share code with it.
  215. isLocal := c.addr() == addr.String()
  216. var fn func(*HostInfo) error
  217. if isLocal {
  218. fn = func(host *HostInfo) error {
  219. // TODO(zariel): should we fetch rpc_address from here?
  220. iter := c.query("SELECT data_center, rack, host_id, tokens, release_version FROM system.local WHERE key='local'")
  221. iter.Scan(&host.dataCenter, &host.rack, &host.hostId, &host.tokens, &host.version)
  222. return iter.Close()
  223. }
  224. } else {
  225. fn = func(host *HostInfo) error {
  226. // TODO(zariel): should we fetch rpc_address from here?
  227. iter := c.query("SELECT data_center, rack, host_id, tokens, release_version FROM system.peers WHERE peer=?", addr)
  228. iter.Scan(&host.dataCenter, &host.rack, &host.hostId, &host.tokens, &host.version)
  229. return iter.Close()
  230. }
  231. }
  232. host := &HostInfo{}
  233. if err := fn(host); err != nil {
  234. return nil, err
  235. }
  236. host.peer = addr.String()
  237. return host, nil
  238. }
  239. func (c *controlConn) awaitSchemaAgreement() error {
  240. return c.withConn(func(conn *Conn) *Iter {
  241. return &Iter{err: conn.awaitSchemaAgreement()}
  242. }).err
  243. }
  244. func (c *controlConn) addr() string {
  245. conn := c.conn.Load().(*Conn)
  246. if conn == nil {
  247. return ""
  248. }
  249. return conn.addr
  250. }
  251. func (c *controlConn) close() {
  252. // TODO: handle more gracefully
  253. close(c.quit)
  254. c.closeWg.Wait()
  255. conn := c.conn.Load().(*Conn)
  256. if conn != nil {
  257. conn.Close()
  258. }
  259. }
  260. var errNoControl = errors.New("gocql: no control connection available")