Merge branch 'master' of ssh://git.onelab.eu/git/myslice
[myslice.git] / manifold / 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 manifold.manifoldquery import ManifoldQuery
9 from manifold.core.query        import Query
10 from manifold.core.result_value import ResultValue
11 from manifold.manifoldapi       import ManifoldAPI
12 from manifold.manifoldresult    import ManifoldException
13 from manifold.util.log          import Log
14
15 debug=False
16 debug=True
17
18 # add artificial delay in s
19 debug_spin=0
20 #debug_spin=1
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 # turn this on if you want the fastest possible (locally cached) feedback
28 # beware that this is very rough though...
29 work_offline=False
30 #work_offline=True
31
32 # this view is what the javascript talks to when it sends a query
33 # see also
34 # myslice/urls.py
35 # as well as 
36 # static/js/manifold.js
37 def proxy (request,format):
38     """the view associated with /manifold/proxy/ 
39 with the query passed using POST"""
40     
41     # expecting a POST
42     if request.method != 'POST':
43         print "manifoldproxy.api: unexpected method %s -- exiting"%request.method
44         return 
45     # we only support json for now
46     # if needed in the future we should probably cater for
47     # format_in : how is the query encoded in POST
48     # format_out: how to serve the results
49     if format != 'json':
50         print "manifoldproxy.proxy: unexpected format %s -- exiting"%format
51         return
52     try:
53         # translate incoming POST request into a query object
54         if debug: print 'manifoldproxy.proxy: request.POST',request.POST
55         manifold_query = Query()
56         #manifold_query = ManifoldQuery()
57         manifold_query.fill_from_POST(request.POST)
58         offline_filename="%s/../offline-%s-%s.json"%(os.path.dirname(__file__),manifold_query.action,manifold_query.object)
59         # retrieve session for request
60
61         # We allow some requests to use the ADMIN user account
62         if (manifold_query.get_from() == 'local:user' and manifold_query.get_action() == 'create') or (manifold_query.get_from() == 'local:platform' and manifold_query.get_action() == 'get'):
63             print "W: Used hardcoded demo account for admin queries"
64             manifold_api_session_auth = {'AuthMethod': 'password', 'Username': 'demo', 'AuthString': 'demo'}
65         else:
66             manifold_api_session_auth = request.session['manifold']['auth']
67
68         if debug_empty and manifold_query.action.lower()=='get':
69             json_answer=json.dumps({'code':0,'value':[]})
70             print "By-passing : debug_empty & 'get' request : returning a fake empty list"
71             return HttpResponse (json_answer, mimetype="application/json")
72         ### patch : return the latest one..
73         if work_offline:
74             # if that won't work then we'll try to update anyways
75             try:
76                 with (file(offline_filename,"r")) as f:
77                     json_answer=f.read()
78                 print "By-passing : using contents from %s"%offline_filename
79                 return HttpResponse (json_answer, mimetype="application/json")
80             except:
81                 import traceback
82                 traceback.print_exc()
83                 print "Could not run in offline mode, PROCEEDING"
84                 pass
85                 
86         # actually forward
87         manifold_api= ManifoldAPI(auth=manifold_api_session_auth)
88         if debug: print '===> manifoldproxy.proxy: sending to backend', manifold_query
89         # for the benefit of the python code, manifoldAPI raises an exception if something is wrong
90         # however in this case we want to propagate the complete manifold result to the js world
91
92         result = manifold_api.forward(manifold_query.to_dict())
93
94         # XXX TEMP HACK
95         if 'description' in result and result['description'] and isinstance(result['description'], (tuple, list, set, frozenset)):
96             result [ 'description' ] = [ ResultValue.to_html (x) for x in result['description'] ]
97
98         json_answer=json.dumps(result)
99         # if in debug mode we save this so we can use offline mode later
100         if debug:
101             with (file(offline_filename,"w")) as f:
102                 f.write(json_answer)
103
104         # this is an artificial delay added for debugging purposes only
105         if debug_spin>0:
106             print "Adding additional artificial delay",debug_spin
107             import time
108             time.sleep(debug_spin)
109
110         return HttpResponse (json_answer, mimetype="application/json")
111
112     except Exception,e:
113         print "** PROXY ERROR **",e
114         import traceback
115         traceback.print_exc()
116
117 #################### 
118 # see CSRF_FAILURE_VIEW in settings.py
119 # the purpose of redefining this was to display the failure reason somehow
120 # this however turns out disappointing/not very informative
121 failure_answer=[ "csrf_failure" ]
122 def csrf_failure(request, reason=""):
123     print "CSRF failure with reason '%s'"%reason
124     return HttpResponseForbidden (json.dumps (failure_answer), mimetype="application/json")