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