Merge branch 'master' of ssh://git.onelab.eu/git/myslice
[myslice.git] / manifold / manifoldapi.py
1 # Manifold API Python interface
2 import copy, 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                     # No password in the logs
74                     logAuth = copy.copy(self.auth)
75                     for obfuscate in ['Authring','session']: 
76                         if obfuscate in logAuth:  logAuth[obfuscate]="XXX"
77                     print "=> auth",logAuth
78                     print "=> args",args,"kwds",kwds
79                 annotations = {
80                     'authentication': self.auth
81                 }
82                 args += (annotations,)
83                 result=getattr(self.server, methodName)(*args, **kwds)
84                 print "%s%r" %(methodName, args)
85                 
86                 if debug:
87                     print '<= result=',
88                     self._print_result(result)
89                     print '<==== backend call %s returned'%(repr()),
90
91                 return ResultValue(**result)
92
93             except Exception,error:
94                 print "** MANIFOLD API ERROR **"
95                 if debug: 
96                     print "===== xmlrpc catch-all exception:",error
97                     import traceback
98                     traceback.print_exc(limit=3)
99                 if "Connection refused" in error:
100                     raise ManifoldException ( ManifoldResult (code=ManifoldCode.SERVER_UNREACHABLE,
101                                                               output="%s answered %s"%(self.url,error)))
102                 # otherwise
103                 print "<==== ERROR On ManifoldAPI.%s"%repr()
104                 raise ManifoldException ( ManifoldResult (code=ManifoldCode.SERVER_UNREACHABLE, output="%s"%error) )
105
106         return func
107
108 def _execute_query(request, query, manifold_api_session_auth):
109     manifold_api = ManifoldAPI(auth=manifold_api_session_auth)
110     print "-"*80
111     print query
112     print query.to_dict()
113     print "-"*80
114     result = manifold_api.forward(query.to_dict())
115     if result['code'] == 2:
116         # XXX only if we know it is the issue
117         del request.session['manifold']
118         raise Exception, 'Error running query: %r' % result
119     
120     if result['code'] == 1:
121         print "WARNING" 
122         print result['description']
123
124     # XXX Handle errors
125     #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}
126
127     return result['value'] 
128
129 def execute_query(request, query):
130     if not 'manifold' in request.session or not 'auth' in request.session['manifold']:
131         raise Exception, "User not authenticated"
132     manifold_api_session_auth = request.session['manifold']['auth']
133     return _execute_query(request, query, manifold_api_session_auth)
134
135 def execute_admin_query(request, query):
136     config = Config()
137     admin_user, admin_password = config.manifold_admin_user_password()
138     admin_auth = {'AuthMethod': 'password', 'Username': admin_user, 'AuthString': admin_password}
139     return _execute_query(request, query, admin_auth)