Commit e294f07a authored by Ilias Tsitsimpis's avatar Ilias Tsitsimpis

astakoclient: Add request for Resource List

Refs #3440
parent 0bcb942d
......@@ -68,7 +68,7 @@ class AstakosClient():
# ----------------------------------
def __init__(self, astakos_url, retry=0,
use_pool=False, pool_size=8, logger=None):
"""Intialize AstakosClient Class
"""Initialize AstakosClient Class
Keyword arguments:
astakos_url -- i.e https://accounts.example.com (string)
......@@ -111,18 +111,17 @@ class AstakosClient():
def _call_astakos(self, token, request_path,
headers=None, body=None, method="GET"):
"""Make the actual call to Astakos Service"""
hashed_token = hashlib.sha1()
hashed_token.update(token)
if token is not None:
hashed_token = hashlib.sha1()
hashed_token.update(token)
using_token = "using token %s" % (hashed_token.hexdigest())
else:
using_token = "without using token"
self.logger.debug(
"Make a %s request to %s using token %s "
"with headers %s and body %s"
% (method, request_path, hashed_token.hexdigest(), headers, body))
"Make a %s request to %s %s with headers %s and body %s"
% (method, request_path, using_token, headers, body))
# Check Input
if not token:
m = "Token not given"
self.logger.error(m)
raise ValueError(m)
if headers is None:
headers = {}
if body is None:
......@@ -133,7 +132,8 @@ class AstakosClient():
# Build request's header and body
kwargs = {}
kwargs['headers'] = copy(headers)
kwargs['headers']['X-Auth-Token'] = token
if token is not None:
kwargs['headers']['X-Auth-Token'] = token
if body:
kwargs['body'] = copy(body)
kwargs['headers'].setdefault(
......@@ -166,6 +166,7 @@ class AstakosClient():
return simplejson.loads(unicode(data))
# ------------------------
# GET /im/authenticate
def get_user_info(self, token, usage=False):
"""Authenticate user and get user's info as a dictionary
......@@ -184,6 +185,8 @@ class AstakosClient():
return self._call_astakos(token, auth_path)
# ----------------------------------
# POST /user_catalogs (or /service/api/user_catalogs)
# with {'uuids': uuids}
def _uuid_catalog(self, token, uuids, req_path):
req_headers = {'content-type': 'application/json'}
req_body = simplejson.dumps({'uuids': uuids})
......@@ -241,6 +244,8 @@ class AstakosClient():
raise NoUserName(uuid)
# ----------------------------------
# POST /user_catalogs (or /service/api/user_catalogs)
# with {'displaynames': display_names}
def _displayname_catalog(self, token, display_names, req_path):
req_headers = {'content-type': 'application/json'}
req_body = simplejson.dumps({'displaynames': display_names})
......@@ -298,9 +303,16 @@ class AstakosClient():
raise NoUUID(display_name)
# ----------------------------------
# GET "/im/get_services"
def get_services(self):
"""Return a list of dicts with the registered services"""
return self._call_astakos("dummy token", "/im/get_services")
return self._call_astakos(None, "/im/get_services")
# ----------------------------------
# GET "/astakos/api/resources"
def get_resources(self):
"""Return a dict of dicts with the available resources"""
return self._call_astakos(None, "/astakos/api/resources")
# --------------------------------------------------------------------
......
......@@ -108,25 +108,25 @@ def _request_status_400(conn, method, url, **kwargs):
def _request_ok(conn, method, url, **kwargs):
"""This request behaves like original Astakos does"""
if url[0:16] == "/im/authenticate":
if url.startswith("/im/authenticate"):
return _req_authenticate(conn, method, url, **kwargs)
elif url[0:14] == "/user_catalogs":
elif url.startswith("/user_catalogs"):
return _req_catalogs(conn, method, url, **kwargs)
elif url.startswith("/astakos/api/resources"):
return _req_resources(conn, method, url, **kwargs)
else:
return _request_status_404(conn, method, url, **kwargs)
def _req_authenticate(conn, method, url, **kwargs):
"""Check if user exists and return his profile"""
global user_1, user_2
global user_1, user_2, token_1, token_2
# Check input
if conn.__class__.__name__ != "HTTPSConnection":
return _request_status_302(conn, method, url, **kwargs)
if method != "GET":
return _request_status_400(conn, method, url, **kwargs)
token = kwargs['headers']['X-Auth-Token']
if token == token_1:
user = dict(user_1)
......@@ -150,10 +150,8 @@ def _req_catalogs(conn, method, url, **kwargs):
# Check input
if conn.__class__.__name__ != "HTTPSConnection":
return _request_status_302(conn, method, url, **kwargs)
if method != "POST":
return _request_status_400(conn, method, url, **kwargs)
token = kwargs['headers']['X-Auth-Token']
if token != token_1 and token != token_2:
return _request_status_401(conn, method, url, **kwargs)
......@@ -183,6 +181,20 @@ def _req_catalogs(conn, method, url, **kwargs):
return ("", simplejson.dumps(return_catalog), 200)
def _req_resources(conn, method, url, **kwargs):
"""Return quota resources"""
global resources
# Check input
if conn.__class__.__name__ != "HTTPSConnection":
return _request_status_302(conn, method, url, **kwargs)
if method != "GET":
return _request_status_400(conn, method, url, **kwargs)
# Return
return ("", simplejson.dumps(resources), 200)
# ----------------------------
# Mock the actual _doRequest
def _mock_request(new_requests):
......@@ -266,6 +278,16 @@ user_2 = \
"display_name": "Storage Space",
"name": "pithos+.diskspace"}]}
resources = {
"cyclades.vm": {
"unit": None,
"description": "Number of virtual machines",
"service": "cyclades"},
"cyclades.ram": {
"unit": "bytes",
"description": "Virtual machine memory",
"service": "cyclades"}}
# --------------------------------------------------------------------
# The actual tests
......@@ -660,6 +682,22 @@ class TestGetUUIDs(unittest.TestCase):
self.fail("Should have raised NoUUID exception")
class TestResources(unittest.TestCase):
"""Test cases for function get_resources"""
# ----------------------------------
# Test function call of get_resources
def test_get_resources(self):
global resources
_mock_request([_request_offline, _request_ok])
try:
client = AstakosClient("https://example.com", retry=1)
result = client.get_resources()
except Exception as err:
self.fail("Shouldn't raise Exception %s" % err)
self.assertEqual(resources, result)
# ----------------------------
# Run tests
if __name__ == "__main__":
......
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