events.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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. if s.schemaDescriber == nil {
  92. return
  93. }
  94. for _, frame := range frames {
  95. switch f := frame.(type) {
  96. case *schemaChangeKeyspace:
  97. s.schemaDescriber.clearSchema(f.keyspace)
  98. case *schemaChangeTable:
  99. s.schemaDescriber.clearSchema(f.keyspace)
  100. }
  101. }
  102. }
  103. func (s *Session) handleNodeEvent(frames []frame) {
  104. type nodeEvent struct {
  105. change string
  106. host net.IP
  107. port int
  108. }
  109. events := make(map[string]*nodeEvent)
  110. for _, frame := range frames {
  111. // TODO: can we be sure the order of events in the buffer is correct?
  112. switch f := frame.(type) {
  113. case *topologyChangeEventFrame:
  114. event, ok := events[f.host.String()]
  115. if !ok {
  116. event = &nodeEvent{change: f.change, host: f.host, port: f.port}
  117. events[f.host.String()] = event
  118. }
  119. event.change = f.change
  120. case *statusChangeEventFrame:
  121. event, ok := events[f.host.String()]
  122. if !ok {
  123. event = &nodeEvent{change: f.change, host: f.host, port: f.port}
  124. events[f.host.String()] = event
  125. }
  126. event.change = f.change
  127. }
  128. }
  129. for _, f := range events {
  130. if gocqlDebug {
  131. Logger.Printf("gocql: dispatching event: %+v\n", f)
  132. }
  133. switch f.change {
  134. case "NEW_NODE":
  135. s.handleNewNode(f.host, f.port, true)
  136. case "REMOVED_NODE":
  137. s.handleRemovedNode(f.host, f.port)
  138. case "MOVED_NODE":
  139. // java-driver handles this, not mentioned in the spec
  140. // TODO(zariel): refresh token map
  141. case "UP":
  142. s.handleNodeUp(f.host, f.port, true)
  143. case "DOWN":
  144. s.handleNodeDown(f.host, f.port)
  145. }
  146. }
  147. }
  148. func (s *Session) handleNewNode(ip net.IP, port int, waitForBinary bool) {
  149. var hostInfo *HostInfo
  150. if s.control != nil && !s.cfg.IgnorePeerAddr {
  151. var err error
  152. hostInfo, err = s.control.fetchHostInfo(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. }
  157. } else {
  158. hostInfo = &HostInfo{peer: ip, port: port}
  159. }
  160. if s.cfg.IgnorePeerAddr && hostInfo.Peer().Equal(ip) {
  161. hostInfo.setPeer(ip)
  162. }
  163. if s.cfg.HostFilter != nil && !s.cfg.HostFilter.Accept(hostInfo) {
  164. return
  165. }
  166. if t := hostInfo.Version().nodeUpDelay(); t > 0 && waitForBinary {
  167. time.Sleep(t)
  168. }
  169. // should this handle token moving?
  170. if existing, ok := s.ring.addHostIfMissing(hostInfo); ok {
  171. existing.update(hostInfo)
  172. hostInfo = existing
  173. }
  174. s.pool.addHost(hostInfo)
  175. s.policy.AddHost(hostInfo)
  176. hostInfo.setState(NodeUp)
  177. if s.control != nil && !s.cfg.IgnorePeerAddr {
  178. s.hostSource.refreshRing()
  179. }
  180. }
  181. func (s *Session) handleRemovedNode(ip net.IP, port int) {
  182. // we remove all nodes but only add ones which pass the filter
  183. host := s.ring.getHost(ip)
  184. if host == nil {
  185. host = &HostInfo{peer: ip, port: port}
  186. }
  187. if s.cfg.HostFilter != nil && !s.cfg.HostFilter.Accept(host) {
  188. return
  189. }
  190. host.setState(NodeDown)
  191. s.policy.RemoveHost(host)
  192. s.pool.removeHost(ip)
  193. s.ring.removeHost(ip)
  194. if !s.cfg.IgnorePeerAddr {
  195. s.hostSource.refreshRing()
  196. }
  197. }
  198. func (s *Session) handleNodeUp(ip net.IP, port int, waitForBinary bool) {
  199. if gocqlDebug {
  200. Logger.Printf("gocql: Session.handleNodeUp: %s:%d\n", ip.String(), port)
  201. }
  202. host := s.ring.getHost(ip)
  203. if host != nil {
  204. if s.cfg.IgnorePeerAddr && host.Peer().Equal(ip) {
  205. // TODO: how can this ever be true?
  206. host.setPeer(ip)
  207. }
  208. if s.cfg.HostFilter != nil && !s.cfg.HostFilter.Accept(host) {
  209. return
  210. }
  211. if t := host.Version().nodeUpDelay(); t > 0 && waitForBinary {
  212. time.Sleep(t)
  213. }
  214. s.pool.hostUp(host)
  215. s.policy.HostUp(host)
  216. host.setState(NodeUp)
  217. return
  218. }
  219. s.handleNewNode(ip, port, waitForBinary)
  220. }
  221. func (s *Session) handleNodeDown(ip net.IP, port int) {
  222. if gocqlDebug {
  223. Logger.Printf("gocql: Session.handleNodeDown: %s:%d\n", ip.String(), port)
  224. }
  225. host := s.ring.getHost(ip)
  226. if host == nil {
  227. host = &HostInfo{peer: ip, port: port}
  228. }
  229. if s.cfg.HostFilter != nil && !s.cfg.HostFilter.Accept(host) {
  230. return
  231. }
  232. host.setState(NodeDown)
  233. s.policy.HostDown(host)
  234. s.pool.hostDown(ip)
  235. }