Class: LitmusPaper::Metric::InternetHealth

Inherits:
Object
  • Object
show all
Defined in:
lib/litmus_paper/metric/internet_health.rb

Instance Method Summary collapse

Constructor Details

#initialize(weight, hosts, options = {}) ⇒ InternetHealth

Returns a new instance of InternetHealth.



4
5
6
7
8
9
# File 'lib/litmus_paper/metric/internet_health.rb', line 4

def initialize(weight, hosts, options = {})
  @weight = weight
  @hosts = hosts
  @options = options
  @timeout = options.fetch(:timeout_seconds, 5) / @hosts.length.to_f
end

Instance Method Details

#current_healthObject



25
26
27
28
29
30
31
32
33
# File 'lib/litmus_paper/metric/internet_health.rb', line 25

def current_health
  health = @weight * @hosts.reduce(Rational(0)) do |memo, host|
    if tcp_connect?(*host.split(':'))
      memo += Rational(1) / Rational(@hosts.length)
    end
    memo
  end
  health.to_i
end

#statsObject



35
36
37
# File 'lib/litmus_paper/metric/internet_health.rb', line 35

def stats
  {}
end

#tcp_connect?(host, port) ⇒ Boolean

Returns:

  • (Boolean)


11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/litmus_paper/metric/internet_health.rb', line 11

def tcp_connect?(host, port)
  Timeout.timeout(@timeout) do
    socket = TCPSocket.new(host, port)
    socket.close
  end
  true
rescue Timeout::Error
  LitmusPaper.logger.info("Timed out connecting to #{host}:#{port} after #{@timeout}s")
  false
rescue => e
  LitmusPaper.logger.info("TCP connect to #{host}:#{port} failed with #{e.message}")
  false
end

#to_sObject



39
40
41
# File 'lib/litmus_paper/metric/internet_health.rb', line 39

def to_s
  "Metric::InternetHealth(#{@weight}, #{@hosts.inspect}, #{@options.inspect})"
end