Skip to content

Instantly share code, notes, and snippets.

@skeptomai
Created February 5, 2009 16:33
Show Gist options
  • Save skeptomai/58805 to your computer and use it in GitHub Desktop.
Save skeptomai/58805 to your computer and use it in GitHub Desktop.
#
# Author:: Tim Dysinger (<tim@dysinger.net>)
# Author:: Benjamin Black (<bb@opscode.com>)
# Author:: Christopher Brown (<cb@opscode.com>)
# Copyright:: Copyright (c) 2009 Opscode, Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'open-uri'
require 'socket'
include Socket::Constants
require_plugin "hostname"
require_plugin "kernel"
require_plugin "virtualization"
require_plugin "network"
EC2_METADATA_URL = "http://169.254.169.254/2008-02-01/meta-data"
def can_metadata_connect?(addr, port, timeout=2)
t = Socket.new(AF_INET, SOCK_STREAM, 0)
saddr = Socket.pack_sockaddr_in(port, addr)
connected = false
begin
t.connect_nonblock(saddr)
rescue Errno::EINPROGRESS
IO::select(nil,[t],nil,timeout)
begin
t.connect_nonblock(saddr)
rescue Errno::EISCONN
t.close
connected = true
rescue SystemCallError
end
rescue SystemCallError
end
connected
end
def has_ec2_mac?
network[:interfaces].values.each do |iface|
unless iface[:arp].nil?
return true if iface[:arp].value?("fe:ff:ff:ff:ff:ff")
end
end
false
end
def metadata(id='')
# Try non-blocking connect with lite spin so we don't "block" if
# the Xen environment is *not* EC2
OpenURI.open_uri("#{EC2_METADATA_URL}/#{id}").read.split("\n").each do |o|
key = "#{id}#{o.gsub(/\=.*$/, '/')}"
if key[-1..-1] != '/'
ec2[key.gsub(/\-|\//, '_').to_sym] =
OpenURI.open_uri("#{EC2_METADATA_URL}/#{key}").gets
else
metadata(key)
end
end
end
def looks_like_ec2?
virtualization[:system] == "xen" && virtualization[:role] == "guest" && has_ec2_mac? && can_metadata_connect?
end
if looks_like_ec2?
ec2 Mash.new
self.metadata
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment