-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathconfig_manager.py
257 lines (212 loc) · 9.69 KB
/
config_manager.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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
#!/usr/bin/env python
'''
Copyright (C) Yadu Nand B <[email protected]> - All Rights Reserved
Unauthorized copying of this file, via any medium is strictly prohibited
Proprietary and confidential
Written by Yadu Nand B <[email protected]>, September 2015
'''
import os
import logging
import bottle
import requests
import time
from boto.dynamodb2.fields import HashKey
from boto.dynamodb2.table import Table
import boto.dynamodb2 as ddb
import boto.ec2
import boto.sqs
import boto.sns
import boto.ses
import boto.ec2.autoscale
from bottle import app, template
from boto.s3.connection import S3Connection
from datetime import datetime
from datetime import date
from dateutil.relativedelta import relativedelta
log_levels = { "DEBUG" : logging.DEBUG,
"INFO" : logging.INFO,
"WARNING" : logging.WARNING,
"ERROR" : logging.ERROR,
"CRITICAL": logging.CRITICAL
}
# Returns true if the credentials were updated
def update_creds_from_metadata_server(app):
#Todo error check for timeout errors from http access
#TOdo error catch for json decode failure
if "keys.expiry" in app.config and app.config["keys.expiry"] > (datetime.now() + relativedelta(hours=1)):
logging.debug("Update creds from metadata cancelled {0} < {1}".format(
app.config["keys.expiry"],
datetime.now()))
return False
URL = app.config["metadata.credurl"]
role = requests.get(URL).content
URL = URL + role
data = requests.get(URL).json()
app.config["keys.expiry"] = datetime.strptime(str(data['Expiration']), '%Y-%m-%dT%H:%M:%SZ')
app.config["keys.key_id"] = str(data['AccessKeyId'])
app.config["keys.key_secret"] = str(data['SecretAccessKey'])
app.config["keys.key_token"] = str(data['Token'])
URL = app.config["metadata.metaserver"]
data = requests.get(URL+"instance-id").text
app.config["instance_id"] = str(data)
URL = app.config["metadata.metaserver"]
data = requests.get(URL+"instance-type").text
app.config["instance_type"] = str(data)
URL = app.config["metadata.metaserver"]
data = requests.get(URL+"placement/availability-zone/").text
app.config["region"] = str(data)
URL = app.config["metadata.metaidentity"]
data = requests.get(URL).json()
app.config["identity"] = data
if "doReload" in app.config and app.config["doReload"] == True:
init(app)
return True
##################################################################
# Annoy human with email
##################################################################
def send_success_mail(data, app):
sesconn = app.config['ses.conn']
job_id = data.get('job_id')
rec_email = data.get('user_email')
rec_name = data.get('username')
src_email = app.config['ses.email_sender']
url = app.config['server.url']
body = template('./templates/completion_email.tpl',
username=rec_name,
job_id=job_id,
url=url)
try:
st = sesconn.send_email(src_email,
"[Turing] Your Job has completed",
body,
[rec_email])
except Exception as e:
return False
return True
##################################################################
# Verify and add user to email list
##################################################################
def verify_email(app, email):
sesconn = app.config['ses.conn']
st = sesconn.verify_email_address(email)
print st
return st
##################################################################
# Send condolences for job failure
##################################################################
def send_failure_mail(data, app):
sesconn = app.config['ses.conn']
job_id = data.get('job_id')
rec_email = data.get('user_email')
rec_name = data.get('username')
src_email = app.config['ses.email_sender']
url = app.config['server.url']
body = template('./templates/failure_email.tpl',
username=rec_name,
job_id=job_id,
url=url)
try:
st = sesconn.send_email(src_email,
"[Turing] Your Job has failed",
body,
[rec_email])
except Exception, e:
return False
return True
def init(app):
ec2 = boto.ec2.connect_to_region(app.config["identity"]['region'],
aws_access_key_id=app.config['keys.key_id'],
aws_secret_access_key=app.config['keys.key_secret'],
security_token=app.config['keys.key_token'])
#print "instance id : ", app.config["instance_id"]
# Get meta tags
reservation = ec2.get_all_instances(instance_ids=app.config["instance_id"])
meta_tags = {}
if reservation :
for tag in reservation[0].instances[0].tags:
meta_tags[str(tag)] = str(reservation[0].instances[0].tags[tag])
#print str(tag), str(reservation[0].instances[0].tags[tag])
#meta_tags = {}
#for tag in ec2.get_all_tags():
# meta_tags[str(tag.name)] = str(tag.value)
# Log the metadata tags
app.config["instance.tags"] = meta_tags
for k in meta_tags:
logging.debug("[TAGS] {0} : {1}".format(k, meta_tags[k]))
sqs = boto.sqs.connect_to_region(app.config["identity"]['region'],
aws_access_key_id=app.config['keys.key_id'],
aws_secret_access_key=app.config['keys.key_secret'],
security_token=app.config['keys.key_token'])
sns = boto.sns.connect_to_region(app.config["identity"]['region'],
aws_access_key_id=app.config['keys.key_id'],
aws_secret_access_key=app.config['keys.key_secret'],
security_token=app.config['keys.key_token'])
ses = boto.ses.connect_to_region(app.config["identity"]['region'],
aws_access_key_id=app.config['keys.key_id'],
aws_secret_access_key=app.config['keys.key_secret'],
security_token=app.config['keys.key_token'])
scale= boto.ec2.autoscale.AutoScaleConnection(aws_access_key_id=app.config['keys.key_id'],
aws_secret_access_key=app.config['keys.key_secret'],
security_token=app.config['keys.key_token'])
s3 = S3Connection(aws_access_key_id=app.config['keys.key_id'],
aws_secret_access_key=app.config['keys.key_secret'],
security_token=app.config['keys.key_token'])
dyno = Table(app.config["instance.tags"]["DynamoDBTableName"],#app.config['dynamodb.table_name'],
schema=[HashKey("job_id")],
connection=ddb.connect_to_region(app.config['dynamodb.region'],
aws_access_key_id=app.config['keys.key_id'],
aws_secret_access_key=app.config['keys.key_secret'],
security_token=app.config['keys.key_token']))
app.config["ec2.conn"] = ec2
app.config["sns.conn"] = sns
app.config["sqs.conn"] = sqs
app.config["ses.conn"] = ses
app.config["s3.conn"] = s3
app.config["scale.conn"]= scale
app.config["dyno.conn"] = dyno
app.config["doReload"] = True
return app
def connect_to_dynamodb(app):
stat = update_creds_from_metadata_server(app)
# If an entry exists for the table and the credentials have
# not been updated then skip the connection
if "dynamodb.table" in app.config and not stat:
return app
dbconn = ddb.connect_to_region(app.config['dynamodb.region'],
aws_access_key_id=app.config['keys.key_id'],
aws_secret_access_key=app.config['keys.key_secret'],
security_token=app.config['keys.key_token'])
dyno = Table(app.config["instance.tags"]["DynamoDBTableName"], #app.config['dynamodb.table_name'],
schema=[HashKey("CustomerUUID")],
connection=dbconn)
app.config["dynamodb.table"] = dyno
return app
def load_configs(filename):
app = bottle.default_app()
try:
app.config.load_config(filename)
except Exception as e:
logging.error("Exception {0} in load_config".format(e))
exit(-1)
logging.debug("Config : \n {0}".format(app.config))
for keys in app.config:
if keys.startswith('keys.'):
print keys
keyfile = app.config[keys].replace('\"', '')
logging.debug("Keyfile : {0}".format(keyfile.replace('\"', '')))
if not os.path.isfile(keyfile):
print "Key file {0} missing!".format(keyfile)
logging.error("Key file {0} missing!".format(keyfile))
exit(-1)
with open(keyfile, 'r') as kf:
ks = kf.readlines()
sp = ks[1].split(',')
app.config[keys] = kf.read()
app.config["keys.key_id"] = sp[1]
app.config["keys.key_secret"] = sp[2]
app.config["keys.key_token"] = ''
#print "keys : ", app.config[keys]
if 'metadata.credurl' in app.config:
update_creds_from_metadata_server(app)
init(app)
return app