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