eba37bb8ba177a28b6007a85d3a023f79f2d2b24
[myslice.git] / manifoldapi / manifoldproxy.py
1 import json
2 import os.path
3
4 # this is for django objects only
5 #from django.core import serializers
6 from django.http                import HttpResponse, HttpResponseForbidden
7
8 #from manifoldapi.manifoldquery import ManifoldQuery
9 from manifold.core.query        import Query
10 from manifold.core.result_value import ResultValue
11 from manifoldapi                import ManifoldAPI
12 from manifoldresult             import ManifoldException
13 from manifold.util.log          import Log
14
15 # from unfold.sessioncache import SessionCache
16
17 from myslice.settings import config, logger
18
19 # register activity
20 import activity.slice
21
22 debug=False
23 #debug=True
24
25 # pretend the server only returns - empty lists to 'get' requests - this is to mimick 
26 # misconfigurations or expired credentials or similar corner case situations
27 debug_empty=False
28 #debug_empty=True
29
30 # this view is what the javascript talks to when it sends a query
31 # see also
32 # myslice/urls.py
33 # as well as 
34 # static/js/manifold.js
35 def proxy (request,format):
36     """the view associated with /manifold/proxy/ with the query passed using POST"""
37     
38     # expecting a POST
39     if request.method != 'POST':
40         logger.error("MANIFOLDPROXY unexpected method {} -- exiting".format(request.method))
41         return HttpResponse ({"ret":0}, content_type="application/json")
42     # we only support json for now
43     # if needed in the future we should probably cater for
44     # format_in : how is the query encoded in POST
45     # format_out: how to serve the results
46     if format != 'json':
47         logger.error("MANIFOLDPROXY unexpected format {} -- exiting".format(format))
48         return HttpResponse ({"ret":0}, content_type="application/json")
49     try:
50         # translate incoming POST request into a query object
51         #logger.debug("MANIFOLDPROXY request.POST {}".format(request.POST))
52
53         manifold_query = Query()
54         #manifold_query = ManifoldQuery()
55         manifold_query.fill_from_POST(request.POST)
56         # retrieve session for request
57
58         # We allow some requests to use the ADMIN user account
59         if (manifold_query.get_from() == 'local:user' and manifold_query.get_action() == 'create') \
60                 or (manifold_query.get_from() == 'local:platform' and manifold_query.get_action() == 'get'):
61             admin_user, admin_password = config.manifold_admin_user_password()
62             manifold_api_session_auth = {'AuthMethod': 'password', 'Username': admin_user, 'AuthString': admin_password}
63         else:
64             if 'manifold' in request.session:
65                 manifold_api_session_auth = request.session['manifold']['auth']
66             else:
67             #manifold_api_session_auth = SessionCache().get_auth(request)
68             #if not manifold_api_session_auth:
69                 return HttpResponse (json.dumps({'code':0,'value':[]}), content_type="application/json")
70                 
71         if debug_empty and manifold_query.action.lower()=='get':
72             return HttpResponse (json.dumps({'code':0,'value':[]}), content_type="application/json")
73                 
74         # actually forward
75         manifold_api= ManifoldAPI(auth=manifold_api_session_auth)
76
77         # for the benefit of the python code, manifoldAPI raises an exception if something is wrong
78         # however in this case we want to propagate the complete manifold result to the js world
79
80         result = manifold_api.forward(manifold_query.to_dict())
81
82         # XXX TEMP HACK
83         if 'description' in result and result['description'] \
84                 and isinstance(result['description'], (tuple, list, set, frozenset)):
85             result [ 'description' ] = [ ResultValue.to_html (x) for x in result['description'] ]
86         
87         #
88         # register activity
89         #
90         # resource reservation
91         if (manifold_query.action.lower() == 'update') :
92             logger.debug(result['value'][0])
93             if 'resource' in result['value'][0] :
94                 for resource in result['value'][0]['resource'] :
95                     activity.slice.resource(request, 
96                             { 
97                                 'slice' :           result['value'][0]['slice_hrn'], 
98                                 'resource' :        resource['hostname'], 
99                                 'resource_type' :   resource['type'],
100                                 'facility' :        resource['facility_name'],
101                                 'testbed' :         resource['testbed_name']
102                             }
103                     )
104         
105         json_answer=json.dumps(result)
106
107         return HttpResponse (json_answer, content_type="application/json")
108
109     except Exception as e:
110         logger.error("MANIFOLDPROXY {}".format(e))
111         import traceback
112         logger.error(traceback.format_exc())
113         return HttpResponse ({"ret":0}, content_type="application/json")
114
115 #################### 
116 # see CSRF_FAILURE_VIEW in settings.py
117 # the purpose of redefining this was to display the failure reason somehow
118 # this however turns out disappointing/not very informative
119 failure_answer=[ "csrf_failure" ]
120 def csrf_failure(request, reason=""):
121     logger.error("CSRF failure with reason '{}'".format(reason))
122     return HttpResponseForbidden (json.dumps (failure_answer), content_type="application/json")