Class: Graphiterb::Sender

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

Instance Method Summary collapse

Constructor Details

#initializeSender

Returns a new instance of Sender.



3
4
5
# File 'lib/graphiterb/sender.rb', line 3

def initialize
  open!
end

Instance Method Details

#open!Object



7
8
9
10
11
12
13
14
15
# File 'lib/graphiterb/sender.rb', line 7

def open!
  begin
    Graphiterb.log.warn "Connecting to server #{Settings.carbon_server} port #{Settings.carbon_port}"
    @socket = TCPSocket.new(Settings.carbon_server, Settings.carbon_port)
  rescue StandardError => e
    Graphiterb.log.warn "Couldn't connect to server #{Settings.carbon_server} port #{Settings.carbon_port}: #{e.class} #{e}"
    $stderr
  end
end

#safely(&block) ⇒ Object



21
22
23
24
25
26
27
28
29
30
# File 'lib/graphiterb/sender.rb', line 21

def safely &block
  begin
    block.call
  rescue StandardError => e
    Graphiterb.log.warn "Sleeping #{Settings.on_error_delay}: #{e.class} #{e}"
    sleep Settings.on_error_delay
    @socket = nil
    return nil
  end
end

#send(*metrics) ⇒ Object



36
37
38
39
40
41
42
43
44
# File 'lib/graphiterb/sender.rb', line 36

def send *metrics
  return if metrics.blank?
  now = timestamp
  safely do
    message = metrics.map{|metric, val, ts| [metric, val, (ts||now)].join(" ") }.join("\n")+"\n"
    socket.puts(message)
    Graphiterb.log.info message.gsub(/\n+/, "\t")
  end
end

#socketObject



17
18
19
# File 'lib/graphiterb/sender.rb', line 17

def socket
  @socket ||= open!
end

#timestampObject



32
33
34
# File 'lib/graphiterb/sender.rb', line 32

def timestamp
  Time.now.to_i
end