class GraphiteAPI::Connector

Attributes

uri[R]

Public Class Methods

new(uri) click to toggle source
# File lib/graphite-api/connector.rb, line 8
def initialize uri
  @uri = URI.parse uri
  @uri = @uri.host ? @uri : URI.parse("udp://#{uri}")
  @socket = nil
end

Public Instance Methods

check!() click to toggle source

Manually init Socket, exception will be thrown on error

# File lib/graphite-api/connector.rb, line 30
def check!
  socket; nil
end
inspect() click to toggle source
# File lib/graphite-api/connector.rb, line 25
def inspect
  "#<#{self.class}:#{object_id}: #{@uri}>"
end
puts(message) click to toggle source
# File lib/graphite-api/connector.rb, line 14
def puts message
  counter = 0
  begin
    Logger.debug [:connector, :puts, @uri.to_s, message]
    socket.puts message + "\n"
  rescue Exception
    @socket = nil
    (counter += 1) <= 5 ? retry : raise
  end
end

Private Instance Methods

init_tcp() click to toggle source
# File lib/graphite-api/connector.rb, line 44
def init_tcp
  host, port = @uri.host, @uri.port
  timeout = Hash[URI.decode_www_form(@uri.query.to_s)].fetch("timeout", 1).to_f
  addr = Socket.getaddrinfo host, nil, :INET
  sockaddr = Socket.pack_sockaddr_in port, addr[0][3]

  sock = Socket.new(Socket.const_get(addr[0][0]), Socket::SOCK_STREAM, 0)
  sock.setsockopt Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1
  begin
    sock.connect_nonblock sockaddr
  rescue IO::WaitWritable
    if IO.select nil, [sock], nil, timeout
      begin
        sock.connect_nonblock sockaddr
      rescue Errno::EISCONN # success
      rescue
        sock.close
        raise
      end
    else
      sock.close
      raise "Connection timeout"
    end
  end
  sock
end
init_udp() click to toggle source
# File lib/graphite-api/connector.rb, line 71
def init_udp
  UDPSocket.new.tap {|x| x.connect @uri.host, @uri.port }
end
socket() click to toggle source
# File lib/graphite-api/connector.rb, line 36
def socket
  if @socket.nil? || @socket.closed?
    @socket = @uri.scheme.eql?("tcp") ? init_tcp : init_udp
  end

  @socket
end