summaryrefslogtreecommitdiff
path: root/up.rb
blob: cf4d07b36650999e3e994242538d4c1f4db9dcf1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#!/usr/bin/env ruby

require "net/http"
require "net/ping"
require "socket"

class Host
  def initialize s
    parts = s.split
    @hostname = parts.first
    @services_and_ports = {}
    @sites = []
    parts.slice(1, parts.size).each { |part|
      if part[0] == "@"
        url = part.slice 1, part.size
        @sites << url
      else
        service, port_and_protocol = part.split ":"
        port, protocol = port_and_protocol.split "/"
        @services_and_ports["#{service}/#{protocol}"] = [port.to_i, protocol]
      end
    }
  end

  def hostname
    return @hostname
  end

  def up? hostname
    ping = Net::Ping::External.new @hostname
    ping.ping?
  end

  def service_up? service, port, protocol
    if protocol == "tcp"
      begin
        sock = TCPSocket.new @hostname, port
        sock.close
        return true
      rescue
        return false
      end
    elsif protocol == "udp"
      system "nc -u -z -w 1 #{@hostname} #{port} &>/dev/null"
      return $?.success?
    else
      STDERR.write "unknown protocol '#{protocol}'\n"
    end
    return false
  end

  def site_up? site
    begin
      url = URI site
      response = Net::HTTP.get_response url
      puts response.code
      return [200, 301, 401].include? response.code.to_i
    rescue
      return false
    end
  end

  def check
    ret = {}
    ret["up"] = up? @hostname
    return ret if not ret["up"]
    @services_and_ports.each_key { |k|
      ret[k] = service_up? k, @services_and_ports[k][0], @services_and_ports[k][1]
    }
    @sites.each { |url|
      ret[url] = site_up? url
    }
    return ret
  end
end

def main
  while line = STDIN.gets
    h = Host.new line
    puts h.check.to_s
  end
end

if __FILE__ == $0
  main
end