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