class Fluent::MetricSenseOutput::Backends::LibratoBackend

Constants

METRIC_INITIALIZE_REQUEST_PER_MODE

Public Class Methods

new() click to toggle source
Calls superclass method
# File lib/fluent/plugin/backends/librato_backend.rb, line 31
def initialize
  super
  @initialized_metrics = {}
end

Public Instance Methods

ensure_metric_initialized(http, name, mode) click to toggle source
# File lib/fluent/plugin/backends/librato_backend.rb, line 122
def ensure_metric_initialized(http, name, mode)
  return if @initialized_metrics[name]

  header = {}
  req = Net::HTTP::Put.new("/v1/metrics/#{CGI.escape name}", header)
  req.basic_auth @librato_user, @librato_token

  log.trace { "librato initialize metric with mode #{mode}: #{name}" }
  req.body = METRIC_INITIALIZE_REQUEST_PER_MODE[mode]
  req.set_content_type("application/json")
  res = http.request(req)

  # TODO error handling
  if res.code !~ /20./
    log.warn "librato_metrics: #{res.code}: #{res.body}"
  else
    @initialized_metrics[name] = true
  end
end
write(data) click to toggle source
# File lib/fluent/plugin/backends/librato_backend.rb, line 36
def write(data)
  http = Net::HTTP.new('metrics-api.librato.com', 443)
  http.open_timeout = 60
  http.use_ssl = true
  http.verify_mode = OpenSSL::SSL::VERIFY_NONE  # FIXME verify
  #http.verify_mode = OpenSSL::SSL::VERIFY_PEER
  http.cert_store = OpenSSL::X509::Store.new
  header = {}

  begin
    # send upto 50 entries at once
    data.each_slice(@batch_size) {|slice|
      req = Net::HTTP::Post.new('/v1/metrics', header)
      req.basic_auth @librato_user, @librato_token

      data = []
      slice.each_with_index {|(tag,time,value,seg_key,seg_val,mode),i|
        if seg_key
          name = "#{tag}:#{seg_key}"
          source = seg_val
        else
          name = tag
          source = nil
        end
        h = {
          "name" => name,
          "measure_time" => time,
          "value" => value,
        }
        h["source"] = source.to_s if source
        data << h
        ensure_metric_initialized(http, name, mode)
      }
      body = {"gauges"=>data}.to_json

      log.trace { "librato metrics: #{data.inspect}" }
      req.body = body
      req.set_content_type("application/json")
      res = http.request(req)

      # TODO error handling
      if res.code != "200"
        log.warn "librato_metrics: #{res.code}: #{res.body}"
      end
    }

  ensure
    http.finish if http.started?
  end
end