-
Notifications
You must be signed in to change notification settings - Fork 1
/
launch.py
235 lines (196 loc) · 8.58 KB
/
launch.py
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
"""
Handle the instance:
* Launch new instance with spot request
* Terminate instance
* Check instance connectivity
"""
import socket
import sys
import time
from errno import ECONNREFUSED
from errno import ETIMEDOUT
def query_yes_no(question, default="yes"):
"""Ask a yes/no question via raw_input() and return their answer.
:param question: is a string that is presented to the user.
:param default: is the presumed answer if the user just hits <Enter>.
It must be "yes" (the default), "no" or None (meaning
an answer is required of the user).
:return: The "answer" return value is True for "yes" or False for "no".
"""
valid = {"yes": True, "y": True, "ye": True,
"no": False, "n": False}
if default is None:
prompt = " [y/n] "
elif default == "yes":
prompt = " [Y/n] "
elif default == "no":
prompt = " [y/N] "
else:
raise ValueError("invalid default answer: '%s'" % default)
while True:
sys.stdout.write(question + prompt)
choice = input().lower()
if default is not None and choice == '':
return valid[default]
elif choice in valid:
return valid[choice]
else:
sys.stdout.write("Please respond with 'yes' or 'no' "
"(or 'y' or 'n').\n")
def ping(host, port):
"""
Ping the port of the host
:param host: the host to ping
:param port: the port of the host to ping
:return: the port if the port is open or False if there is a connection error
"""
try:
socket.socket().connect((host, port))
print(str(port) + " Open")
return port
except socket.error as err:
if err.errno == ECONNREFUSED or err.errno == ETIMEDOUT:
return False
raise
def wait_ping(client, instance_ids, pending_instance_ids):
"""Wait that all the instance have open the ssh port (22)
:param client: the ec2 client
:param instance_ids: id of all the instance to ping
:param pending_instance_ids: id of the remaining instance to ping
:return: Exit when all the instance are reachable on port 22
"""
results = client.describe_instances(InstanceIds=pending_instance_ids)
for result in results["Reservations"]:
for instance in result["Instances"]:
if ping(instance["PublicDnsName"], 22) == 22:
pending_instance_ids.pop(pending_instance_ids.index(instance["InstanceId"]))
print("instance `{}` ping ok!".format(instance["InstanceId"]))
else:
print("pinging on `{}`".format(instance["InstanceId"]))
if len(pending_instance_ids) == 0:
print("all instances running!")
else:
time.sleep(2)
wait_ping(client, instance_ids, pending_instance_ids)
def wait_for_running(client, instance_ids, pending_instance_ids):
"""Wait that all the instance are in running state
:param client: the ec2 client
:param instance_ids: id of all the instance to check running
:param pending_instance_ids: id of the remaining instance to check running
:return: Exit when all the instance are running
"""
results = client.describe_instances(InstanceIds=pending_instance_ids)
for result in results["Reservations"]:
for instance in result["Instances"]:
if instance["State"]["Name"] == 'running':
pending_instance_ids.pop(pending_instance_ids.index(instance["InstanceId"]))
print("instance `{}` running!".format(instance["InstanceId"]))
else:
print("waiting on `{}`".format(instance["InstanceId"]))
if len(pending_instance_ids) == 0:
print("all instances running!")
else:
time.sleep(10)
wait_for_running(client, instance_ids, pending_instance_ids)
def wait_for_fulfillment(client, request_ids, pending_request_ids):
"""Wait that all the spot instance request are fulfilled
:param client: the ec2 client
:param request_ids: id of all the spot instance request to fulfill
:param pending_request_ids: id of the remaining spot instance request to fulfill
:return: Exit when all the spot request are fulfilled
"""
results = client.describe_spot_instance_requests(SpotInstanceRequestIds=pending_request_ids)
for result in results["SpotInstanceRequests"]:
if result["Status"]["Code"] == 'fulfilled':
pending_request_ids.pop(pending_request_ids.index(result["SpotInstanceRequestId"]))
print("spot request `{}` fulfilled!".format(result["SpotInstanceRequestId"]))
else:
print("waiting on `{}`".format(result["SpotInstanceRequestId"]))
if len(pending_request_ids) == 0:
print("all spots fulfilled!")
else:
time.sleep(10)
wait_for_fulfillment(client, request_ids, pending_request_ids)
def terminate(client, spot_request_ids, instance_ids):
"""Delete all the spot_request_ids and terminate al the instance_ids
:param client: the ec2 client
:param spot_request_ids: id of all the spot instance request to delete
:param instance_ids: id of all the instance to terminate
:return:
"""
# DELETE SPOT REQUEST
client.cancel_spot_instance_requests(SpotInstanceRequestIds=spot_request_ids)
# TERMINATE INSTANCE
client.instances.filter(InstanceIds=instance_ids).stop()
client.instances.filter(InstanceIds=instance_ids).terminate()
def check_spot_price(client, config):
"""Check the current spot price on the selected amazon region of the instance type choosen
and compare with the one provided by the user
:param client: the ec2 client
:param config: the configuration dictionary of the user
:return: Exit if the spot price of the user is too low (< current price + 20%)
"""
spot_price_history_response = client.describe_spot_price_history(
InstanceTypes=[config["Aws"]["InstanceType"]],
ProductDescriptions=['Linux/UNIX'],
AvailabilityZone=config["Aws"]["AZ"])
print(spot_price_history_response['SpotPriceHistory'][0])
last_spot_price = [float(x['SpotPrice']) for x in
spot_price_history_response['SpotPriceHistory'][:10]]
print(last_spot_price)
print("Number of responses:", len(spot_price_history_response['SpotPriceHistory']))
spot_price = float(sum(last_spot_price)) / max(len(last_spot_price), 1)
spot_price += (spot_price * 0.2)
spot_price = float("{0:.2f}".format(spot_price))
print("LAST 10 SPOT PRICE + 20%: " + str(spot_price))
print("YOUR PRICE: " + str(config["Aws"]["Price"]))
if float(config["Aws"]["Price"]) < spot_price:
print("ERROR PRICE")
exit(1)
def launch(client, num_instance, config):
"""
Launch num_instance on Amazon EC2 with spot request
:param client: the ec2 client
:param num_instance: number of instance to launch
:param config: the configuration dictionary of the user
:return: the list of spot request's ids
"""
if query_yes_no("Are you sure to launch " + str(num_instance) + " new instance?", "no"):
check_spot_price(client, config)
spot_request_response = client.request_spot_instances(
SpotPrice=config["Aws"]["Price"],
InstanceCount=num_instance,
Type='one-time',
AvailabilityZoneGroup=
config["Aws"]["AZ"],
LaunchSpecification={
"ImageId": config["Aws"]["AMI"],
"KeyName": config["Aws"]["KeyPair"],
"SecurityGroups": [
config["Aws"]["SecurityGroup"],
],
'Placement': {
'AvailabilityZone': config["Aws"]["AZ"],
},
"InstanceType": config["Aws"]["InstanceType"],
"EbsOptimized": config["Aws"]["EbsOptimized"],
"BlockDeviceMappings": [
{
"DeviceName": "/dev/sda1",
"Ebs": {
"DeleteOnTermination": True,
"VolumeType": "gp2",
"VolumeSize": 200,
"SnapshotId": config["Aws"]["SnapshotId"]
}
},
{
"DeviceName": "/dev/sdb",
"VirtualName": "ephemeral0"
}
],
})
print([req["SpotInstanceRequestId"] for req in
spot_request_response["SpotInstanceRequests"]])
return [req["SpotInstanceRequestId"] for req in
spot_request_response["SpotInstanceRequests"]]