class Dogapi::APIService

Superclass that deals with the details of communicating with the DataDog API

Public Class Methods

new(api_key, application_key, silent=true, timeout=nil) click to toggle source
# File lib/dogapi/common.rb, line 72
def initialize(api_key, application_key, silent=true, timeout=nil)
  @api_key = api_key
  @application_key = application_key
  @api_host = Dogapi.find_datadog_host()
  @silent = silent
  @timeout = timeout || 5
end

Public Instance Methods

connect() { |conn| ... } click to toggle source

Manages the HTTP connection

# File lib/dogapi/common.rb, line 81
def connect
  connection = Net::HTTP

  # After ruby 2.0 Net::HTTP looks for the env variable but not ruby 1.9
  if RUBY_VERSION < "2.0.0"
    proxy = ENV["HTTPS_PROXY"] || ENV["https_proxy"] || ENV["HTTP_PROXY"] || ENV["http_proxy"]
    if proxy
      proxy_uri = URI.parse(proxy)
      connection = Net::HTTP::Proxy(proxy_uri.host, proxy_uri.port, proxy_uri.user, proxy_uri.password)
    end
  end

  uri = URI.parse(@api_host)
  session = connection.new(uri.host, uri.port)
  session.open_timeout = @timeout
  session.use_ssl = uri.scheme == 'https'
  session.start do |conn|
    conn.read_timeout = @timeout
    yield(conn)
  end
end
request(method, url, params, body, send_json) click to toggle source

Prepares the request and handles the response

method is an implementation of Net::HTTP::Request (e.g. Net::HTTP::Post)

params is a Hash that will be converted to request parameters

# File lib/dogapi/common.rb, line 117
def request(method, url, params, body, send_json)
  resp_obj = nil
  resp = nil
  connect do |conn|
    if params and params.size > 0
      qs_params = params.map { |k, v| k.to_s + "=" + v.to_s }
      qs = "?" + qs_params.join("&")
      url = url + qs
    end

    req = method.new(url)

    if send_json
      req.content_type = 'application/json'
      req.body = MultiJson.dump(body)
    end

    resp = conn.request(req)
    resp_str = resp.body

    if resp.code != 204 and resp.body != '' and resp.body != 'null' and resp.body != nil
      begin
        resp_obj = MultiJson.load(resp.body)
      rescue
        raise 'Invalid JSON Response: ' + resp.body
      end
    else
      resp_obj = {}
    end
  end
  return resp.code, resp_obj
end
suppress_error_if_silent(e) click to toggle source
# File lib/dogapi/common.rb, line 103
def suppress_error_if_silent(e)
  if @silent
    warn e
    return -1, {}
  else
    raise e
  end
end