Class: TSD::Client

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

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Client

Returns a new instance of Client.



10
11
12
13
14
15
16
# File 'lib/tsd_client.rb', line 10

def initialize options = {}
  @options = {
    host:    '0.0.0.0',
    port:    4242,
    timeout: 120, # seconds
  }.merge options
end

Instance Method Details

#put(options) ⇒ Object



37
38
39
40
41
42
43
44
45
46
# File 'lib/tsd_client.rb', line 37

def put options
  Timeout::timeout @options[:timeout] do
    TCPSocket.open @options[:host], @options[:port] do |socket|
      socket.puts Format.put options

      response, _, _ = socket.recvmsg_nonblock rescue nil
      response.chomp if response
    end
  end
end

#query(options) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/tsd_client.rb', line 18

def query options
  response = Timeout::timeout @options[:timeout] do
    Net::HTTP.start @options[:host], @options[:port] do |http|
      http.request Net::HTTP::Get.new Format.query options
    end
  end

  if response.kind_of? Net::HTTPSuccess
    response.body.split("\n").map do |record|
      metric, timestamp, value, *tags = record.split "\s"

      Hash[[:metric, :time, :value, :tags].zip([
        metric, Time.at(timestamp.to_i), value.to_f, Hash[tags.map {|tag| tag.split('=')}]])]
    end
  else
    raise 'query failed: ' + response.code
  end
end