800429aa857a020381446d05692ff269c497439a
[unfold.git] / rest / sfa_api.py
1 import os
2 import json
3 import ConfigParser 
4
5 from django.shortcuts           import render_to_response
6 from django.http import HttpResponse
7
8 from sfa.trust.certificate      import Keypair, Certificate
9 from sfa.client.sfaserverproxy  import SfaServerProxy
10 from sfa.client.return_value    import ReturnValue
11 from sfa.util.xrn               import Xrn, get_leaf, get_authority, hrn_to_urn, urn_to_hrn
12
13 from manifold.core.query        import Query
14 from manifold.models            import db
15 from manifold.models.platform   import Platform
16 from manifold.models.user       import User
17
18 from unfold.loginrequired       import LoginRequiredView
19
20 from myslice.settings import logger
21
22 def dispatch(request, method):
23     Config = ConfigParser.ConfigParser()
24     Config.read(os.getcwd() + "/myslice/monitor.ini")
25
26     # hardcoded user to be replaced by auth
27     user_email = "loic.baron@lip6.fr"
28
29     # Get this as parameters
30     slice_hrn = "fed4fire.upmc.berlin"
31     urn = hrn_to_urn(slice_hrn, "slice")
32     #urn = hrn_to_urn("fed4fire.upmc.loic_baron", "user")
33
34     platforms = list()
35     options   = list()
36     rspec = ''
37     results = dict()
38
39     if request.method == 'POST':
40         req_items = request.POST
41     elif request.method == 'GET':
42         req_items = request.GET
43
44     for el in req_items.items():
45         if el[0].startswith('rspec'):
46             rspec += el[1]
47         if el[0].startswith('platform'):
48             platforms += req_items.getlist('platform[]')
49         elif el[0].startswith('options'):
50             options += req_items.getlist('options[]')
51
52     if len(platforms)==0:
53         platforms.append('myslice')
54     #results = {'method':method,'platforms':platforms,'rspec':rspec,'options':options}
55
56     from manifoldapi.manifoldapi    import execute_admin_query
57     for pf in platforms:
58         platform = get_platform_config(pf)
59         logger.debug("platform={}".format(platform))
60         if 'sm' in platform and len(platform['sm']) > 0:
61             logger.debug('sm')
62             server_url = platform['sm']
63         if 'rm' in platform and len(platform['rm']) > 0:
64             logger.debug('rm')
65             server_url = platform['rm']
66         if 'registry' in platform and len(platform['registry']) > 0:
67             logger.debug('registry')
68             server_url = platform['registry']
69     
70         if not Config.has_option('monitor', 'cert') :
71              return HttpResponse(json.dumps({'error' : '-1'}), content_type="application/json")
72
73         cert = os.path.abspath(Config.get('monitor', 'cert'))
74         if not os.path.isfile(cert) :
75              return HttpResponse(json.dumps({'error' : '-1'}), content_type="application/json")
76
77         if not Config.has_option('monitor', 'pkey') :
78              return HttpResponse(json.dumps({'error' : '-2'}), content_type="application/json")
79
80         pkey = os.path.abspath(Config.get('monitor', 'pkey'))
81         if not os.path.isfile(pkey) :
82              return HttpResponse(json.dumps({'error' : '-2'}), content_type="application/json")
83  
84         server = SfaServerProxy(server_url, pkey, cert)
85
86         # Get user config from Manifold
87         user_config = get_user_config(user_email, pf)
88         if 'delegated_user_credential' in user_config:
89             user_cred = user_config['delegated_user_credential']
90         else:
91             user_cred = {}
92
93         #if 'delegated_slice_credentials' in user_config:
94         #    for slice_name, cred in user_config['delegated_slice_credentials']:
95         #        if slice_name == slice_param
96
97         if method == "GetVersion": 
98             result = server.GetVersion()
99         elif method == "ListResources":
100             api_options = {}
101             #api_options ['call_id'] = unique_call_id()
102             api_options['geni_rspec_version'] = {'type': 'GENI', 'version': '3'}
103             result = server.ListResources([user_cred], api_options)
104         elif method == "Describe":
105             api_options = {}
106             #api_options ['call_id'] = unique_call_id()
107             api_options['geni_rspec_version'] = {'type': 'GENI', 'version': '3'}
108             result = server.Describe([urn] ,[object_cred], api_options)
109
110         else:
111             return HttpResponse(json.dumps({'error' : '-3','msg':'method not supported yet'}), content_type="application/json")
112
113         results[pf] = result
114
115     return HttpResponse(json.dumps(results), content_type="application/json")
116
117 def get_user_account(user_email, platform_name):
118     """
119     Returns the user configuration for a given platform.
120     This function does not resolve references.
121     """
122     user = db.query(User).filter(User.email == user_email).one()
123     platform = db.query(Platform).filter(Platform.platform == platform_name).one()
124     accounts = [a for a in user.accounts if a.platform == platform]
125     if not accounts:
126         raise Exception, "this account does not exist"
127
128     if accounts[0].auth_type == 'reference':
129         pf = json.loads(accounts[0].config)['reference_platform']
130         return get_user_account(user_email, pf)
131
132     return accounts[0]
133
134 def get_user_config(user_email, platform_name):
135     account = get_user_account(user_email, platform_name)
136     return json.loads(account.config) if account.config else {}
137
138 def get_platform_config(platform_name):
139     platform = db.query(Platform).filter(Platform.platform == platform_name).one()
140     return json.loads(platform.config) if platform.config else {}