1 # Manifold API Python interface
2 import copy, xmlrpclib, ssl
4 from myslice.configengine import ConfigEngine
6 from django.contrib import messages
7 from django.shortcuts import redirect
8 from manifoldresult import ManifoldResult, ManifoldCode, ManifoldException
9 from manifold.core.result_value import ResultValue
16 ########## ugly stuff for hopefully nicer debug messages
17 def mytruncate (obj, l):
21 return (repr[:l1]+'..') if len(repr)>l1 else repr
23 from time import time, gmtime, strftime
24 from math import trunc
25 def mytime (start=None):
28 msg=strftime("%H:%M:%S-", gmtime())+"%03d"%((t-trunc(t))*1000)
29 if start is not None: msg += " (%03fs)"%(t-start)
35 def __init__ (self, auth=None, cainfo=None):
42 self.multicall = False
43 self.url = ConfigEngine().manifold_url()
45 # Manifold uses a self signed certificate
46 # https://www.python.org/dev/peps/pep-0476/
47 context = ssl._create_unverified_context()
48 self.server = xmlrpclib.Server(self.url, verbose=False, allow_none=True, context=context)
50 def __repr__ (self): return "ManifoldAPI[%s]"%self.url
52 def _print_value (self, value):
54 if isinstance (value,list): print "[%d]"%len(value),
55 elif isinstance (value,dict): print "{%d}"%len(value),
56 print mytruncate (value,80)
58 # a one-liner to give a hint of what the return value looks like
59 def _print_result (self, result):
60 if not result: print "[no/empty result]"
61 elif isinstance (result,str): print "result is '%s'"%result
62 elif isinstance (result,list): print "result is a %d-elts list"%len(result)
63 elif isinstance (result,dict):
64 print "result is a dict with %d keys : %s"%(len(result),result.keys())
65 for (k,v) in result.iteritems():
66 if v is None: continue
67 if k=='value': self._print_value(v)
68 else: print '+++',k,':',mytruncate (v,30)
69 else: print "[dont know how to display result] %s"%result
71 # how to display a call
72 def _repr_query (self,methodName, query):
73 try: action=query['action']
75 try: subject=query['object']
77 # most of the time, we run 'forward'
78 if methodName=='forward': return "forward(%s(%s))"%(action,subject)
79 else: return "%s(%s)"%(action,subject)
81 # xxx temporary code for scaffolding a ManifolResult on top of an API that does not expose error info
82 # as of march 2013 we work with an API that essentially either returns the value, or raises
83 # an xmlrpclib.Fault exception with always the same 8002 code
84 # since most of the time we're getting this kind of issues for expired sessions
85 # (looks like sessions are rather short-lived), for now the choice is to map these errors on
86 # a SESSION_EXPIRED code
87 def __getattr__(self, methodName):
88 def func(*args, **kwds):
90 def repr(): return self._repr_query (methodName, args[0])
94 print "====>",msg,"ManifoldAPI.%s"%repr(),"url",self.url
95 # No password in the logs
96 logAuth = copy.copy(self.auth)
97 for obfuscate in ['Authring','session']:
98 if obfuscate in logAuth: logAuth[obfuscate]="XXX"
99 if debug_deep: print "=> auth",logAuth
100 if debug_deep: print "=> args",args,"kwds",kwds
102 'authentication': self.auth
104 args += (annotations,)
105 result=getattr(self.server, methodName)(*args, **kwds)
106 print "%s%r" %(methodName, args)
110 self._print_result(result)
111 end,msg = mytime(start)
112 print "<====",msg,"backend call %s returned"%(repr())
114 return ResultValue(**result)
116 except Exception,error:
117 print "** MANIFOLD API ERROR **"
119 print "===== xmlrpc catch-all exception:",error
121 traceback.print_exc(limit=3)
122 if "Connection refused" in error:
123 raise ManifoldException ( ManifoldResult (code=ManifoldCode.SERVER_UNREACHABLE,
124 output="%s answered %s"%(self.url,error)))
126 print "<==== ERROR On ManifoldAPI.%s"%repr()
127 raise ManifoldException ( ManifoldResult (code=ManifoldCode.SERVER_UNREACHABLE, output="%s"%error) )
131 def _execute_query(request, query, manifold_api_session_auth):
132 manifold_api = ManifoldAPI(auth=manifold_api_session_auth)
135 print query.to_dict()
137 result = manifold_api.forward(query.to_dict())
138 if result['code'] == 2:
139 # this is gross; at the very least we need to logout()
140 # but most importantly there is a need to refine that test, since
141 # code==2 does not necessarily mean an expired session
142 # XXX only if we know it is the issue
143 del request.session['manifold']
144 # Flush django session
145 request.session.flush()
146 #raise Exception, 'Error running query: %r' % result
148 if result['code'] == 1:
150 print result['description']
153 #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}
155 return result['value']
157 def execute_query(request, query):
158 if not 'manifold' in request.session or not 'auth' in request.session['manifold']:
159 request.session.flush()
160 #raise Exception, "User not authenticated"
161 host = request.get_host()
163 manifold_api_session_auth = request.session['manifold']['auth']
164 return _execute_query(request, query, manifold_api_session_auth)
166 def execute_admin_query(request, query):
167 admin_user, admin_password = ConfigEngine().manifold_admin_user_password()
168 admin_auth = {'AuthMethod': 'password', 'Username': admin_user, 'AuthString': admin_password}
169 return _execute_query(request, query, admin_auth)