added request for metadata calls to be able to handle errors in messages
[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     # a one-liner to give a hint of what the return value looks like
36     def _print_result (self, result):
37         if not result:                        print "[no/empty result]"
38         elif isinstance (result,str):         print "result is '%s'"%result
39         elif isinstance (result,list):        print "result is a %d-elts list"%len(result)
40         elif isinstance (result,dict):        
41             print "result is a dict with %d keys : %s"%(len(result),result.keys())
42             for (k,v) in result.iteritems(): 
43                 if v is None: continue
44                 print '+++',k,':',mytruncate (v,60)
45         else:                                 print "[dont know how to display result] %s"%result
46
47     # xxx temporary code for scaffolding a ManifolResult on top of an API that does not expose error info
48     # as of march 2013 we work with an API that essentially either returns the value, or raises 
49     # an xmlrpclib.Fault exception with always the same 8002 code
50     # since most of the time we're getting this kind of issues for expired sessions
51     # (looks like sessions are rather short-lived), for now the choice is to map these errors on 
52     # a SESSION_EXPIRED code
53     def __getattr__(self, methodName):
54         def func(*args, **kwds):
55             # how to display a call
56             def repr ():
57                 # most of the time, we run 'forward'
58                 if methodName=='forward':
59                     try:    action="forward(%s)"%args[0]['action']
60                     except: action="forward(??)"
61                 else: action=methodName
62                 return action
63             try:
64                 if debug:
65                     print "====> ManifoldAPI.%s"%repr(),"url",self.url
66                     print "=> auth",self.auth
67                     print "=> args",args,"kwds",kwds
68                 annotations = {
69                     'authentication': self.auth
70                 }
71                 args += (annotations,)
72                 result=getattr(self.server, methodName)(*args, **kwds)
73                 print "%s%r" %(methodName, args)
74                 
75                 if debug:
76                     print '<= result=',
77                     self._print_result(result)
78                     print '<==== backend call %s returned'%(repr()),
79
80                 return ResultValue(**result)
81
82             except Exception,error:
83                 print "** MANIFOLD API ERROR **"
84                 if "Connection refused" in error:
85                     raise ManifoldException ( ManifoldResult (code=ManifoldCode.SERVER_UNREACHABLE,
86                                                               output="%s answered %s"%(self.url,error)))
87                 # otherwise
88                 if debug: 
89                     print "===== xmlrpc catch-all exception:",error
90                     import traceback
91                     traceback.print_exc(limit=3)
92                 print "<==== ERROR On ManifoldAPI.%s"%repr()
93                 raise ManifoldException ( ManifoldResult (code=ManifoldCode.SERVER_UNREACHABLE, output="%s"%error) )
94
95         return func
96
97 def _execute_query(request, query, manifold_api_session_auth):
98     manifold_api = ManifoldAPI(auth=manifold_api_session_auth)
99     print "-"*80
100     print query
101     print query.to_dict()
102     print "-"*80
103     result = manifold_api.forward(query.to_dict())
104     if result['code'] == 2:
105         raise Exception, 'Error running query: %r' % result
106     
107     if result['code'] == 1:
108         print "WARNING" 
109         print result['description']
110
111     # XXX Handle errors
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}
113
114     return result['value'] 
115
116 def execute_query(request, query):
117     if not 'manifold' in request.session or not 'auth' in request.session['manifold']:
118         raise Exception, "User not authenticated"
119     manifold_api_session_auth = request.session['manifold']['auth']
120     return _execute_query(request, query, manifold_api_session_auth)
121
122 def execute_admin_query(request, query):
123     config = Config()
124     admin_user, admin_password = config.manifold_admin_user_password()
125     admin_auth = {'AuthMethod': 'password', 'Username': admin_user, 'AuthString': admin_password}
126     return _execute_query(request, query, admin_auth)