detector.rb 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. require 'faye/websocket'
  2. require 'eventmachine'
  3. require 'psych'
  4. class FlappingDetector
  5. def initialize ws_addr, threshold = 10
  6. @ws_addr = ws_addr
  7. @flapping = {}
  8. @flapping.default = 0
  9. @threshold = threshold
  10. end
  11. def run
  12. EM.run do
  13. ws = Faye::WebSocket::Client.new(@ws_addr)
  14. register_open_handler ws
  15. register_message_handler ws
  16. register_close_handler ws
  17. end
  18. end
  19. private
  20. def check_for_flapping
  21. time_waited = Time.now - @start
  22. puts "Checking for flapping... #{time_waited} seconds since the connection was established."
  23. @flapping.each_pair do |prefix, count|
  24. if count > ((time_waited.to_i / 60) + 1) * @threshold
  25. puts "#{prefix} is flapping. I reveived #{count} updates for it."
  26. end
  27. end
  28. end
  29. def register_open_handler ws
  30. ws.on :open do
  31. puts 'Connection established.'
  32. @start = Time.now
  33. Thread.new do
  34. puts "Threshold is #{@threshold} updates per minute."
  35. loop do
  36. check_for_flapping
  37. puts 'Waiting...'
  38. sleep 1
  39. end
  40. end
  41. end
  42. end
  43. def register_message_handler ws
  44. ws.on :message do |event|
  45. data = Psych.safe_load event.data
  46. case data['table']
  47. when 'route'
  48. @flapping[data['data']['prefix']] += 1
  49. when 'neighbour'
  50. @flapping[data['data']['if']] += 1
  51. end
  52. end
  53. end
  54. def register_close_handler ws
  55. ws.on :close do |event|
  56. ws = nil
  57. puts "Connection closed. Code: #{event.code}; Reason: #{event.reason}"
  58. end
  59. end
  60. end