myslice/config becomes myslice/configengine to avoid confusion
[myslice.git] / manifold / manifoldapi.py
1 # Manifold API Python interface
2 import copy, xmlrpclib
3
4 from myslice.configengine import ConfigEngine
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 debug_deep=False
13 #debug_deep=True
14
15 ########## ugly stuff for hopefully nicer debug messages
16 def mytruncate (obj, l):
17     # we will add '..' 
18     l1=l-2
19     repr="%s"%obj
20     return (repr[:l1]+'..') if len(repr)>l1 else repr
21
22 from time import time, gmtime, strftime
23 from math import trunc
24 def mytime (start=None):
25     gm=gmtime()
26     t=time()
27     msg=strftime("%H:%M:%S-", gmtime())+"%03d"%((t-trunc(t))*1000)
28     if start is not None: msg += " (%03fs)"%(t-start)
29     return t,msg
30 ##########
31
32 class ManifoldAPI:
33
34     def __init__ (self, auth=None, cainfo=None):
35         
36         self.auth = auth
37         self.cainfo = cainfo
38         self.errors = []
39         self.trace = []
40         self.calls = {}
41         self.multicall = False
42         self.url = ConfigEngine().manifold_url()
43         self.server = xmlrpclib.Server(self.url, verbose=False, allow_none=True)
44
45     def __repr__ (self): return "ManifoldAPI[%s]"%self.url
46
47     def _print_value (self, value):
48         print "+++",'value',
49         if isinstance (value,list):     print "[%d]"%len(value),
50         elif isinstance (value,dict):   print "{%d}"%len(value),
51         print mytruncate (value,80)
52     
53     # a one-liner to give a hint of what the return value looks like
54     def _print_result (self, result):
55         if not result:                        print "[no/empty result]"
56         elif isinstance (result,str):         print "result is '%s'"%result
57         elif isinstance (result,list):        print "result is a %d-elts list"%len(result)
58         elif isinstance (result,dict):        
59             print "result is a dict with %d keys : %s"%(len(result),result.keys())
60             for (k,v) in result.iteritems(): 
61                 if v is None: continue
62                 if k=='value':  self._print_value(v)
63                 else:           print '+++',k,':',mytruncate (v,30)
64         else:                                 print "[dont know how to display result] %s"%result
65
66     # how to display a call
67     def _repr_query (self,methodName, query):
68         try:    action=query['action']
69         except: action="???"
70         try:    subject=query['object']
71         except: subject="???"
72         # most of the time, we run 'forward'
73         if methodName=='forward':       return "forward(%s(%s))"%(action,subject)
74         else:                           return "%s(%s)"%(action,subject)
75
76     # xxx temporary code for scaffolding a ManifolResult on top of an API that does not expose error info
77     # as of march 2013 we work with an API that essentially either returns the value, or raises 
78     # an xmlrpclib.Fault exception with always the same 8002 code
79     # since most of the time we're getting this kind of issues for expired sessions
80     # (looks like sessions are rather short-lived), for now the choice is to map these errors on 
81     # a SESSION_EXPIRED code
82     def __getattr__(self, methodName):
83         def func(*args, **kwds):
84             # shorthand
85             def repr(): return self._repr_query (methodName, args[0])
86             try:
87                 if debug:
88                     start,msg = mytime()
89                     print "====>",msg,"ManifoldAPI.%s"%repr(),"url",self.url
90                     # No password in the logs
91                     logAuth = copy.copy(self.auth)
92                     for obfuscate in ['Authring','session']: 
93                         if obfuscate in logAuth:  logAuth[obfuscate]="XXX"
94                     if debug_deep: print "=> auth",logAuth
95                     if debug_deep: print "=> args",args,"kwds",kwds
96                 annotations = {
97                     'authentication': self.auth
98                 }
99                 args += (annotations,)
100                 result=getattr(self.server, methodName)(*args, **kwds)
101                 print "%s%r" %(methodName, args)
102                 
103                 if debug:
104                     print '<= result=',
105                     self._print_result(result)
106                     end,msg = mytime(start)
107                     print "<====",msg,"backend call %s returned"%(repr())
108
109                 return ResultValue(**result)
110
111             except Exception,error:
112                 print "** MANIFOLD API ERROR **"
113                 if debug: 
114                     print "===== xmlrpc catch-all exception:",error
115                     import traceback
116                     traceback.print_exc(limit=3)
117                 if "Connection refused" in error:
118                     raise ManifoldException ( ManifoldResult (code=ManifoldCode.SERVER_UNREACHABLE,
119                                                               output="%s answered %s"%(self.url,error)))
120                 # otherwise
121                 print "<==== ERROR On ManifoldAPI.%s"%repr()
122                 raise ManifoldException ( ManifoldResult (code=ManifoldCode.SERVER_UNREACHABLE, output="%s"%error) )
123
124         return func
125
126 def _execute_query(request, query, manifold_api_session_auth):
127     manifold_api = ManifoldAPI(auth=manifold_api_session_auth)
128     print "-"*80
129     print query
130     print query.to_dict()
131     print "-"*80
132     result = manifold_api.forward(query.to_dict())
133     if result['code'] == 2:
134         # this is gross; at the very least we need to logout() 
135         # but most importantly there is a need to refine that test, since 
136         # code==2 does not necessarily mean an expired session
137         # XXX only if we know it is the issue
138         del request.session['manifold']
139         # Flush django session
140         request.session.flush()
141         #raise Exception, 'Error running query: %r' % result
142     
143     if result['code'] == 1:
144         print "WARNING" 
145         print result['description']
146
147     # XXX Handle errors
148     #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}
149
150     return result['value'] 
151
152 def execute_query(request, query):
153     if not 'manifold' in request.session or not 'auth' in request.session['manifold']:
154         request.session.flush()
155         raise Exception, "User not authenticated"
156     manifold_api_session_auth = request.session['manifold']['auth']
157     return _execute_query(request, query, manifold_api_session_auth)
158
159 def execute_admin_query(request, query):
160     admin_user, admin_password = ConfigEngine().manifold_admin_user_password()
161     admin_auth = {'AuthMethod': 'password', 'Username': admin_user, 'AuthString': admin_password}
162     return _execute_query(request, query, admin_auth)