1 # Manifold API Python interface
2 import copy, xmlrpclib, ssl
3 from myslice.settings import config, logger, DEBUG
5 from django.contrib import messages
6 from django.shortcuts import redirect
7 from manifoldresult import ManifoldResult, ManifoldCode, ManifoldException
8 from manifold.core.result_value import ResultValue
15 def __init__(self, auth=None, cainfo=None):
22 self.multicall = False
23 self.url = config.manifold_url()
25 # Manifold uses a self signed certificate
26 # https://www.python.org/dev/peps/pep-0476/
27 if hasattr(ssl, '_create_unverified_context'):
28 self.server = xmlrpclib.Server(self.url, verbose=False, allow_none=True, context=ssl._create_unverified_context())
30 self.server = xmlrpclib.Server(self.url, verbose=False, allow_none=True)
32 # xxx temporary code for scaffolding a ManifolResult on top of an API that does not expose error info
33 # as of march 2013 we work with an API that essentially either returns the value, or raises
34 # an xmlrpclib.Fault exception with always the same 8002 code
35 # since most of the time we're getting this kind of issues for expired sessions
36 # (looks like sessions are rather short-lived), for now the choice is to map these errors on
37 # a SESSION_EXPIRED code
38 def __getattr__(self, methodName):
40 def func(*args, **kwds):
46 #logger.debug("MANIFOLD %s( %s( %s ) ) to %s" % (methodName, args[0]['action'], args[0]['object'], self.url))
48 if ('Username' in self.auth) :
49 username = self.auth['Username']
53 args += ({ 'authentication': self.auth },)
55 result = getattr(self.server, methodName)(*args, **kwds)
57 logger.debug("MANIFOLD %s( %s( %s ) ) as %s to %s executed in %s seconds -> %s" %
59 args[0]['action'] or '',
60 args[0]['object'] or '',
63 (time.time() - start),
66 return ResultValue(**result)
68 except Exception, error:
70 print "===== xmlrpc catch-all exception:", error
72 traceback.print_exc(limit=3)
74 if "Connection refused" in error:
75 raise ManifoldException ( ManifoldResult (code=ManifoldCode.SERVER_UNREACHABLE,
76 output="%s answered %s" % (self.url,error)))
78 logger.error("MANIFOLD %s( %s( %s ) ) as %s to %s executed in %s seconds -> %s" %
80 args[0]['action'] or '',
81 args[0]['object'] or '',
84 (time.time() - start),
86 logger.error("MANIFOLD %s", error)
87 raise ManifoldException ( ManifoldResult (code = ManifoldCode.SERVER_UNREACHABLE, output = "%s" % error) )
91 def _execute_query(request, query, manifold_api_session_auth):
93 manifold_api = ManifoldAPI(auth = manifold_api_session_auth)
95 logger.debug("MANIFOLD QUERY : %s" % " ".join(str(query).split()))
96 #logger.debug("MANIFOLD DICT : %s" % query.to_dict())
97 result = manifold_api.forward(query.to_dict())
98 if result['code'] == 2:
99 # this is gross; at the very least we need to logout()
100 # but most importantly there is a need to refine that test, since
101 # code==2 does not necessarily mean an expired session
102 # XXX only if we know it is the issue
103 del request.session['manifold']
104 # Flush django session
105 request.session.flush()
106 #raise Exception, 'Error running query: %r' % result
108 if result['code'] == 1:
109 logger.warning("MANIFOLD : %s" % 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):
117 if not 'manifold' in request.session or not 'auth' in request.session['manifold']:
118 request.session.flush()
119 #raise Exception, "User not authenticated"
120 host = request.get_host()
123 manifold_api_session_auth = request.session['manifold']['auth']
125 return _execute_query(request, query, manifold_api_session_auth)
127 def execute_admin_query(request, query):
128 admin_user, admin_password = config.manifold_admin_user_password()
129 admin_auth = {'AuthMethod': 'password', 'Username': admin_user, 'AuthString': admin_password}
130 return _execute_query(request, query, admin_auth)