Rest SFA Client
authorLoic Baron <loic.baron@lip6.fr>
Mon, 4 May 2015 22:13:03 +0000 (00:13 +0200)
committerLoic Baron <loic.baron@lip6.fr>
Mon, 4 May 2015 22:13:03 +0000 (00:13 +0200)
rest/json_encoder.py [new file with mode: 0644]
rest/sfa_api.py

diff --git a/rest/json_encoder.py b/rest/json_encoder.py
new file mode 100644 (file)
index 0000000..e52aafc
--- /dev/null
@@ -0,0 +1,12 @@
+import json
+import datetime
+import xmlrpclib
+from time import mktime
+
+class MyEncoder(json.JSONEncoder):
+
+    def default(self, obj):
+        if isinstance(obj, datetime.datetime) or isinstance(obj, xmlrpclib.DateTime):
+            return int(mktime(obj.timetuple()))
+
+        return json.JSONEncoder.default(self, obj)
index 800429a..62c883e 100644 (file)
@@ -1,9 +1,11 @@
 import os
 import json
 import ConfigParser 
+import datetime
+from time                       import mktime
 
 from django.shortcuts           import render_to_response
-from django.http import HttpResponse
+from django.http                import HttpResponse
 
 from sfa.trust.certificate      import Keypair, Certificate
 from sfa.client.sfaserverproxy  import SfaServerProxy
@@ -17,24 +19,24 @@ from manifold.models.user       import User
 
 from unfold.loginrequired       import LoginRequiredView
 
-from myslice.settings import logger
+from myslice.settings           import logger
+
+from rest.json_encoder          import MyEncoder
 
 def dispatch(request, method):
     Config = ConfigParser.ConfigParser()
     Config.read(os.getcwd() + "/myslice/monitor.ini")
 
-    # hardcoded user to be replaced by auth
-    user_email = "loic.baron@lip6.fr"
-
-    # Get this as parameters
-    slice_hrn = "fed4fire.upmc.berlin"
-    urn = hrn_to_urn(slice_hrn, "slice")
-    #urn = hrn_to_urn("fed4fire.upmc.loic_baron", "user")
+    #logger.debug(request.session['user']['email'])
+    user_email = request.session['user']['email']
 
     platforms = list()
-    options   = list()
+    options   = dict()
     rspec = ''
     results = dict()
+    urn = ''
+    hrn = ''
+    object_type = ''
 
     if request.method == 'POST':
         req_items = request.POST
@@ -44,27 +46,51 @@ def dispatch(request, method):
     for el in req_items.items():
         if el[0].startswith('rspec'):
             rspec += el[1]
-        if el[0].startswith('platform'):
+        elif el[0].startswith('platform'):
             platforms += req_items.getlist('platform[]')
-        elif el[0].startswith('options'):
-            options += req_items.getlist('options[]')
+        #elif el[0].startswith('options'):
+        #    options += req_items.getlist('options[]')
+        elif el[0].startswith('hrn'):
+            hrn = el[1]
+        elif el[0].startswith('urn'):
+            urn = el[1]
+        elif el[0].startswith('type'):
+            object_type = el[1]
+
+    if method not in ['GetVersion','ListResources']:
+        try:
+            if not hrn:
+                hrn = urn_to_hrn(urn)
+            else:
+                urn = hrn_to_urn(hrn, object_type) 
+        except Exception,e:
+            logger.error(e)
+            raise Exception, "Provide urn OR hrn + type as parameters of method %s" % method
 
     if len(platforms)==0:
-        platforms.append('myslice')
+        platforms = get_platforms()
+        #platforms.append('myslice')
     #results = {'method':method,'platforms':platforms,'rspec':rspec,'options':options}
 
+    result = []
+    api_options = {}
+    api_options['geni_rspec_version'] = {'type': 'GENI', 'version': '3'}
+    server_am = False
     from manifoldapi.manifoldapi    import execute_admin_query
     for pf in platforms:
         platform = get_platform_config(pf)
         logger.debug("platform={}".format(platform))
         if 'sm' in platform and len(platform['sm']) > 0:
             logger.debug('sm')
+            server_am = True
             server_url = platform['sm']
         if 'rm' in platform and len(platform['rm']) > 0:
             logger.debug('rm')
+            server_am = False
             server_url = platform['rm']
         if 'registry' in platform and len(platform['registry']) > 0:
             logger.debug('registry')
+            server_am = False
             server_url = platform['registry']
     
         if not Config.has_option('monitor', 'cert') :
@@ -83,36 +109,104 @@ def dispatch(request, method):
  
         server = SfaServerProxy(server_url, pkey, cert)
 
-        # Get user config from Manifold
-        user_config = get_user_config(user_email, pf)
-        if 'delegated_user_credential' in user_config:
-            user_cred = user_config['delegated_user_credential']
-        else:
-            user_cred = {}
-
-        #if 'delegated_slice_credentials' in user_config:
-        #    for slice_name, cred in user_config['delegated_slice_credentials']:
-        #        if slice_name == slice_param
-
-        if method == "GetVersion": 
-            result = server.GetVersion()
-        elif method == "ListResources":
-            api_options = {}
-            #api_options ['call_id'] = unique_call_id()
-            api_options['geni_rspec_version'] = {'type': 'GENI', 'version': '3'}
-            result = server.ListResources([user_cred], api_options)
-        elif method == "Describe":
-            api_options = {}
-            #api_options ['call_id'] = unique_call_id()
-            api_options['geni_rspec_version'] = {'type': 'GENI', 'version': '3'}
-            result = server.Describe([urn] ,[object_cred], api_options)
-
-        else:
-            return HttpResponse(json.dumps({'error' : '-3','msg':'method not supported yet'}), content_type="application/json")
-
-        results[pf] = result
-
-    return HttpResponse(json.dumps(results), content_type="application/json")
+        try:
+            # Get user config from Manifold
+            user_config = get_user_config(user_email, pf)
+            if 'delegated_user_credential' in user_config:
+                user_cred = user_config['delegated_user_credential']
+            else:
+                user_cred = {}
+
+            if object_type:
+                if 'delegated_%s_credentials'%object_type in user_config:
+                    for obj_name, cred in user_config['delegated_%s_credentials'%object_type].items():
+                        if obj_name == hrn:
+                            object_cred = cred
+
+            # Both AM & Registry
+            if method == "GetVersion": 
+                result = server.GetVersion()
+            else:
+                # AM V3
+                if server_am:
+                    if method == "ListResources":
+                        result = server.ListResources([user_cred], api_options)
+                    elif method == "Describe":
+                        # if GetVersion = v2
+                        # ListResources(slice_hrn)
+                        # else GetVersion = v3
+                        result = server.Describe([urn] ,[object_cred], api_options)
+                    elif method == 'Renew':
+                        result = server.Renew([urn] ,[object_cred], api_options)
+                    elif method == 'Delete':
+                        result = server.Delete([urn] ,[object_cred], api_options)
+                    elif method == 'Allocate':
+                        # if GetVersion = v2
+                        # CreateSliver(slice_hrn)
+                        # else GetVersion = v3
+                        api_options['call_id']    = unique_call_id()
+                        # List of users comes from the Registry
+                        api_options['sfa_users']  = sfa_users
+                        api_options['geni_users'] = geni_users
+                        result = server.Allocate([urn] ,[object_cred], rspec, api_options)
+                    elif method == 'Provision':
+                        # if GetVersion = v2
+                        # Nothing it is not supported by v2 AMs
+                        api_options['call_id']    = unique_call_id()
+                        # List of users comes from the Registry
+                        api_options['sfa_users']  = sfa_users
+                        api_options['geni_users'] = geni_users
+                        result = server.Provision([urn] ,[object_cred], api_options)
+                    elif method == 'Status':
+                        result = server.Status([urn] ,[object_cred], api_options)
+                    elif method == 'PerformOperationalAction':
+                        # if GetVersion = v2
+                        # Nothing it is not supported by v2 AMs
+                        result = server.PerformOperationalAction([urn] ,[object_cred], action, api_options)
+                    elif method == 'Shutdown':
+                        result = server.Shutdown(urn ,[object_cred], api_options)
+                    else:
+                        #return HttpResponse(json.dumps({'error' : '-3','msg':'method not supported by AM'}), content_type="application/json")
+                        logger.debug('method %s not handled by AM' % method)
+                        result = []
+                else:
+                    if method == "List":
+                        # hrn is required
+                        result = server.List(hrn, user_cred, options)
+                        logger.debug(result)
+                    elif method == "Resolve":
+                        # hrn is required
+                        # details can be True or False
+                        options['details']=True
+                        result = server.Resolve(hrn, user_cred, options)
+                        logger.debug(result)
+                    elif method == "Register":
+                        # record_dict must be crafted
+                        # auth_cred must be selected in the list of auth_creds from user's account
+                        result = server.Register(record_dict, auth_cred)
+                    elif method == "Update":
+                        # record_dict must be crafted
+                        # object_cred must be selected in the list of creds for the object type
+                        # from user's account
+                        result = server.Update(record_dict, object_cred)
+                    elif method == "Remove":
+                        # hrn is required
+                        # auth_cred must be selected in the list of auth_creds from user's account
+                        # object_type is required
+                        result = server.Remove(hrn, auth_cred, object_type)
+                    else:
+                        #return HttpResponse(json.dumps({'error' : '-3','msg':'method not supported by Registry'}), content_type="application/json")
+                        logger.debug('method %s not handled by Registry' % method)
+                        result = []
+
+            results[pf] = result
+        except Exception,e:
+            import traceback
+            logger.error(traceback.format_exc())
+            logger.error(e)
+            results[pf] = {'error':'-3', 'error_msg': str(e)}
+
+    return HttpResponse(json.dumps(results, cls=MyEncoder), content_type="application/json")
 
 def get_user_account(user_email, platform_name):
     """
@@ -135,6 +229,14 @@ def get_user_config(user_email, platform_name):
     account = get_user_account(user_email, platform_name)
     return json.loads(account.config) if account.config else {}
 
+def get_platforms():
+    ret = list()
+    platforms = db.query(Platform).all()
+    for p in platforms:
+        ret.append(p.platform)
+    return ret
+
+
 def get_platform_config(platform_name):
     platform = db.query(Platform).filter(Platform.platform == platform_name).one()
     return json.loads(platform.config) if platform.config else {}