manifold api prints out result with finer grain (esp. value)
[myslice.git] / manifold / manifoldapi.py
1 # Manifold API Python interface
2 import xmlrpclib
3
4 from myslice.config import Config
5
6 from django.contrib import messages
7 from manifoldresult import ManifoldResult, ManifoldCode, ManifoldException
8 from manifold.core.result_value import ResultValue
9
10 debug=False
11 debug=True
12
13 def mytruncate (obj, l):
14     # we will add '..' 
15     l1=l-2
16     repr="%s"%obj
17     return (repr[:l1]+'..') if len(repr)>l1 else repr
18
19 class ManifoldAPI:
20
21     def __init__(self, auth=None, cainfo=None):
22         
23         self.auth = auth
24         self.cainfo = cainfo
25         self.errors = []
26         self.trace = []
27         self.calls = {}
28         self.multicall = False
29         config = Config()
30         self.url = config.manifold_url()
31         self.server = xmlrpclib.Server(self.url, verbose=False, allow_none=True)
32
33     def __repr__ (self): return "ManifoldAPI[%s]"%self.url
34
35     def _print_value (self, value):
36         print "+++",'value',
37         if isinstance (value,list):     print "[%d]"%len(value),
38         elif isinstance (value,dict):   print "{%d}"%len(value),
39         print mytruncate (value,80)
40     
41     # a one-liner to give a hint of what the return value looks like
42     def _print_result (self, result):
43         if not result:                        print "[no/empty result]"
44         elif isinstance (result,str):         print "result is '%s'"%result
45         elif isinstance (result,list):        print "result is a %d-elts list"%len(result)
46         elif isinstance (result,dict):        
47             print "result is a dict with %d keys : %s"%(len(result),result.keys())
48             for (k,v) in result.iteritems(): 
49                 if v is None: continue
50                 if k=='value':  self._print_value(v)
51                 else:           print '+++',k,':',mytruncate (v,30)
52         else:                                 print "[dont know how to display result] %s"%result
53
54     # xxx temporary code for scaffolding a ManifolResult on top of an API that does not expose error info
55     # as of march 2013 we work with an API that essentially either returns the value, or raises 
56     # an xmlrpclib.Fault exception with always the same 8002 code
57     # since most of the time we're getting this kind of issues for expired sessions
58     # (looks like sessions are rather short-lived), for now the choice is to map these errors on 
59     # a SESSION_EXPIRED code
60     def __getattr__(self, methodName):
61         def func(*args, **kwds):
62             # how to display a call
63             def repr ():
64                 # most of the time, we run 'forward'
65                 if methodName=='forward':
66                     try:    action="forward(%s)"%args[0]['action']
67                     except: action="forward(??)"
68                 else: action=methodName
69                 return action
70             try:
71                 if debug:
72                     print "====> ManifoldAPI.%s"%repr(),"url",self.url
73                     print "=> auth",self.auth
74                     print "=> args",args,"kwds",kwds
75                 annotations = {
76                     'authentication': self.auth
77                 }
78                 args += (annotations,)
79                 result=getattr(self.server, methodName)(*args, **kwds)
80                 if debug:
81                     print '<= result=',
82                     self._print_result(result)
83                     print '<==== backend call %s returned'%(repr()),
84
85                 return ResultValue(**result)
86
87             except Exception,error:
88                 print "** MANIFOLD API ERROR **"
89                 if "Connection refused" in error:
90                     raise ManifoldException ( ManifoldResult (code=ManifoldCode.SERVER_UNREACHABLE,
91                                                               output="%s answered %s"%(self.url,error)))
92                 # otherwise
93                 if debug: 
94                     print "===== xmlrpc catch-all exception:",error
95                     import traceback
96                     traceback.print_exc(limit=3)
97                 print "<==== ERROR On ManifoldAPI.%s"%repr()
98                 raise ManifoldException ( ManifoldResult (code=ManifoldCode.SERVER_UNREACHABLE, output="%s"%error) )
99
100         return func
101
102 def _execute_query(request, query, manifold_api_session_auth):
103     manifold_api = ManifoldAPI(auth=manifold_api_session_auth)
104     print "-"*80
105     print query
106     print query.to_dict()
107     print "-"*80
108     result = manifold_api.forward(query.to_dict())
109     if result['code'] == 2:
110         raise Exception, 'Error running query: %r' % result
111     
112     if result['code'] == 1:
113         print "WARNING" 
114         print result['description']
115
116     # XXX Handle errors
117     #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
119     return result['value'] 
120
121 def execute_query(request, query):
122     if not 'manifold' in request.session or not 'auth' in request.session['manifold']:
123         raise Exception, "User not authenticated"
124     manifold_api_session_auth = request.session['manifold']['auth']
125     return _execute_query(request, query, manifold_api_session_auth)
126
127 def execute_admin_query(request, query):
128     config = Config()
129     admin_user, admin_password = config.manifold_admin_user_password()
130     admin_auth = {'AuthMethod': 'password', 'Username': admin_user, 'AuthString': admin_password}
131     return _execute_query(request, query, admin_auth)