class Facter::GCE::Metadata

@api private

Constants

CONNECTION_ERRORS
METADATA_URL

Public Class Methods

new(url = METADATA_URL) click to toggle source
# File lib/facter/gce/metadata.rb, line 22
def initialize(url = METADATA_URL)
  @url = url
end

Public Instance Methods

fetch() click to toggle source
# File lib/facter/gce/metadata.rb, line 26
def fetch
  with_metadata_server do |body|
    # This will only be reached if the confine associated with this class
    # was true which means that JSON was required, but it's a bit
    # questionable that we're relying on JSON being loaded as a side
    # effect of that.
    hash = ::JSON.parse(body)
    transform_metadata!(hash)
    hash
  end
end

Private Instance Methods

transform_metadata!(data) click to toggle source

@return [void]

# File lib/facter/gce/metadata.rb, line 66
def transform_metadata!(data)
  case data
  when Hash
    data.keys.each do |key|
      value = data[key]
      if ["image", "machineType", "zone", "network"].include? key
        data[key] = value.split('/').last
      elsif key == "sshKeys"
        data['sshKeys'] = value.split("\n")
      end
      transform_metadata!(value)
    end
  when Array
    data.each do |value|
      transform_metadata!(value)
    end
  end
  nil
end
with_metadata_server() { |body| ... } click to toggle source
# File lib/facter/gce/metadata.rb, line 40
def with_metadata_server
  retry_limit = 3
  timeout = 0.05
  body = nil
  attempts = 0

  begin
    Timeout.timeout(timeout) do
      body = open(@url, :proxy => nil).read
    end
  rescue *CONNECTION_ERRORS => e
    attempts = attempts + 1
    if attempts < retry_limit
      retry
    else
      Facter.log_exception(e, "Unable to fetch metadata from #{@url}: #{e.message}")
      return nil
    end
  end

  if body
    yield body
  end
end