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