events.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  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. frame, err := framer.parseFrame()
  70. if err != nil {
  71. // TODO: logger
  72. Logger.Printf("gocql: unable to parse event frame: %v\n", err)
  73. return
  74. }
  75. if gocqlDebug {
  76. Logger.Printf("gocql: handling frame: %v\n", frame)
  77. }
  78. switch f := frame.(type) {
  79. case *schemaChangeKeyspace, *schemaChangeFunction,
  80. *schemaChangeTable, *schemaChangeAggregate, *schemaChangeType:
  81. s.schemaEvents.debounce(frame)
  82. case *topologyChangeEventFrame, *statusChangeEventFrame:
  83. s.nodeEvents.debounce(frame)
  84. default:
  85. Logger.Printf("gocql: invalid event frame (%T): %v\n", f, f)
  86. }
  87. }
  88. func (s *Session) handleSchemaEvent(frames []frame) {
  89. // TODO: debounce events
  90. for _, frame := range frames {
  91. switch f := frame.(type) {
  92. case *schemaChangeKeyspace:
  93. s.schemaDescriber.clearSchema(f.keyspace)
  94. s.handleKeyspaceChange(f.keyspace, f.change)
  95. case *schemaChangeTable:
  96. s.schemaDescriber.clearSchema(f.keyspace)
  97. case *schemaChangeAggregate:
  98. s.schemaDescriber.clearSchema(f.keyspace)
  99. case *schemaChangeFunction:
  100. s.schemaDescriber.clearSchema(f.keyspace)
  101. case *schemaChangeType:
  102. s.schemaDescriber.clearSchema(f.keyspace)
  103. }
  104. }
  105. }
  106. func (s *Session) handleKeyspaceChange(keyspace, change string) {
  107. s.control.awaitSchemaAgreement()
  108. s.policy.KeyspaceChanged(KeyspaceUpdateEvent{Keyspace: keyspace, Change: change})
  109. }
  110. func (s *Session) handleNodeEvent(frames []frame) {
  111. type nodeEvent struct {
  112. change string
  113. host net.IP
  114. port int
  115. }
  116. events := make(map[string]*nodeEvent)
  117. for _, frame := range frames {
  118. // TODO: can we be sure the order of events in the buffer is correct?
  119. switch f := frame.(type) {
  120. case *topologyChangeEventFrame:
  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. case *statusChangeEventFrame:
  128. event, ok := events[f.host.String()]
  129. if !ok {
  130. event = &nodeEvent{change: f.change, host: f.host, port: f.port}
  131. events[f.host.String()] = event
  132. }
  133. event.change = f.change
  134. }
  135. }
  136. for _, f := range events {
  137. if gocqlDebug {
  138. Logger.Printf("gocql: dispatching event: %+v\n", f)
  139. }
  140. switch f.change {
  141. case "NEW_NODE":
  142. s.handleNewNode(f.host, f.port, true)
  143. case "REMOVED_NODE":
  144. s.handleRemovedNode(f.host, f.port)
  145. case "MOVED_NODE":
  146. // java-driver handles this, not mentioned in the spec
  147. // TODO(zariel): refresh token map
  148. case "UP":
  149. s.handleNodeUp(f.host, f.port, true)
  150. case "DOWN":
  151. s.handleNodeDown(f.host, f.port)
  152. }
  153. }
  154. }
  155. func (s *Session) addNewNode(host *HostInfo) {
  156. if s.cfg.filterHost(host) {
  157. return
  158. }
  159. host.setState(NodeUp)
  160. s.pool.addHost(host)
  161. s.policy.AddHost(host)
  162. }
  163. func (s *Session) handleNewNode(ip net.IP, port int, waitForBinary bool) {
  164. if gocqlDebug {
  165. Logger.Printf("gocql: Session.handleNewNode: %s:%d\n", ip.String(), port)
  166. }
  167. ip, port = s.cfg.translateAddressPort(ip, port)
  168. // Get host info and apply any filters to the host
  169. hostInfo, err := s.hostSource.getHostInfo(ip, port)
  170. if err != nil {
  171. Logger.Printf("gocql: events: unable to fetch host info for (%s:%d): %v\n", ip, port, err)
  172. return
  173. } else if hostInfo == nil {
  174. // If hostInfo is nil, this host was filtered out by cfg.HostFilter
  175. return
  176. }
  177. if t := hostInfo.Version().nodeUpDelay(); t > 0 && waitForBinary {
  178. time.Sleep(t)
  179. }
  180. // should this handle token moving?
  181. hostInfo = s.ring.addOrUpdate(hostInfo)
  182. s.addNewNode(hostInfo)
  183. if s.control != nil && !s.cfg.IgnorePeerAddr {
  184. // TODO(zariel): debounce ring refresh
  185. s.hostSource.refreshRing()
  186. }
  187. }
  188. func (s *Session) handleRemovedNode(ip net.IP, port int) {
  189. if gocqlDebug {
  190. Logger.Printf("gocql: Session.handleRemovedNode: %s:%d\n", ip.String(), port)
  191. }
  192. ip, port = s.cfg.translateAddressPort(ip, port)
  193. // we remove all nodes but only add ones which pass the filter
  194. host := s.ring.getHost(ip)
  195. if host == nil {
  196. host = &HostInfo{connectAddress: ip, port: port}
  197. }
  198. if s.cfg.HostFilter != nil && !s.cfg.HostFilter.Accept(host) {
  199. return
  200. }
  201. host.setState(NodeDown)
  202. s.policy.RemoveHost(host)
  203. s.pool.removeHost(ip)
  204. s.ring.removeHost(ip)
  205. if !s.cfg.IgnorePeerAddr {
  206. s.hostSource.refreshRing()
  207. }
  208. }
  209. func (s *Session) handleNodeUp(eventIp net.IP, eventPort int, waitForBinary bool) {
  210. if gocqlDebug {
  211. Logger.Printf("gocql: Session.handleNodeUp: %s:%d\n", eventIp.String(), eventPort)
  212. }
  213. ip, _ := s.cfg.translateAddressPort(eventIp, eventPort)
  214. host := s.ring.getHost(ip)
  215. if host == nil {
  216. // TODO(zariel): avoid the need to translate twice in this
  217. // case
  218. s.handleNewNode(eventIp, eventPort, waitForBinary)
  219. return
  220. }
  221. if s.cfg.HostFilter != nil && !s.cfg.HostFilter.Accept(host) {
  222. return
  223. }
  224. if t := host.Version().nodeUpDelay(); t > 0 && waitForBinary {
  225. time.Sleep(t)
  226. }
  227. s.addNewNode(host)
  228. }
  229. func (s *Session) handleNodeDown(ip net.IP, port int) {
  230. if gocqlDebug {
  231. Logger.Printf("gocql: Session.handleNodeDown: %s:%d\n", ip.String(), port)
  232. }
  233. host := s.ring.getHost(ip)
  234. if host == nil {
  235. host = &HostInfo{connectAddress: ip, port: port}
  236. }
  237. if s.cfg.HostFilter != nil && !s.cfg.HostFilter.Accept(host) {
  238. return
  239. }
  240. host.setState(NodeDown)
  241. s.policy.HostDown(host)
  242. s.pool.hostDown(ip)
  243. }