Class: ZenossApi::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/zenoss_api.rb

Instance Method Summary collapse

Constructor Details

#initialize(url, username, password, verify_ssl = true) ⇒ Client

Returns a new instance of Client.



89
90
91
92
93
94
95
96
97
98
# 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

Instance Method Details

#_normalize_response(r) ⇒ Hash

_normalize_response

Parameters:

  • zenoss (Hash)

    router response

Returns:

  • (Hash)

    normalized response



126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
# 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) ⇒ Object



100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
# 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) ⇒ Hash

http post to api

Parameters:

  • url (String)

    of api endpoint

  • json (String)

    data

Returns:

  • (Hash)

    result of api query



149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
# 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) ⇒ Object



206
207
208
209
210
211
212
213
214
215
216
217
# 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']) ⇒ Hash

get device properties

Parameters:

  • device (String)

    the name of the device (device title or id)

  • properties (Array) (defaults to: ['uid'])

    properties to be returned; default uid

Returns:

  • (Hash)

    of device properties or nil if device not found



236
237
238
239
240
241
242
243
244
# 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

#getDevicesInDeviceClass(device_class = '/zport/dmd/Devices', keys = ['uid'], limit = nil) ⇒ hash

get a list of devices under a device class

Parameters:

  • device_class (String) (defaults to: '/zport/dmd/Devices')

    device class to search

Returns:

  • (hash)


280
281
282
283
# 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

#getDeviceUidByName(device) ⇒ Object



219
220
# File 'lib/zenoss_api.rb', line 219

def getDeviceUidByName(device)
end

#getResultHash(result) ⇒ String

helper method to extract hash from a router query

Parameters:

  • result (Hash)

    response from router request

Returns:

  • (String)

    device uid



258
259
260
# File 'lib/zenoss_api.rb', line 258

def getResultHash(result)
  result['hash']
end

#getResultUid(result) ⇒ String

helper method to extract uid from a router device query

Parameters:

  • result (Hash)

    response from router request

Returns:

  • (String)

    device uid



250
251
252
# File 'lib/zenoss_api.rb', line 250

def getResultUid(result)
  result['devices'][0]['uid']
end

#router(router, method, data = {}, options = {}) ⇒ Hash

api endpoint router method

Parameters:

  • router (String)

    name of the zenoss api router

  • method (String)

    name of the zenoss api method

  • data (hash) (defaults to: {})

    api method arguments

  • options (Hash) (defaults to: {})

    api execution control options

Returns:

  • (Hash)

    result of api query



173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
# 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) ⇒ Object

set device location

Parameters:

  • uids (Array)

    list of device uids



225
226
227
228
229
# 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 = ) ⇒ Object

sets the production state on a device

Parameters:

  • device (String)

    the name of the device (device title or id)

  • state (Int) (defaults to: )

    production state to set



266
267
268
269
270
271
272
273
274
# 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") ⇒ Object



198
199
200
201
202
203
204
# 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