control.go 7.5 KB

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