Class: EC2_Utils

Inherits:
Object
  • Object
show all
Defined in:
lib/audit/lib/ec2_utils.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(ec2_options) ⇒ EC2_Utils

Returns a new instance of EC2_Utils.



7
8
9
# File 'lib/audit/lib/ec2_utils.rb', line 7

def initialize(ec2_options)
	@ec2 = AWS::EC2::Base.new(ec2_options)
end

Instance Attribute Details

#ec2Object (readonly)

Returns the value of attribute ec2.



4
5
6
# File 'lib/audit/lib/ec2_utils.rb', line 4

def ec2
  @ec2
end

Instance Method Details

#get_cheapest_instance_type(machine_id) ⇒ Object



69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/audit/lib/ec2_utils.rb', line 69

def get_cheapest_instance_type(machine_id)
	machines = @ec2.describe_images(:image_id => machine_id)
	begin
		return "t1.micro" if machines['imagesSet']['item'][0]['rootDeviceType'] == "ebs"
		return 'm1.small' if machines['imagesSet']['item'][0]['architecture'] == "i386"
		return "m1.large" if machines['imagesSet']['item'][0]['architecture'] == "x86_64"
	rescue => err
	end

	puts "ERROR: Finding cheapest instance type in EC2_Utils::get_cheapest_instance_type for machine_id = #{machine_id}"
	return "t1.micro"
end

#get_image_id(instance_id) ⇒ Object



45
46
47
48
49
50
51
52
# File 'lib/audit/lib/ec2_utils.rb', line 45

def get_image_id(instance_id)
	instances = @ec2.describe_instances(:instance_id => instance_id)
	if instances then
		return instances["reservationSet"]["item"][0]["instancesSet"]["item"][0]["imageId"]
	else
		return "none"
	end
end

#get_instance_public_dns(instance_id) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/audit/lib/ec2_utils.rb', line 17

def get_instance_public_dns(instance_id)
	error_count = 0
	begin
		while (true) do
			instances = @ec2.describe_instances(:instance_id => instance_id)
			# protect against nil errors because parts of the structure are not initialized when the DNS is not known
			begin
				dns_name = instances["reservationSet"]["item"][0]["instancesSet"]["item"][0]["dnsName"]
				return dns_name if dns_name
			rescue => err
			end
			sleep(5)
		end
	rescue => err
		error_count += 1
		raise err if error_count > 3
		
		sleep(5)
		retry
	end
end

#get_instance_statesObject



55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/audit/lib/ec2_utils.rb', line 55

def get_instance_states()
	instanceStates = []
	@ec2.describe_instances()['reservationSet']['item'].each do|x|
		x['instancesSet']['item'].each do|y|
			instanceStates << {:instance_id => y['instanceId'], 
			                   :state => y['instanceState']['name'],
			                   :image_id => y['imageId'],
			                   :runtime => (DateTime.now() - DateTime.strptime(y['launchTime'], "%Y-%m-%dT%H:%M:%S")) * 24.0}
		end
	end
	return instanceStates
end

#get_instance_volumes(instance_id) ⇒ Object



154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
# File 'lib/audit/lib/ec2_utils.rb', line 154

def get_instance_volumes(instance_id)
	volumes = []
	instances = @ec2.describe_instances(:instance_id => [instance_id])
	
	instances['reservationSet']['item'].each do|reservationSet|
		next unless reservationSet['instancesSet']
		
		reservationSet['instancesSet']['item'].each do|instancesSet|
			next unless instancesSet['blockDeviceMapping']
			
			instancesSet['blockDeviceMapping']['item'].each do|blockDeviceMapping|
				next unless blockDeviceMapping['ebs']
				
				volumes << blockDeviceMapping['ebs']['volumeId']
			end
		end
	end
	
	return volumes
end

#get_spot_prices(options = {}) ⇒ Object



204
205
206
207
208
209
210
211
212
213
214
215
216
217
# File 'lib/audit/lib/ec2_utils.rb', line 204

def get_spot_prices(options = {})
	arg = {:start_time => Time.now() - 1, :end_time => Time.now()}
	arg[:instance_type] = options[:instance_type] if options[:instance_type]
	spot_prices = ec2.describe_spot_price_history(arg)
	
	prices = {}
	if spot_prices["spotPriceHistorySet"] then
		spot_prices["spotPriceHistorySet"]["item"].each do|spot_price|
			(prices[spot_price["instanceType"]] ||= {})[spot_price["productDescription"]] = {:price => spot_price["spotPrice"], :timestamp => spot_price["timestamp"]}
		end
	end
	
	return prices
end

#start_instance(options) ⇒ Object



83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
# File 'lib/audit/lib/ec2_utils.rb', line 83

def start_instance(options)
	raise "Invalid parameters to EC2_Utils::start_instance: :id is missing" unless options[:id]

	if /^ami-.*$/.match(options[:id]) then
		raise "Invalid parameters to EC2_Utils::start_instance: :ssh_keypair is missing" unless options[:ssh_keypair]
		raise "Invalid parameters to EC2_Utils::start_instance: :instance_type is missing" unless options[:instance_type]
		raise "Invalid parameters to EC2_Utils::start_instance: :security_group is missing" unless options[:security_group]
	
		instance_id = false
		if options[:max_price] then
			spot_request = @ec2.request_spot_instances(
				:image_id => options[:id], 
				:instance_count => 1, 
				:key_name => options[:ssh_keypair], 
				:security_group => options[:security_group], 
				:disable_api_termination => false, 
				:instance_type => options[:instance_type],
				:spot_price => options[:max_price],
				:valid_from => nil,
				:valid_until => nil)
				
			spot_request_id = spot_request['spotInstanceRequestSet']['item'][0]['spotInstanceRequestId']
			begin
				spot_reqs = ec2.describe_spot_instance_requests()
				spot_req = spot_reqs['spotInstanceRequestSet']['item'].reject{|x| x['spotInstanceRequestId'] != spot_request_id}
				
				raise "Spot request #{spot_request_id} seems to have disappeared" if spot_req.length() != 1
				
				if spot_req[0]['instanceId'] then
					instance_id = spot_req[0]['instanceId']
				end
				
				sleep(30)
			end until instance_id
		else
			instance = @ec2.run_instances(
				:image_id => options[:id], 
				:max_count => 1, 
				:key_name => options[:ssh_keypair], 
				:security_group => options[:security_group], 
				:disable_api_termination => false, 
				:instance_type => options[:instance_type])
			instance_id = instance["instancesSet"]["item"][0]["instanceId"] 
		end
		
		image_id = options[:id]                                                                                                                                                                                                                                                                                                                                                                                                                                                                          
	elsif /^i-.*$/.match(options[:id]) then 
		instance_id = options[:id] 
		image_id = get_image_id(instance_id) 
	else 
		raise "Unknown identifier #{options[:id]}"                                                                                                                                                                                                                                      
	end 

	puts "instance #{instance_id} started, waiting for IP address" if options[:verbose]
	begin 
		dns_name = get_instance_public_dns(instance_id) 
	rescue => err
		puts "ERROR: During DNS request of AMI" if options[:verbose]
	end
	
	if dns_name.nil? || dns_name.empty? then 
		puts "ERROR: No DNS name for AMI found" if options[:verbose]
		raise "No DNS name for AMI found"
	end
	
	return {:machine_id => image_id,
	        :instance_id => instance_id,
	        :public_dns => dns_name}
end

#terminate_instance(instance_id) ⇒ Object



176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
# File 'lib/audit/lib/ec2_utils.rb', line 176

def terminate_instance(instance_id)
	volumes = get_instance_volumes(instance_id)
	
	@ec2.terminate_instances(:instance_id => [instance_id])

	begin
		#wait till instance is terminated
		begin
			instance_state = @ec2.describe_instances(:instance_id => [instance_id])['reservationSet']['item'][0]['instancesSet']['item'][0]['instanceState']['name']
		end unless instance_state == "terminated"
		
		#delete volumes
		volumes.each do|volume|
			begin
				@ec2.detach_volumes(:volume_id => volume)
			rescue => err
			end
			
			@ec2.delete_volume(:volume_id => volume)
		end
	rescue => err
		if err.class() == AWS::Error  && /The volume 'vol-[0-9a-f]{8}' does not exist/.match(err.message()) then
			#ignore error
		end
	end
end