class Ec2Meta::Fetcher

Constants

API_HOST
API_VERSION

Public Class Methods

new(options = {}) click to toggle source
# File lib/ec2_meta/fetcher.rb, line 13
def initialize(options = {})
  @options = options
  @cache = ::Ec2Meta::Cache.new
end

Public Instance Methods

fetch(path) click to toggle source
# File lib/ec2_meta/fetcher.rb, line 18
def fetch(path)
  @cache.fetch(path) do
    res = http_client.get(request_path(path))
    break res.body if res.code != '404'

    raise MetaNotFound, "'#{path}' not found." if fail_on_not_found?
    nil
  end
rescue Timeout::Error => e
  logger.error 'Can\'t fetch EC2 metadata from EC2 METADATA API.'
  logger.error 'ec2_meta gem is only available on AWS EC2 instance.'
  raise e
rescue MetaNotFound => e
  raise e
rescue => e
  logger.error "Can't fetch EC2 metadata from EC2 METADATA API.(#{e.message})"
  logger.error e.backtrace.join("\n")
  raise e
end

Private Instance Methods

fail_on_not_found?() click to toggle source
# File lib/ec2_meta/fetcher.rb, line 58
def fail_on_not_found?
  @options[:fail_on_not_found]
end
http_client() click to toggle source
# File lib/ec2_meta/fetcher.rb, line 44
def http_client
  return @http_client unless @http_client.nil?

  @http_client = Net::HTTP.new(API_HOST)
  @http_client.open_timeout = @options[:open_timeout] || 2.0
  @http_client.read_timeout = @options[:read_timeout] || 2.0

  @http_client
end
logger() click to toggle source
# File lib/ec2_meta/fetcher.rb, line 40
def logger
  @options[:logger]
end
request_path(path) click to toggle source
# File lib/ec2_meta/fetcher.rb, line 54
def request_path(path)
  '/' + API_VERSION + path
end