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, url, auth=None, cainfo=None):
33 self.multicall = False
35 # Manifold uses a self signed certificate
36 # https://www.python.org/dev/peps/pep-0476/
37 try: turn_off_server_verify = { 'context' : ssl._create_unverified_context() }
38 except: turn_off_server_verify = {}
39 self.server = xmlrpclib.Server(self.url, verbose=False, allow_none=True,
40 **turn_off_server_verify)
42 # xxx temporary code for scaffolding a ManifolResult on top of an API that does not expose error info
43 # as of march 2013 we work with an API that essentially either returns the value, or raises
44 # an xmlrpclib.Fault exception with always the same 8002 code
45 # since most of the time we're getting this kind of issues for expired sessions
46 # (looks like sessions are rather short-lived), for now the choice is to map these errors on
47 # a SESSION_EXPIRED code
48 def __getattr__(self, methodName):
50 def func(*args, **kwds):
54 # the message to display
55 auth_message = "<AuthMethod not set in {}>".format(self.auth) if 'AuthMethod' not in self.auth \
56 else "[session]" if self.auth['AuthMethod'] == 'session' \
57 else "user:{}".format(self.auth['Username']) if self.auth['AuthMethod'] == 'password' \
58 else "anonymous" if self.auth['AuthMethod'] == 'anonymous' \
59 else "[???]" + "{}".format(self.auth)
60 end_message = "MANIFOLD <- {}( {}( {} ) ) with auth={} to {}"\
62 args[0]['action'] or '',
63 args[0]['object'] or '',
67 args += ({ 'authentication': self.auth },)
68 result = getattr(self.server, methodName)(*args, **kwds)
69 logger.debug("{} executed in {} seconds -> {}"\
70 .format(end_message, time.time() - start, truncate_result(result)))
71 return ResultValue(**result)
73 except Exception as error:
74 logger.error("===== xmlrpc catch-all exception: {}".format(error))
76 logger.error(traceback.format_exc(limit=3))
78 if "Connection refused" in error:
79 raise ManifoldException ( ManifoldResult (code=ManifoldCode.SERVER_UNREACHABLE,
80 output="{} answered {}".format(self.url, error)))
82 logger.error("{} FAILED - executed in {} seconds"\
83 .format(end_message, time.time() - start))
84 logger.error("MANIFOLD {}".format(error))
85 raise ManifoldException ( ManifoldResult (code = ManifoldCode.SERVER_UNREACHABLE,
86 output = "{}".format(error)))
90 def _execute_query(url, request, query, manifold_api_session_auth):
92 manifold_api = ManifoldAPI(url, auth = manifold_api_session_auth)
94 logger.debug("MANIFOLD -> QUERY : {}".format(" ".join(str(query).split())))
95 result = manifold_api.forward(query.to_dict())
96 if result['code'] == 2:
97 # this is gross; at the very least we need to logout()
98 # but most importantly there is a need to refine that test, since
99 # code==2 does not necessarily mean an expired session
100 # XXX only if we know it is the issue
101 #SessionCache().end_session(request)
102 # Flush django session
103 del request.session['manifold']
105 request.session.flush()
106 #raise Exception, 'Error running query: {}'.format(result)
108 if result['code'] == 1:
109 logger.warning("MANIFOLD : {}".format(result['description']))
112 #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}
114 return result['value']
116 def execute_query(request, query):
118 #logger.debug("EXECUTE QUERY: request - {}".format(request.session.items()))
120 if not 'manifold' in request.session or not 'auth' in request.session['manifold']:
121 #manifold_api_session_auth = SessionCache().get_auth(request)
122 #if not manifold_api_session_auth:
123 request.session.flush()
124 #raise Exception, "User not authenticated"
125 host = request.get_host()
128 manifold_api_session_auth = request.session['manifold']['auth']
130 from myslice.settings import config
131 url = config.manifold_url()
132 return _execute_query(url, request, query, manifold_api_session_auth)
134 def execute_admin_query(request, query):
136 from myslice.settings import config
137 url = config.manifold_url()
139 admin_user, admin_password = config.manifold_admin_user_password()
140 if not admin_user or not admin_password:
141 logger.error("""CONFIG: you need to setup admin_user and admin_password in myslice.ini
142 Some functions won't work properly until you do so""")
143 admin_auth = {'AuthMethod': 'password', 'Username': admin_user, 'AuthString': admin_password}
145 return _execute_query(url, request, query, admin_auth)