This repository has been archived by the owner on Sep 23, 2020. It is now read-only.
/
dev.py
565 lines (456 loc) · 20.4 KB
/
dev.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
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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
import base64
import json
import logging
from django.contrib.auth import authenticate, login
from django.http import HttpResponse, HttpResponseBadRequest, \
HttpResponseNotFound, HttpResponseServerError, HttpResponseRedirect
from django.views.decorators.http import require_http_methods
from phantomweb.util import get_user_object
from phantomweb.phantom_web_exceptions import PhantomWebException
from phantomweb.workload import phantom_get_sites, get_all_launch_configurations, \
get_launch_configuration, get_launch_configuration_by_name, create_launch_configuration, \
set_host_max_pair, get_all_domains, create_domain, get_domain_by_name, get_domain, \
remove_domain, modify_domain, get_domain_instances, get_domain_instance, \
terminate_domain_instance
log = logging.getLogger('phantomweb.api.dev')
DOC_URI = "http://www.nimbusproject.org/doc/phantom/latest/api.html"
API_VERSION = 'dev'
def basic_http_auth(f):
def wrap(request, *args, **kwargs):
if request.user:
if request.user.is_authenticated():
# Already logged in, just return the result of the view
return f(request, *args, **kwargs)
if request.META.get('HTTP_AUTHORIZATION', False):
authtype, auth = request.META['HTTP_AUTHORIZATION'].split(' ')
auth = base64.b64decode(auth)
username, password = auth.split(':')
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return f(request, *args, **kwargs)
else:
r = HttpResponse("Your account has been disabled", status=401, mimetype='application/javascript')
r['WWW-Authenticate'] = 'Basic realm="api"'
return r
else:
r = HttpResponse("Your username and password were incorrect", status=401,
mimetype='application/javascript')
r['WWW-Authenticate'] = 'Basic realm="api"'
return r
else:
r = HttpResponse("Auth Required", status=401, mimetype='application/javascript')
r['WWW-Authenticate'] = 'Basic realm="api"'
return r
return wrap
def has_all_required_params(params, content):
for param in params:
if param not in content:
return False
return True
@basic_http_auth
@require_http_methods(["GET"])
def sites(request):
user_obj = get_user_object(request.user.username)
all_sites = phantom_get_sites(request.GET, user_obj)
response_list = []
for site in all_sites:
site_name = str(site)
site_dict = {
"id": site_name,
"credentials": "/api/%s/credentials/%s" % (API_VERSION, site_name),
"uri": "/api/%s/sites/%s" % (API_VERSION, site_name)
}
response_list.append(site_dict)
h = HttpResponse(json.dumps(response_list), mimetype='application/javascript')
return h
@basic_http_auth
@require_http_methods(["GET"])
def site_resource(request, site):
user_obj = get_user_object(request.user.username)
all_sites = phantom_get_sites(request.GET, user_obj)
if site in all_sites:
response_dict = {
"id": site,
"credentials": "/api/%s/credentials/%s" % (API_VERSION, site),
"uri": "/api/%s/sites/%s" % (API_VERSION, site)
}
h = HttpResponse(json.dumps(response_dict), mimetype='application/javascript')
else:
h = HttpResponseNotFound('Site %s not found' % site, mimetype='application/javascript')
return h
@basic_http_auth
@require_http_methods(["GET", "POST"])
def credentials(request):
user_obj = get_user_object(request.user.username)
if request.method == "GET":
all_clouds = user_obj.get_clouds()
response_list = []
for cloud in all_clouds.values():
credentials_name = cloud.cloudname
credentials_dict = {
"id": credentials_name,
"access_key": cloud.iaas_key,
"secret_key": cloud.iaas_secret,
"key_name": cloud.keyname,
"uri": "/api/%s/credentials/%s" % (API_VERSION, credentials_name)
}
response_list.append(credentials_dict)
h = HttpResponse(json.dumps(response_list), mimetype='application/javascript')
elif request.method == "POST":
try:
content = json.loads(request.body)
except:
msg = "Bad request. No JSON. See API docs: %s" % DOC_URI
return HttpResponseBadRequest(msg)
required_params = ["id", "access_key", "secret_key", "key_name"]
if not has_all_required_params(required_params, content):
return HttpResponseBadRequest()
site = content["id"]
access_key = content["access_key"]
secret_key = content["secret_key"]
key_name = content["key_name"]
# Check that the site exists
all_sites = phantom_get_sites(request.POST, user_obj)
if site not in all_sites:
return HttpResponseBadRequest()
response_dict = {
"id": site,
"access_key": access_key,
"secret_key": secret_key,
"key_name": key_name,
"uri": "/api/%s/credentials/%s" % (API_VERSION, site)
}
# Add credentials to DTRS
try:
user_obj.add_site(site, access_key, secret_key, key_name)
except:
log.exception("Failed to add credentials for site %s" % site)
return HttpResponseServerError()
h = HttpResponse(json.dumps(response_dict), status=201, mimetype='application/javascript')
return h
@basic_http_auth
@require_http_methods(["GET", "PUT", "DELETE"])
def credentials_resource(request, site):
user_obj = get_user_object(request.user.username)
if request.method == "GET":
all_clouds = user_obj.get_clouds()
cloud = all_clouds.get(site)
if cloud is not None:
response_dict = {
"id": cloud.cloudname,
"access_key": cloud.iaas_key,
"secret_key": cloud.iaas_secret,
"key_name": cloud.keyname,
"uri": "/api/%s/credentials/%s" % (API_VERSION, cloud.cloudname)
}
h = HttpResponse(json.dumps(response_dict), mimetype='application/javascript')
else:
h = HttpResponseNotFound('Credentials for site %s not found' % site, mimetype='application/javascript')
elif request.method == "PUT":
try:
content = json.loads(request.body)
except:
return HttpResponseBadRequest()
required_params = ["id", "access_key", "secret_key", "key_name"]
if not has_all_required_params(required_params, content):
return HttpResponseBadRequest()
if site != content["id"]:
return HttpResponseBadRequest()
access_key = content["access_key"]
secret_key = content["secret_key"]
key_name = content["key_name"]
# Check that the site exists
all_sites = phantom_get_sites(request.REQUEST, user_obj)
if site not in all_sites:
return HttpResponseBadRequest()
# Check that credentials exist
if site not in user_obj.get_clouds():
return HttpResponseBadRequest()
response_dict = {
"id": site,
"access_key": access_key,
"secret_key": secret_key,
"key_name": key_name,
"uri": "/api/%s/credentials/%s" % (API_VERSION, site)
}
# Add credentials to DTRS
try:
user_obj.add_site(site, access_key, secret_key, key_name)
except:
log.exception("Failed to add credentials for site %s" % site)
return HttpResponseServerError()
h = HttpResponse(json.dumps(response_dict), status=201, mimetype='application/javascript')
elif request.method == "DELETE":
# Check that credentials exist
if site not in user_obj.get_clouds():
return HttpResponseBadRequest()
# Remove credentials from DTRS
try:
user_obj.delete_site(site)
except:
log.exception("Failed to remove credentials for site %s" % site)
return HttpResponseServerError()
h = HttpResponse(status=204)
return h
@basic_http_auth
@require_http_methods(["GET", "POST"])
def launchconfigurations(request):
if request.method == "GET":
all_launch_configurations = get_all_launch_configurations(request.user.username)
response_list = []
for lc in all_launch_configurations:
lc_dict = {
"id": lc.id,
"name": lc.name,
"owner": lc.username,
"uri": "/api/%s/launchconfigurations/%s" % (API_VERSION, lc.id),
"cloud_params": {}
}
user_obj = get_user_object(lc.username)
dt = user_obj.get_dt(lc.name)
host_max_pairs = lc.hostmaxpairdb_set.all()
for hmp in host_max_pairs:
cloud = hmp.cloud_name
mapping = dt["mappings"][cloud]
lc_dict["cloud_params"][cloud] = {
"max_vms": hmp.max_vms,
"common": hmp.common_image,
"rank": hmp.rank,
"image_id": mapping["iaas_image"],
"instance_type": mapping["iaas_allocation"],
"user_data": dt["contextualization"].get("userdata")
}
response_list.append(lc_dict)
h = HttpResponse(json.dumps(response_list), mimetype='application/javascript')
elif request.method == "POST":
try:
content = json.loads(request.body)
except:
return HttpResponseBadRequest()
required_params = ["name", "cloud_params"]
if not has_all_required_params(required_params, content):
return HttpResponseBadRequest()
name = content['name']
cloud_params = content['cloud_params']
username = request.user.username
user_obj = get_user_object(username)
lc = get_launch_configuration_by_name(username, name)
if lc is not None:
# LC already exists, redirect to existing one
return HttpResponseRedirect("/api/%s/launchconfigurations/%s" % (API_VERSION, lc.id))
lc = create_launch_configuration(username, name)
lc.save()
configured_clouds = user_obj.get_clouds()
# TODO: validate these values
for cloud_name, cloud in cloud_params.iteritems():
if cloud_name not in configured_clouds.keys():
msg = "%s is not configured. Check your profile" % cloud_name
return HttpResponseBadRequest(msg)
set_host_max_pair(cloud_name=cloud_name, max_vms=cloud['max_vms'],
launch_config=lc, rank=int(cloud['rank']), common_image=cloud["common"])
host_max_pairs = lc.hostmaxpairdb_set.all()
response_dict = {
"id": lc.id,
"name": name,
"owner": username,
"cloud_params": cloud_params,
"uri": "/api/%s/launchconfigurations/%s" % (API_VERSION, lc.id),
}
h = HttpResponse(json.dumps(response_dict), status=201, mimetype='application/javascript')
return h
@basic_http_auth
@require_http_methods(["GET", "PUT", "DELETE"])
def launchconfiguration_resource(request, id):
if request.method == "GET":
lc = get_launch_configuration(id)
if lc is not None and lc.username == request.user.username:
response_dict = {
"id": lc.id,
"name": lc.name,
"owner": lc.username,
"uri": "/api/%s/launchconfigurations/%s" % (API_VERSION, lc.id),
"cloud_params": {}
}
user_obj = get_user_object(lc.username)
dt = user_obj.get_dt(lc.name)
host_max_pairs = lc.hostmaxpairdb_set.all()
for hmp in host_max_pairs:
cloud = hmp.cloud_name
mapping = dt["mappings"][cloud]
response_dict["cloud_params"][cloud] = {
"max_vms": hmp.max_vms,
"common": hmp.common_image,
"rank": hmp.rank,
"image_id": mapping["iaas_image"],
"instance_type": mapping["iaas_allocation"],
"user_data": dt["contextualization"].get("userdata")
}
h = HttpResponse(json.dumps(response_dict), mimetype='application/javascript')
else:
h = HttpResponseNotFound('Launch configuration %s not found' % id, mimetype='application/javascript')
return h
elif request.method == "PUT":
lc = get_launch_configuration(id)
if lc is None:
msg = "Launch configuration %s not found" % id
return HttpResponseNotFound(msg, mimetype='application/javascript')
try:
content = json.loads(request.body)
except:
return HttpResponseBadRequest()
required_params = ["name", "cloud_params"]
if not has_all_required_params(required_params, content):
return HttpResponseBadRequest()
name = content['name']
cloud_params = content['cloud_params']
username = request.user.username
user_obj = get_user_object(username)
required_cloud_params = ['image_id', 'instance_type', 'max_vms', 'common', 'rank', 'user_data']
configured_clouds = user_obj.get_clouds()
# TODO: validate these values
for cloud_name, cloud in cloud_params.iteritems():
if cloud_name not in configured_clouds.keys():
msg = "%s is not configured. Check your profile" % cloud_name
return HttpResponseBadRequest(msg)
if not has_all_required_params(required_cloud_params, cloud):
msg = "%s does not have all of the required parameters" % cloud_name
return HttpResponseBadRequest(msg)
set_host_max_pair(cloud_name=cloud_name, max_vms=cloud['max_vms'],
launch_config=lc, rank=int(cloud['rank']), common_image=cloud["common"])
response_dict = {
"id": lc.id,
"name": name,
"owner": username,
"cloud_params": cloud_params,
"uri": "/api/%s/launchconfigurations/%s" % (API_VERSION, lc.id),
}
h = HttpResponse(json.dumps(response_dict), status=200, mimetype='application/javascript')
return h
elif request.method == "DELETE":
lc = get_launch_configuration(id)
if lc is not None and lc.username == request.user.username:
user_obj = get_user_object(lc.username)
user_obj.remove_dt(lc.name)
host_max_pairs = lc.hostmaxpairdb_set.all()
for hmp in host_max_pairs:
hmp.delete()
lc.delete()
h = HttpResponse(status=204)
else:
h = HttpResponseNotFound('Launch configuration %s not found' % id, mimetype='application/javascript')
return h
@basic_http_auth
@require_http_methods(["GET", "POST"])
def domains(request):
if request.method == "GET":
username = request.user.username
domains = get_all_domains(username)
response = domains
h = HttpResponse(json.dumps(response), status=200, mimetype='application/javascript')
return h
elif request.method == "POST":
try:
content = json.loads(request.body)
except:
return HttpResponseBadRequest()
username = request.user.username
name = content.get('name')
if name is None:
return HttpResponseBadRequest("You must provide a name for your domain")
domain = get_domain_by_name(username, name)
if domain is not None:
# Domain already exists, redirect to existing one
return HttpResponseRedirect("/api/%s/domains/%s" % (API_VERSION, domain['id']))
try:
response = create_domain(username, name, content)
except PhantomWebException as p:
return HttpResponseBadRequest(p.message)
response['owner'] = username
response['uri'] = "/api/%s/domains/%s" % (API_VERSION, response['id'])
h = HttpResponse(json.dumps(response), status=201, mimetype='application/javascript')
return h
@basic_http_auth
@require_http_methods(["GET", "PUT", "DELETE"])
def domain_resource(request, id):
if request.method == "GET":
username = request.user.username
response = get_domain(username, id)
if response is None:
return HttpResponseNotFound('Domain %s not found' % id, mimetype='application/javascript')
response['owner'] = username
response['uri'] = "/api/%s/domains/%s" % (API_VERSION, id)
return HttpResponse(json.dumps(response), mimetype='application/javascript')
elif request.method == "PUT":
username = request.user.username
response = get_domain(username, id)
if response is None:
return HttpResponseNotFound('Domain %s not found' % id, mimetype='application/javascript')
try:
content = json.loads(request.body)
except:
return HttpResponseBadRequest()
try:
response = modify_domain(username, id, content)
except PhantomWebException as p:
return HttpResponseBadRequest(p.message)
response['owner'] = username
response['uri'] = "/api/%s/domains/%s" % (API_VERSION, response['id'])
h = HttpResponse(json.dumps(response), status=200, mimetype='application/javascript')
return h
elif request.method == "DELETE":
username = request.user.username
response = get_domain(username, id)
if response is None:
return HttpResponseNotFound('Domain %s not found' % id, mimetype='application/javascript')
response = remove_domain(username, id)
h = HttpResponse(status=204)
return h
@basic_http_auth
@require_http_methods(["GET"])
def instances(request, domain_id):
if request.method == "GET":
username = request.user.username
response = get_domain_instances(username, domain_id)
if response is None:
return HttpResponseNotFound('domain %s not found' % domain_id, mimetype='application/javascript')
for instance in response:
instance['owner'] = username
instance['cloud'] = "/api/%s/sites/%s" % (API_VERSION, instance.get('cloud'))
instance['uri'] = "/api/%s/domains/%s/instances/%s" % (
API_VERSION, domain_id, instance.get('id'))
return HttpResponse(json.dumps(response), mimetype='application/javascript')
@basic_http_auth
@require_http_methods(["GET", "DELETE"])
def instance_resource(request, domain_id, instance_id):
if request.method == "GET":
username = request.user.username
response = get_domain_instances(username, domain_id)
if response is None:
return HttpResponseNotFound('domain %s not found' % domain_id, mimetype='application/javascript')
wanted_instance = None
for instance in response:
if instance.get('id') == instance_id:
wanted_instance = instance
break
if wanted_instance is None:
return HttpResponseNotFound('instance %s not found' % instance_id, mimetype='application/javascript')
wanted_instance['owner'] = username
wanted_instance['cloud'] = "/api/%s/sites/%s" % (API_VERSION, wanted_instance.get('cloud'))
wanted_instance['uri'] = "/api/%s/domains/%s/instances/%s" % (
API_VERSION, domain_id, wanted_instance.get('id'))
return HttpResponse(json.dumps(wanted_instance), mimetype='application/javascript')
elif request.method == "DELETE":
username = request.user.username
instance = get_domain_instance(username, domain_id, instance_id)
if instance is None:
print "instance not found"
return HttpResponseNotFound('instance %s not found' % domain_id, mimetype='application/javascript')
try:
terminate_domain_instance(username, domain_id, instance_id)
except PhantomWebException as p:
print "problem deleting: %s" % p.message
return HttpResponseServerError("Couldn't remove instance %s" % instance_id)
h = HttpResponse(status=204)
return h