1 # Manifold API Python interface
6 from django.contrib import messages
7 from django.shortcuts import redirect
9 from manifold.core.result_value import ResultValue
10 from manifoldresult import ManifoldResult, ManifoldCode, ManifoldException, truncate_result
12 # from unfold.sessioncache import SessionCache
14 from myslice.settings import config, logger
18 def __init__(self, auth=None, cainfo=None):
25 self.multicall = False
26 self.url = config.manifold_url()
28 # Manifold uses a self signed certificate
29 # https://www.python.org/dev/peps/pep-0476/
30 if hasattr(ssl, '_create_unverified_context'):
31 self.server = xmlrpclib.Server(self.url, verbose=False, allow_none=True,
32 context=ssl._create_unverified_context())
34 self.server = xmlrpclib.Server(self.url, verbose=False, allow_none=True)
36 # xxx temporary code for scaffolding a ManifolResult on top of an API that does not expose error info
37 # as of march 2013 we work with an API that essentially either returns the value, or raises
38 # an xmlrpclib.Fault exception with always the same 8002 code
39 # since most of the time we're getting this kind of issues for expired sessions
40 # (looks like sessions are rather short-lived), for now the choice is to map these errors on
41 # a SESSION_EXPIRED code
42 def __getattr__(self, methodName):
44 def func(*args, **kwds):
48 # the message to display
49 auth_message = "<AuthMethod not set in {}>".format(self.auth) if 'AuthMethod' not in self.auth \
50 else "[session]" if self.auth['AuthMethod'] == 'session' \
51 else "user:{}".format(self.auth['Username']) if self.auth['AuthMethod'] == 'password' \
52 else "anonymous" if self.auth['AuthMethod'] == 'anonymous' \
53 else "[???]" + "{}".format(self.auth)
54 end_message = "MANIFOLD <- {}( {}( {} ) ) with auth={} to {}"\
56 args[0]['action'] or '',
57 args[0]['object'] or '',
61 args += ({ 'authentication': self.auth },)
62 result = getattr(self.server, methodName)(*args, **kwds)
63 logger.debug("{} executed in {} seconds -> {}"\
64 .format(end_message, time.time() - start, truncate_result(result)))
65 return ResultValue(**result)
67 except Exception as error:
68 logger.error("===== xmlrpc catch-all exception: {}".format(error))
70 logger.error(traceback.format_exc(limit=3))
72 if "Connection refused" in error:
73 raise ManifoldException ( ManifoldResult (code=ManifoldCode.SERVER_UNREACHABLE,
74 output="{} answered {}".format(self.url, error)))
76 logger.error("{} FAILED - executed in {} seconds"\
77 .format(end_message, time.time() - start))
78 logger.error("MANIFOLD {}".format(error))
79 raise ManifoldException ( ManifoldResult (code = ManifoldCode.SERVER_UNREACHABLE,
80 output = "{}".format(error)))
84 def _execute_query(request, query, manifold_api_session_auth):
86 manifold_api = ManifoldAPI(auth = manifold_api_session_auth)
88 logger.debug("MANIFOLD -> QUERY : {}".format(" ".join(str(query).split())))
89 result = manifold_api.forward(query.to_dict())
90 if result['code'] == 2:
91 # this is gross; at the very least we need to logout()
92 # but most importantly there is a need to refine that test, since
93 # code==2 does not necessarily mean an expired session
94 # XXX only if we know it is the issue
95 #SessionCache().end_session(request)
96 # Flush django session
97 del request.session['manifold']
99 request.session.flush()
100 #raise Exception, 'Error running query: {}'.format(result)
102 if result['code'] == 1:
103 logger.warning("MANIFOLD : {}".format(result['description']))
106 #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}
108 return result['value']
110 def execute_query(request, query):
112 logger.debug("EXECUTE QUERY: request - {}".format(request.session.items()))
114 if not 'manifold' in request.session or not 'auth' in request.session['manifold']:
115 #manifold_api_session_auth = SessionCache().get_auth(request)
116 #if not manifold_api_session_auth:
117 request.session.flush()
118 #raise Exception, "User not authenticated"
119 host = request.get_host()
122 manifold_api_session_auth = request.session['manifold']['auth']
124 return _execute_query(request, query, manifold_api_session_auth)
126 def execute_admin_query(request, query):
127 admin_user, admin_password = config.manifold_admin_user_password()
128 if not admin_user or not admin_password:
129 logger.error("""CONFIG: you need to setup admin_user and admin_password in myslice.ini
130 Some functions won't work properly until you do so""")
131 admin_auth = {'AuthMethod': 'password', 'Username': admin_user, 'AuthString': admin_password}
132 return _execute_query(request, query, admin_auth)