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