events.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. package gocql
  2. import (
  3. "net"
  4. "sync"
  5. "time"
  6. )
  7. type eventDebouncer struct {
  8. name string
  9. timer *time.Timer
  10. mu sync.Mutex
  11. events []frame
  12. callback func([]frame)
  13. quit chan struct{}
  14. }
  15. func newEventDebouncer(name string, eventHandler func([]frame)) *eventDebouncer {
  16. e := &eventDebouncer{
  17. name: name,
  18. quit: make(chan struct{}),
  19. timer: time.NewTimer(eventDebounceTime),
  20. callback: eventHandler,
  21. }
  22. e.timer.Stop()
  23. go e.flusher()
  24. return e
  25. }
  26. func (e *eventDebouncer) stop() {
  27. e.quit <- struct{}{} // sync with flusher
  28. close(e.quit)
  29. }
  30. func (e *eventDebouncer) flusher() {
  31. for {
  32. select {
  33. case <-e.timer.C:
  34. e.mu.Lock()
  35. e.flush()
  36. e.mu.Unlock()
  37. case <-e.quit:
  38. return
  39. }
  40. }
  41. }
  42. const (
  43. eventBufferSize = 1000
  44. eventDebounceTime = 1 * time.Second
  45. )
  46. // flush must be called with mu locked
  47. func (e *eventDebouncer) flush() {
  48. if len(e.events) == 0 {
  49. return
  50. }
  51. // if the flush interval is faster than the callback then we will end up calling
  52. // the callback multiple times, probably a bad idea. In this case we could drop
  53. // frames?
  54. go e.callback(e.events)
  55. e.events = make([]frame, 0, eventBufferSize)
  56. }
  57. func (e *eventDebouncer) debounce(frame frame) {
  58. e.mu.Lock()
  59. e.timer.Reset(eventDebounceTime)
  60. // TODO: probably need a warning to track if this threshold is too low
  61. if len(e.events) < eventBufferSize {
  62. e.events = append(e.events, frame)
  63. } else {
  64. Logger.Printf("%s: buffer full, dropping event frame: %s", e.name, frame)
  65. }
  66. e.mu.Unlock()
  67. }
  68. func (s *Session) handleEvent(framer *framer) {
  69. // TODO(zariel): need to debounce events frames, and possible also events
  70. defer framerPool.Put(framer)
  71. frame, err := framer.parseFrame()
  72. if err != nil {
  73. // TODO: logger
  74. Logger.Printf("gocql: unable to parse event frame: %v\n", err)
  75. return
  76. }
  77. if gocqlDebug {
  78. Logger.Printf("gocql: handling frame: %v\n", frame)
  79. }
  80. // TODO: handle medatadata events
  81. switch f := frame.(type) {
  82. case *schemaChangeKeyspace, *schemaChangeFunction, *schemaChangeTable:
  83. s.schemaEvents.debounce(frame)
  84. case *topologyChangeEventFrame, *statusChangeEventFrame:
  85. s.nodeEvents.debounce(frame)
  86. default:
  87. Logger.Printf("gocql: invalid event frame (%T): %v\n", f, f)
  88. }
  89. }
  90. func (s *Session) handleSchemaEvent(frames []frame) {
  91. s.mu.RLock()
  92. defer s.mu.RUnlock()
  93. if s.schemaDescriber == nil {
  94. return
  95. }
  96. for _, frame := range frames {
  97. switch f := frame.(type) {
  98. case *schemaChangeKeyspace:
  99. s.schemaDescriber.clearSchema(f.keyspace)
  100. case *schemaChangeTable:
  101. s.schemaDescriber.clearSchema(f.keyspace)
  102. }
  103. }
  104. }
  105. func (s *Session) handleNodeEvent(frames []frame) {
  106. type nodeEvent struct {
  107. change string
  108. host net.IP
  109. port int
  110. }
  111. events := make(map[string]*nodeEvent)
  112. for _, frame := range frames {
  113. // TODO: can we be sure the order of events in the buffer is correct?
  114. switch f := frame.(type) {
  115. case *topologyChangeEventFrame:
  116. event, ok := events[f.host.String()]
  117. if !ok {
  118. event = &nodeEvent{change: f.change, host: f.host, port: f.port}
  119. events[f.host.String()] = event
  120. }
  121. event.change = f.change
  122. case *statusChangeEventFrame:
  123. event, ok := events[f.host.String()]
  124. if !ok {
  125. event = &nodeEvent{change: f.change, host: f.host, port: f.port}
  126. events[f.host.String()] = event
  127. }
  128. event.change = f.change
  129. }
  130. }
  131. for _, f := range events {
  132. if gocqlDebug {
  133. Logger.Printf("gocql: dispatching event: %+v\n", f)
  134. }
  135. switch f.change {
  136. case "NEW_NODE":
  137. s.handleNewNode(f.host, f.port, true)
  138. case "REMOVED_NODE":
  139. s.handleRemovedNode(f.host, f.port)
  140. case "MOVED_NODE":
  141. // java-driver handles this, not mentioned in the spec
  142. // TODO(zariel): refresh token map
  143. case "UP":
  144. s.handleNodeUp(f.host, f.port, true)
  145. case "DOWN":
  146. s.handleNodeDown(f.host, f.port)
  147. }
  148. }
  149. }
  150. func (s *Session) handleNewNode(ip net.IP, port int, waitForBinary bool) {
  151. // Get host info and apply any filters to the host
  152. hostInfo, err := s.hostSource.getHostInfo(ip, port)
  153. if err != nil {
  154. Logger.Printf("gocql: events: unable to fetch host info for (%s:%d): %v\n", ip, port, err)
  155. return
  156. } else if hostInfo == nil {
  157. // If hostInfo is nil, this host was filtered out by cfg.HostFilter
  158. return
  159. }
  160. if t := hostInfo.Version().nodeUpDelay(); t > 0 && waitForBinary {
  161. time.Sleep(t)
  162. }
  163. // should this handle token moving?
  164. if existing, ok := s.ring.addHostIfMissing(hostInfo); ok {
  165. existing.update(hostInfo)
  166. hostInfo = existing
  167. }
  168. s.pool.addHost(hostInfo)
  169. s.policy.AddHost(hostInfo)
  170. hostInfo.setState(NodeUp)
  171. if s.control != nil && !s.cfg.IgnorePeerAddr {
  172. // TODO(zariel): debounce ring refresh
  173. s.hostSource.refreshRing()
  174. }
  175. }
  176. func (s *Session) handleRemovedNode(ip net.IP, port int) {
  177. // we remove all nodes but only add ones which pass the filter
  178. host := s.ring.getHost(ip)
  179. if host == nil {
  180. host = &HostInfo{connectAddress: ip, port: port}
  181. }
  182. if s.cfg.HostFilter != nil && !s.cfg.HostFilter.Accept(host) {
  183. return
  184. }
  185. host.setState(NodeDown)
  186. s.policy.RemoveHost(host)
  187. s.pool.removeHost(ip)
  188. s.ring.removeHost(ip)
  189. if !s.cfg.IgnorePeerAddr {
  190. s.hostSource.refreshRing()
  191. }
  192. }
  193. func (s *Session) handleNodeUp(ip net.IP, port int, waitForBinary bool) {
  194. if gocqlDebug {
  195. Logger.Printf("gocql: Session.handleNodeUp: %s:%d\n", ip.String(), port)
  196. }
  197. host := s.ring.getHost(ip)
  198. if host != nil {
  199. // If we receive a node up event and user has asked us to ignore the peer address use
  200. // the address provide by the event instead the address provide by peer the table.
  201. if s.cfg.IgnorePeerAddr && !host.ConnectAddress().Equal(ip) {
  202. host.SetConnectAddress(ip)
  203. }
  204. if s.cfg.HostFilter != nil && !s.cfg.HostFilter.Accept(host) {
  205. return
  206. }
  207. if t := host.Version().nodeUpDelay(); t > 0 && waitForBinary {
  208. time.Sleep(t)
  209. }
  210. s.pool.hostUp(host)
  211. s.policy.HostUp(host)
  212. host.setState(NodeUp)
  213. return
  214. }
  215. s.handleNewNode(ip, port, waitForBinary)
  216. }
  217. func (s *Session) handleNodeDown(ip net.IP, port int) {
  218. if gocqlDebug {
  219. Logger.Printf("gocql: Session.handleNodeDown: %s:%d\n", ip.String(), port)
  220. }
  221. host := s.ring.getHost(ip)
  222. if host == nil {
  223. host = &HostInfo{connectAddress: ip, port: port}
  224. }
  225. if s.cfg.HostFilter != nil && !s.cfg.HostFilter.Accept(host) {
  226. return
  227. }
  228. host.setState(NodeDown)
  229. s.policy.HostDown(host)
  230. s.pool.hostDown(ip)
  231. }