Commit d710661b authored by Stavros Sachtouris's avatar Stavros Sachtouris

Apply pep8 to APIserver.py

parent 50cd207b
......@@ -44,7 +44,7 @@ def parse_arguments(args):
)
parser = OptionParser(**kw)
parser.disable_interspersed_args()
parser.add_option(
"--enable_voms",
action="store_true", dest="enable_voms", default=False,
......@@ -53,13 +53,13 @@ def parse_arguments(args):
"--voms_db",
action="store", type="string", dest="voms_db",
help="Path to sqlite database file")
(opts, args) = parser.parse_args(args)
if opts.enable_voms and not opts.voms_db:
print "--voms_db option required"
parser.print_help()
return (opts, args)
......@@ -73,15 +73,15 @@ class MyAPP(wsgi.Application):
super(MyAPP,self).__init__(registry=snfRegistry())
self._register_backends()
VALIDATOR_APP = validator(self)
def _register_backends(self):
print "Inside Register Backends"
COMPUTE_BACKEND = ComputeBackend()
NETWORK_BACKEND = NetworkBackend()
NETWORK_BACKEND = NetworkBackend()
NETWORKINTERFACE_BACKEND = NetworkInterfaceBackend()
IPNETWORK_BACKEND = IpNetworkBackend()
IPNETWORKINTERFACE_BACKEND = IpNetworkInterfaceBackend()
self.register_backend(COMPUTE, COMPUTE_BACKEND)
self.register_backend(START, COMPUTE_BACKEND)
self.register_backend(STOP, COMPUTE_BACKEND)
......@@ -89,15 +89,15 @@ class MyAPP(wsgi.Application):
self.register_backend(SUSPEND, COMPUTE_BACKEND)
self.register_backend(RESOURCE_TEMPLATE, MixinBackend())
self.register_backend(OS_TEMPLATE, MixinBackend())
# Network related backends
self.register_backend(NETWORK, NETWORK_BACKEND)
self.register_backend(IPNETWORK, IPNETWORK_BACKEND)
self.register_backend(NETWORKINTERFACE,NETWORKINTERFACE_BACKEND)
self.register_backend(NETWORKINTERFACE, NETWORKINTERFACE_BACKEND)
self.register_backend(IPNETWORKINTERFACE, IPNETWORKINTERFACE_BACKEND)
self.register_backend(snf_addons.SNF_USER_DATA_EXT, SNFBackend())
self.register_backend(snf_addons.SNF_KEY_PAIR_EXT, SNFBackend())
self.register_backend(snf_addons.SNF_USER_DATA_EXT, SNFBackend())
self.register_backend(snf_addons.SNF_KEY_PAIR_EXT, SNFBackend())
def refresh_images(self, snf, client):
try:
images = snf.list_images()
......@@ -107,11 +107,11 @@ class MyAPP(wsgi.Application):
"http://schemas.ogf.org/occi/os_tpl#",
occify_terms(str(image['name'])),
[OS_TEMPLATE],
title='IMAGE', attributes = IMAGE_ATTRIBUTES)
title='IMAGE', attributes=IMAGE_ATTRIBUTES)
self.register_backend(IMAGE, MixinBackend())
except:
raise HTTPError(404, "Unauthorized access")
def refresh_flavors(self, snf, client):
flavors = snf.list_flavors()
print "Retrieving details for each flavor"
......@@ -147,31 +147,31 @@ class MyAPP(wsgi.Application):
title='FLAVOR', attributes=FLAVOR_ATTRIBUTES)
self.register_backend(FLAVOR, MixinBackend())
def refresh_network_instances(self,client):
def refresh_network_instances(self, client):
print "@ refresh NETWORKS"
network_details = client.list_networks(detail='True')
resources = self.registry.resources
occi_keys = resources.keys()
for network in network_details:
if '/network/'+str(network['id']) not in occi_keys:
netID = '/network/'+str(network['id'])
netID = '/network/'+str(network['id'])
snf_net = core_model.Resource(netID, NETWORK, [IPNETWORK])
snf_net.attributes['occi.core.id'] = str(network['id'])
#This info comes from the network details
snf_net.attributes['occi.core.id'] = str(network['id'])
# This info comes from the network details
snf_net.attributes['occi.network.state'] = str(
network['status'])
snf_net.attributes['occi.network.gateway'] = ''
if network['public'] == True:
if network['public'] is True:
snf_net.attributes['occi.network.type'] = "Public = True"
else:
snf_net.attributes['occi.network.type'] = "Public = False"
self.registry.add_resource(netID, snf_net, None)
self.registry.add_resource(netID, snf_net, None)
def refresh_compute_instances(self, snf, client):
"""Syncing registry with cyclades resources"""
print "@ Refresh COMPUTE INSTANCES"
print "@ Refresh COMPUTE INSTANCES"
servers = snf.list_servers()
snf_keys = []
......@@ -180,7 +180,7 @@ class MyAPP(wsgi.Application):
resources = self.registry.resources
occi_keys = resources.keys()
print occi_keys
for serverID in occi_keys:
if '/compute/' in serverID and resources[serverID].attributes[
......@@ -188,8 +188,8 @@ class MyAPP(wsgi.Application):
self.registry.delete_resource(serverID, None)
occi_keys = resources.keys()
#Compute instances in synnefo not available in registry
diff = [x for x in snf_keys if '/compute/'+x not in occi_keys]
# Compute instances in synnefo not available in registry
diff = [x for x in snf_keys if '/compute/'+x not in occi_keys]
for key in diff:
details = snf.get_server_details(int(key))
flavor = snf.get_flavor_details(details['flavor']['id'])
......@@ -198,9 +198,9 @@ class MyAPP(wsgi.Application):
flavor=details['flavor']['id'], vm=key)
image = snf.get_image_details(details['image']['id'])
for i in self.registry.backends:
if i.term == occify_terms(str(image['name'])):
if i.term == occify_terms(str(image['name'])):
rel_image = i
if i.term == occify_terms(str(flavor['name'])):
if i.term == occify_terms(str(flavor['name'])):
rel_flavor = i
resource = Resource(key, COMPUTE, [rel_flavor, rel_image])
......@@ -214,7 +214,7 @@ class MyAPP(wsgi.Application):
resource.attributes['occi.compute.memory'] = str(flavor['ram'])
resource.attributes['occi.core.title'] = str(details['name'])
networkIDs = details['addresses'].keys()
if len(networkIDs)>0:
if len(networkIDs) > 0:
resource.attributes['occi.compute.hostname'] = str(
details['addresses'][networkIDs[0]][0]['addr'])
else:
......@@ -231,42 +231,42 @@ class MyAPP(wsgi.Application):
NETWORKINTERFACE, [IPNETWORKINTERFACE], resource,
self.registry.resources['/network/'+str(netKey)])
for version in details['addresses'][netKey]:
for version in details['addresses'][netKey]:
ip4address = ''
ip6address = ''
if version['version']==4:
if version['version'] == 4:
ip4address = str(version['addr'])
allocheme = str(version['OS-EXT-IPS:type'])
elif version['version']==6:
ip6address = str(version['addr'])
elif version['version'] == 6:
ip6address = str(version['addr'])
allocheme = str(version['OS-EXT-IPS:type'])
if 'attachments' in details.keys():
for item in details['attachments']:
NET_LINK.attributes = {
'occi.core.id':link_id,
'occi.networkinterface.allocation' : allocheme,
'occi.core.id': link_id,
'occi.networkinterface.allocation': allocheme,
'occi.networking.interface': str(item['id']),
'occi.networkinterface.mac' : str(
'occi.networkinterface.mac': str(
item['mac_address']),
'occi.networkinterface.address' : ip4address,
'occi.networkinterface.ip6' : ip6address}
'occi.networkinterface.address': ip4address,
'occi.networkinterface.ip6': ip6address}
elif len(details['addresses'][netKey]) > 0:
NET_LINK.attributes ={
'occi.core.id':link_id,
'occi.networkinterface.allocation' : allocheme,
NET_LINK.attributes = {
'occi.core.id': link_id,
'occi.networkinterface.allocation': allocheme,
'occi.networking.interface': '',
'occi.networkinterface.mac' : '',
'occi.networkinterface.address' : ip4address,
'occi.networkinterface.ip6' : ip6address}
'occi.networkinterface.mac': '',
'occi.networkinterface.address': ip4address,
'occi.networkinterface.ip6': ip6address}
else:
NET_LINK.attributes ={
'occi.core.id':link_id,
'occi.networkinterface.allocation' : '',
NET_LINK.attributes = {
'occi.core.id': link_id,
'occi.networkinterface.allocation': '',
'occi.networking.interface': '',
'occi.networkinterface.mac' : '',
'occi.networkinterface.address' :'',
'occi.networkinterface.ip6' : '' }
'occi.networkinterface.mac': '',
'occi.networkinterface.address': '',
'occi.networkinterface.ip6': ''}
resource.links.append(NET_LINK)
self.registry.add_resource(link_id, NET_LINK, None)
except ClientError as ce:
......@@ -276,19 +276,18 @@ class MyAPP(wsgi.Application):
continue
else:
raise ce
#Compute instances in registry not available in synnefo
# Compute instances in registry not available in synnefo
diff = [x for x in occi_keys if x[9:] not in snf_keys]
for key in diff:
if '/network/' not in key:
self.registry.delete_resource(key, None)
def __call__(self, environ, response):
# Enable VOMS Authorization
"""Enable VOMS Authorization"""
print "SNF_OCCI application has been called!"
req = Request(environ)
if not req.environ.has_key('HTTP_X_AUTH_TOKEN'):
print "An authentication token has NOT been provided!"
status = '401 Not Authorized'
......@@ -296,7 +295,7 @@ class MyAPP(wsgi.Application):
('Content-Type', 'text/html'),
('Www-Authenticate', 'Keystone uri=\'{uri}\''.format(
uri=KEYSTONE_URL))]
response(status,headers)
response(status, headers)
print 'Ask for redirect to URL {uri}'.format(uri=KEYSTONE_URL)
return [str(response)]
print 'An authentication token has been provided'
......@@ -306,10 +305,6 @@ class MyAPP(wsgi.Application):
snf_project = req.environ['HTTP_X_SNF_PROJECT']
except KeyError:
print "No project provided, go to plan B"
# status = '400 Bad Request No Project Provided'
# headers = [('Content-Type', 'text/html'),('Www-Authenticate','Keystone uri=\'https://okeanos-occi2.hellasgrid.gr:5000/main\'')]
# response(status,headers)
# return [str(response)]
astakosClient = astakos.AstakosClient(
KAMAKI_CONFIG['astakos_url'], environ['HTTP_AUTH_TOKEN'])
projects = astakosClient.get_projects()
......@@ -321,18 +316,25 @@ class MyAPP(wsgi.Application):
snf_project = project['id']
print "Project found"
break
if ENABLE_VOMS:
compClient = ComputeClient(KAMAKI_CONFIG['compute_url'], environ['HTTP_AUTH_TOKEN'])
cyclClient = CycladesClient(KAMAKI_CONFIG['compute_url'], environ['HTTP_AUTH_TOKEN'])
netClient = CycladesNetworkClient(KAMAKI_CONFIG['network_url'], environ['HTTP_AUTH_TOKEN'])
if ENABLE_VOMS:
compClient = ComputeClient(
KAMAKI_CONFIG['compute_url'], environ['HTTP_AUTH_TOKEN'])
cyclClient = CycladesClient(
KAMAKI_CONFIG['compute_url'], environ['HTTP_AUTH_TOKEN'])
netClient = CycladesNetworkClient(
KAMAKI_CONFIG['network_url'], environ['HTTP_AUTH_TOKEN'])
try:
#Up-to-date flavors and images
# Up-to-date flavors and images
self.refresh_images(compClient, cyclClient)
self.refresh_flavors_norecursive(compClient, cyclClient)
self.refresh_network_instances(netClient)
self.refresh_compute_instances(compClient, cyclClient)
# token will be represented in self.extras
return self._call_occi(environ, response, security = None, token = environ['HTTP_AUTH_TOKEN'], snf = compClient, client = cyclClient, snf_network=netClient, snf_project=snf_project)
return self._call_occi(
environ, response,
security=None, token=environ['HTTP_AUTH_TOKEN'],
snf=compClient, client=cyclClient,
snf_network=netClient, snf_project=snf_project)
except HTTPError:
print "Exception from unauthorized access!"
status = '401 Not Authorized'
......@@ -340,7 +342,7 @@ class MyAPP(wsgi.Application):
('Content-Type', 'text/html'),
('Www-Authenticate', 'Keystone uri=\'{uri}\''.format(
uri=KEYSTONE_URL))]
response(status,headers)
response(status, headers)
print 'Ask for redirect to {uri}'.format(uri=KEYSTONE_URL)
return [str(response)]
else:
......@@ -352,13 +354,13 @@ class MyAPP(wsgi.Application):
netClient = CycladesNetworkClient(
KAMAKI_CONFIG['network_url'], environ['HTTP_AUTH_TOKEN'])
#Up-to-date flavors and images
self.refresh_images(compClient,cyclClient)
self.refresh_flavors_norecursive(compClient,cyclClient)
# Up-to-date flavors and images
self.refresh_images(compClient, cyclClient)
self.refresh_flavors_norecursive(compClient, cyclClient)
self.refresh_network_instances(cyclClient)
self.refresh_compute_instances(compClient,cyclClient)
self.refresh_compute_instances(compClient, cyclClient)
# token will be represented in self.extras
return self._call_occi(
environ, response,
......@@ -370,45 +372,44 @@ class MyAPP(wsgi.Application):
def application(env, start_response):
"""/v2.0/tokens"""
print "In /v2.0/tokens"
t = snf_voms.VomsAuthN()
t = snf_voms.VomsAuthN()
user_dn, user_vo, user_fqans, snf_token, snf_project = t.process_request(
env)
print (user_dn, user_vo, user_fqans)
env['HTTP_AUTH_TOKEN'] = snf_token
env['SNF_PROJECT'] = snf_project
# Get user authentication details
print "@ refresh_user authentication details"
pool = False
astakosClient = astakos.AstakosClient(
KAMAKI_CONFIG['astakos_url'], env['HTTP_AUTH_TOKEN'] , use_pool=pool)
KAMAKI_CONFIG['astakos_url'], env['HTTP_AUTH_TOKEN'], use_pool=pool)
user_details = astakosClient.authenticate()
response = {
'access': {
'token': {
'issued_at': '',
'expires': user_details['access']['token']['expires'] ,
'id':env['HTTP_AUTH_TOKEN']
'expires': user_details['access']['token']['expires'],
'id': env['HTTP_AUTH_TOKEN']
},
'serviceCatalog': [],
'user': {
'username': user_dn,
'roles_links':user_details['access']['user']['roles_links'],
'roles_links': user_details['access']['user']['roles_links'],
'id': user_details['access']['user']['id'],
'roles':[],
'name':user_dn
'roles': [],
'name': user_dn
},
'metadata': {
'is_admin': 0,
'roles': user_details['access']['user']['roles']
}
}
}
}
status = '200 OK'
headers = [('Content-Type', 'application/json')]
start_response(status,headers)
headers = [('Content-Type', 'application/json')]
start_response(status, headers)
body = json.dumps(response)
print body
return [body]
......@@ -423,12 +424,9 @@ def app_factory(global_config, **local_config):
def tenant_application(env, start_response):
"""/v2.0/tennants"""
print "In /v2.0/tennants"
#t =snf_voms.VomsAuthN()
#(user_dn, user_vo, user_fqans) = t.process_request(env)
#print (user_dn, user_vo, user_fqans)
req = Request(env)
if req.environ.has_key('HTTP_X_AUTH_TOKEN'):
env['HTTP_AUTH_TOKEN']= req.environ['HTTP_X_AUTH_TOKEN']
env['HTTP_AUTH_TOKEN'] = req.environ['HTTP_X_AUTH_TOKEN']
else:
raise HTTPError(404, "Unauthorized access")
......@@ -438,10 +436,10 @@ def tenant_application(env, start_response):
astakosClient = astakos.AstakosClient(
KAMAKI_CONFIG['astakos_url'], env['HTTP_AUTH_TOKEN'], use_pool=pool)
user_details = astakosClient.authenticate()
response = {
'tenants_links': [],
'tenants':[
'tenants': [
{
'description': 'Instances of EGI Federated Clouds TF',
'enabled': True,
......@@ -452,7 +450,7 @@ def tenant_application(env, start_response):
}
status = '200 OK'
headers = [('Content-Type', 'application/json'), ]
start_response(status,headers)
start_response(status, headers)
body = json.dumps(response)
print body
return [body]
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment