-
Notifications
You must be signed in to change notification settings - Fork 926
Expand file tree
/
Copy pathscrape-ec2-prices.py
More file actions
executable file
·333 lines (279 loc) · 11.2 KB
/
scrape-ec2-prices.py
File metadata and controls
executable file
·333 lines (279 loc) · 11.2 KB
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
#!/usr/bin/env python
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
import os
import re
import copy
import json
import time
import atexit
from collections import OrderedDict, defaultdict
import tqdm # pylint: disable=import-error
import ijson # pylint: disable=import-error
import requests
# Buffer size for ijson.parse() function. Larger buffer size results in increased memory
# consumption, but faster parsing.
IJSON_BUF_SIZE = 30 * 65536
# same URL as the one used by scrape-ec2-sizes.py, now it has official data on pricing
URL = "https://pricing.us-east-1.amazonaws.com/offers/v1.0/aws/AmazonEC2/current/index.json"
RE_NUMERIC_OTHER = re.compile(r"(?:([0-9]+)|([-A-Z_a-z]+)|([^-0-9A-Z_a-z]+))")
BASE_PATH = os.path.dirname(os.path.abspath(__file__))
PRICING_FILE_PATH = os.path.join(BASE_PATH, "../libcloud/data/pricing.json")
PRICING_FILE_PATH = os.path.abspath(PRICING_FILE_PATH)
FILEPATH = os.environ.get("TMP_JSON", "/tmp/ec.json")
INSTANCE_SIZES = [
"micro",
"small",
"medium",
"large",
"xlarge",
"x-large",
"extra-large",
]
def download_json():
if os.path.isfile(FILEPATH):
mtime_str = time.strftime("%Y-%m-%d %H:%I:%S UTC", time.gmtime(os.path.getmtime(FILEPATH)))
print("Using data from existing cached file {} (mtime={})".format(FILEPATH, mtime_str))
return open(FILEPATH), True
def remove_partial_cached_file():
if os.path.isfile(FILEPATH):
os.remove(FILEPATH)
# File not cached locally, download data and cache it
with requests.get(URL, stream=True) as response:
atexit.register(remove_partial_cached_file)
total_size_in_bytes = int(response.headers.get("content-length", 0))
progress_bar = tqdm.tqdm(total=total_size_in_bytes, unit="iB", unit_scale=True)
chunk_size = 10 * 1024 * 1024
with open(FILEPATH, "wb") as fp:
# NOTE: We use shutil.copyfileobj with large chunk size instead of
# response.iter_content with large chunk size since data we
# download is massive and copyfileobj is more efficient.
# shutil.copyfileobj(response.raw, fp, 10 * 1024 * 1024)
for chunk_data in response.iter_content(chunk_size):
progress_bar.update(len(chunk_data))
fp.write(chunk_data)
progress_bar.close()
atexit.unregister(remove_partial_cached_file)
return FILEPATH, False
def get_json():
if not os.path.isfile(FILEPATH):
return download_json()[0], False
mtime_str = time.strftime("%Y-%m-%d %H:%I:%S UTC", time.gmtime(os.path.getmtime(FILEPATH)))
print("Using data from existing cached file {} (mtime={})".format(FILEPATH, mtime_str))
return FILEPATH, True
# Prices and sizes are in different dicts and categorized by sku
def get_all_prices():
# return variable
# prices = {sku : {price: int, unit: string}}
prices = {}
current_sku = ""
current_rate_code = ""
amazonEC2_offer_code = "JRTCKXETXF"
json_file, from_file = get_json()
with open(json_file) as f:
print("Starting to parse pricing data, this could take up to 15 minutes...")
parser = ijson.parse(f, buf_size=IJSON_BUF_SIZE)
# use parser because file is very large
for prefix, event, value in tqdm.tqdm(parser):
if "products" in prefix:
continue
if (prefix, event) == ("terms.OnDemand", "map_key"):
current_sku = value
prices[current_sku] = {}
elif (prefix, event) == (
f"terms.OnDemand.{current_sku}.{current_sku}.{amazonEC2_offer_code}.priceDimensions",
"map_key",
):
current_rate_code = value
elif (prefix, event) == (
f"terms.OnDemand.{current_sku}.{current_sku}.{amazonEC2_offer_code}.priceDimensions"
f".{current_rate_code}.unit",
"string",
):
prices[current_sku]["unit"] = value
elif (prefix, event) == (
f"terms.OnDemand.{current_sku}.{current_sku}.{amazonEC2_offer_code}.priceDimensions"
f".{current_rate_code}.pricePerUnit.USD",
"string",
):
prices[current_sku]["price"] = value
return prices
# For each combination of location - size - os the file has a different sku.
# For each sku we have a price
def scrape_ec2_pricing():
skus = {}
prices = get_all_prices()
json_file, from_file = get_json()
with open(json_file) as f:
print("Starting to parse pricing data, this could take up to 15 minutes...")
# use parser because file is very large
parser = ijson.parse(f, buf_size=IJSON_BUF_SIZE)
current_sku = ""
for prefix, event, value in tqdm.tqdm(parser):
if "terms" in prefix:
break
if (prefix, event) == ("products", "map_key"):
current_sku = value
skus[current_sku] = {"sku": value}
elif (prefix, event) == (f"products.{current_sku}.productFamily", "string"):
skus[current_sku]["family"] = value
elif (prefix, event) == (
f"products.{current_sku}.attributes.location",
"string",
):
skus[current_sku]["locationName"] = value
elif (prefix, event) == (
f"products.{current_sku}.attributes.locationType",
"string",
):
skus[current_sku]["locationType"] = value
elif (prefix, event) == (
f"products.{current_sku}.attributes.instanceType",
"string",
):
skus[current_sku]["size"] = value
elif (prefix, event) == (
f"products.{current_sku}.attributes.operatingSystem",
"string",
):
skus[current_sku]["os"] = value
elif (prefix, event) == (
f"products.{current_sku}.attributes.usagetype",
"string",
):
skus[current_sku]["usage_type"] = value
elif (prefix, event) == (
f"products.{current_sku}.attributes.preInstalledSw",
"string",
):
skus[current_sku]["preInstalledSw"] = value
elif (prefix, event) == (
f"products.{current_sku}.attributes.regionCode",
"string",
):
skus[current_sku]["location"] = value
# only get prices of compute instances atm
elif (prefix, event) == (f"products.{current_sku}", "end_map"):
family = skus[current_sku].get("family")
if family is None or (
"Compute Instance" not in family and "Dedicated Host" not in family
):
del skus[current_sku]
ec2_linux = defaultdict(OrderedDict)
ec2_windows = defaultdict(OrderedDict)
ec2_rhel = defaultdict(OrderedDict)
ec2_rhel_ha = defaultdict(OrderedDict)
ec2_suse = defaultdict(OrderedDict)
os_map = {
"Linux": ec2_linux,
"Windows": ec2_windows,
"RHEL": ec2_rhel,
"SUSE": ec2_suse,
"Red Hat Enterprise Linux with HA": ec2_rhel_ha,
}
for sku in skus:
if skus[sku]["locationType"] != "AWS Region":
continue
# skip any SQL
if skus[sku].get("preInstalledSw") != "NA":
continue
os = skus[sku]["os"]
if os == "NA":
continue
os_dict = os_map.get(os)
# new OS, until it is documented skip it
if os_dict is None:
print(f"Unexpected OS {os}")
continue
size = skus[sku]["size"]
location = skus[sku]["location"]
# size is first seen
if not os_dict.get(size):
os_dict[size] = {}
# if price already exists pick the BoxUsage usage type which means on demand
if os_dict.get(size, {}).get(location) and "BoxUsage" not in skus[sku]["usage_type"]:
continue
# if price is not a number then label it as not available
try:
price = float(prices[sku]["price"])
os_dict[size][location] = price
except ValueError:
os_dict[size][location] = "n/a"
except KeyError:
# size is available only reserved
del os_dict[size]
return {
"ec2_linux": ec2_linux,
"ec2_windows": ec2_windows,
"ec2_rhel": ec2_rhel,
"ec2_suse": ec2_suse,
"ec2_rhel_ha": ec2_rhel_ha,
}
def update_pricing_file(pricing_file_path, pricing_data):
with open(pricing_file_path) as fp:
content = fp.read()
data = json.loads(content)
original_data = copy.deepcopy(data)
data["compute"].update(pricing_data)
if data == original_data:
# Nothing has changed, bail out early and don't update "updated" attribute
print("Nothing has changed, skipping update.")
return
data["updated"] = int(time.time())
# Always sort the pricing info
data = sort_nested_dict(data)
content = json.dumps(data, indent=4)
lines = content.splitlines()
lines = [line.rstrip() for line in lines]
content = "\n".join(lines)
with open(pricing_file_path, "w") as fp:
fp.write(content)
def sort_nested_dict(value):
"""
Recursively sort a nested dict.
"""
result = OrderedDict()
for key, value in sorted(value.items(), key=sort_key_by_numeric_other):
if isinstance(value, (dict, OrderedDict)):
result[key] = sort_nested_dict(value)
else:
result[key] = value
return result
def sort_key_by_numeric_other(key_value):
"""
Split key into numeric, alpha and other part and sort accordingly.
"""
result = []
for numeric, alpha, other in RE_NUMERIC_OTHER.findall(key_value[0]):
numeric = int(numeric) if numeric else -1
alpha = INSTANCE_SIZES.index(alpha) if alpha in INSTANCE_SIZES else alpha
alpha = str(alpha)
item = tuple([numeric, alpha, other])
result.append(item)
return tuple(result)
def main():
print(
"Scraping EC2 pricing data (if this runs for the first time "
"it has to download a 7GB file, depending on your bandwith "
"it might take a while)...."
)
pricing_data = scrape_ec2_pricing()
update_pricing_file(pricing_file_path=PRICING_FILE_PATH, pricing_data=pricing_data)
print("Pricing data updated")
if __name__ == "__main__":
main()