Class: DeltaCloud::API
- Inherits:
-
Object
- Object
- DeltaCloud::API
- Defined in:
- lib/deltacloud.rb,
lib/base_object.rb
Defined Under Namespace
Classes: Action, Base, Stateful
Instance Attribute Summary collapse
-
#api_driver ⇒ Object
readonly
Returns the value of attribute api_driver.
-
#api_provider ⇒ Object
readonly
Returns the value of attribute api_provider.
-
#api_uri ⇒ Object
readonly
Returns the value of attribute api_uri.
-
#api_version ⇒ Object
readonly
Returns the value of attribute api_version.
-
#driver_name ⇒ Object
readonly
Returns the value of attribute driver_name.
-
#entry_points ⇒ Object
readonly
Returns the value of attribute entry_points.
-
#features ⇒ Object
readonly
Returns the value of attribute features.
Instance Method Summary collapse
-
#api_host ⇒ Object
Return API hostname.
-
#api_path ⇒ Object
Return API path.
-
#api_port ⇒ Object
Return API port.
-
#base_object(model, response) ⇒ Object
Add default attributes [id and href] to class.
- #base_object_collection(model, response) ⇒ Object
- #connect {|_self| ... } ⇒ Object
-
#declare_entry_points_methods(entry_points) ⇒ Object
Define methods based on ‘rel’ attribute in entry point Two methods are declared: ‘images’ and ‘image’.
-
#discover_entry_points ⇒ Object
Get /api and parse entry points.
-
#discovered? ⇒ Boolean
Skip parsing /api when we already got entry points.
-
#documentation(collection, operation = nil) ⇒ Object
This method will retrieve API documentation for given collection.
- #extended_headers ⇒ Object
-
#feature?(collection, name) ⇒ Boolean
Check if specified collection have wanted feature.
-
#initialize(user_name, password, api_url, opts = {}) {|_self| ... } ⇒ API
constructor
A new instance of API.
-
#instance_state(name) ⇒ Object
Select instance state specified by name.
-
#instance_states ⇒ Object
List available instance states and transitions between them.
-
#method_missing(name, *args) ⇒ Object
Generate create_* methods dynamically.
-
#request(*args, &block) ⇒ Object
Basic request method.
- #response_error(response) ⇒ Object
- #response_successful?(code) ⇒ Boolean
- #use_config!(opts = {}) ⇒ Object
- #use_driver(driver, opts = {}) ⇒ Object
-
#with_config(opts) {|api_instance| ... } ⇒ Object
This method can be used to switch back-end cloud for API instance using HTTP headers.
-
#xml_to_class(base_object, item) ⇒ Object
Convert XML response to defined Ruby Class.
Constructor Details
#initialize(user_name, password, api_url, opts = {}) {|_self| ... } ⇒ API
Returns a new instance of API.
72 73 74 75 76 77 78 79 80 81 82 83 84 |
# File 'lib/deltacloud.rb', line 72 def initialize(user_name, password, api_url, opts={}, &block) opts[:version] = true @api_driver, @api_provider = opts[:driver], opts[:provider] @username, @password = opts[:username] || user_name, opts[:password] || password @api_uri = URI.parse(api_url) @features, @entry_points = {}, {} @verbose = opts[:verbose] || false discover_entry_points if entry_points.include?(:buckets) extend(ClientBucketMethods) end yield self if block_given? end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(name, *args) ⇒ Object
Generate create_* methods dynamically
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 |
# File 'lib/deltacloud.rb', line 293 def method_missing(name, *args) if name.to_s =~ /^([\w_]+)_ids$/ return self.send(:"#{$1.pluralize}").map { |o| o.id } end if name.to_s =~ /^create_(\w+)/ params = args[0] if args[0] and args[0].class.eql?(Hash) params ||= args[1] if args[1] and args[1].class.eql?(Hash) params ||= {} # FIXME: This fixes are related to Instance model and should be # replaced by 'native' parameter names params[:realm_id] ||= params[:realm] if params[:realm] params[:keyname] ||= params[:key_name] if params[:key_name] params[:user_data] = Base64::encode64(params[:user_data]) if params[:user_data] if params[:hardware_profile] and params[:hardware_profile].class.eql?(Hash) params[:hardware_profile].each do |k,v| params[:"hwp_#{k}"] ||= v end else params[:hwp_id] ||= params[:hardware_profile] end params[:image_id] ||= params[:image_id] || args[0] if args[0].class!=Hash obj = nil request(:post, entry_points[:"#{$1}s"], {}, params) do |response| obj = base_object(:"#{$1}", response) response_error(response) unless response_successful?(response.code) yield obj if block_given? end return obj end raise NoMethodError end |
Instance Attribute Details
#api_driver ⇒ Object (readonly)
Returns the value of attribute api_driver.
70 71 72 |
# File 'lib/deltacloud.rb', line 70 def api_driver @api_driver end |
#api_provider ⇒ Object (readonly)
Returns the value of attribute api_provider.
70 71 72 |
# File 'lib/deltacloud.rb', line 70 def api_provider @api_provider end |
#api_uri ⇒ Object (readonly)
Returns the value of attribute api_uri.
69 70 71 |
# File 'lib/deltacloud.rb', line 69 def api_uri @api_uri end |
#api_version ⇒ Object (readonly)
Returns the value of attribute api_version.
69 70 71 |
# File 'lib/deltacloud.rb', line 69 def api_version @api_version end |
#driver_name ⇒ Object (readonly)
Returns the value of attribute driver_name.
69 70 71 |
# File 'lib/deltacloud.rb', line 69 def driver_name @driver_name end |
#entry_points ⇒ Object (readonly)
Returns the value of attribute entry_points.
69 70 71 |
# File 'lib/deltacloud.rb', line 69 def entry_points @entry_points end |
#features ⇒ Object (readonly)
Returns the value of attribute features.
69 70 71 |
# File 'lib/deltacloud.rb', line 69 def features @features end |
Instance Method Details
#api_host ⇒ Object
Return API hostname
123 |
# File 'lib/deltacloud.rb', line 123 def api_host; @api_uri.host ; end |
#api_path ⇒ Object
Return API path
129 |
# File 'lib/deltacloud.rb', line 129 def api_path; @api_uri.path ; end |
#api_port ⇒ Object
Return API port
126 |
# File 'lib/deltacloud.rb', line 126 def api_port; @api_uri.port ; end |
#base_object(model, response) ⇒ Object
Add default attributes [id and href] to class
177 178 179 180 |
# File 'lib/deltacloud.rb', line 177 def base_object(model, response) c = DeltaCloud.add_class("#{model}", DeltaCloud::guess_model_type(response)) xml_to_class(c, Nokogiri::XML(response).xpath("#{model.to_s.singularize}").first) end |
#base_object_collection(model, response) ⇒ Object
170 171 172 173 174 |
# File 'lib/deltacloud.rb', line 170 def base_object_collection(model, response) Nokogiri::XML(response).xpath("#{model}/#{model.to_s.singularize}").collect do |item| base_object(model, item.to_s) end end |
#connect {|_self| ... } ⇒ Object
118 119 120 |
# File 'lib/deltacloud.rb', line 118 def connect(&block) yield self end |
#declare_entry_points_methods(entry_points) ⇒ Object
Define methods based on ‘rel’ attribute in entry point Two methods are declared: ‘images’ and ‘image’
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 |
# File 'lib/deltacloud.rb', line 133 def declare_entry_points_methods(entry_points) API.instance_eval do entry_points.keys.select {|k| [:instance_states].include?(k)==false }.each do |model| define_method model do |*args| request(:get, entry_points[model], args.first) do |response| base_object_collection(model, response) end end define_method :"#{model.to_s.singularize}" do |*args| request(:get, "#{entry_points[model]}/#{args[0]}") do |response| base_object(model, response) end end define_method :"fetch_#{model.to_s.singularize}" do |url| url =~ /\/#{model}\/(.*)$/ self.send(model.to_s.singularize.to_sym, $1) end end #define methods for blobs: if(entry_points.include?(:buckets)) define_method :"blob" do |*args| bucket = args[0]["bucket"] blob = args[0][:id] request(:get, "#{entry_points[:buckets]}/#{bucket}/#{blob}") do |response| base_object("blob", response) end end end end end |
#discover_entry_points ⇒ Object
Get /api and parse entry points
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 |
# File 'lib/deltacloud.rb', line 266 def discover_entry_points return if discovered? request(:get, @api_uri.to_s) do |response| if response.code == 301 @api_uri = response.headers[:location] return discover_entry_points end api_xml = Nokogiri::XML(response) @driver_name = api_xml.xpath('/api').first[:driver] @api_version = api_xml.xpath('/api').first[:version] api_xml.css("api > link").each do |entry_point| rel, href = entry_point['rel'].to_sym, entry_point['href'] @entry_points.store(rel, href) entry_point.css("feature").each do |feature| @features[rel] ||= [] @features[rel] << feature['name'].to_sym end end end declare_entry_points_methods(@entry_points) end |
#discovered? ⇒ Boolean
Skip parsing /api when we already got entry points
439 440 441 |
# File 'lib/deltacloud.rb', line 439 def discovered? true if @entry_points!={} end |
#documentation(collection, operation = nil) ⇒ Object
This method will retrieve API documentation for given collection
444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 |
# File 'lib/deltacloud.rb', line 444 def documentation(collection, operation=nil) data = {} request(:get, "/docs/#{collection}") do |body| document = Nokogiri::XML(body) if operation data[:operation] = operation data[:description] = document.xpath('/docs/collection/operations/operation[@name = "'+operation+'"]/description').first.text.strip return false unless data[:description] data[:params] = [] (document/"/docs/collection/operations/operation[@name='#{operation}']/parameter").each do |param| data[:params] << { :name => param['name'], :required => param['type'] == 'optional', :type => (param/'class').text } end else data[:description] = (document/'/docs/collection/description').text data[:collection] = collection data[:operations] = (document/"/docs/collection/operations/operation").collect{ |o| o['name'] } end end return Documentation.new(self, data) end |
#extended_headers ⇒ Object
350 351 352 353 354 355 |
# File 'lib/deltacloud.rb', line 350 def extended_headers headers = {} headers["X-Deltacloud-Driver"] = @api_driver.to_s if @api_driver headers["X-Deltacloud-Provider"] = @api_provider.to_s if @api_provider headers end |
#feature?(collection, name) ⇒ Boolean
Check if specified collection have wanted feature
411 412 413 |
# File 'lib/deltacloud.rb', line 411 def feature?(collection, name) @features.has_key?(collection) && @features[collection].include?(name) end |
#instance_state(name) ⇒ Object
Select instance state specified by name
434 435 436 |
# File 'lib/deltacloud.rb', line 434 def instance_state(name) instance_states.select { |s| s.name.to_s.eql?(name.to_s) }.first end |
#instance_states ⇒ Object
List available instance states and transitions between them
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 |
# File 'lib/deltacloud.rb', line 416 def instance_states states = [] request(:get, entry_points[:instance_states]) do |response| Nokogiri::XML(response).xpath('states/state').each do |state_el| state = DeltaCloud::InstanceState::State.new(state_el['name']) state_el.xpath('transition').each do |transition_el| state.transitions << DeltaCloud::InstanceState::Transition.new( transition_el['to'], transition_el['action'] ) end states << state end end states end |
#request(*args, &block) ⇒ Object
Basic request method
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 |
# File 'lib/deltacloud.rb', line 381 def request(*args, &block) conf = { :method => (args[0] || 'get').to_sym, :path => (args[1]=~/^http/) ? args[1] : "#{api_uri.to_s}#{args[1]}", :query_args => args[2] || {}, :form_data => args[3] || {}, :timeout => args[4] || 45, :open_timeout => args[5] || 10 } if conf[:query_args] != {} conf[:path] += '?' + URI.escape(conf[:query_args].collect{ |key, value| "#{key}=#{value}" }.join('&')).to_s end if conf[:method].eql?(:post) resource = RestClient::Resource.new(conf[:path], :open_timeout => conf[:open_timeout], :timeout => conf[:timeout]) resource.send(:post, conf[:form_data], default_headers.merge(extended_headers)) do |response, request, block| response_error(response) unless response_successful? response.code yield response.to_s if block_given? end else resource = RestClient::Resource.new(conf[:path], :open_timeout => conf[:open_timeout], :timeout => conf[:timeout]) resource.send(conf[:method], default_headers.merge(extended_headers)) do |response, request, block| response_error(response) unless response_successful? response.code yield response.to_s if block_given? end end end |
#response_error(response) ⇒ Object
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 |
# File 'lib/deltacloud.rb', line 363 def response_error(response) xml = Nokogiri::XML(response.to_s) if (xml/'message').empty? and response.code.to_s =~ /4(\d{2})/ DeltaCloud::HTTPError.client_error(response.code) else opts = { :driver => (xml/'backend').first[:driver], :provider => (xml/'backend').first[:provider], :params => (xml/'request/param').inject({}) { |r,p| r[:"#{p[:name]}"] = p.text; r } } backtrace = (xml/'backtrace').empty? ? nil : (xml/'backtrace').first.text.split("\n")[1..10].map { |l| l.strip } DeltaCloud::HTTPError.server_error(xml.root[:status] || response.code, (xml/'message').first.text, opts, backtrace) end end |
#response_successful?(code) ⇒ Boolean
357 358 359 360 361 |
# File 'lib/deltacloud.rb', line 357 def response_successful?(code) return true if code.to_s =~ /^2(\d{2})$/ return true if code.to_s =~ /^3(\d{2})$/ return false end |
#use_config!(opts = {}) ⇒ Object
345 346 347 348 |
# File 'lib/deltacloud.rb', line 345 def use_config!(opts={}) @api_uri = URI.parse(opts[:url]) if opts[:url] use_driver(opts[:driver], opts) end |
#use_driver(driver, opts = {}) ⇒ Object
331 332 333 334 335 336 337 338 339 340 341 342 343 |
# File 'lib/deltacloud.rb', line 331 def use_driver(driver, opts={}) if driver @api_driver = driver @driver_name = driver @api_provider = opts[:provider] if opts[:provider] @features, @entry_points = {}, {} discover_entry_points end @username = opts[:username] if opts[:username] @password = opts[:password] if opts[:password] @api_provider = opts[:provider] if opts[:provider] return self end |
#with_config(opts) {|api_instance| ... } ⇒ Object
This method can be used to switch back-end cloud for API instance using HTTP headers. Options must include:
:driver => 'rhevm|ec2|gogrid|...',
:username => 'API key for backend',
:password => 'API secret key for backend',
Optionally you can pass also :provider option to change provider entry-point
Example usage: client = Deltacloud::new(‘url’, ‘username’, ‘password’) … client.with_config(:driver => ‘ec2’, :username => ”, :password => ”) do |ec2|
ec2.realms
end
Note: After this block finish client instance will be set back to default state
108 109 110 111 112 113 114 115 116 |
# File 'lib/deltacloud.rb', line 108 def with_config(opts, &block) api_instance = self.dup api_instance.use_driver(opts[:driver], :username => opts[:username], :password => opts[:password], :provider => opts[:provider]) yield api_instance if block_given? api_instance end |
#xml_to_class(base_object, item) ⇒ Object
Convert XML response to defined Ruby Class
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 258 259 260 261 262 263 |
# File 'lib/deltacloud.rb', line 183 def xml_to_class(base_object, item) return nil unless item params = { :id => item['id'], :url => item['href'], :name => item.name, :client => self } params.merge!({ :initial_state => (item/'state').text.sanitize }) if (item/'state').length > 0 obj = base_object.new(params) # Traverse across XML document and deal with elements item.xpath('./*').each do |attribute| # Do a link for elements which are links to other REST models if self.entry_points.keys.include?(:"#{attribute.name}s") obj.add_link!(attribute.name, attribute['id']) && next unless (attribute.name == 'bucket' && item.name == 'blob') end # Do a HWP property for hardware profile properties if attribute.name == 'property' if attribute['value'] =~ /^(\d+)\.(\d+)$/ obj.add_hwp_property!(attribute['name'], attribute, :float) && next else obj.add_hwp_property!(attribute['name'], attribute, :integer) && next end end # If there are actions, add they to ActionObject/StateFullObject if attribute.name == 'actions' (attribute/'link').each do |link| (obj.add_run_action!(item['id'], link) && next) if link[:rel] == 'run' obj.add_action_link!(item['id'], link) end && next end if attribute.name == 'mount' obj.add_link!("instance", (attribute/"./instance/@id").first.value) obj.add_text!("device", (attribute/"./device/@name").first.value) next end #deal with blob metadata if (attribute.name == 'user_metadata') = {} attribute.children.select {|x| x.name=="entry" }.each do |element| value = element.content.gsub!(/(\n) +/,'') [element['key']] = value end obj.add_collection!(attribute.name, .inspect) && next end if (['public_addresses', 'private_addresses'].include? attribute.name) obj.add_addresses!(attribute.name, (attribute/'*')) && next end if ('authentication'.include? attribute.name) obj.add_authentication!(attribute[:type], (attribute/'*')) && next end #deal with providers if(attribute.name == 'provider') obj.add_provider!(attribute.attributes['id'].value, (attribute/'entrypoint')) && next end # Deal with collections like public-addresses, private-addresses if (attribute/'./*').length > 0 obj.add_collection!(attribute.name, (attribute/'*').collect { |value| value.text }) && next end #deal with blobs for buckets if(attribute.name == 'blob') obj.add_blob!(attribute.attributes['id'].value) && next end # Anything else is treaten as text object obj.add_text!(attribute.name, attribute.text.convert) end return obj end |