class Telegraf::Agent

Constants

DEFAULT_CONNECTION

Attributes

logger[R]
tags[R]
uri[R]

Public Class Methods

new(uri = nil, logger: nil, tags: {}) click to toggle source
# File lib/telegraf/agent.rb, line 9
def initialize(uri = nil, logger: nil, tags: {})
  @uri = URI.parse(uri || DEFAULT_CONNECTION)
  @tags = tags
  @logger = logger
end

Public Instance Methods

write(*args, **kwargs) click to toggle source
# File lib/telegraf/agent.rb, line 15
def write(*args, **kwargs)
  write!(*args, **kwargs)
rescue StandardError => e
  logger&.error('telegraf') do
    e.to_s + e.backtrace.join("\n")
  end
end
write!(data, series: nil, tags: nil, values: nil) click to toggle source
# File lib/telegraf/agent.rb, line 23
def write!(data, series: nil, tags: nil, values: nil)
  tags = tags.merge(@tags) unless @tags.empty?

  if values
    data = [{series: series || data.to_s, tags: tags, values: values}]
  end

  socket = connect @uri
  socket.write dump data
ensure
  socket&.close
end

Private Instance Methods

connect(uri) click to toggle source
# File lib/telegraf/agent.rb, line 44
def connect(uri)
  case uri.scheme.downcase
    when 'unix'
      Socket.new(:UNIX, :STREAM).tap do |socket|
        socket.connect(Socket.pack_sockaddr_un(uri.path))
      end
    when 'unixgram'
      Socket.new(:UNIX, :DGRAM).tap do |socket|
        socket.connect(Socket.pack_sockaddr_un(uri.path))
      end
    when 'tcp', 'tcp4', 'tcp6'
      TCPSocket.new uri.host, uri.port
    when 'udp', 'udp4', 'udp6'
      UDPSocket.new.tap do |socket|
        socket.connect uri.host, uri.port
      end
    else
      raise "Unknown connection type: #{uri.scheme}"
  end
end
dump(data) click to toggle source
# File lib/telegraf/agent.rb, line 38
def dump(data)
  data.each.map do |point|
    ::InfluxDB::PointValue.new(point).dump
  end.join("\n")
end