1 # Manifold API Python interface
7 except: import xmlrpc.client as xmlrpclib
9 from django.contrib import messages
10 from django.shortcuts import redirect
12 from manifold.core.result_value import ResultValue
13 from manifoldresult import ManifoldResult, ManifoldCode, ManifoldException, truncate_result
15 # being available from the outside (r2lab django web site)
17 from myslice.settings import logger
20 logger = logging.getLogger('manifoldapi')
25 def __init__(self, auth=None, cainfo=None):
32 self.multicall = False
34 from myslice.settings import config
35 self.url = config.manifold_url()
37 self.url = "https://portal.onelab.eu:7080/"
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)
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):
54 def func(*args, **kwds):
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 {}"\
66 args[0]['action'] or '',
67 args[0]['object'] or '',
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)
77 except Exception as error:
78 logger.error("===== xmlrpc catch-all exception: {}".format(error))
80 logger.error(traceback.format_exc(limit=3))
82 if "Connection refused" in error:
83 raise ManifoldException ( ManifoldResult (code=ManifoldCode.SERVER_UNREACHABLE,
84 output="{} answered {}".format(self.url, error)))
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)))
94 def _execute_query(request, query, manifold_api_session_auth):
96 manifold_api = ManifoldAPI(auth = manifold_api_session_auth)
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']
109 request.session.flush()
110 #raise Exception, 'Error running query: {}'.format(result)
112 if result['code'] == 1:
113 logger.warning("MANIFOLD : {}".format(result['description']))
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}
118 return result['value']
120 def execute_query(request, query):
122 logger.debug("EXECUTE QUERY: request - {}".format(request.session.items()))
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()
132 manifold_api_session_auth = request.session['manifold']['auth']
134 return _execute_query(request, query, manifold_api_session_auth)
136 def execute_admin_query(request, query):
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)