use logger instead of print as often as possible
[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
11 from manifoldresult import ManifoldResult, ManifoldCode, ManifoldException, truncate_result
12
13 from myslice.settings import config, logger
14
15 class ManifoldAPI:
16
17     def __init__(self, auth=None, cainfo=None):
18         
19         self.auth = auth
20         self.cainfo = cainfo
21         self.errors = []
22         self.trace = []
23         self.calls = {}
24         self.multicall = False
25         self.url = config.manifold_url()
26         
27         # Manifold uses a self signed certificate
28         # https://www.python.org/dev/peps/pep-0476/
29         if hasattr(ssl, '_create_unverified_context'): 
30             self.server = xmlrpclib.Server(self.url, verbose=False, allow_none=True,
31                                            context=ssl._create_unverified_context())
32         else :
33             self.server = xmlrpclib.Server(self.url, verbose=False, allow_none=True)
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(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     #logger.debug("MANIFOLD DICT : {}".format(query.to_dict()))
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         del request.session['manifold']
96         # Flush django session
97         request.session.flush()
98         #raise Exception, 'Error running query: {}'.format(result)
99     
100     if result['code'] == 1:
101         log.warning("MANIFOLD : {}".format(result['description']))
102
103     # XXX Handle errors
104     #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}
105
106     return result['value'] 
107
108 def execute_query(request, query):
109     if not 'manifold' in request.session or not 'auth' in request.session['manifold']:
110         request.session.flush()
111         #raise Exception, "User not authenticated"
112         host = request.get_host()
113         return redirect('/')
114     
115     manifold_api_session_auth = request.session['manifold']['auth']
116     
117     return _execute_query(request, query, manifold_api_session_auth)
118
119 def execute_admin_query(request, query):
120     admin_user, admin_password = config.manifold_admin_user_password()
121     if not admin_user or not admin_password:
122         logger.error("""CONFIG: you need to setup admin_user and admin_password in myslice.ini
123 Some functions won't work properly until you do so""")
124     admin_auth = {'AuthMethod': 'password', 'Username': admin_user, 'AuthString': admin_password}
125     return _execute_query(request, query, admin_auth)