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