class Nagios::API::Interface

Attributes

base_url[RW]
password[RW]
use_cache[RW]
username[RW]

Public Class Methods

new(args = {}) click to toggle source
# File lib/nagios/api/interface.rb, line 11
def initialize(args = {})
  @base_url = args[:base_url]
  @username = args[:username]
  @password = args[:password]
  @use_cache = args[:use_cache]
end

Public Instance Methods

authentication_options() click to toggle source
# File lib/nagios/api/interface.rb, line 38
def authentication_options
  !username.nil? ? { username: username, password: password } : {}
end
memcached() click to toggle source
# File lib/nagios/api/interface.rb, line 26
def memcached
  @memcached ||= Memcached.new("localhost:11211")
end
post(path, params) click to toggle source
# File lib/nagios/api/interface.rb, line 42
def post(path, params)
  args = { url: base_url + path, headers: { 'Accept' => 'application/json', 'Content-Type' => 'application/json' } }
  args.merge!(authentication_options)
  result = CurbFu.post(args, params.to_json)

  if result.success?
    data = JSON.parse(result.body)
    
    if data['success']
      return data['content']
    else
      raise BackendAPIError, data['content']
    end
  else
    raise HTTPError, "Error communicating with API server: #{result.status}"
  end
end
query(path) click to toggle source
# File lib/nagios/api/interface.rb, line 18
def query(path)
  result = query_from_api(path)
  
  return result unless use_cache
  save_to_cache(path, result) if result
  result ||= query_from_cache(path)
end
query_from_api(path) click to toggle source
# File lib/nagios/api/interface.rb, line 60
def query_from_api(path)
  args = { url: base_url + path, headers: { Accept: 'application/json' } }
  args.merge!(authentication_options)
  result = CurbFu.get(args)

  if result.success?
    data = JSON.parse(result.body)
    
    if data['success']
      return data['content']
    else
      raise BackendAPIError
    end
  else
    raise HTTPError, "Error communicating with API server: #{result.status}"
  end
end
query_from_cache(path) click to toggle source
# File lib/nagios/api/interface.rb, line 34
def query_from_cache(path)
  memcached.get(path) rescue nil
end
save_to_cache(path, data) click to toggle source
# File lib/nagios/api/interface.rb, line 30
def save_to_cache(path, data)
  memcached.set path, data, 0
end