control.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. package gocql
  2. import (
  3. crand "crypto/rand"
  4. "errors"
  5. "fmt"
  6. "log"
  7. "math/rand"
  8. "net"
  9. "strconv"
  10. "sync/atomic"
  11. "time"
  12. "golang.org/x/net/context"
  13. )
  14. var (
  15. randr *rand.Rand
  16. )
  17. func init() {
  18. b := make([]byte, 4)
  19. if _, err := crand.Read(b); err != nil {
  20. panic(fmt.Sprintf("unable to seed random number generator: %v", err))
  21. }
  22. randr = rand.New(rand.NewSource(int64(readInt(b))))
  23. }
  24. // Ensure that the atomic variable is aligned to a 64bit boundary
  25. // so that atomic operations can be applied on 32bit architectures.
  26. type controlConn struct {
  27. session *Session
  28. conn atomic.Value
  29. retry RetryPolicy
  30. started int32
  31. quit chan struct{}
  32. }
  33. func createControlConn(session *Session) *controlConn {
  34. control := &controlConn{
  35. session: session,
  36. quit: make(chan struct{}),
  37. retry: &SimpleRetryPolicy{NumRetries: 3},
  38. }
  39. control.conn.Store((*Conn)(nil))
  40. return control
  41. }
  42. func (c *controlConn) heartBeat() {
  43. if !atomic.CompareAndSwapInt32(&c.started, 0, 1) {
  44. return
  45. }
  46. sleepTime := 1 * time.Second
  47. for {
  48. select {
  49. case <-c.quit:
  50. return
  51. case <-time.After(sleepTime):
  52. }
  53. resp, err := c.writeFrame(&writeOptionsFrame{})
  54. if err != nil {
  55. goto reconn
  56. }
  57. switch resp.(type) {
  58. case *supportedFrame:
  59. // Everything ok
  60. sleepTime = 5 * time.Second
  61. continue
  62. case error:
  63. goto reconn
  64. default:
  65. panic(fmt.Sprintf("gocql: unknown frame in response to options: %T", resp))
  66. }
  67. reconn:
  68. // try to connect a bit faster
  69. sleepTime = 1 * time.Second
  70. c.reconnect(true)
  71. // time.Sleep(5 * time.Second)
  72. continue
  73. }
  74. }
  75. var hostLookupPreferV4 = false
  76. func hostInfo(addr string, defaultPort int) (*HostInfo, error) {
  77. var port int
  78. host, portStr, err := net.SplitHostPort(addr)
  79. if err != nil {
  80. host = addr
  81. port = defaultPort
  82. } else {
  83. port, err = strconv.Atoi(portStr)
  84. if err != nil {
  85. return nil, err
  86. }
  87. }
  88. ip := net.ParseIP(host)
  89. if ip == nil {
  90. ips, err := net.LookupIP(host)
  91. if err != nil {
  92. return nil, err
  93. } else if len(ips) == 0 {
  94. return nil, fmt.Errorf("No IP's returned from DNS lookup for %q", addr)
  95. }
  96. if hostLookupPreferV4 {
  97. for _, v := range ips {
  98. if v4 := v.To4(); v4 != nil {
  99. ip = v4
  100. break
  101. }
  102. }
  103. if ip == nil {
  104. ip = ips[0]
  105. }
  106. } else {
  107. // TODO(zariel): should we check that we can connect to any of the ips?
  108. ip = ips[0]
  109. }
  110. }
  111. return &HostInfo{peer: ip, port: port}, nil
  112. }
  113. func (c *controlConn) shuffleDial(endpoints []string) (conn *Conn, err error) {
  114. // TODO: accept a []*HostInfo
  115. perm := randr.Perm(len(endpoints))
  116. shuffled := make([]string, len(endpoints))
  117. for i, endpoint := range endpoints {
  118. shuffled[perm[i]] = endpoint
  119. }
  120. // shuffle endpoints so not all drivers will connect to the same initial
  121. // node.
  122. for _, addr := range shuffled {
  123. if addr == "" {
  124. return nil, fmt.Errorf("invalid address: %q", addr)
  125. }
  126. port := c.session.cfg.Port
  127. addr = JoinHostPort(addr, port)
  128. var host *HostInfo
  129. host, err = hostInfo(addr, port)
  130. if err != nil {
  131. return nil, fmt.Errorf("invalid address: %q: %v", addr, err)
  132. }
  133. hostInfo, _ := c.session.ring.addHostIfMissing(host)
  134. conn, err = c.session.connect(hostInfo, c)
  135. if err == nil {
  136. return conn, err
  137. }
  138. log.Printf("gocql: unable to dial control conn %v: %v\n", addr, err)
  139. }
  140. if err != nil {
  141. return nil, err
  142. }
  143. return conn, nil
  144. }
  145. func (c *controlConn) connect(endpoints []string) error {
  146. if len(endpoints) == 0 {
  147. return errors.New("control: no endpoints specified")
  148. }
  149. conn, err := c.shuffleDial(endpoints)
  150. if err != nil {
  151. return fmt.Errorf("control: unable to connect to initial hosts: %v", err)
  152. }
  153. if err := c.setupConn(conn); err != nil {
  154. conn.Close()
  155. return fmt.Errorf("control: unable to setup connection: %v", err)
  156. }
  157. // we could fetch the initial ring here and update initial host data. So that
  158. // when we return from here we have a ring topology ready to go.
  159. go c.heartBeat()
  160. return nil
  161. }
  162. func (c *controlConn) setupConn(conn *Conn) error {
  163. if err := c.registerEvents(conn); err != nil {
  164. conn.Close()
  165. return err
  166. }
  167. c.conn.Store(conn)
  168. host, portstr, err := net.SplitHostPort(conn.conn.RemoteAddr().String())
  169. if err != nil {
  170. return err
  171. }
  172. port, err := strconv.Atoi(portstr)
  173. if err != nil {
  174. return err
  175. }
  176. c.session.handleNodeUp(net.ParseIP(host), port, false)
  177. return nil
  178. }
  179. func (c *controlConn) registerEvents(conn *Conn) error {
  180. var events []string
  181. if !c.session.cfg.Events.DisableTopologyEvents {
  182. events = append(events, "TOPOLOGY_CHANGE")
  183. }
  184. if !c.session.cfg.Events.DisableNodeStatusEvents {
  185. events = append(events, "STATUS_CHANGE")
  186. }
  187. if !c.session.cfg.Events.DisableSchemaEvents {
  188. events = append(events, "SCHEMA_CHANGE")
  189. }
  190. if len(events) == 0 {
  191. return nil
  192. }
  193. framer, err := conn.exec(context.Background(),
  194. &writeRegisterFrame{
  195. events: events,
  196. }, nil)
  197. if err != nil {
  198. return err
  199. }
  200. frame, err := framer.parseFrame()
  201. if err != nil {
  202. return err
  203. } else if _, ok := frame.(*readyFrame); !ok {
  204. return fmt.Errorf("unexpected frame in response to register: got %T: %v\n", frame, frame)
  205. }
  206. return nil
  207. }
  208. func (c *controlConn) reconnect(refreshring bool) {
  209. // TODO: simplify this function, use session.ring to get hosts instead of the
  210. // connection pool
  211. var host *HostInfo
  212. oldConn := c.conn.Load().(*Conn)
  213. if oldConn != nil {
  214. host = oldConn.host
  215. oldConn.Close()
  216. }
  217. var newConn *Conn
  218. if host != nil {
  219. // try to connect to the old host
  220. conn, err := c.session.connect(host, c)
  221. if err != nil {
  222. // host is dead
  223. // TODO: this is replicated in a few places
  224. c.session.handleNodeDown(host.Peer(), host.Port())
  225. } else {
  226. newConn = conn
  227. }
  228. }
  229. // TODO: should have our own roundrobbin for hosts so that we can try each
  230. // in succession and guantee that we get a different host each time.
  231. if newConn == nil {
  232. host := c.session.ring.rrHost()
  233. if host == nil {
  234. c.connect(c.session.ring.endpoints)
  235. return
  236. }
  237. var err error
  238. newConn, err = c.session.connect(host, c)
  239. if err != nil {
  240. // TODO: add log handler for things like this
  241. return
  242. }
  243. }
  244. if err := c.setupConn(newConn); err != nil {
  245. newConn.Close()
  246. log.Printf("gocql: control unable to register events: %v\n", err)
  247. return
  248. }
  249. if refreshring {
  250. c.session.hostSource.refreshRing()
  251. }
  252. }
  253. func (c *controlConn) HandleError(conn *Conn, err error, closed bool) {
  254. if !closed {
  255. return
  256. }
  257. oldConn := c.conn.Load().(*Conn)
  258. if oldConn != conn {
  259. return
  260. }
  261. c.reconnect(true)
  262. }
  263. func (c *controlConn) writeFrame(w frameWriter) (frame, error) {
  264. conn := c.conn.Load().(*Conn)
  265. if conn == nil {
  266. return nil, errNoControl
  267. }
  268. framer, err := conn.exec(context.Background(), w, nil)
  269. if err != nil {
  270. return nil, err
  271. }
  272. return framer.parseFrame()
  273. }
  274. func (c *controlConn) withConn(fn func(*Conn) *Iter) *Iter {
  275. const maxConnectAttempts = 5
  276. connectAttempts := 0
  277. for i := 0; i < maxConnectAttempts; i++ {
  278. conn := c.conn.Load().(*Conn)
  279. if conn == nil {
  280. if connectAttempts > maxConnectAttempts {
  281. break
  282. }
  283. connectAttempts++
  284. c.reconnect(false)
  285. continue
  286. }
  287. return fn(conn)
  288. }
  289. return &Iter{err: errNoControl}
  290. }
  291. // query will return nil if the connection is closed or nil
  292. func (c *controlConn) query(statement string, values ...interface{}) (iter *Iter) {
  293. q := c.session.Query(statement, values...).Consistency(One).RoutingKey([]byte{})
  294. for {
  295. iter = c.withConn(func(conn *Conn) *Iter {
  296. return conn.executeQuery(q)
  297. })
  298. if gocqlDebug && iter.err != nil {
  299. log.Printf("control: error executing %q: %v\n", statement, iter.err)
  300. }
  301. q.attempts++
  302. if iter.err == nil || !c.retry.Attempt(q) {
  303. break
  304. }
  305. }
  306. return
  307. }
  308. func (c *controlConn) fetchHostInfo(ip net.IP, port int) (*HostInfo, error) {
  309. // TODO(zariel): we should probably move this into host_source or atleast
  310. // share code with it.
  311. localHost := c.host()
  312. if localHost == nil {
  313. return nil, errors.New("unable to fetch host info, invalid conn host")
  314. }
  315. isLocal := localHost.Peer().Equal(ip)
  316. var fn func(*HostInfo) error
  317. // TODO(zariel): fetch preferred_ip address (is it >3.x only?)
  318. if isLocal {
  319. fn = func(host *HostInfo) error {
  320. iter := c.query("SELECT data_center, rack, host_id, tokens, release_version FROM system.local WHERE key='local'")
  321. iter.Scan(&host.dataCenter, &host.rack, &host.hostId, &host.tokens, &host.version)
  322. return iter.Close()
  323. }
  324. } else {
  325. fn = func(host *HostInfo) error {
  326. iter := c.query("SELECT data_center, rack, host_id, tokens, release_version FROM system.peers WHERE peer=?", ip)
  327. iter.Scan(&host.dataCenter, &host.rack, &host.hostId, &host.tokens, &host.version)
  328. return iter.Close()
  329. }
  330. }
  331. host := &HostInfo{
  332. port: port,
  333. peer: ip,
  334. }
  335. if err := fn(host); err != nil {
  336. return nil, err
  337. }
  338. return host, nil
  339. }
  340. func (c *controlConn) awaitSchemaAgreement() error {
  341. return c.withConn(func(conn *Conn) *Iter {
  342. return &Iter{err: conn.awaitSchemaAgreement()}
  343. }).err
  344. }
  345. func (c *controlConn) host() *HostInfo {
  346. conn := c.conn.Load().(*Conn)
  347. if conn == nil {
  348. return nil
  349. }
  350. return conn.host
  351. }
  352. func (c *controlConn) close() {
  353. if atomic.CompareAndSwapInt32(&c.started, 1, -1) {
  354. c.quit <- struct{}{}
  355. }
  356. conn := c.conn.Load().(*Conn)
  357. if conn != nil {
  358. conn.Close()
  359. }
  360. }
  361. var errNoControl = errors.New("gocql: no control connection available")