class ZenossApi::Client

Public Class Methods

new(url, username, password, verify_ssl = true) click to toggle source
# File lib/zenoss_api.rb, line 89
def initialize(url, username, password, verify_ssl = true)
  @url = url
  @auth = {:username => username, :password => password}
  @rec_count = 1
  @headers = {
    'Content-Type' => 'application/json', 
    'Accept' => 'application/json',
  }
  @verify = verify_ssl
end

Public Instance Methods

_normalize_response(r) click to toggle source

_normalize_response @param [Hash] zenoss router response @return [Hash] normalized response

# File lib/zenoss_api.rb, line 126
def _normalize_response(r)
  data = {
    'action' => r['action'],
    'method' => r['method'],
  }
  result = r['result']
  begin
    data.merge!(result)
  rescue TypeError
    # zenoss returns inconsistent result types, this is not a hash
    type = ROUTER_RETURN_TYPE[data['action']]
    data[type] = result
    data['totalCount'] = result.length
    data['success'] = true
  end 
  data
end
_paginated_post(url, payload, xoffset=0) click to toggle source
# File lib/zenoss_api.rb, line 100
def _paginated_post(url, payload, xoffset=0)
  Enumerator.new do |y|
    total = 0
    offset = 0
    key = ROUTER_RETURN_KEYS[payload[0]['action']]
    limit = payload[0]['data'][0]['limit']
    loop do
      response = self._post(url, payload.to_json)
      totalCount = response['totalCount']
      data = response[key]
      total += data.length
      offset += limit
      payload[0]['data'][0]['start'] = offset
      
      data.each do |element|
        y.yield element
      end

      break if (data.empty? || total >= totalCount)
    end
  end
end
_post(url, payload) click to toggle source

http post to api

@param [String] url of api endpoint @param [String] json data @return [Hash] result of api query

# File lib/zenoss_api.rb, line 149
def _post(url, payload) 
 #### TODO wrap in rescue and handle exceptions
 response = HTTParty.post(url,
   {
     :body => payload,
     :basic_auth => @auth,
     :headers => @headers,
     :timeout => 300,
     :verify => @verify,
   }) 
 if response.code == 200
   _normalize_response(response)
 else 
   raise ({ code: response.code, response: response }).to_json
 end
end
_validateUid(u, type) click to toggle source
# File lib/zenoss_api.rb, line 206
def _validateUid(u, type)
  if u.match(/^\/zport\/dmd\/.*$/)
    u 
  else 
    response = self.getDeviceProperties(u, [ "uid" ])
    if not response.nil?
      response[type][0]['uid']
    else 
      nil
    end
  end
end
getDeviceProperties(device, properties=['uid']) click to toggle source

get device properties

@param device [String] the name of the device (device title or id) @param properties [Array] properties to be returned; default uid @return [Hash] of device properties or nil if device not found

# File lib/zenoss_api.rb, line 236
def getDeviceProperties(device, properties=['uid'])
  data = { 'keys' => properties, 'params' => { 'name' => device }, }
  result = self.router("DeviceRouter", "getDevices", data)
  if result['success'] == true and result['totalCount'] == 1
    result
  else
    nil
  end
end
getDeviceUidByName(device) click to toggle source
# File lib/zenoss_api.rb, line 219
def getDeviceUidByName(device)
end
getDevicesInDeviceClass(device_class='/zport/dmd/Devices', keys=['uid'], limit=nil) click to toggle source

get a list of devices under a device class

@param device_class [String] device class to search @return [hash]

# File lib/zenoss_api.rb, line 280
def getDevicesInDeviceClass(device_class='/zport/dmd/Devices', keys=['uid'], limit=nil)
  data = { 'uid' => device_class, 'keys' => keys, 'limit' => limit }
  result = self.router('DeviceRouter', 'getDevices', data)
end
getResultHash(result) click to toggle source

helper method to extract hash from a router query

@param result [Hash] response from router request @return [String] device uid

# File lib/zenoss_api.rb, line 258
def getResultHash(result)
  result['hash']
end
getResultUid(result) click to toggle source

helper method to extract uid from a router device query

@param result [Hash] response from router request @return [String] device uid

# File lib/zenoss_api.rb, line 250
def getResultUid(result)
  result['devices'][0]['uid']
end
router(router, method, data={}, options={}) click to toggle source

api endpoint router method

@param router [String] name of the zenoss api router @param method [String] name of the zenoss api method @param data [hash] api method arguments @param options [Hash] api execution control options @return [Hash] result of api query

# File lib/zenoss_api.rb, line 173
def router(router, method, data={}, options={})
  if data.empty? 
    _data = []
  else 
    _data = [ data ]
  end

  raise "Error: #{router} is not a valid route." unless ROUTERS.key?(router.to_sym)

  api_call = "#{@url}/zport/dmd/#{ROUTERS[router.to_sym]}_router"
  payload = [{ 
    'action' => router,
    'method' => method,
    'data' => _data,
    'type' => 'rpc',
    'tid' => @rec_count
  }]

   if options[:paginate]  
     self._paginated_post(api_call, payload)
   else 
     self._post(api_call, payload.to_json) 
   end
end
setDeviceLocation(uids, location) click to toggle source

set device location

@param uids [Array] list of device uids

# File lib/zenoss_api.rb, line 225
def setDeviceLocation(uids, location)
  validated = self.validateUids(uids)
  data = { 'uids' => uids, 'ranges' => [], 'target' => location }
  response = self.router("DeviceRouter", "moveDevices", data)
end
setProductionState(device, state = PRODUCTION_STATE[:production]) click to toggle source

sets the production state on a device

@param device [String] the name of the device (device title or id) @param state [Int] production state to set

# File lib/zenoss_api.rb, line 266
def setProductionState(device, state = PRODUCTION_STATE[:production])
  result = self.getDeviceProperties(device, ["uid"])
  data = { 
    'uids' => [ self.getResultUid(result) ],
    'hashcheck' => self.getResultHash(result),
    'prodState' => state,
  }
  self.router("DeviceRouter", "setProductionState", data)
end
validateUids(uids, type="devices") click to toggle source
# File lib/zenoss_api.rb, line 198
def validateUids(uids, type="devices")
  if uids.kind_of?(Array)
    uids.collect { |x| self._validateUid(x, type) }
  else 
    [ self._validateUid(uids, type) ]
  end 
end