Sha256: c7c1c51cfd76ab0ef19876538faa0af6d7c7e5e4de6ed93fd584d70a382d1902

Contents?: true

Size: 1.04 KB

Versions: 3

Compression:

Stored size: 1.04 KB

Contents

module LitmusPaper
  module Metric
    class InternetHealth
      def initialize(weight, hosts, options = {})
        @weight = weight
        @hosts = hosts
        @options = options
        @timeout = options.fetch(:timeout_seconds, 5)
      end

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

      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

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

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
litmus_paper-0.9.5 lib/litmus_paper/metric/internet_health.rb
litmus_paper-0.9.4 lib/litmus_paper/metric/internet_health.rb
litmus_paper-0.9.3 lib/litmus_paper/metric/internet_health.rb