-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlibnova.py
More file actions
766 lines (649 loc) · 26.5 KB
/
libnova.py
File metadata and controls
766 lines (649 loc) · 26.5 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
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
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
#!/usr/bin/env python
# Description
# This is the library that interacts with IRM-nova from one side and OpenStack from the other
#
#
#
# Status
# - all functions are implemented and seem to be working
#
#
#
import requests, json, os, copy
import re
#from bottle import route, run,response,request,re
import ConfigParser
#from threading import Thread
import logging
import logging.handlers as handlers
#from pudb import set_trace; set_trace()
def createLogger():
#Config and format for logging messages
global logger
logger = logging.getLogger("Rotating Log")
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter(fmt='%(asctime)s.%(msecs)d - %(levelname)s: %(filename)s - %(funcName)s: %(message)s', datefmt='%d/%m/%Y %H:%M:%S')
handler = handlers.TimedRotatingFileHandler("n-irm.log",when="H",interval=24,backupCount=0)
## Logging format
handler.setFormatter(formatter)
if not logger.handlers:
logger.addHandler(handler)
def libnovaInit(conf_file):
global CONFIG
if 'CONFIG' not in globals():
CONFIG = ConfigParser.RawConfigParser()
CONFIG.read(conf_file)
def getIP(url):
logger.info("Called")
address_regexp = re.compile ('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}')
try:
result = address_regexp.search(url)
except AttributeError:
print "N-Irm: [getIP] Failed to get IP. result variable could not search url. Possible url fault"
logger.error("url error caused result variable to have incorrect assignment")
if result:
return result.group()
else:
return None
logger.info("Completed!")
def createToken(os_api_url, tenantName, username, password):
logger.info("Called")
headers = {'content-type': 'application/json'}
data = json.dumps({"auth": {"tenantName": tenantName, "passwordCredentials": {"username": username, "password": password}}})
token_url = os_api_url+"/v2.0/tokens"
#print "token_url: "+token_url
try:
r = requests.post(token_url, data, headers=headers)
global token_id
token_id = r.json()['access']['token']['id']
#print r.text
except AttributeError:
print "N-Irm: [createToken] Unable to use r variable with json. Fault with token_url, or data variables"
logger.error("Fault with token_url or data variable, caused r to be unusable with json")
except Exception.message, e:
response.status = 400
error = {"message":e,"code":response.status}
logger.error(error)
return error
if token_id:
logger.info("Created token: "+token_id)
return token_id
else:
return None
logger.info("Completed!")
def getEndPoints(os_api_url, token_id):
logger.info("Called")
endpoints_url = os_api_url+"/v2.0/tokens/"+token_id+"/endpoints"
headers = {'X-Auth-Token': token_id}
urls = []
if str(token_id) not in str(headers):
raise AttributeError("N-Irm: [getEndPoints] Failure to assign headers. Possibly incorrect token_id")
logger.error("Failed to assign headers. Possible fault in token_id")
try:
r = requests.get(endpoints_url, headers=headers)
endpoints = r.json()['endpoints']
except AttributeError:
print "N-Irm [getEndPoints] Failure to assign endpoints. Possibly incorrect endpoints_url or unable to acces endpoints"
logger.error("Failed to assign endpoints. Possible incorrect endpoints_url or unable to access endpoints")
except Exception.message, e:
response.status = 400
error = {"message":e,"code":response.status}
logger.error(error)
return error
# print endpoints
for majorkey in endpoints:
if majorkey['type'] == 'compute':
global public_url
public_url = majorkey['publicURL']
#print public_url
urls.append(public_url)
if majorkey['type'] == 'network':
global net_url
net_url = majorkey['publicURL']
#print net_url
urls.append(net_url)
if urls:
logger.info("Urls: "+str(urls))
return urls
else:
return None
logger.info("Completed!")
# get hosts from nova and return a list
def getHosts():
logger.info("Called")
headers = {'X-Auth-Token': token_id}
if str(token_id) not in str(headers):
raise AttributeError("N-Irm: [getHosts] Failure to assign headers. Possibly incorrect token_id")
logger.error("Failed to assign headers. Possible fault in token_id")
try:
r = requests.get(public_url+'/os-hosts', headers=headers)
# this needs to be fixed with a more appropriate error check
if r.json():
print "Request OK"
#logger.info("Hosts: "+r.text)
except ValueError:
print "N-Irm: [getHosts] r = requests.get failed. Possible error with public_url or hostname"
logger.error("Error within public_url or hostname. ")
except Exception.message, e:
response.status = 400
error = {"message":e,"code":response.status}
logger.error(error)
return error
hosts = []
for majorkey in r.json()['hosts']:
if majorkey['service'] == 'compute':
hosts.append(majorkey['host_name'])
logger.info("Completed!")
if hosts:
return hosts
else:
return None
def getListInstances():
logger.info("Called")
headers = {'X-Auth-Token': token_id}
#headers = None
subname = "HARNESS"
if str(token_id) not in str(headers):
raise AttributeError("N-Irm: [getHostDetails] Failure to assign headers. Possibly incorrect token_id")
logger.error("Failed to assign headers. Possible fault in token_id")
r = requests.get(public_url+'/servers', headers=headers)
#print r
reservations = None
try:
instanceList = []
response = r.json()
#print response
for instance in response['servers']:
#print "INSTANCE:",instance['name']
if subname in instance['name']:
#print "GOT ",subname, instance
instanceList.append(instance['id'])
#print instanceList
reservations = {"ReservationID":instanceList}
#print json.dumps(reservations)
except ValueError:
print "N-Irm: [getInstanceList] r = requests.get failed. Possible error with public_url or hostname"
print ""
logger.error("Error within public_url or hostname")
#print hostDetails
if reservations:
return reservations
else:
return None
logger.info("Completed!")
#@route('/method/checkReservationInfo/<ID>', method='GET')
def getInstanceInfo(ID):
logger.info("Called")
headers = {'X-Auth-Token': token_id}
if str(token_id) not in str(headers):
raise AttributeError("N-Irm: [getInstanceInfo] Failure to assign headers. Possibly incorrect token_id")
logger.error("Failed to assign headers. Possible fault in token_id")
r = requests.get(public_url+'/servers/'+ID, headers=headers)
logger.info("Info for instance: "+ID)
logger.info("Completed!")
if r:
return r.json()
else:
return None
# load resources information not available through nova from file in JSON format
def loadHostList():
logger.info("Called")
hostlistfile = CONFIG.get('main','HOSTLIST')
with open(hostlistfile) as f:
try:
hosts = json.load(f)
except AttributeError:
print "N-Irm [loadHostList] Failed to load variable f into hosts"
logger.error("Attempt to load variable f into hosts failed")
f.close()
if hosts:
return hosts
else:
return None
logger.info("Completed!")
def getHostDetails(hostname):
logger.info("Called")
headers = {'X-Auth-Token': token_id}
#headers = None
if str(token_id) not in str(headers):
raise AttributeError("N-Irm: [getHostDetails] Failure to assign headers. Possibly incorrect token_id")
logger.error("Failed to assign headers. Possible fault in token_id")
try:
r = requests.get(public_url+'/os-hosts/'+hostname, headers=headers)
hostDetails = r.json()
logger.info("Host Details: "+json.dumps(hostDetails))
except ValueError:
print "N-Irm: [getHostDetails] r = requests.get failed. Possible error with public_url or hostname"
print ""
logger.error("Error within public_url or hostname")
except Exception.message, e:
response.status = 400
error = {"message":e,"code":response.status}
logger.error(error)
return error
#print hostDetails
logger.info("Completed!")
if hostDetails:
return hostDetails
else:
return None
Machines = None
def createListAvailableResources(public_url,token_id,option):
logger.info("Called")
res = {option:{}}
h_list = getHosts()
#print "h_list",h_list
global Machines
if Machines == None:
Machines = {}
try:
path = os.path.dirname(os.path.abspath(__file__))
with open(path + '/machines.json') as data_file:
Machines = json.load(data_file)
except:
pass
mem_pr = float(CONFIG.get('overcommit','MEM_PRESERVE'))
if mem_pr < 100:
mem_pr = mem_pr / 100
else:
mem_pr = 0.1
# loop through all hosts
for novah in h_list:
# get details from nova
hostDetails = getHostDetails(novah)
itype = getInstanceType(novah)
#print hostDetails
nCores = 0
memory = 0
total_cpu = 0
used_cpu = 0
total_mem = 0
used_mem = 0
total_disk = 0
used_disk = 0
# load detail from nova reply
if 'host' in hostDetails:
#print "::::>", hostDetails['host']
for majorkey in hostDetails['host']:
if majorkey['resource']['project'] == '(total)':
total_mem = majorkey['resource']['memory_mb'] * int(CONFIG.get('overcommit', 'MEM_RATIO'))
total_cpu = majorkey['resource']['cpu'] * int(CONFIG.get('overcommit', 'CPU_RATIO'))
total_disk = majorkey['resource']['disk_gb'] * int(CONFIG.get('overcommit', 'DISK_RATIO'))
for m in Machines:
if m in novah:
if "Cores" in Machines[m]:
total_cpu = Machines[m]["Cores"]
if "Memory" in Machines[m]:
total_memory = Machines[m]["Memory"]
break
if majorkey['resource']['project'] == '(used_now)':
used_mem = majorkey['resource']['memory_mb']
used_cpu = majorkey['resource']['cpu']
used_disk = majorkey['resource']['disk_gb']
# calculate available resources
nCores = total_cpu - used_cpu
# memory is calculated 10% less than actual value to avoid commiting it all
memory = int(total_mem - used_mem - mem_pr * total_mem)
disk = total_disk - used_disk
res[option][novah] = {'Type':'Machine','Attributes':{'Cores':nCores,"Memory":memory}}
if itype not in ["docker","LXC"]:
#print "itype in createListAvailableResources 1",itype
res[option][novah]['Attributes']['Disk'] = disk
#else:
#print "itype in createListAvailableResources 2",itype
if "{'Resources': []}" in res:
raise AttributeError('N-Irm: [createListAvailableResources] resources variable is empty. Failure to append data variable')
logger.error("Failed to append 'data' variable. 'Resources' variable empty")
logger.info("Completed!")
if res:
return res
else:
return None
def createFlavor(name,vcpu,ram,disk):
logger.info("Called")
headers = {'content-type': 'application/json','X-Auth-Token': token_id}
if str(token_id) not in str(headers):
raise AttributeError("N-Irm: [createFlavor] Failure to assign headers. Possibly incorrect token_id")
logger.error("Failed to assign headers. Possible fault in token_id")
data = json.dumps({"flavor": {\
"name": name,\
"ram": ram,\
"vcpus": vcpu,\
"disk": disk/1024,\
"id": name}})
# add here a check if that flavor name exists already and in that case return the correspondent ID
# add here a check if that flavor name exists already and in that case return the correspondent ID
# without trying to create a new one as it will fail
r = requests.post(public_url+'/flavors', data, headers=headers)
#print r.json()
logger.info("Completed!")
def deleteFlavor(ID):
logger.info("Called")
headers = {'X-Auth-Token': token_id}
if str(token_id) not in str(headers):
raise AttributeError("N-Irm: [deleteFlavor] Failure to assign headers. Possibly incorrect token_id")
logger.error("Failed to assign headers. Possible fault in token_id")
r = requests.delete(public_url+'/flavors/'+ID, headers=headers)
logger.info("Completed!")
def cleanFlavors():
logger.info("Called")
headers = {'X-Auth-Token': token_id}
try:
r = requests.get(public_url+'/flavors', headers=headers)
for flavor in r.json()['flavors']:
if "HARNESS" in flavor['name']:
deleteFlavor(flavor['id'])
#print flavor
except ValueError:
error = {"message":"ValueError","code":"500"}
print error
logger.error(error)
return error
except requests.exceptions.RequestException:
error = {"message":"RequestException","code":"500"}
print error
logger.error(error)
return error
logger.info("Completed!")
def createRandomID(size):
import binascii
return binascii.b2a_hex(os.urandom(size))
logger.info("Random ID generated")
def getInstanceStatus(ID):
logger.info("Called")
headers = {'X-Auth-Token': token_id}
if str(token_id) not in str(headers):
raise AttributeError("N-Irm: [getInstanceStatus] Failure to assign headers. Possibly incorrect token_id")
logger.error("Failed to assign headers. Possible fault in token_id")
r = requests.get(public_url+'/servers/'+ID, headers=headers)
#print r.json()['server']['id']
try:
status = r.json()['server']['status']
except TypeError:
print "N-Irm: [getInstanceStatus] Fault in ID. Cannot access ['server'] ['status']"
logger.info("Completed!")
if status:
return status
else:
return None
def getImageUUIDbyName(name):
logger.info("Called")
headers = {'X-Auth-Token': token_id}
if str(token_id) not in str(headers):
raise AttributeError("N-Irm: [getInstanceStatus] Failure to assign headers. Possibly incorrect token_id")
logger.error("Failed to assign headers. Possible fault in token_id")
r = requests.get(public_url+'/images', headers=headers)
try:
imageId=""
for image in r.json()["images"]:
if image["name"] == name:
imageId = image["id"]
break
else:
imageId = "Image Not Found"
#print imageId
except Exception.message, e:
response.status = 500
error = {"message":e,"code":response.status}
logger.error(error)
return error
logger.info("Completed!")
return imageId
def getNetUUIDbyName(name):
logger.info("Called")
headers = {'content-type': 'application/json','X-Auth-Token': token_id}
if str(token_id) not in str(headers):
raise AttributeError("N-Irm: [getNetUUIDbyName] Failure to assign headers. Possibly incorrect token_id")
logger.error("Failed to assign headers. Possible fault in token_id")
try:
r = requests.get(public_url+'/os-networks', headers=headers)
netId = ""
for net in r.json()["networks"]:
if net["label"] == name:
netId = net["id"]
break
else:
netId = "Net ID not Found"
except Exception.message, e:
response.status = 500
error = {"message":e,"code":response.status}
logger.error(error)
return error
logger.info("Completed!")
return netId
def getSubnetUUIDbyName(name):
logger.info("Called")
headers = {'content-type': 'application/json','X-Auth-Token': token_id}
if str(token_id) not in str(headers):
raise AttributeError("N-Irm: [getSubnetUUIDbyName] Failure to assign headers. Possibly incorrect token_id")
logger.error("Failed to assign headers. Possible fault in token_id")
try:
r = requests.get(net_url+'/v2.0/subnets', headers=headers)
#print "response json",r.json()
subnetId = ""
hname = "HARNESS-"+name
#print "hname",hname
for subnet in r.json()["subnets"]:
if subnet["name"] == hname:
subnetId = subnet["id"]
break
else:
subnetId = "Net ID not Found"
except Exception.message, e:
response.status = 500
error = {"message":e,"code":response.status}
logger.error(error)
return error
logger.info("Completed!")
return subnetId
def getMGTSubnetByNetUUID(netuuid,userSubnetUUID):
logger.info("Called")
headers = {'content-type': 'application/json','X-Auth-Token': token_id}
#print "token_id",token_id
if str(token_id) not in str(headers):
raise AttributeError("N-Irm: [getInstanceStatus] Failure to assign headers. Possibly incorrect token_id")
logger.error("Failed to assign headers. Possible fault in token_id")
try:
#print "userSubnetUUID",userSubnetUUID
#print "net_url",net_url
r = requests.get(net_url+'/v2.0/networks', headers=headers)
subnetId = ""
#print "response json",r.json()
for net in r.json()["networks"]:
#print net
if net["id"] == netuuid:
for sub in net['subnets']:
if sub != userSubnetUUID:
subnetId = sub
break
else:
continue
break
else:
subnetId = "Net ID not Found"
except Exception.message, e:
response.status = 500
error = {"message":e,"code":response.status}
logger.error(error)
return error
except Exception, e:
#response.status = 404
print "ERROR",e
error = {"message":e,"code":404}
logger.error(error)
return error
logger.info("Completed!")
return subnetId
def createPort(netuuid,mgtSubnetUUID,userSubnetUUID,portName):
logger.info("Called")
headers = {'content-type': 'application/json','X-Auth-Token': token_id}
if str(token_id) not in str(headers):
raise AttributeError("N-Irm: [getInstanceStatus] Failure to assign headers. Possibly incorrect token_id")
logger.error("Failed to assign headers. Possible fault in token_id")
try:
data = json.dumps({"port": {\
"name": portName,\
"network_id": netuuid,\
"fixed_ips":[{\
"subnet_id": mgtSubnetUUID,\
},\
{\
"subnet_id": userSubnetUUID}]}})
#print data
r = requests.post(net_url+'/v2.0/ports', data, headers=headers).json()
portID = ""
if "port" not in r:
raise Exception("subnet not valid!")
if r["port"]["id"]:
portID = r["port"]["id"]
print portID
else:
portID = "Port ID not found"
except Exception as e:
error = {"message":e.message,"code": 500}
logger.error(error)
return error
except Exception, e:
#response.status = 404
print "ERROR",e
error = {"message":e,"code":404}
logger.error(error)
return error
logger.info("Completed!")
return portID
def getNetworks():
logger.info("Called")
headers = {'X-Auth-Token': token_id}
if str(token_id) not in str(headers):
raise AttributeError("N-Irm: [getNetworks] Failure to assign headers. Possibly incorrect token_id")
logger.error("Failed to assign headers. Possible fault in token_id")
r = requests.get(public_url+'/os-networks', headers=headers)
networks = []
for net in r.json()['networks']:
networks.append(net['label'])
logger.info("Completed!")
if len(networks) > 0:
return networks
else:
return None
def checkResources(data):
logger.info("Called")
reply = {"Instances":{}}
if data['ReservationID']:
#print "Data not empty"
req = data
try:
for ID in req['ReservationID']:
print "ID",ID
ERROR = False
status = "false"
osstatus = "BUILD"
try:
while osstatus == "BUILD":
info = getInstanceInfo(ID)
osstatus = info['server']['status']
logger.info("Status: "+osstatus)
if osstatus == "ACTIVE":
status = "true"
logger.info("Status: "+osstatus)
#print "setting status"
except TypeError:
print "N-Irm: [verifyResources] Payload present but fault in ID. Could be missing or incorrect."
#print " "
logger.error("Fault in the payload's ID. Either missing or incorrect, must match an existent ID")
ERROR = True
if not ERROR:
IP = []
# change to private to vmnet in field below
for private in info['server']['addresses'][CONFIG.get('network', 'NET_ID')]:
if private['OS-EXT-IPS:type'] == CONFIG.get('network', 'IP_TYPE'):
IP.append(private['addr'])
#print "IP:", IP
#data = {"Ready":status,"Address":IP}
data = {"Ready":status,"Address":[';'.join(IP)]}
reply["Instances"][ID] = data
# When there is no ID, this case occurs
if ID in req['ReservationID'] is None:
raise UnboundLocalError('N-Irm: [verifyResources] Attempting to use ID variable before it has a value. Ensure payload has "<instanceID>"')
logger.error("ID has not been assigned before being used. Ensure payload has a present and correct instance ID")
except UnboundLocalError:
raise UnboundLocalError("N-Irm: [verifyResources] Attempting to reference variable before it has been assigned. Payload may be missing. Or ID is missing or empty. Please check payload!")
logger.error("Variable being referenced before payload or ID is assigned, possibly missing or empty. ")
else:
raise TypeError("N-Irm: [checkResources] data is empty!")
logger.info("Completed!")
return reply
def deleteResources(reservations):
logger.info("Called")
headers = {'X-Auth-Token': token_id}
try:
for ID in reservations['ReservationID']:
try:
#forces it to break is incorrect ID
info = getInstanceInfo(ID)
osstatus = info['server']['status']
#deletion of correct ID
r = requests.delete(public_url+'/servers/'+ID, headers=headers)
except TypeError:
print " "
raise TypeError("N-Irm: [releaseResources] Payload present but fault in ID. Could be missing or incorrect.")
logger.error("Payload was incorrect. ID possibly missing or incorrect")
# Thrown to enforce exception below
logger.info("Completed!")
return "DONE"
if ID in reservations['ReservationID'] is None:
raise UnboundLocalError
except UnboundLocalError:
raise UnboundLocalError("N-Irm: [releaseResources] Payload may be missing. Or ID is missing or empty. Please check Payload!")
logger.error("Fault with payload and ID. If payload is present, Id may be missing or empty")
return error
def createResources(data):
logger.info("Called")
headers = {'content-type': 'application/json','X-Auth-Token': token_id}
try:
r = requests.post(public_url+'/servers', data, headers=headers)
except Exception.message, e:
response.status = 400
error = {"message":e,"code":response.status}
logger.error(error)
return error
logger.info("Completed!")
return r
def getInstanceName(uuid):
print "In getInstanceName"
logger.info("Called")
headers = {'X-Auth-Token': token_id}
try:
if str(token_id) not in str(headers):
raise AttributeError("N-Irm: [getNetworks] Failure to assign headers. Possibly incorrect token_id")
logger.error("Failed to assign headers. Possible fault in token_id")
r = requests.get(public_url+'/servers/'+uuid, headers=headers)
result = r.json()
instanceName = result["server"]["OS-EXT-SRV-ATTR:instance_name"]
except AttributeError:
print "N-Irm: [getNetworks] Failure to assign headers. Possibly incorrect token_id"
logger.error("Failed to assign headers. Possible fault in token_id")
logger.info("Completed!")
return instanceName
def getInstanceType(host):
logger.info("Called")
headers = {'X-Auth-Token': token_id}
if str(token_id) not in str(headers):
raise AttributeError("N-Irm: [getNetworks] Failure to assign headers. Possibly incorrect token_id")
logger.error("Failed to assign headers. Possible fault in token_id")
try:
r = requests.get(public_url+'/os-hypervisors/detail', headers=headers)
htype = ""
result = r.json()
for h in result['hypervisors']:
if h['service']['host'] == host:
htype = h['hypervisor_type']
break
except Exception.message, e:
response.status = 400
error = {"message":e,"code":response.status}
logger.error(error)
return error
logger.info("Instance Type: "+htype)
logger.info("Completed!")
return htype