Class: TSD::Client

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ Client

Returns a new instance of Client.



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

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

Instance Attribute Details

#optionsObject (readonly)

Returns the value of attribute options.



10
11
12
# File 'lib/tsd_client.rb', line 10

def options
  @options
end

Instance Method Details

#put(options) ⇒ Object



41
42
43
44
45
46
47
# File 'lib/tsd_client.rb', line 41

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

#query(options) ⇒ Object



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

def query options
  response = nil

  Timeout::timeout @options[:timeout] do
    response = 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").collect 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.collect {|tag| tag.split('=')}]])]
    end
  else
    raise 'query failed: ' + response.code
  end
end