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