manifoldapi made python3-compatible
[myslice.git] / manifoldapi / manifoldapi.py
1 # Manifold API Python interface
2 import copy
3 import ssl
4
5 # for python3
6 try:    import xmlrpclib
7 except: import xmlrpc.client as xmlrpclib
8
9 from django.contrib import messages
10 from django.shortcuts import redirect
11
12 from manifold.core.result_value import ResultValue
13 from manifoldresult import ManifoldResult, ManifoldCode, ManifoldException, truncate_result
14
15 # being available from the outside (r2lab django web site)
16 try:
17     from myslice.settings import logger
18 except:
19     import logging
20     logger = logging.getLogger('manifoldapi')
21     
22
23 class ManifoldAPI:
24
25     def __init__(self, auth=None, cainfo=None):
26         
27         self.auth = auth
28         self.cainfo = cainfo
29         self.errors = []
30         self.trace = []
31         self.calls = {}
32         self.multicall = False
33         try:
34             from myslice.settings import config
35             self.url = config.manifold_url()
36         except:
37             self.url = "https://portal.onelab.eu:7080/"
38         
39         # Manifold uses a self signed certificate
40         # https://www.python.org/dev/peps/pep-0476/
41         try:    turn_off_server_verify = { 'context' : ssl._create_unverified_context() } 
42         except: turn_off_server_verify = {}
43         self.server = xmlrpclib.Server(self.url, verbose=False, allow_none=True,
44                                        **turn_off_server_verify)
45
46     # xxx temporary code for scaffolding a ManifolResult on top of an API that does not expose error info
47     # as of march 2013 we work with an API that essentially either returns the value, or raises 
48     # an xmlrpclib.Fault exception with always the same 8002 code
49     # since most of the time we're getting this kind of issues for expired sessions
50     # (looks like sessions are rather short-lived), for now the choice is to map these errors on 
51     # a SESSION_EXPIRED code
52     def __getattr__(self, methodName):
53
54         def func(*args, **kwds):
55             import time
56             start = time.time()
57             
58             # the message to display
59             auth_message = "<AuthMethod not set in {}>".format(self.auth) if 'AuthMethod' not in self.auth \
60                            else "[session]" if self.auth['AuthMethod'] == 'session' \
61                            else "user:{}".format(self.auth['Username']) if self.auth['AuthMethod'] == 'password' \
62                            else "anonymous" if self.auth['AuthMethod'] == 'anonymous' \
63                            else "[???]" + "{}".format(self.auth)
64             end_message = "MANIFOLD <- {}( {}( {} ) ) with auth={} to {}"\
65                           .format(methodName,
66                                   args[0]['action'] or '', 
67                                   args[0]['object'] or '',
68                                   auth_message,
69                                   self.url)
70             try:
71                 args += ({ 'authentication': self.auth },)
72                 result = getattr(self.server, methodName)(*args, **kwds)
73                 logger.debug("{} executed in {} seconds -> {}"\
74                              .format(end_message, time.time() - start, truncate_result(result)))
75                 return ResultValue(**result)
76
77             except Exception as error:
78                 logger.error("===== xmlrpc catch-all exception: {}".format(error))
79                 import traceback
80                 logger.error(traceback.format_exc(limit=3))
81                 
82                 if "Connection refused" in error:
83                     raise ManifoldException ( ManifoldResult (code=ManifoldCode.SERVER_UNREACHABLE,
84                                                               output="{} answered {}".format(self.url, error)))
85                 # otherwise
86                 logger.error("{} FAILED - executed in {} seconds"\
87                              .format(end_message, time.time() - start)) 
88                 logger.error("MANIFOLD {}".format(error))
89                 raise ManifoldException ( ManifoldResult (code = ManifoldCode.SERVER_UNREACHABLE,
90                                                           output = "{}".format(error)))
91
92         return func
93
94 def _execute_query(request, query, manifold_api_session_auth):
95     
96     manifold_api = ManifoldAPI(auth = manifold_api_session_auth)
97     
98     logger.debug("MANIFOLD -> QUERY : {}".format(" ".join(str(query).split())))
99     result = manifold_api.forward(query.to_dict())
100     if result['code'] == 2:
101         # this is gross; at the very least we need to logout() 
102         # but most importantly there is a need to refine that test, since 
103         # code==2 does not necessarily mean an expired session
104         # XXX only if we know it is the issue
105         #SessionCache().end_session(request)
106         # Flush django session
107         del request.session['manifold']
108
109         request.session.flush()
110         #raise Exception, 'Error running query: {}'.format(result)
111     
112     if result['code'] == 1:
113         logger.warning("MANIFOLD : {}".format(result['description']))
114
115     # XXX Handle errors
116     #Error running query: {'origin': [0, 'XMLRPCAPI'], 'code': 2, 'description': 'No such session: No row was found for one()', 'traceback': 'Traceback (most recent call last):\n  File "/usr/local/lib/python2.7/dist-packages/manifold/core/xmlrpc_api.py", line 68, in xmlrpc_forward\n    user = Auth(auth).check()\n  File "/usr/local/lib/python2.7/dist-packages/manifold/auth/__init__.py", line 245, in check\n    return self.auth_method.check()\n  File "/usr/local/lib/python2.7/dist-packages/manifold/auth/__init__.py", line 95, in check\n    raise AuthenticationFailure, "No such session: %s" % e\nAuthenticationFailure: No such session: No row was found for one()\n', 'type': 2, 'ts': None, 'value': None}
117
118     return result['value'] 
119
120 def execute_query(request, query):
121     
122     logger.debug("EXECUTE QUERY: request - {}".format(request.session.items()))
123     
124     if not 'manifold' in request.session or not 'auth' in request.session['manifold']:
125     #manifold_api_session_auth = SessionCache().get_auth(request)
126     #if not manifold_api_session_auth:
127         request.session.flush()
128         #raise Exception, "User not authenticated"
129         host = request.get_host()
130         return redirect('/')
131     
132     manifold_api_session_auth = request.session['manifold']['auth']
133
134     return _execute_query(request, query, manifold_api_session_auth)
135
136 def execute_admin_query(request, query):
137     # xxx config
138     admin_user, admin_password = config.manifold_admin_user_password()
139     if not admin_user or not admin_password:
140         logger.error("""CONFIG: you need to setup admin_user and admin_password in myslice.ini
141 Some functions won't work properly until you do so""")
142     admin_auth = {'AuthMethod': 'password', 'Username': admin_user, 'AuthString': admin_password}
143     return _execute_query(request, query, admin_auth)