diff --git a/lib/haproxy.rb b/lib/haproxy.rb index 7a1d4b9..d691b50 100644 --- a/lib/haproxy.rb +++ b/lib/haproxy.rb @@ -8,13 +8,20 @@ module HAProxy - def self.read_stats(from) - uri = URI.parse(from) + def self.read_stats(*from) + if from.length == 1 + from = from[0] + uri = URI.parse(from) - if uri.is_a?(URI::Generic) and File.socket?(uri.path) - HAProxy::SocketReader.new(uri.path) + if uri.is_a?(URI::Generic) and File.socket?(uri.path) + HAProxy::SocketReader.new(uri.path) + else + raise NotImplementedError, "Invalid socket path provided." + end + elsif from.length == 2 + HAProxy::SocketReader.new(from[0], from[1]) else - raise NotImplementedError, "Currently only sockets are implemented" + raise NotImplementedError, "Only UNIX Sockets and host/port combinations are supported" end end diff --git a/lib/haproxy/socket_reader.rb b/lib/haproxy/socket_reader.rb index 51776e7..f69d6bc 100644 --- a/lib/haproxy/socket_reader.rb +++ b/lib/haproxy/socket_reader.rb @@ -5,9 +5,15 @@ module HAProxy class SocketReader < HAProxy::StatsReader - def initialize(path) - raise ArgumentError, "Socket #{path} doesn't exists or is not a UNIX socket" unless File.exists?(path) and File.socket?(path) - @path = path + def initialize(*args) + if args.length == 1 + path = args[0] + raise ArgumentError, "Socket #{path} doesn't exists or is not a UNIX socket" unless File.exists?(path) and File.socket?(path) + @path = path + elsif args.length == 2 + @host = args[0] + @port = args[1] + end end def info @@ -92,12 +98,19 @@ def servers protected def send_cmd(cmd, &block) - socket = UNIXSocket.new(@path) + if @path + socket = UNIXSocket.new(@path) + else + socket = TCPSocket.new(@host, @port) + end + socket.write(cmd + ';') socket.each do |line| next if line.chomp.empty? yield(line.strip) end + + socket.close unless @path end end