Import error for Log
[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     """the view associated with /manifold/proxy/ with the query passed using POST"""
36     
37     # expecting a POST
38     if request.method != 'POST':
39         logger.error("MANIFOLDPROXY unexpected method {} -- exiting".format(request.method))
40         return HttpResponse ({"ret":0}, content_type="application/json")
41     # we only support json for now
42     # if needed in the future we should probably cater for
43     # format_in : how is the query encoded in POST
44     # format_out: how to serve the results
45     if format != 'json':
46         logger.error("MANIFOLDPROXY unexpected format {} -- exiting".format(format))
47         return HttpResponse ({"ret":0}, content_type="application/json")
48     try:
49         # translate incoming POST request into a query object
50         #logger.debug("MANIFOLDPROXY request.POST {}".format(request.POST))
51
52         manifold_query = Query()
53         #manifold_query = ManifoldQuery()
54         manifold_query.fill_from_POST(request.POST)
55         # retrieve session for request
56
57         # We allow some requests to use the ADMIN user account
58         if (manifold_query.get_from() == 'local:user' and manifold_query.get_action() == 'create') \
59                 or (manifold_query.get_from() == 'local:platform' and manifold_query.get_action() == 'get'):
60             admin_user, admin_password = config.manifold_admin_user_password()
61             manifold_api_session_auth = {'AuthMethod': 'password', 'Username': admin_user, 'AuthString': admin_password}
62         else:
63             if 'manifold' in request.session:
64                 manifold_api_session_auth = request.session['manifold']['auth']
65             else:
66             #manifold_api_session_auth = SessionCache().get_auth(request)
67             #if not manifold_api_session_auth:
68                 return HttpResponse (json.dumps({'code':0,'value':[]}), content_type="application/json")
69                 
70         if debug_empty and manifold_query.action.lower()=='get':
71             return HttpResponse (json.dumps({'code':0,'value':[]}), content_type="application/json")
72                 
73         # actually forward
74         manifold_api= ManifoldAPI(auth=manifold_api_session_auth)
75
76         # for the benefit of the python code, manifoldAPI raises an exception if something is wrong
77         # however in this case we want to propagate the complete manifold result to the js world
78
79         result = manifold_api.forward(manifold_query.to_dict())
80
81         # XXX TEMP HACK
82         if 'description' in result and result['description'] \
83                 and isinstance(result['description'], (tuple, list, set, frozenset)):
84             result [ 'description' ] = [ ResultValue.to_html (x) for x in result['description'] ]
85         
86         #
87         # register activity
88         #
89         # resource reservation
90         if (manifold_query.action.lower() == 'update') :
91             logger.debug(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, content_type="application/json")
107
108     except Exception as e:
109         logger.error("MANIFOLDPROXY {}".format(e))
110         import traceback
111         logger.error(traceback.format_exc())
112         return HttpResponse ({"ret":0}, content_type="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     logger.error("CSRF failure with reason '{}'".format(reason))
121     return HttpResponseForbidden (json.dumps (failure_answer), content_type="application/json")