Class: LMRest::APIClient
- Inherits:
-
Object
- Object
- LMRest::APIClient
- Includes:
- RequestParams
- Defined in:
- lib/lm_rest/api_client.rb
Constant Summary collapse
- ITEMS_SIZE_LIMIT =
1000- ITEMS_SIZE_DEFAULT =
50- BASE_URL_PREFIX =
'https://'- BASE_URL_SUFFIX =
'.logicmonitor.com/santaba/rest'
Instance Attribute Summary collapse
-
#access_id ⇒ Object
readonly
Returns the value of attribute access_id.
-
#api_url ⇒ Object
readonly
Returns the value of attribute api_url.
-
#company ⇒ Object
readonly
Returns the value of attribute company.
Class Method Summary collapse
- .define_child_methods(resource_type, attributes) ⇒ Object
- .process_paths ⇒ Object
-
.setup ⇒ Object
Define methods based on the JSON structure.
Instance Method Summary collapse
-
#ack_collector_down(id, comment) ⇒ Object
Ack a down collector, pass the ID and a comment.
-
#initialize(company = nil, access_id = nil, access_key = nil) ⇒ APIClient
constructor
A new instance of APIClient.
-
#paginate(uri, params) ⇒ Object
Handles making multiple requests to the API if pagination is necessary.
- #request(method, uri, params = {}) ⇒ Object
-
#run_report(id, type = "generateReport") ⇒ Object
run a report.
- #sign(method, uri, data = nil) ⇒ Object
- #snakerize(string) ⇒ Object
- #uri_to_resource_uri(uri) ⇒ Object
Methods included from RequestParams
Constructor Details
#initialize(company = nil, access_id = nil, access_key = nil) ⇒ APIClient
Returns a new instance of APIClient.
21 22 23 24 25 26 27 |
# File 'lib/lm_rest/api_client.rb', line 21 def initialize(company = nil, access_id = nil, access_key = nil) APIClient.setup @company = company @access_id = access_id @access_key = access_key @api_url = BASE_URL_PREFIX + company + BASE_URL_SUFFIX end |
Instance Attribute Details
#access_id ⇒ Object (readonly)
Returns the value of attribute access_id.
19 20 21 |
# File 'lib/lm_rest/api_client.rb', line 19 def access_id @access_id end |
#api_url ⇒ Object (readonly)
Returns the value of attribute api_url.
19 20 21 |
# File 'lib/lm_rest/api_client.rb', line 19 def api_url @api_url end |
#company ⇒ Object (readonly)
Returns the value of attribute company.
19 20 21 |
# File 'lib/lm_rest/api_client.rb', line 19 def company @company end |
Class Method Details
.define_child_methods(resource_type, attributes) ⇒ Object
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 |
# File 'lib/lm_rest/api_client.rb', line 259 def self.define_child_methods(resource_type, attributes) parent_singular = attributes['method_names']['singular'] parent_plural = attributes['method_names']['plural'] parent_resource_uri = attributes['url'] parent_id = attributes['parent_id_key'] children = attributes['children'] children.each do |child_name| if @@api_json[child_name] child = @@api_json[child_name] else raise "Child resource " + child_name + " not defined." end child_singular = child['method_names']['singular'] child_plural = child['method_names']['plural'] child_resource_uri = attributes['url'].split("/").last child['actions'].each do |action| case action when 'get' define_method("get_#{parent_singular}_#{child_plural}") do |id, params = {}, &block| uri = lambda { |params| "#{parent_resource_uri}/#{id}/#{child['method_names']['plural']}#{RequestParams.parameterize(params)}" } Resource.parse paginate(uri, params) end when 'add' when 'update' when 'delete' end end end end |
.process_paths ⇒ Object
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 |
# File 'lib/lm_rest/api_client.rb', line 183 def self.process_paths resource_uri = attributes['url'] @@api_json[paths].keys.each do |path| path.keys.each do |action| case action when 'get' uri = lambda { |params| "#{resource_uri}#{RequestParams.parameterize(params)}"} method_name = snakerize(@@api_json['paths'][path][action][operationId]) unless plural.nil? # Define a method to fetch multiple resources with optional params define_method("get_#{plural}") do |params = {}| Resource.parse paginate(uri, params) end end # Define a method to get one resource by it's id number, with optional # params, thought now that I think about it I'm not sure why you'd pass # params when grabbing just one resource. # Some resources are Singletons unless singular.nil? define_method("get_#{singular}") do |*args| case args.size when 0 Resource.parse request(:get, "#{resource_uri}", nil) when 1 Resource.parse request(:get, "#{resource_uri}/#{args[0]}", nil) when 2 Resource.parse request(:get, "#{resource_uri}/#{args[0]}#{RequestParams.parameterize(args[1])}", nil) else raise ArgumentError.new("wrong number for arguments (#{args.count} for 1..2)") end end end when 'add' # Define a method to add a new resource to the account define_method("add_#{singular}") do |properties| if properties.class == LMRest::Resource Resource.parse request(:post, "#{resource_uri}", properties.to_h) else Resource.parse request(:post, "#{resource_uri}", properties) end end when 'update' # Define a method to update a resource define_method("update_#{singular}") do |id, properties = {}| if id.class == LMRest::Resource Resource.parse request(:put, "#{resource_uri}/#{id.id}", id.to_h) else Resource.parse request(:put, "#{resource_uri}/#{id}", properties) end end when 'delete' # Define a method to delete the resource define_method("delete_#{singular}") do |id| if id.class == LMRest::Resource id = id.id Resource.parse request(:delete, "#{resource_uri}/#{id}", nil) else Resource.parse request(:delete, "#{resource_uri}/#{id}", nil) end end end end end end |
.setup ⇒ Object
Define methods based on the JSON structure
295 296 297 298 299 300 301 302 |
# File 'lib/lm_rest/api_client.rb', line 295 def self.setup @@api_definition_path = File.(File.join(File.dirname(__FILE__), "../../api.json")) @@api_json = JSON.parse(File.read(@@api_definition_path)) @@api_json.each do |resource_type, attributes| define_action_methods(resource_type, attributes) if attributes['actions'] define_child_methods(resource_type, attributes) if attributes['children'] end end |
Instance Method Details
#ack_collector_down(id, comment) ⇒ Object
Ack a down collector, pass the ID and a comment
305 306 307 308 309 310 311 |
# File 'lib/lm_rest/api_client.rb', line 305 def ack_collector_down(id, comment) if id.class == LMRest::Resource Resource.parse request(:post, "/setting/collectors/#{id.id}/ackdown", {comment: comment}) else Resource.parse request(:post, "/setting/collectors/#{id}/ackdown", {comment: comment}) end end |
#paginate(uri, params) ⇒ Object
Handles making multiple requests to the API if pagination is necessary. Pagination is transparent, and simplifies requests that result in more than ITEMS_SIZE_LIMIT being returned.
If you need to walk through resources page-by-page manullay, use the request() method with the ‘offset’ and ‘size’ params
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 |
# File 'lib/lm_rest/api_client.rb', line 116 def paginate(uri, params) # Hooray for pagination logic! if (params[:size] == 0 || params[:size].nil? || params[:size] > ITEMS_SIZE_LIMIT) # save user-entered size in a param for use later user_size = params[:size] # set our size param to the max params[:size] = ITEMS_SIZE_LIMIT # Set our offset to grab the first page of results params[:offset] ||= 0 # make the initial request body = request(:get, uri.call(params), nil) # pull the actual items out of the request body and into our # item_collector while we build up the items list item_collector = body['items'] # The API sends the total number of objects back in the first request. # We need this to determine how many more pages to pull total = body['total'] # If user didn't pass size param, set it to total # This just means you'll get all items if not specifying a size user_size ||= total # If the user passed a size larger than what's available, set it to # total to retrieve all items if user_size > total user_size = total end # calculate the remaining number of items (after first request) # then use that to figure out how many more times we need to call # request() to get all the items, then do it pages_remaining = ((user_size - ITEMS_SIZE_LIMIT).to_f/ITEMS_SIZE_LIMIT).ceil pages_remaining.times do |page| # Increment the offset by the limit to get the next page params[:offset] += ITEMS_SIZE_LIMIT # if this is the last page, get the remainder if page == pages_remaining - 1 params[:size] = user_size%ITEMS_SIZE_LIMIT else # else, get a whole page params[:size] = ITEMS_SIZE_LIMIT end # make a subsequent request with modified params body = request(:get, uri.call(params), nil) # add these items to our item_collector item_collector += body['items'] end body['items'] = item_collector body else # No pagination required, just request the page request(:get, uri.call(params), nil) end end |
#request(method, uri, params = {}) ⇒ Object
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 |
# File 'lib/lm_rest/api_client.rb', line 76 def request(method, uri, params={}) headers = {} headers['Authorization'] = sign(method, uri, params) headers['Content-Type'] = 'application/json' headers['Accept'] = 'application/json, text/javascript' headers['X-version'] = '2' url = api_url + uri #puts "URL: " + url #puts headers json_params = params.to_json case method when :get response = RestClient.get(url, headers) when :post response = RestClient.post(url, json_params, headers) when :put response = RestClient.put(url, json_params, headers) when :delete response = RestClient.delete(url, headers: headers) end if response.code != 200 puts response.code.to_s + ":" + response.body.to_s raise end JSON.parse(response.body) end |
#run_report(id, type = "generateReport") ⇒ Object
run a report
314 315 316 317 318 319 320 |
# File 'lib/lm_rest/api_client.rb', line 314 def run_report(id, type = "generateReport") if id.class == LMRest::Resource Resource.parse request(:post, "/functions", {reportId: id.id, type: type}) else Resource.parse request(:post, "/functions", {reportId: id, type: type}) end end |
#sign(method, uri, data = nil) ⇒ Object
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
# File 'lib/lm_rest/api_client.rb', line 49 def sign(method, uri, data = nil) resource_uri = uri_to_resource_uri(uri) time = DateTime.now.strftime('%Q') http_method = method.to_s.upcase if data.nil? || data.empty? data = '' else data = data.to_json.to_s end = "#{http_method}#{time}#{data}#{resource_uri}" signature = Base64.strict_encode64( OpenSSL::HMAC.hexdigest( OpenSSL::Digest.new('sha256'), access_key, ) ) "LMv1 #{access_id}:#{signature}:#{time}" end |
#snakerize(string) ⇒ Object
41 42 43 44 45 46 47 |
# File 'lib/lm_rest/api_client.rb', line 41 def snakerize(string) string.gsub(/::/, '/'). gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2'). gsub(/([a-z\d])([A-Z])/,'\1_\2'). tr("-", "_"). downcase end |
#uri_to_resource_uri(uri) ⇒ Object
29 30 31 32 33 34 35 36 37 38 39 |
# File 'lib/lm_rest/api_client.rb', line 29 def uri_to_resource_uri(uri) # Split the URL down to the resource # # Here's an example of the process: # /setting/datasources/1/graphs?key-value& # /setting/datasources/1/graphs # /setting/datasources/ # /setting/datasources # uri.split("?")[0].split("/").join("/") end |