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