Module: RightAws::RightAwsBaseInterface

Constant Summary collapse

DEFAULT_SIGNATURE_VERSION =
'2'
BLOCK_DEVICE_KEY_MAPPING =

:nodoc:

{                                                           # :nodoc:
:device_name               => 'DeviceName',
:virtual_name              => 'VirtualName',
:no_device                 => 'NoDevice',
:ebs_snapshot_id           => 'Ebs.SnapshotId',
:ebs_volume_size           => 'Ebs.VolumeSize',
:ebs_delete_on_termination => 'Ebs.DeleteOnTermination' }
@@caching =
false

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#aws_access_key_idObject (readonly)

Current aws_access_key_id



244
245
246
# File 'lib/awsbase/right_awsbase.rb', line 244

def aws_access_key_id
  @aws_access_key_id
end

#aws_secret_access_keyObject (readonly)

Current aws_secret_access_key



246
247
248
# File 'lib/awsbase/right_awsbase.rb', line 246

def aws_secret_access_key
  @aws_secret_access_key
end

#cacheObject (readonly)

Cache



262
263
264
# File 'lib/awsbase/right_awsbase.rb', line 262

def cache
  @cache
end

#connectionObject (readonly)

RightHttpConnection instance



260
261
262
# File 'lib/awsbase/right_awsbase.rb', line 260

def connection
  @connection
end

#last_errorsObject

Last AWS errors list (used by AWSErrorHandler)



252
253
254
# File 'lib/awsbase/right_awsbase.rb', line 252

def last_errors
  @last_errors
end

#last_requestObject (readonly)

Last HTTP request object



248
249
250
# File 'lib/awsbase/right_awsbase.rb', line 248

def last_request
  @last_request
end

#last_request_idObject

Returns Amazons request ID for the latest request



254
255
256
# File 'lib/awsbase/right_awsbase.rb', line 254

def last_request_id
  @last_request_id
end

#last_responseObject (readonly)

Last HTTP response object



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

def last_response
  @last_response
end

#loggerObject

Logger object



256
257
258
# File 'lib/awsbase/right_awsbase.rb', line 256

def logger
  @logger
end

#paramsObject

Initial params hash



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

def params
  @params
end

#signature_versionObject (readonly)

Signature version (all services except s3)



264
265
266
# File 'lib/awsbase/right_awsbase.rb', line 264

def signature_version
  @signature_version
end

Class Method Details

.cachingObject



236
237
238
# File 'lib/awsbase/right_awsbase.rb', line 236

def self.caching
  @@caching
end

.caching=(caching) ⇒ Object



239
240
241
# File 'lib/awsbase/right_awsbase.rb', line 239

def self.caching=(caching)
  @@caching = caching
end

Instance Method Details

#amazonize_block_device_mappings(block_device_mappings, key = 'BlockDeviceMapping') ⇒ Object

:nodoc:



648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
# File 'lib/awsbase/right_awsbase.rb', line 648

def amazonize_block_device_mappings(block_device_mappings, key = 'BlockDeviceMapping') # :nodoc:
  result = {}
  unless block_device_mappings.right_blank?
    block_device_mappings = [block_device_mappings] unless block_device_mappings.is_a?(Array)
    block_device_mappings.each_with_index do |b, idx|
      BLOCK_DEVICE_KEY_MAPPING.each do |local_name, remote_name|
        value = b[local_name]
        case local_name
        when :no_device then value = value ? '' : nil   # allow to pass :no_device as boolean
        end
        result["#{key}.#{idx+1}.#{remote_name}"] = value unless value.nil?
      end
    end
  end
  result
end

#amazonize_list(masks, list, options = {}) ⇒ Object

Format array of items into Amazons handy hash (‘?’ is a place holder): Options:

 :default => "something"   : Set a value to "something" when it is nil
 :default => :skip_nils    : Skip nil values

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"}


615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
# File 'lib/awsbase/right_awsbase.rb', line 615

def amazonize_list(masks, list, options={}) #:nodoc:
  groups = {}
  Array(list).each_with_index do |list_item, i|
    Array(masks).each_with_index do |mask, mask_idx|
      key = mask[/\?/] ? mask.dup : mask.dup + '.?'
      key.sub!('?', (i+1).to_s)
      value = Array(list_item)[mask_idx]
      if value.is_a?(Array)
        groups.merge!(amazonize_list(key, value, options))
      else
        if value.nil?
          next if options[:default] == :skip_nils
          value = options[:default]
        end
        # Hack to avoid having unhandled '?' in keys : do replace them all with '1':
        #  bad:  ec2.amazonize_list(['Filter.?.Key', 'Filter.?.Value.?'], { a: => :b }) => {"Filter.1.Key"=>:a, "Filter.1.Value.?"=>1}
        #  good: ec2.amazonize_list(['Filter.?.Key', 'Filter.?.Value.?'], { a: => :b }) => {"Filter.1.Key"=>:a, "Filter.1.Value.1"=>1}
        key.gsub!('?', '1')
        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 if do_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.

Returns:

  • (Boolean)


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
352
353
354
355
# File 'lib/awsbase/right_awsbase.rb', line 327

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

Returns:

  • (Boolean)


318
319
320
# File 'lib/awsbase/right_awsbase.rb', line 318

def caching?
  @params.key?(:cache) ? @params[:cache] : @@caching
end

#destroy_connection(request, reason) ⇒ Object

:nodoc:



381
382
383
384
385
386
387
388
# File 'lib/awsbase/right_awsbase.rb', line 381

def destroy_connection(request, reason) # :nodoc:
  connections = get_connections_storage(request[:aws_service])
  server_url  = get_server_url(request)
  if connections[server_url]
    connections[server_url][:connection].finish(reason)
    connections.delete(server_url)
  end
end

#generate_request_impl(verb, action, options = {}) ⇒ Object

ACF, AMS, EC2, LBS and SDB uses this guy SQS and S3 use their own methods



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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
# File 'lib/awsbase/right_awsbase.rb', line 419

def generate_request_impl(verb, action, options={}) #: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
  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!(options)
  # 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_hash = { :request  => request,
                   :server   => @params[:server],
                   :port     => @params[:port],
                   :protocol => @params[:protocol] }
  request_hash.merge!(@params[:connection_options])
  request_hash.merge!(@with_connection_options)
  
  # If an action is marked as "non-retryable" and there was no :raise_on_timeout option set
  # explicitly then do set that option
  if Array(RightAwsBase::raise_on_timeout_on_actions).include?(action) && !request_hash.has_key?(:raise_on_timeout)
    request_hash.merge!(:raise_on_timeout => true)
  end

  request_hash
end

#get_connection(request) ⇒ Object

Expire the connection if it has expired.



391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
# File 'lib/awsbase/right_awsbase.rb', line 391

def get_connection(request) # :nodoc:
  server_url         = get_server_url(request)
  connection_storage = get_connections_storage(request[:aws_service])
  life_time_scratch  = Time.now-@params[:connection_lifetime]
  # Delete out-of-dated connections
  connections_in_list = 0
  connection_storage.to_a.sort{|conn1, conn2| conn2[1][:last_used_at] <=> conn1[1][:last_used_at]}.each do |serv_url, conn_opts|
    if    @params[:max_connections] <= connections_in_list
      conn_opts[:connection].finish('out-of-limit')
      connection_storage.delete(server_url)
    elsif conn_opts[:last_used_at] < life_time_scratch
      conn_opts[:connection].finish('out-of-date')
      connection_storage.delete(server_url)
    else
      connections_in_list += 1
    end
  end
  connection = (connection_storage[server_url] ||= {})
  connection[:last_used_at] = Time.now
  connection[:connection] ||= Rightscale::HttpConnection.new(:exception => RightAws::AwsError, :logger => @logger)
end

#get_connections_storage(aws_service) ⇒ Object

:nodoc:



374
375
376
377
378
379
# File 'lib/awsbase/right_awsbase.rb', line 374

def get_connections_storage(aws_service) # :nodoc:
  case @params[:connections].to_s
  when 'dedicated' then @connections_storage        ||= {}
  else                  Thread.current[aws_service] ||= {}
  end
end

#get_server_url(request) ⇒ Object


HTTP Connections handling




370
371
372
# File 'lib/awsbase/right_awsbase.rb', line 370

def get_server_url(request) # :nodoc:
  "#{request[:protocol]}://#{request[:server]}:#{request[:port]}"
end

#incrementally_list_items(action, parser_class, params = {}, &block) ⇒ Object

Incrementally lists something.



575
576
577
578
579
580
581
582
583
584
585
586
# File 'lib/awsbase/right_awsbase.rb', line 575

def incrementally_list_items(action, parser_class, params={}, &block) # :nodoc:
  params = params.dup
  params['MaxItems'] = params.delete(:max_items) if params[:max_items]
  params['Marker']   = params.delete(:marker)    if params[:marker]
  last_response = nil
  loop do
    last_response    = request_info( generate_request(action, params), parser_class.new(:logger => @logger))
    params['Marker'] = last_response[:marker]
    break unless block && block.call(last_response) && !last_response[:marker].right_blank?
  end
  last_response
end

#init(service_info, aws_access_key_id, aws_secret_access_key, params = {}) ⇒ Object

:nodoc:

Raises:



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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
# File 'lib/awsbase/right_awsbase.rb', line 266

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].right_blank?
  raise AwsError.new("AWS access keys are required to operate on #{service_info[:name]}") \
    if aws_access_key_id.right_blank? || aws_secret_access_key.right_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].right_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
  # a set of options to be passed to RightHttpConnection object
  @params[:connection_options] = {} unless @params[:connection_options].is_a?(Hash) 
  @with_connection_options = {}
  @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.logger       if !@logger && defined?(::Rails) && ::Rails.respond_to?(: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:



361
362
363
364
# File 'lib/awsbase/right_awsbase.rb', line 361

def on_exception(options={:raise=>true, :log=>true}) # :nodoc:
  raise if $!.is_a?(AwsNoChange)
  AwsError::on_aws_exception(self, options)
end

#request_cache_or_info(method, link, parser_class, benchblock, use_cache = true, &block) ⇒ Object

:nodoc:



553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
# File 'lib/awsbase/right_awsbase.rb', line 553

def request_cache_or_info(method, link, parser_class, benchblock, use_cache=true, &block) #: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 ? block.call(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.



468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
# File 'lib/awsbase/right_awsbase.rb', line 468

def request_info_impl(aws_service, benchblock, request, parser, &block) #:nodoc:
  request[:aws_service] = aws_service
  @connection    = get_connection(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
      begin
        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
      rescue Exception => e
        # Kill a connection if we run into a low level connection error
        destroy_connection(request, "error: #{e.message}")
        raise e
      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! do
      begin
        response = @connection.request(request)
      rescue Exception => e
        # Kill a connection if we run into a low level connection error
        destroy_connection(request, "error: #{e.message}")
        raise e
      end
    end
      # 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



308
309
310
311
312
313
314
315
# File 'lib/awsbase/right_awsbase.rb', line 308

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



357
358
359
# File 'lib/awsbase/right_awsbase.rb', line 357

def update_cache(function, hash)
  (@cache[function.to_sym] ||= {}).merge!(hash) if caching?
end

#with_connection_options(options, &block) ⇒ Object

Execute a block of code with custom set of settings for right_http_connection. Accepts next options (see Rightscale::HttpConnection for explanation):

:raise_on_timeout
:http_connection_retry_count
:http_connection_open_timeout
:http_connection_read_timeout
:http_connection_retry_delay
:user_agent
:exception

Example #1:

# Try to create a snapshot but stop with exception if timeout is received
# to avoid having a duplicate API calls that create duplicate snapshots.
ec2 = Rightscale::Ec2::new(aws_access_key_id, aws_secret_access_key)
ec2.with_connection_options(:raise_on_timeout => true) do
  ec2.create_snapshot('vol-898a6fe0', 'KD: WooHoo!!')
end

Example #2:

# Opposite case when the setting is global:
@ec2 = Rightscale::Ec2::new(aws_access_key_id, aws_secret_access_key,
                         :connection_options => { :raise_on_timeout => true })
# Create an SSHKey but do tries on timeout
ec2.with_connection_options(:raise_on_timeout => false) do
  new_key = ec2.create_key_pair('my_test_key')
end

Example #3:

# Global settings (HttpConnection level):
Rightscale::HttpConnection::params[:http_connection_open_timeout] = 5
Rightscale::HttpConnection::params[:http_connection_read_timeout] = 250
Rightscale::HttpConnection::params[:http_connection_retry_count]  = 2

# Local setings (RightAws level)
ec2 = Rightscale::Ec2::new(AWS_ID, AWS_KEY,
  :region => 'us-east-1',
  :connection_options => {
    :http_connection_read_timeout => 2,
    :http_connection_retry_count  => 5,
    :user_agent => 'Mozilla 4.0'
  })

# Custom settings (API call level)
ec2.with_connection_options(:raise_on_timeout => true,
                            :http_connection_read_timeout => 10,
                            :user_agent => '') do
  pp ec2.describe_images
end


717
718
719
720
721
722
# File 'lib/awsbase/right_awsbase.rb', line 717

def with_connection_options(options, &block)
  @with_connection_options = options
  block.call self
ensure
  @with_connection_options = {}
end