events.go 5.9 KB

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