class AWS::Base

This class provides all the methods for using the EC2 or ELB service including the handling of header signing and other security concerns. This class uses the Net::HTTP library to interface with the AWS Query API interface. You should not instantiate this directly, instead you should setup an instance of 'AWS::EC2::Base' or 'AWS::ELB::Base'.

Attributes

port[R]
proxy_server[R]
server[R]
use_ssl[R]

Public Class Methods

new( options = {} ) click to toggle source

@option options [String] :access_key_id (“”) The user's AWS Access Key ID @option options [String] :secret_access_key (“”) The user's AWS Secret Access Key @option options [Boolean] :use_ssl (true) Connect using SSL? @option options [String] :server (“ec2.amazonaws.com”) The server API endpoint host @option options [String] :proxy_server (nil) An HTTP proxy server FQDN @return [Object] the object.

# File lib/AWS.rb, line 123
def initialize( options = {} )

  options = { :access_key_id => "",
              :secret_access_key => "",
              :use_ssl => true,
              :server => default_host,
              :proxy_server => nil
              }.merge(options)

  @server = options[:server]
  @proxy_server = options[:proxy_server]
  @use_ssl = options[:use_ssl]

  raise ArgumentError, "No :access_key_id provided" if options[:access_key_id].nil? || options[:access_key_id].empty?
  raise ArgumentError, "No :secret_access_key provided" if options[:secret_access_key].nil? || options[:secret_access_key].empty?
  raise ArgumentError, "No :use_ssl value provided" if options[:use_ssl].nil?
  raise ArgumentError, "Invalid :use_ssl value provided, only 'true' or 'false' allowed" unless options[:use_ssl] == true || options[:use_ssl] == false
  raise ArgumentError, "No :server provided" if options[:server].nil? || options[:server].empty?

  if options[:port]
    # user-specified port
    @port = options[:port]
  elsif @use_ssl
    # https
    @port = 443
  else
    # http
    @port = 80
  end

  @access_key_id = options[:access_key_id]
  @secret_access_key = options[:secret_access_key]

  # Use proxy server if defined
  # Based on patch by Mathias Dalheimer.  20070217
  proxy = @proxy_server ? URI.parse(@proxy_server) : OpenStruct.new
  @http = Net::HTTP::Proxy( proxy.host,
                            proxy.port,
                            proxy.user,
                            proxy.password).new(options[:server], @port)

  @http.use_ssl = @use_ssl

  # Don't verify the SSL certificates.  Avoids SSL Cert warning in log on every GET.
  @http.verify_mode = OpenSSL::SSL::VERIFY_NONE

end

Public Instance Methods

extract_user_data( options = {} ) click to toggle source

If :user_data is passed in then URL escape and Base64 encode it as needed. Need for URL Escape + Base64 encoding is determined by :base64_encoded param.

# File lib/AWS.rb, line 174
def extract_user_data( options = {} )
  return unless options[:user_data]
  if options[:user_data]
    if options[:base64_encoded]
      Base64.encode64(options[:user_data]).gsub(/\n/, "").strip()
    else
      options[:user_data]
    end
  end
end

Protected Instance Methods

aws_error?(response) click to toggle source

Raises the appropriate error if the specified Net::HTTPResponse object contains an AWS error; returns false otherwise.

# File lib/AWS.rb, line 290
def aws_error?(response)

  # return false if we got a HTTP 200 code,
  # otherwise there is some type of error (40x,50x) and
  # we should try to raise an appropriate exception
  # from one of our exception classes defined in
  # exceptions.rb
  return false if response.is_a?(Net::HTTPSuccess)

  # parse the XML document so we can walk through it
  doc = REXML::Document.new(response.body)

  # Check that the Error element is in the place we would expect.
  # and if not raise a generic error exception
  unless doc.root.elements['Errors'].elements['Error'].name == 'Error'
    raise Error, "Unexpected error format. response.body is: #{response.body}"
  end

  # An valid error response looks like this:
  # <?xml version="1.0"?><Response><Errors><Error><Code>InvalidParameterCombination</Code><Message>Unknown parameter: foo</Message></Error></Errors><RequestID>291cef62-3e86-414b-900e-17246eccfae8</RequestID></Response>
  # AWS throws some exception codes that look like Error.SubError.  Since we can't name classes this way
  # we need to strip out the '.' in the error 'Code' and we name the error exceptions with this
  # non '.' name as well.
  error_code    = doc.root.elements['Errors'].elements['Error'].elements['Code'].text.gsub('.', '')
  error_message = doc.root.elements['Errors'].elements['Error'].elements['Message'].text

  # Raise one of our specific error classes if it exists.
  # otherwise, throw a generic EC2 Error with a few details.
  if AWS.const_defined?(error_code)
    raise AWS.const_get(error_code), error_message
  else
    raise AWS::Error, error_message
  end

end
get_aws_auth_param(params, secret_access_key, server) click to toggle source

Set the Authorization header using AWS signed header authentication

# File lib/AWS.rb, line 267
def get_aws_auth_param(params, secret_access_key, server)
  canonical_string =  AWS.canonical_string(params, server)
  encoded_canonical = AWS.encode(secret_access_key, canonical_string)
end
make_request(action, params, data='') click to toggle source

Make the connection to AWS EC2 passing in our request. This is generally called from within a 'Response' class object or one of its sub-classes so the response is interpreted in its proper context. See lib/EC2/responses.rb

# File lib/AWS.rb, line 231
def make_request(action, params, data='')

  @http.start do

    # remove any keys that have nil or empty values
    params.reject! { |key, value| value.nil? or value.empty?}

    params.merge!( {"Action" => action,
                    "SignatureVersion" => "2",
                    "SignatureMethod" => 'HmacSHA1',
                    "AWSAccessKeyId" => @access_key_id,
                    "Version" => api_version,
                    "Timestamp"=>Time.now.getutc.iso8601} )

    sig = get_aws_auth_param(params, @secret_access_key, @server)

    query = params.sort.collect do |param|
      CGI::escape(param[0]) + "=" + CGI::escape(param[1])
    end.join("&") + "&Signature=" + sig

    req = Net::HTTP::Post.new("/")
    req.content_type = 'application/x-www-form-urlencoded'
    req['User-Agent'] = "github-amazon-ec2-ruby-gem"

    response = @http.request(req, query)

    # Make a call to see if we need to throw an error based on the response given by EC2
    # All error classes are defined in EC2/exceptions.rb
    aws_error?(response)
    return response

  end

end
pathhashlist(key, arr_of_hashes, mappings) click to toggle source

Same as pathlist except it deals with arrays of hashes. So if you pass in args (“People”, [{:name=>'jon', :age=>'22'}, {:name=>'chris'}], {:name => 'Name', :age => 'Age'}) you should get {“People.1.Name”=>“jon”, “People.1.Age”=>'22', 'People.2.Name'=>'chris'}

# File lib/AWS.rb, line 214
def pathhashlist(key, arr_of_hashes, mappings)
  raise ArgumentError, "expected a key that is a String" unless key.is_a? String
  raise ArgumentError, "expected a arr_of_hashes that is an Array" unless arr_of_hashes.is_a? Array
  arr_of_hashes.each{|h| raise ArgumentError, "expected each element of arr_of_hashes to be a Hash" unless h.is_a?(Hash)}
  raise ArgumentError, "expected a mappings that is an Hash" unless mappings.is_a? Hash
  params = {}
  arr_of_hashes.each_with_index do |hash, i|
    hash.each do |attribute, value|
      params["#{key}.#{i+1}.#{mappings[attribute]}"] = value.to_s
    end
  end
  params
end
pathlist(key, arr) click to toggle source

pathlist is a utility method which takes a key string and and array as input. It converts the array into a Hash with the hash key being 'Key.n' where 'n' increments by 1 for each iteration. So if you pass in args (“ImageId”, [“123”, “456”]) you should get {“ImageId.1”=>“123”, “ImageId.2”=>“456”} returned.

# File lib/AWS.rb, line 193
def pathlist(key, arr)
  params = {}

  # ruby 1.9 will barf if we pass in a string instead of the array expected.
  # it will fail on each_with_index below since string is not enumerable.
  if arr.is_a? String
    new_arr = []
    new_arr << arr
    arr = new_arr
  end

  arr.each_with_index do |value, i|
    params["#{key}.#{i+1}"] = value
  end
  params
end
response_generator( options = {} ) click to toggle source

allow us to have a one line call in each method which will do all of the work in making the actual request to AWS.

# File lib/AWS.rb, line 274
def response_generator( options = {} )

  options = {
    :action => "",
    :params => {}
  }.merge(options)

  raise ArgumentError, ":action must be provided to response_generator" if options[:action].nil? || options[:action].empty?

  http_response = make_request(options[:action], options[:params])
  http_xml = http_response.body
  return Response.parse(:xml => http_xml)
end