control.go 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  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 := 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. cfg := *c.session.connCfg
  139. cfg.disableCoalesce = true
  140. var err error
  141. for _, host := range shuffled {
  142. var conn *Conn
  143. c.session.dial(host, &cfg, c)
  144. conn, err = c.session.connect(host, c)
  145. if err == nil {
  146. return conn, nil
  147. }
  148. Logger.Printf("gocql: unable to dial control conn %v: %v\n", host.ConnectAddress(), err)
  149. }
  150. return nil, err
  151. }
  152. // this is going to be version dependant and a nightmare to maintain :(
  153. var protocolSupportRe = regexp.MustCompile(`the lowest supported version is \d+ and the greatest is (\d+)$`)
  154. func parseProtocolFromError(err error) int {
  155. // I really wish this had the actual info in the error frame...
  156. matches := protocolSupportRe.FindAllStringSubmatch(err.Error(), -1)
  157. if len(matches) != 1 || len(matches[0]) != 2 {
  158. if verr, ok := err.(*protocolError); ok {
  159. return int(verr.frame.Header().version.version())
  160. }
  161. return 0
  162. }
  163. max, err := strconv.Atoi(matches[0][1])
  164. if err != nil {
  165. return 0
  166. }
  167. return max
  168. }
  169. func (c *controlConn) discoverProtocol(hosts []*HostInfo) (int, error) {
  170. hosts = shuffleHosts(hosts)
  171. connCfg := *c.session.connCfg
  172. connCfg.ProtoVersion = 4 // TODO: define maxProtocol
  173. handler := connErrorHandlerFn(func(c *Conn, err error, closed bool) {
  174. // we should never get here, but if we do it means we connected to a
  175. // host successfully which means our attempted protocol version worked
  176. if !closed {
  177. c.Close()
  178. }
  179. })
  180. var err error
  181. for _, host := range hosts {
  182. var conn *Conn
  183. conn, err = c.session.dial(host, &connCfg, handler)
  184. if conn != nil {
  185. conn.Close()
  186. }
  187. if err == nil {
  188. return connCfg.ProtoVersion, nil
  189. }
  190. if proto := parseProtocolFromError(err); proto > 0 {
  191. return proto, nil
  192. }
  193. }
  194. return 0, err
  195. }
  196. func (c *controlConn) connect(hosts []*HostInfo) error {
  197. if len(hosts) == 0 {
  198. return errors.New("control: no endpoints specified")
  199. }
  200. conn, err := c.shuffleDial(hosts)
  201. if err != nil {
  202. return fmt.Errorf("control: unable to connect to initial hosts: %v", err)
  203. }
  204. if err := c.setupConn(conn); err != nil {
  205. conn.Close()
  206. return fmt.Errorf("control: unable to setup connection: %v", err)
  207. }
  208. // we could fetch the initial ring here and update initial host data. So that
  209. // when we return from here we have a ring topology ready to go.
  210. go c.heartBeat()
  211. return nil
  212. }
  213. type connHost struct {
  214. conn *Conn
  215. host *HostInfo
  216. }
  217. func (c *controlConn) setupConn(conn *Conn) error {
  218. if err := c.registerEvents(conn); err != nil {
  219. conn.Close()
  220. return err
  221. }
  222. // TODO(zariel): do we need to fetch host info everytime
  223. // the control conn connects? Surely we have it cached?
  224. host, err := conn.localHostInfo(context.TODO())
  225. if err != nil {
  226. return err
  227. }
  228. ch := &connHost{
  229. conn: conn,
  230. host: host,
  231. }
  232. c.conn.Store(ch)
  233. c.session.handleNodeUp(host.ConnectAddress(), host.Port(), false)
  234. return nil
  235. }
  236. func (c *controlConn) registerEvents(conn *Conn) error {
  237. var events []string
  238. if !c.session.cfg.Events.DisableTopologyEvents {
  239. events = append(events, "TOPOLOGY_CHANGE")
  240. }
  241. if !c.session.cfg.Events.DisableNodeStatusEvents {
  242. events = append(events, "STATUS_CHANGE")
  243. }
  244. if !c.session.cfg.Events.DisableSchemaEvents {
  245. events = append(events, "SCHEMA_CHANGE")
  246. }
  247. if len(events) == 0 {
  248. return nil
  249. }
  250. framer, err := conn.exec(context.Background(),
  251. &writeRegisterFrame{
  252. events: events,
  253. }, nil)
  254. if err != nil {
  255. return err
  256. }
  257. frame, err := framer.parseFrame()
  258. if err != nil {
  259. return err
  260. } else if _, ok := frame.(*readyFrame); !ok {
  261. return fmt.Errorf("unexpected frame in response to register: got %T: %v\n", frame, frame)
  262. }
  263. return nil
  264. }
  265. func (c *controlConn) reconnect(refreshring bool) {
  266. if !atomic.CompareAndSwapInt32(&c.reconnecting, 0, 1) {
  267. return
  268. }
  269. defer atomic.StoreInt32(&c.reconnecting, 0)
  270. // TODO: simplify this function, use session.ring to get hosts instead of the
  271. // connection pool
  272. var host *HostInfo
  273. ch := c.getConn()
  274. if ch != nil {
  275. host = ch.host
  276. ch.conn.Close()
  277. }
  278. var newConn *Conn
  279. if host != nil {
  280. // try to connect to the old host
  281. conn, err := c.session.connect(host, c)
  282. if err != nil {
  283. // host is dead
  284. // TODO: this is replicated in a few places
  285. if c.session.cfg.ConvictionPolicy.AddFailure(err, host) {
  286. c.session.handleNodeDown(host.ConnectAddress(), host.Port())
  287. }
  288. } else {
  289. newConn = conn
  290. }
  291. }
  292. // TODO: should have our own round-robin for hosts so that we can try each
  293. // in succession and guarantee that we get a different host each time.
  294. if newConn == nil {
  295. host := c.session.ring.rrHost()
  296. if host == nil {
  297. c.connect(c.session.ring.endpoints)
  298. return
  299. }
  300. var err error
  301. newConn, err = c.session.connect(host, c)
  302. if err != nil {
  303. // TODO: add log handler for things like this
  304. return
  305. }
  306. }
  307. if err := c.setupConn(newConn); err != nil {
  308. newConn.Close()
  309. Logger.Printf("gocql: control unable to register events: %v\n", err)
  310. return
  311. }
  312. if refreshring {
  313. c.session.hostSource.refreshRing()
  314. }
  315. }
  316. func (c *controlConn) HandleError(conn *Conn, err error, closed bool) {
  317. if !closed {
  318. return
  319. }
  320. oldConn := c.getConn()
  321. if oldConn.conn != conn {
  322. return
  323. }
  324. c.reconnect(false)
  325. }
  326. func (c *controlConn) getConn() *connHost {
  327. return c.conn.Load().(*connHost)
  328. }
  329. func (c *controlConn) writeFrame(w frameWriter) (frame, error) {
  330. ch := c.getConn()
  331. if ch == nil {
  332. return nil, errNoControl
  333. }
  334. framer, err := ch.conn.exec(context.Background(), w, nil)
  335. if err != nil {
  336. return nil, err
  337. }
  338. return framer.parseFrame()
  339. }
  340. func (c *controlConn) withConnHost(fn func(*connHost) *Iter) *Iter {
  341. const maxConnectAttempts = 5
  342. connectAttempts := 0
  343. for i := 0; i < maxConnectAttempts; i++ {
  344. ch := c.getConn()
  345. if ch == nil {
  346. if connectAttempts > maxConnectAttempts {
  347. break
  348. }
  349. connectAttempts++
  350. c.reconnect(false)
  351. continue
  352. }
  353. return fn(ch)
  354. }
  355. return &Iter{err: errNoControl}
  356. }
  357. func (c *controlConn) withConn(fn func(*Conn) *Iter) *Iter {
  358. return c.withConnHost(func(ch *connHost) *Iter {
  359. return fn(ch.conn)
  360. })
  361. }
  362. // query will return nil if the connection is closed or nil
  363. func (c *controlConn) query(statement string, values ...interface{}) (iter *Iter) {
  364. q := c.session.Query(statement, values...).Consistency(One).RoutingKey([]byte{}).Trace(nil)
  365. for {
  366. iter = c.withConn(func(conn *Conn) *Iter {
  367. return conn.executeQuery(context.TODO(), q)
  368. })
  369. if gocqlDebug && iter.err != nil {
  370. Logger.Printf("control: error executing %q: %v\n", statement, iter.err)
  371. }
  372. q.AddAttempts(1, c.getConn().host)
  373. if iter.err == nil || !c.retry.Attempt(q) {
  374. break
  375. }
  376. }
  377. return
  378. }
  379. func (c *controlConn) awaitSchemaAgreement() error {
  380. return c.withConn(func(conn *Conn) *Iter {
  381. return &Iter{err: conn.awaitSchemaAgreement(context.TODO())}
  382. }).err
  383. }
  384. func (c *controlConn) close() {
  385. if atomic.CompareAndSwapInt32(&c.started, 1, -1) {
  386. c.quit <- struct{}{}
  387. }
  388. ch := c.getConn()
  389. if ch != nil {
  390. ch.conn.Close()
  391. }
  392. }
  393. var errNoControl = errors.New("gocql: no control connection available")