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