Module: RightAws::RightAwsBaseInterface
- Included in:
- AcfInterface, AcwInterface, AsInterface, Ec2, ElbInterface, RdsInterface, S3Interface, SdbInterface, SqsGen2Interface, SqsInterface
- Defined in:
- lib/awsbase/right_awsbase.rb
Constant Summary collapse
- DEFAULT_SIGNATURE_VERSION =
'2'
- @@caching =
false
Instance Attribute Summary collapse
-
#aws_access_key_id ⇒ Object
readonly
Current aws_access_key_id.
-
#cache ⇒ Object
readonly
Cache.
-
#connection ⇒ Object
readonly
RightHttpConnection instance.
-
#last_errors ⇒ Object
Last AWS errors list (used by AWSErrorHandler).
-
#last_request ⇒ Object
readonly
Last HTTP request object.
-
#last_request_id ⇒ Object
Returns Amazons request ID for the latest request.
-
#last_response ⇒ Object
readonly
Last HTTP response object.
-
#logger ⇒ Object
Logger object.
-
#params ⇒ Object
Initial params hash.
-
#signature_version ⇒ Object
readonly
Signature version (all services except s3).
Class Method Summary collapse
Instance Method Summary collapse
-
#amazonize_list(masks, list) ⇒ Object
Format array of items into Amazons handy hash (‘?’ is a place holder):.
-
#cache_hits?(function, response, do_raise = :raise) ⇒ Boolean
Check if the aws function response hits the cache or not.
-
#caching? ⇒ Boolean
Returns
true
if the describe_xxx responses are being cached. -
#generate_request_impl(verb, action, options = {}) ⇒ Object
ACF, AMS, EC2, LBS and SDB uses this guy SQS and S3 use their own methods.
-
#get_connection(aws_service, request) ⇒ Object
:nodoc.
-
#init(service_info, aws_access_key_id, aws_secret_access_key, params = {}) ⇒ Object
:nodoc:.
-
#on_exception(options = {:raise=>true, :log=>true}) ⇒ Object
:nodoc:.
-
#request_cache_or_info(method, link, parser_class, benchblock, use_cache = true) ⇒ Object
:nodoc:.
-
#request_info_impl(aws_service, benchblock, request, parser, &block) ⇒ Object
All services uses this guy.
- #signed_service_params(aws_secret_access_key, service_hash, http_verb = nil, host = nil, service = nil) ⇒ Object
- #update_cache(function, hash) ⇒ Object
Instance Attribute Details
#aws_access_key_id ⇒ Object (readonly)
Current aws_access_key_id
191 192 193 |
# File 'lib/awsbase/right_awsbase.rb', line 191 def aws_access_key_id @aws_access_key_id end |
#cache ⇒ Object (readonly)
Cache
207 208 209 |
# File 'lib/awsbase/right_awsbase.rb', line 207 def cache @cache end |
#connection ⇒ Object (readonly)
RightHttpConnection instance
205 206 207 |
# File 'lib/awsbase/right_awsbase.rb', line 205 def connection @connection end |
#last_errors ⇒ Object
Last AWS errors list (used by AWSErrorHandler)
197 198 199 |
# File 'lib/awsbase/right_awsbase.rb', line 197 def last_errors @last_errors end |
#last_request ⇒ Object (readonly)
Last HTTP request object
193 194 195 |
# File 'lib/awsbase/right_awsbase.rb', line 193 def last_request @last_request end |
#last_request_id ⇒ Object
Returns Amazons request ID for the latest request
199 200 201 |
# File 'lib/awsbase/right_awsbase.rb', line 199 def last_request_id @last_request_id end |
#last_response ⇒ Object (readonly)
Last HTTP response object
195 196 197 |
# File 'lib/awsbase/right_awsbase.rb', line 195 def last_response @last_response end |
#logger ⇒ Object
Logger object
201 202 203 |
# File 'lib/awsbase/right_awsbase.rb', line 201 def logger @logger end |
#params ⇒ Object
Initial params hash
203 204 205 |
# File 'lib/awsbase/right_awsbase.rb', line 203 def params @params end |
#signature_version ⇒ Object (readonly)
Signature version (all services except s3)
209 210 211 |
# File 'lib/awsbase/right_awsbase.rb', line 209 def signature_version @signature_version end |
Class Method Details
.caching ⇒ Object
183 184 185 |
# File 'lib/awsbase/right_awsbase.rb', line 183 def self.caching @@caching end |
.caching=(caching) ⇒ Object
186 187 188 |
# File 'lib/awsbase/right_awsbase.rb', line 186 def self.caching=(caching) @@caching = caching end |
Instance Method Details
#amazonize_list(masks, list) ⇒ Object
Format array of items into Amazons handy hash (‘?’ is a place holder):
amazonize_list('Item', ['a', 'b', 'c']) =>
{ 'Item.1' => 'a', 'Item.2' => 'b', 'Item.3' => 'c' }
amazonize_list('Item.?.instance', ['a', 'c']) #=>
{ 'Item.1.instance' => 'a', 'Item.2.instance' => 'c' }
amazonize_list(['Item.?.Name', 'Item.?.Value'], {'A' => 'a', 'B' => 'b'}) #=>
{ 'Item.1.Name' => 'A', 'Item.1.Value' => 'a',
'Item.2.Name' => 'B', 'Item.2.Value' => 'b' }
amazonize_list(['Item.?.Name', 'Item.?.Value'], [['A','a'], ['B','b']]) #=>
{ 'Item.1.Name' => 'A', 'Item.1.Value' => 'a',
'Item.2.Name' => 'B', 'Item.2.Value' => 'b' }
amazonize_list(['Filter.?.Key', 'Filter.?.Value.?'], {'A' => ['aa','ab'], 'B' => ['ba','bb']}) #=>
amazonize_list(['Filter.?.Key', 'Filter.?.Value.?'], [['A',['aa','ab']], ['B',['ba','bb']]]) #=>
{"Filter.1.Key"=>"A",
"Filter.1.Value.1"=>"aa",
"Filter.1.Value.2"=>"ab",
"Filter.2.Key"=>"B",
"Filter.2.Value.1"=>"ba",
"Filter.2.Value.2"=>"bb"}
497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 |
# File 'lib/awsbase/right_awsbase.rb', line 497 def amazonize_list(masks, list) #:nodoc: groups = {} list.to_a.each_with_index do |list_item, i| masks.to_a.each_with_index do |mask, mask_idx| key = mask[/\?/] ? mask.dup : mask.dup + '.?' key.sub!('?', (i+1).to_s) value = list_item.to_a[mask_idx] if value.is_a?(Array) groups.merge!(amazonize_list(key, value)) else groups[key] = value end end end groups end |
#cache_hits?(function, response, do_raise = :raise) ⇒ Boolean
Check if the aws function response hits the cache or not. If the cache hits:
-
raises an
AwsNoChange
exception ifdo_raise
==:raise
. -
returnes parsed response from the cache if it exists or
true
otherwise.
If the cache miss or the caching is off then returns false
.
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 |
# File 'lib/awsbase/right_awsbase.rb', line 269 def cache_hits?(function, response, do_raise=:raise) result = false if caching? function = function.to_sym # get rid of requestId (this bad boy was added for API 2008-08-08+ and it is uniq for every response) # feb 04, 2009 (load balancer uses 'RequestId' hence use 'i' modifier to hit it also) response = response.sub(%r{<requestId>.+?</requestId>}i, '') response_md5 = MD5.md5(response).to_s # check for changes unless @cache[function] && @cache[function][:response_md5] == response_md5 # well, the response is new, reset cache data update_cache(function, {:response_md5 => response_md5, :timestamp => Time.now, :hits => 0, :parsed => nil}) else # aha, cache hits, update the data and throw an exception if needed @cache[function][:hits] += 1 if do_raise == :raise raise(AwsNoChange, "Cache hit: #{function} response has not changed since "+ "#{@cache[function][:timestamp].strftime('%Y-%m-%d %H:%M:%S')}, "+ "hits: #{@cache[function][:hits]}.") else result = @cache[function][:parsed] || true end end end result end |
#caching? ⇒ Boolean
Returns true
if the describe_xxx responses are being cached
260 261 262 |
# File 'lib/awsbase/right_awsbase.rb', line 260 def caching? @params.key?(:cache) ? @params[:cache] : @@caching end |
#generate_request_impl(verb, action, options = {}) ⇒ Object
ACF, AMS, EC2, LBS and SDB uses this guy SQS and S3 use their own methods
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 |
# File 'lib/awsbase/right_awsbase.rb', line 315 def generate_request_impl(verb, action, ={}) #:nodoc: # Form a valid http verb: 'GET' or 'POST' (all the other are not supported now) http_verb = verb.to_s.upcase # remove empty keys from request options .delete_if { |key, value| value.nil? } # prepare service data service_hash = {"Action" => action, "AWSAccessKeyId" => @aws_access_key_id, "Version" => @params[:api_version] } service_hash.merge!() # Sign request options service_params = signed_service_params(@aws_secret_access_key, service_hash, http_verb, @params[:server], @params[:service]) # Use POST if the length of the query string is too large # see http://docs.amazonwebservices.com/AmazonSimpleDB/2007-11-07/DeveloperGuide/MakingRESTRequests.html if http_verb != 'POST' && service_params.size > 2000 http_verb = 'POST' if signature_version == '2' service_params = signed_service_params(@aws_secret_access_key, service_hash, http_verb, @params[:server], @params[:service]) end end # create a request case http_verb when 'GET' request = Net::HTTP::Get.new("#{@params[:service]}?#{service_params}") when 'POST' request = Net::HTTP::Post.new(@params[:service]) request.body = service_params request['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8' else raise "Unsupported HTTP verb #{verb.inspect}!" end # prepare output hash { :request => request, :server => @params[:server], :port => @params[:port], :protocol => @params[:protocol] } end |
#get_connection(aws_service, request) ⇒ Object
:nodoc
353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 |
# File 'lib/awsbase/right_awsbase.rb', line 353 def get_connection(aws_service, request) #:nodoc server_url = "#{request[:protocol]}://#{request[:server]}:#{request[:port]}}" # case @params[:connections].to_s when 'dedicated' @connections_storage ||= {} else # 'dedicated' @connections_storage = (Thread.current[aws_service] ||= {}) end # @connections_storage[server_url] ||= {} @connections_storage[server_url][:last_used_at] = Time.now @connections_storage[server_url][:connection] ||= Rightscale::HttpConnection.new(:exception => RightAws::AwsError, :logger => @logger) # keep X most recent connections (but were used not far than Y minutes ago) connections = 0 @connections_storage.to_a.sort{|i1, i2| i2[1][:last_used_at] <=> i1[1][:last_used_at]}.to_a.each do |i| if i[0] != server_url && (@params[:max_connections] <= connections || i[1][:last_used_at] < Time.now - @params[:connection_lifetime]) # delete the connection from the list @connections_storage.delete(i[0]) # then finish it i[1][:connection].finish((@params[:max_connections] <= connections) ? "out-of-limit" : "out-of-date") rescue nil else connections += 1 end end @connections_storage[server_url][:connection] end |
#init(service_info, aws_access_key_id, aws_secret_access_key, params = {}) ⇒ Object
:nodoc:
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 |
# File 'lib/awsbase/right_awsbase.rb', line 211 def init(service_info, aws_access_key_id, aws_secret_access_key, params={}) #:nodoc: @params = params # If one defines EC2_URL he may forget to use a single slash as an "empty service" path. # Amazon does not like this therefore add this bad boy if he is missing... service_info[:default_service] = '/' if service_info[:default_service].blank? raise AwsError.new("AWS access keys are required to operate on #{service_info[:name]}") \ if aws_access_key_id.blank? || aws_secret_access_key.blank? @aws_access_key_id = aws_access_key_id @aws_secret_access_key = aws_secret_access_key # if the endpoint was explicitly defined - then use it if @params[:endpoint_url] @params[:server] = URI.parse(@params[:endpoint_url]).host @params[:port] = URI.parse(@params[:endpoint_url]).port @params[:service] = URI.parse(@params[:endpoint_url]).path # make sure the 'service' path is not empty @params[:service] = service_info[:default_service] if @params[:service].blank? @params[:protocol] = URI.parse(@params[:endpoint_url]).scheme @params[:region] = nil else @params[:server] ||= service_info[:default_host] @params[:server] = "#{@params[:region]}.#{@params[:server]}" if @params[:region] @params[:port] ||= service_info[:default_port] @params[:service] ||= service_info[:default_service] @params[:protocol] ||= service_info[:default_protocol] end # @params[:multi_thread] ||= defined?(AWS_DAEMON) @params[:connections] ||= :shared # || :dedicated @params[:max_connections] ||= 10 @params[:connection_lifetime] ||= 20*60 @params[:api_version] ||= service_info[:default_api_version] @logger = @params[:logger] @logger = RAILS_DEFAULT_LOGGER if !@logger && defined?(RAILS_DEFAULT_LOGGER) @logger = Logger.new(STDOUT) if !@logger @logger.info "New #{self.class.name} using #{@params[:connections]} connections mode" @error_handler = nil @cache = {} @signature_version = (params[:signature_version] || DEFAULT_SIGNATURE_VERSION).to_s end |
#on_exception(options = {:raise=>true, :log=>true}) ⇒ Object
:nodoc:
303 304 305 306 |
# File 'lib/awsbase/right_awsbase.rb', line 303 def on_exception(={:raise=>true, :log=>true}) # :nodoc: raise if $!.is_a?(AwsNoChange) AwsError::on_aws_exception(self, ) end |
#request_cache_or_info(method, link, parser_class, benchblock, use_cache = true) ⇒ Object
:nodoc:
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 |
# File 'lib/awsbase/right_awsbase.rb', line 452 def request_cache_or_info(method, link, parser_class, benchblock, use_cache=true) #:nodoc: # We do not want to break the logic of parsing hence will use a dummy parser to process all the standard # steps (errors checking etc). The dummy parser does nothig - just returns back the params it received. # If the caching is enabled and hit then throw AwsNoChange. # P.S. caching works for the whole images list only! (when the list param is blank) # check cache response, params = request_info(link, RightDummyParser.new) cache_hits?(method.to_sym, response.body) if use_cache parser = parser_class.new(:logger => @logger) benchblock.xml.add!{ parser.parse(response, params) } result = block_given? ? yield(parser) : parser.result # update parsed data update_cache(method.to_sym, :parsed => result) if use_cache result end |
#request_info_impl(aws_service, benchblock, request, parser, &block) ⇒ Object
All services uses this guy.
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 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 |
# File 'lib/awsbase/right_awsbase.rb', line 382 def request_info_impl(aws_service, benchblock, request, parser, &block) #:nodoc: @connection = get_connection(aws_service, request) @last_request = request[:request] @last_response = nil response = nil blockexception = nil if(block != nil) # TRB 9/17/07 Careful - because we are passing in blocks, we get a situation where # an exception may get thrown in the block body (which is high-level # code either here or in the application) but gets caught in the # low-level code of HttpConnection. The solution is not to let any # exception escape the block that we pass to HttpConnection::request. # Exceptions can originate from code directly in the block, or from user # code called in the other block which is passed to response.read_body. benchblock.service.add! do responsehdr = @connection.request(request) do |response| ######### begin @last_response = response if response.is_a?(Net::HTTPSuccess) @error_handler = nil response.read_body(&block) else @error_handler = AWSErrorHandler.new(self, parser, :errors_list => self.class.amazon_problems) unless @error_handler check_result = @error_handler.check(request) if check_result @error_handler = nil return check_result end raise AwsError.new(@last_errors, @last_response.code, @last_request_id) end rescue Exception => e blockexception = e end end ######### #OK, now we are out of the block passed to the lower level if(blockexception) raise blockexception end benchblock.xml.add! do parser.parse(responsehdr) end return parser.result end else benchblock.service.add!{ response = @connection.request(request) } # check response for errors... @last_response = response if response.is_a?(Net::HTTPSuccess) @error_handler = nil benchblock.xml.add! { parser.parse(response) } return parser.result else @error_handler = AWSErrorHandler.new(self, parser, :errors_list => self.class.amazon_problems) unless @error_handler check_result = @error_handler.check(request) if check_result @error_handler = nil return check_result end raise AwsError.new(@last_errors, @last_response.code, @last_request_id) end end rescue @error_handler = nil raise end |
#signed_service_params(aws_secret_access_key, service_hash, http_verb = nil, host = nil, service = nil) ⇒ Object
250 251 252 253 254 255 256 257 |
# File 'lib/awsbase/right_awsbase.rb', line 250 def signed_service_params(aws_secret_access_key, service_hash, http_verb=nil, host=nil, service=nil ) case signature_version.to_s when '0' then AwsUtils::sign_request_v0(aws_secret_access_key, service_hash) when '1' then AwsUtils::sign_request_v1(aws_secret_access_key, service_hash) when '2' then AwsUtils::sign_request_v2(aws_secret_access_key, service_hash, http_verb, host, service) else raise AwsError.new("Unknown signature version (#{signature_version.to_s}) requested") end end |
#update_cache(function, hash) ⇒ Object
299 300 301 |
# File 'lib/awsbase/right_awsbase.rb', line 299 def update_cache(function, hash) (@cache[function.to_sym] ||= {}).merge!(hash) if caching? end |