control.go 9.8 KB

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