proposal for improving the dont-verify-ssl hack
[myslice.git] / manifoldapi / manifoldapi.py
1 # Manifold API Python interface
2 import copy
3 import xmlrpclib
4 import ssl
5
6 from django.contrib import messages
7 from django.shortcuts import redirect
8
9 from manifold.core.result_value import ResultValue
10 from manifoldresult import ManifoldResult, ManifoldCode, ManifoldException, truncate_result
11
12 # from unfold.sessioncache import SessionCache
13
14 from myslice.settings import config, logger
15
16 class ManifoldAPI:
17
18     def __init__(self, auth=None, cainfo=None):
19         
20         self.auth = auth
21         self.cainfo = cainfo
22         self.errors = []
23         self.trace = []
24         self.calls = {}
25         self.multicall = False
26         self.url = config.manifold_url()
27         
28         # Manifold uses a self signed certificate
29         # https://www.python.org/dev/peps/pep-0476/
30         try:    turn_off_server_verify = { 'context' : ssl._create_unverified_context() } 
31         except: turn_off_server_verify = {}
32         self.server = xmlrpclib.Server(self.url, verbose=False, allow_none=True,
33                                        **turn_off_server_verify)
34
35     # xxx temporary code for scaffolding a ManifolResult on top of an API that does not expose error info
36     # as of march 2013 we work with an API that essentially either returns the value, or raises 
37     # an xmlrpclib.Fault exception with always the same 8002 code
38     # since most of the time we're getting this kind of issues for expired sessions
39     # (looks like sessions are rather short-lived), for now the choice is to map these errors on 
40     # a SESSION_EXPIRED code
41     def __getattr__(self, methodName):
42
43         def func(*args, **kwds):
44             import time
45             start = time.time()
46             
47             # the message to display
48             auth_message = "<AuthMethod not set in {}>".format(self.auth) if 'AuthMethod' not in self.auth \
49                            else "[session]" if self.auth['AuthMethod'] == 'session' \
50                            else "user:{}".format(self.auth['Username']) if self.auth['AuthMethod'] == 'password' \
51                            else "anonymous" if self.auth['AuthMethod'] == 'anonymous' \
52                            else "[???]" + "{}".format(self.auth)
53             end_message = "MANIFOLD <- {}( {}( {} ) ) with auth={} to {}"\
54                           .format(methodName,
55                                   args[0]['action'] or '', 
56                                   args[0]['object'] or '',
57                                   auth_message,
58                                   self.url)
59             try:
60                 args += ({ 'authentication': self.auth },)
61                 result = getattr(self.server, methodName)(*args, **kwds)
62                 logger.debug("{} executed in {} seconds -> {}"\
63                              .format(end_message, time.time() - start, truncate_result(result)))
64                 return ResultValue(**result)
65
66             except Exception as error:
67                 logger.error("===== xmlrpc catch-all exception: {}".format(error))
68                 import traceback
69                 logger.error(traceback.format_exc(limit=3))
70                 
71                 if "Connection refused" in error:
72                     raise ManifoldException ( ManifoldResult (code=ManifoldCode.SERVER_UNREACHABLE,
73                                                               output="{} answered {}".format(self.url, error)))
74                 # otherwise
75                 logger.error("{} FAILED - executed in {} seconds"\
76                              .format(end_message, time.time() - start)) 
77                 logger.error("MANIFOLD {}".format(error))
78                 raise ManifoldException ( ManifoldResult (code = ManifoldCode.SERVER_UNREACHABLE,
79                                                           output = "{}".format(error)))
80
81         return func
82
83 def _execute_query(request, query, manifold_api_session_auth):
84     
85     manifold_api = ManifoldAPI(auth = manifold_api_session_auth)
86     
87     logger.debug("MANIFOLD -> QUERY : {}".format(" ".join(str(query).split())))
88     result = manifold_api.forward(query.to_dict())
89     if result['code'] == 2:
90         # this is gross; at the very least we need to logout() 
91         # but most importantly there is a need to refine that test, since 
92         # code==2 does not necessarily mean an expired session
93         # XXX only if we know it is the issue
94         #SessionCache().end_session(request)
95         # Flush django session
96         del request.session['manifold']
97
98         request.session.flush()
99         #raise Exception, 'Error running query: {}'.format(result)
100     
101     if result['code'] == 1:
102         logger.warning("MANIFOLD : {}".format(result['description']))
103
104     # XXX Handle errors
105     #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}
106
107     return result['value'] 
108
109 def execute_query(request, query):
110     
111     logger.debug("EXECUTE QUERY: request - {}".format(request.session.items()))
112     
113     if not 'manifold' in request.session or not 'auth' in request.session['manifold']:
114     #manifold_api_session_auth = SessionCache().get_auth(request)
115     #if not manifold_api_session_auth:
116         request.session.flush()
117         #raise Exception, "User not authenticated"
118         host = request.get_host()
119         return redirect('/')
120     
121     manifold_api_session_auth = request.session['manifold']['auth']
122
123     return _execute_query(request, query, manifold_api_session_auth)
124
125 def execute_admin_query(request, query):
126     admin_user, admin_password = config.manifold_admin_user_password()
127     if not admin_user or not admin_password:
128         logger.error("""CONFIG: you need to setup admin_user and admin_password in myslice.ini
129 Some functions won't work properly until you do so""")
130     admin_auth = {'AuthMethod': 'password', 'Username': admin_user, 'AuthString': admin_password}
131     return _execute_query(request, query, admin_auth)