module Tamber

Constants

DEFAULT_CA_BUNDLE_PATH
VERSION

Attributes

api_version[RW]
engine_key[RW]
open_timeout[RW]
project_key[RW]
read_timeout[RW]
verify_ssl_certs[RW]

Public Class Methods

api_url(api_base_url=nil, url='') click to toggle source
# File lib/tamber.rb, line 51
def self.api_url(api_base_url=nil, url='')
  (api_base_url || @api_url) + url
end
ca_bundle_path() click to toggle source
# File lib/tamber.rb, line 55
def self.ca_bundle_path
  @ca_bundle_path
end
ca_bundle_path=(path) click to toggle source
# File lib/tamber.rb, line 59
def self.ca_bundle_path=(path)
  @ca_bundle_path = path
end
execute_request(opts) click to toggle source
# File lib/tamber.rb, line 185
def self.execute_request(opts)
  RestClient::Request.execute(opts)
end
general_api_error(rbody) click to toggle source
# File lib/tamber.rb, line 149
def self.general_api_error(rbody)
  TamberError.new("Invalid response object from API: "+rbody.inspect)
end
handle_restclient_error(e, request_opts) click to toggle source
# File lib/tamber.rb, line 153
def self.handle_restclient_error(e, request_opts)
  case e
  when Errno::ECONNREFUSED
    message = "Could not connect to Tamber at #{api_url}. " \
    "Please check that your internet connection and DNS are working by running " \
    "'host tamber.com' from the command line and try again. " \
    "Still borked? Email us at support@tamber.com and we'll get to the bottom of it."

  when RestClient::RequestTimeout
    message = "Could not connect to Tamber at #{api_url}. " \
    "Please check your internet connection and try again. " \
    "Still borked? Email us at support@tamber.com and we'll get to the bottom of it."

  when RestClient::SSLCertificateNotVerified
    message = "Could not establish a secure connection to Tamber, you may " \
              "need to upgrade your OpenSSL version. To check, try running " \
              "'openssl s_client -connect api.tamber.com:443' from the " \
              "command line."

  when RestClient::ServerBrokeConnection
    message = "Connection was broken before the request could complete (either by " \
    "the Tamber server or a network failure)."

  else
    message = "Unexpected request error. If this problem persists, please let us know by " \
    "emailing us at support@tamber.com."

  end

  raise NetworkError.new(message + "\n\n(#{e.message})")
end
parse(response) click to toggle source
# File lib/tamber.rb, line 189
def self.parse(response)
  begin
    response = JSON.parse(response.body)
    if response["success"]
      response = response["result"]
    else
      raise TamberError.new(response["error"])
    end
  rescue JSON::ParserError
    raise general_api_error(response.body)
  end
  Util.symbolize_names(response)
end
request(method, url, params={}) click to toggle source
# File lib/tamber.rb, line 63
def self.request(method, url, params={})

  if project_key =~ /\s/
    raise TamberError.new('Your project key is invalid, as it contains ' \
                          'whitespace. (HINT: You can double-check your project key from the ' \
                          'Tamber dashboard. See https://dashboard.tamber.com to get your engine\'s key, or ' \
                          'email support@tamber.com if you have any questions.)')
  end

  if engine_key =~ /\s/
    raise TamberError.new('Your engine key is invalid, as it contains ' \
                          'whitespace. (HINT: You can double-check your project key from the ' \
                          'Tamber dashboard. See https://dashboard.tamber.com to get your engine\'s key, or ' \
                          'email support@tamber.com if you have any questions.)')
  end

  if verify_ssl_certs
    request_opts = {:verify_ssl => OpenSSL::SSL::VERIFY_PEER,
                    :ssl_ca_file => @ca_bundle_path}
  else
    request_opts = {:verify_ssl => false}
    unless @verify_ssl_warned
      @verify_ssl_warned = true
      $stderr.puts("WARNING: Running without SSL cert verification. " \
                   "You should never do this in production. " \
                   "Execute 'Tamber.verify_ssl_certs = true' to enable verification.")
    end
  end

  url = @api_url + url

  case method.to_s.downcase.to_sym
  when :get, :head, :delete
    # Make params into GET parameters
    url += "#{URI.parse(url).query ? '&' : '?'}#{Util.encode_parameters(params)}" if params && params.any?
    payload = nil
  else
    payload = Util.encode_parameters(params)
  end

  request_opts.update(:headers => request_headers(project_key, engine_key, method),
                      :method => method, :open_timeout => open_timeout,
                      :payload => payload, :url => url, :timeout => read_timeout)

  response = execute_request_with_rescues(request_opts)

  [parse(response)]
end
request_headers(pkey, ekey, method) click to toggle source
# File lib/tamber.rb, line 114
def self.request_headers(pkey, ekey, method)
  pkey ||= ''
  ekey ||= ''
  encoded_key  = Base64.encode64(pkey + ':' + ekey)
  headers = {
    :user_agent => "Tamber/v1 RubyBindings/#{Tamber::VERSION}",
    :authorization => "Basic "+encoded_key,
    :content_type => 'application/x-www-form-urlencoded'
  }

  headers[:tamber_version] = api_version if api_version

  begin
    headers.update(:x_tamber_client_user_agent => JSON.generate(user_agent))
  rescue => e
    headers.update(:x_tamber_client_raw_user_agent => user_agent.inspect,
                   :error => "#{e} (#{e.class})")
  end
end
user_agent() click to toggle source
# File lib/tamber.rb, line 134
def self.user_agent
  lang_version = "#{RUBY_VERSION} p#{RUBY_PATCHLEVEL} (#{RUBY_RELEASE_DATE})"

  {
    :bindings_version => Tamber::VERSION,
    :lang => 'ruby',
    :lang_version => lang_version,
    :platform => RUBY_PLATFORM,
    :engine => defined?(RUBY_ENGINE) ? RUBY_ENGINE : '',
    :publisher => 'tamber',
    :hostname => Socket.gethostname,
  }

end

Private Class Methods

execute_request_with_rescues(request_opts) click to toggle source
# File lib/tamber.rb, line 205
def self.execute_request_with_rescues(request_opts)
  # response = execute_request(request_opts)
  begin
    response = execute_request(request_opts)
  rescue SocketError => e
    response = handle_restclient_error(e, request_opts)
  rescue NoMethodError => e
    # Work around RestClient bug
    if e.message =~ /\WRequestFailed\W/
      raise TamberError.new('Unexpected HTTP response code')
    else
      raise
    end
  rescue RestClient::ExceptionWithResponse => e
    puts "ExceptionWithResponse: #{e}"
    if e.response
      puts "e.response"
      parse(e.response)
    else
      response = handle_restclient_error(e, request_opts)
    end
  rescue RestClient::Exception, Errno::ECONNREFUSED => e
    response = handle_restclient_error(e, request_opts)
  end

  response
end