control.go 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. package gocql
  2. import (
  3. "errors"
  4. "fmt"
  5. "sync/atomic"
  6. "time"
  7. )
  8. // Ensure that the atomic variable is aligned to a 64bit boundary
  9. // so that atomic operations can be applied on 32bit architectures.
  10. type controlConn struct {
  11. connecting uint64
  12. session *Session
  13. conn atomic.Value
  14. retry RetryPolicy
  15. quit chan struct{}
  16. }
  17. func createControlConn(session *Session) *controlConn {
  18. control := &controlConn{
  19. session: session,
  20. quit: make(chan struct{}),
  21. retry: &SimpleRetryPolicy{NumRetries: 3},
  22. }
  23. control.conn.Store((*Conn)(nil))
  24. go control.heartBeat()
  25. return control
  26. }
  27. func (c *controlConn) heartBeat() {
  28. for {
  29. select {
  30. case <-c.quit:
  31. return
  32. case <-time.After(5 * time.Second):
  33. }
  34. resp, err := c.writeFrame(&writeOptionsFrame{})
  35. if err != nil {
  36. goto reconn
  37. }
  38. switch resp.(type) {
  39. case *supportedFrame:
  40. continue
  41. case error:
  42. goto reconn
  43. default:
  44. panic(fmt.Sprintf("gocql: unknown frame in response to options: %T", resp))
  45. }
  46. reconn:
  47. c.reconnect(true)
  48. // time.Sleep(5 * time.Second)
  49. continue
  50. }
  51. }
  52. func (c *controlConn) reconnect(refreshring bool) {
  53. if !atomic.CompareAndSwapUint64(&c.connecting, 0, 1) {
  54. return
  55. }
  56. success := false
  57. defer func() {
  58. // debounce reconnect a little
  59. if success {
  60. go func() {
  61. time.Sleep(500 * time.Millisecond)
  62. atomic.StoreUint64(&c.connecting, 0)
  63. }()
  64. } else {
  65. atomic.StoreUint64(&c.connecting, 0)
  66. }
  67. }()
  68. oldConn := c.conn.Load().(*Conn)
  69. // TODO: should have our own roundrobbin for hosts so that we can try each
  70. // in succession and guantee that we get a different host each time.
  71. host, conn := c.session.pool.Pick(nil)
  72. if conn == nil {
  73. return
  74. }
  75. newConn, err := Connect(conn.addr, conn.cfg, c, c.session)
  76. if err != nil {
  77. host.Mark(err)
  78. // TODO: add log handler for things like this
  79. return
  80. }
  81. host.Mark(nil)
  82. c.conn.Store(newConn)
  83. success = true
  84. if oldConn != nil {
  85. oldConn.Close()
  86. }
  87. if refreshring && c.session.cfg.DiscoverHosts {
  88. c.session.hostSource.refreshRing()
  89. }
  90. }
  91. func (c *controlConn) HandleError(conn *Conn, err error, closed bool) {
  92. if !closed {
  93. return
  94. }
  95. oldConn := c.conn.Load().(*Conn)
  96. if oldConn != conn {
  97. return
  98. }
  99. c.reconnect(true)
  100. }
  101. func (c *controlConn) writeFrame(w frameWriter) (frame, error) {
  102. conn := c.conn.Load().(*Conn)
  103. if conn == nil {
  104. return nil, errNoControl
  105. }
  106. framer, err := conn.exec(w, nil)
  107. if err != nil {
  108. return nil, err
  109. }
  110. return framer.parseFrame()
  111. }
  112. func (c *controlConn) withConn(fn func(*Conn) *Iter) *Iter {
  113. const maxConnectAttempts = 5
  114. connectAttempts := 0
  115. for i := 0; i < maxConnectAttempts; i++ {
  116. conn := c.conn.Load().(*Conn)
  117. if conn == nil {
  118. if connectAttempts > maxConnectAttempts {
  119. break
  120. }
  121. connectAttempts++
  122. c.reconnect(false)
  123. continue
  124. }
  125. return fn(conn)
  126. }
  127. return &Iter{err: errNoControl}
  128. }
  129. // query will return nil if the connection is closed or nil
  130. func (c *controlConn) query(statement string, values ...interface{}) (iter *Iter) {
  131. q := c.session.Query(statement, values...).Consistency(One)
  132. for {
  133. iter = c.withConn(func(conn *Conn) *Iter {
  134. return conn.executeQuery(q)
  135. })
  136. q.attempts++
  137. if iter.err == nil || !c.retry.Attempt(q) {
  138. break
  139. }
  140. }
  141. return
  142. }
  143. func (c *controlConn) awaitSchemaAgreement() error {
  144. return c.withConn(func(conn *Conn) *Iter {
  145. return &Iter{err: conn.awaitSchemaAgreement()}
  146. }).err
  147. }
  148. func (c *controlConn) addr() string {
  149. conn := c.conn.Load().(*Conn)
  150. if conn == nil {
  151. return ""
  152. }
  153. return conn.addr
  154. }
  155. func (c *controlConn) close() {
  156. // TODO: handle more gracefully
  157. close(c.quit)
  158. }
  159. var errNoControl = errors.New("gocql: no control connection available")