123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172 |
- require 'faye/websocket'
- require 'eventmachine'
- require 'psych'
- class FlappingDetector
- def initialize ws_addr, threshold = 10
- @ws_addr = ws_addr
- @flapping = {}
- @flapping.default = 0
- @threshold = threshold
- end
- def run
- EM.run do
- ws = Faye::WebSocket::Client.new(@ws_addr)
- register_open_handler ws
- register_message_handler ws
- register_close_handler ws
- end
- end
- private
- def check_for_flapping
- time_waited = Time.now - @start
- puts "Checking for flapping... #{time_waited} seconds since the connection was established."
- @flapping.each_pair do |prefix, count|
- if count > ((time_waited.to_i / 60) + 1) * @threshold
- puts "#{prefix} is flapping. I reveived #{count} updates for it."
- end
- end
- end
- def register_open_handler ws
- ws.on :open do
- puts 'Connection established.'
- @start = Time.now
- Thread.new do
- puts "Threshold is #{@threshold} updates per minute."
- loop do
- check_for_flapping
- puts 'Waiting...'
- sleep 1
- end
- end
- end
- end
- def register_message_handler ws
- ws.on :message do |event|
- data = Psych.safe_load event.data
- case data['table']
- when 'route'
- @flapping[data['data']['prefix']] += 1
- when 'neighbour'
- @flapping[data['data']['if']] += 1
- end
- end
- end
- def register_close_handler ws
- ws.on :close do |event|
- ws = nil
- puts "Connection closed. Code: #{event.code}; Reason: #{event.reason}"
- end
- end
- end
|