forked from davidsiaw/sumomo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
update-spec.rb
381 lines (322 loc) · 9.89 KB
/
update-spec.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
require 'json'
puts "Updates the data in the custom_resources folder"
`aws ec2 describe-instance-types > itypes`
data = JSON.parse(File.read('itypes'))
start = {
a: 2.0,
c: 2.5,
d: 2.0,
f: 2.0,
g: 2.0,
h: 2.0,
i: 3.0,
m: 2.0,
p: 2.0,
r: 2.0,
t: 1.0,
v: 2.0,
x: 2.0,
z: 2.0
}
types = []
types2 = []
data['InstanceTypes'].each do |info|
virt = 'pv'
if info["GpuInfo"]
virt = 'ecs-gpu-hvm'
elsif info["SupportedVirtualizationTypes"].last == 'hvm'
virt = 'ecs-hvm'
end
mount = 'ebs'
arch = info["ProcessorInfo"]["SupportedArchitectures"].last
raise 'UNKNOWN ARCH COMBINATION' if arch == 'arm64' && mount == 's3'
pattern = "amzn2-ami-#{virt}-2.0.*#{arch}-#{mount}"
if arch == 'x86_64_mac'
pattern = 'amzn-ec2-macos-*'
end
gennum = /[0-9]/.match(info['InstanceType']).to_s.to_i
ecu = (( start[ info['InstanceType'][0].to_sym ] + gennum.to_f * 0.5) * (info['VCpuInfo']['DefaultVCpus']).to_f * 1024).floor
types << " '#{info['InstanceType']}': { cpu: #{info['VCpuInfo']['DefaultVCpus'] * 1024}, memory: #{info["MemoryInfo"]["SizeInMiB"]}, gen: #{gennum}, ecu: #{ecu}, arch: '#{info["ProcessorInfo"]["SupportedArchitectures"].last}' }"
types2 << " '#{info['InstanceType']}': { pattern: '#{pattern}' }"
end
def align(arr)
result = []
lengths = arr[0].split(':').map{|x| x.length}
arr.each do |x|
tokens = x.split(':')
tokens.each_with_index do |y,i|
if y.length > lengths[i]
lengths[i] = y.length
end
end
end
arr.each do |x|
tokens = x.split(':')
newtokens = []
tokens.each_with_index do |y,i|
newtokens << (' ' * (lengths[i] - y.length) + y)
end
result << newtokens.join(':')
end
result
end
types.sort!
types2.sort!
types = align(types)
types2 = align(types2)
selectspot = <<~SELECTSPOT
var ec2 = new aws.EC2({region: request.ResourceProperties.Region});
if (request.RequestType == "Delete")
{
Cloudformation.send(request, context, Cloudformation.SUCCESS, {}, "Success");
return;
}
var prices = []
var exclude_string = request.ResourceProperties.ExcludeString || ""
var look_back = request.ResourceProperties.LookBack;
var want_to_pay = request.ResourceProperties.TargetPrice;
var exclude = exclude_string.split(",")
var typeToCapability = {
#{types.join(",\n")}
}
function pick_lowest_prices(prices)
{
var item_map = {};
for(var i in prices)
{
var price = prices[i];
if (!item_map[price.type] || item_map[price.type].price > price.price)
{
item_map[price.type] = price;
}
}
var result = [];
for(var i in item_map)
{
result.push(item_map[i]);
}
return result;
}
function score_type(type)
{
return (typeToCapability[type].cpu + typeToCapability[type].memory) * (1 + typeToCapability[type].gen * 0.05);
}
function difference(v1, v2)
{
return Math.abs(v1-v2);
}
function complete()
{
prices = pick_lowest_prices(prices);
prices.sort(function(a,b) {
if (a.price < b.price) {
return -1;
}
if (a.price > b.price) {
return 1;
}
return 0;
});
var index = 0;
for(var i in prices)
{
index = i;
if(prices[i].price > want_to_pay)
{
break;
}
}
shortlist = prices.splice(0, index)
var result = prices[0];
if (shortlist.length != 0)
{
shortlist.sort(function(a,b) {
if (score_type(a.type) > score_type(b.type)) {
return -1;
}
if (score_type(a.type) < score_type(b.type)) {
return 1;
}
return 0;
});
//for(var i in shortlist)
//{
// console.log(shortlist[i]);
//}
result = shortlist[0];
}
response = {
Price: String(result.price + 0.0001),
Zone: String(result.zone),
AveragePrice: String(result.average_price),
HighLine: String(result.high_line),
HighTime: String(result.high_time),
LowLine: String(result.low_line),
LowTime: String(result.low_time),
CpuUnits: String(typeToCapability[result.type].cpu),
CpuRating: String(typeToCapability[result.type].ecu),
MemRating: String(typeToCapability[result.type].memory)
}
Cloudformation.send(request, context, Cloudformation.SUCCESS, response, "Success", result.type);
console.log(JSON.stringify(prices));
}
function get_spot_prices(zones)
{
var newest_price={};
var xtotal={};
var xcount={};
var xhigh={};
var xlow={};
var xhightime={};
var xlowtime={};
function collect_data(zone, remaining, next_token)
{
if (remaining === 0 || next_token === null)
{
for(var type in newest_price)
{
var included = true;
for(var i=0;i<exclude.length;i++)
{
if(type.indexOf(exclude[i]) != -1)
{
included = false;
break;
}
}
if (!included)
{
continue;
}
prices.push({
type: type,
price: newest_price[type],
zone: zones[0],
average_price: xtotal[type]/xcount[type],
high_line: xhigh[type],
high_time: xhightime[type],
low_line: xlow[type],
low_time: xlowtime[type],
});
}
zones.splice(0,1);
get_spot_prices(zones);
}
else
{
ec2.describeSpotPriceHistory({
AvailabilityZone: zone,
MaxResults: 1000,
NextToken: next_token
}, function(err, data) {
if (err)
{
console.log(err, err.stack); // an error occurred
Cloudformation.send(request, context, Cloudformation.FAILED, {}, JSON.stringify(err));
}
else
{
//console.log(JSON.stringify(data.SpotPriceHistory))
for(var i=0;i<data.SpotPriceHistory.length;i++)
{
var history = data.SpotPriceHistory[i];
if (!newest_price[history.InstanceType])
{
newest_price[history.InstanceType] = Number(history.SpotPrice);
xtotal[history.InstanceType] = Number(history.SpotPrice);
xcount[history.InstanceType] = 1;
xhigh[history.InstanceType] = Number(history.SpotPrice);
xlow[history.InstanceType] = Number(history.SpotPrice);
xhightime[history.InstanceType] = history.Timestamp;
xlowtime[history.InstanceType] = history.Timestamp;
}
else
{
xtotal[history.InstanceType]+= Number(history.SpotPrice);
xcount[history.InstanceType]+= 1;
if (xhigh[history.InstanceType] < Number(history.SpotPrice))
{
xhigh[history.InstanceType] = Number(history.SpotPrice);
xhightime[history.InstanceType] = history.Timestamp;
}
if (xlow[history.InstanceType] > Number(history.SpotPrice))
{
xlow[history.InstanceType] = Number(history.SpotPrice);
xlowtime[history.InstanceType] = history.Timestamp;
}
}
}
collect_data(zone, remaining-1, data.NextToken);
}
});
}
}
if (zones.length == 0)
{
complete();
}
else
{
collect_data(zones[0], look_back);
}
}
ec2.describeAvailabilityZones({}, function(err, data) {
if (err)
{
console.log(err, err.stack); // an error occurred
Cloudformation.send(request, context, Cloudformation.FAILED, {}, JSON.stringify(err));
}
else
{
var zones = data.AvailabilityZones.map(function(x) {return x.ZoneName;});
get_spot_prices(zones);
}
});
SELECTSPOT
lookup = <<~AMILOOKUP
var typeToPattern = {
#{types2.join(",\n")}
}
var ec2 = new aws.EC2({region: request.ResourceProperties.Region});
var describeImagesParams = {
Filters: [{ Name: "name", Values: [typeToPattern[request.ResourceProperties.InstanceType].pattern]}],
Owners: [request.ResourceProperties.Architecture == "HVMG2" ? "679593333241" : "amazon"]
};
// Check if the image is a beta or rc image. The Lambda function won't return any of those images.
function isBeta(imageName) {
return imageName.toLowerCase().indexOf("beta") > -1 || imageName.toLowerCase().indexOf(".rc") > -1;
}
// Get AMI IDs with the specified name pattern and owner
ec2.describeImages(describeImagesParams, function(err, describeImagesResult)
{
if (err)
{
console.log(err, err.stack); // an error occurred
Cloudformation.send(request, context, Cloudformation.FAILED, {}, JSON.stringify(err));
}
else
{
var response = {}
var id = "NONE";
var images = describeImagesResult.Images;
// Sort images by name in descending order. The names contain the AMI version, formatted as YYYY.MM.Ver.
images.sort(function(x, y) { return y.Name.localeCompare(x.Name); });
for (var j = 0; j < images.length; j++)
{
if (isBeta(images[j].Name)) continue;
id = images[j].ImageId;
response["Name"] = images[j].Name;
response["ImageType"] = images[j].ImageType;
response["CreationDate"] = images[j].CreationDate;
response["Description"] = images[j].Description;
response["RootDeviceType"] = images[j].RootDeviceType;
response["RootDeviceName"] = images[j].RootDeviceName;
response["VirtualizationType"] = images[j].VirtualizationType;
break;
}
Cloudformation.send(request, context, Cloudformation.SUCCESS, response, "Success", id);
}
});
AMILOOKUP
File.write('data/sumomo/custom_resources/SelectSpot.js', selectspot);
File.write('data/sumomo/custom_resources/AMILookup.js', lookup);