Class: Rdeadman::HostMonitor

Inherits:
Object
  • Object
show all
Defined in:
lib/rdeadman/monitor.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(host, interval = 5) ⇒ HostMonitor

Returns a new instance of HostMonitor.



11
12
13
14
15
16
17
18
# File 'lib/rdeadman/monitor.rb', line 11

def initialize(host, interval = 5)
  @host = host
  @address = resolve_address(host)
  @interval = interval
  @results = []
  @sent_packets = 0
  @lost_packets = 0
end

Instance Attribute Details

#addressObject (readonly)

Returns the value of attribute address.



9
10
11
# File 'lib/rdeadman/monitor.rb', line 9

def address
  @address
end

#hostObject (readonly)

Returns the value of attribute host.



9
10
11
# File 'lib/rdeadman/monitor.rb', line 9

def host
  @host
end

#intervalObject (readonly)

Returns the value of attribute interval.



9
10
11
# File 'lib/rdeadman/monitor.rb', line 9

def interval
  @interval
end

#lost_packetsObject (readonly)

Returns the value of attribute lost_packets.



9
10
11
# File 'lib/rdeadman/monitor.rb', line 9

def lost_packets
  @lost_packets
end

#resultsObject (readonly)

Returns the value of attribute results.



9
10
11
# File 'lib/rdeadman/monitor.rb', line 9

def results
  @results
end

#sent_packetsObject (readonly)

Returns the value of attribute sent_packets.



9
10
11
# File 'lib/rdeadman/monitor.rb', line 9

def sent_packets
  @sent_packets
end

Instance Method Details

#avg_rttObject



46
47
48
49
# File 'lib/rdeadman/monitor.rb', line 46

def avg_rtt
  avg = @results.select { |r| r.is_a?(Numeric) }.sum.to_f / @results.size
  avg.nan? ? 0 : avg.round(2)
end

#loss_rateObject



42
43
44
# File 'lib/rdeadman/monitor.rb', line 42

def loss_rate
  (@lost_packets.to_f / @sent_packets * 100).round(2)
end

#monitorObject



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/rdeadman/monitor.rb', line 26

def monitor
  pinger = Net::Ping::External.new(@host)
  loop do
    @sent_packets += 1
    if pinger.ping
      rtt = (pinger.duration * 1000).round(2) # msに変換
      @results << rtt
    else
      @lost_packets += 1
      @results << "X"
    end
    yield self if block_given?
    sleep @interval
  end
end

#resolve_address(host) ⇒ Object



20
21
22
23
24
# File 'lib/rdeadman/monitor.rb', line 20

def resolve_address(host)
  IPSocket.getaddress(host)
rescue SocketError
  "Unknown"
end

#result_graphObject



51
52
53
# File 'lib/rdeadman/monitor.rb', line 51

def result_graph
  @results.map { |r| r.is_a?(Numeric) ? "" : "X" }.join
end