2to3 -f except
[sfa.git] / sfa / server / xmlrpcapi.py
1 #
2 # SFA XML-RPC and SOAP interfaces
3 #
4
5 import string
6 import xmlrpclib
7
8 # SOAP support is optional
9 try:
10     import SOAPpy
11     from SOAPpy.Parser import parseSOAPRPC
12     from SOAPpy.Types import faultType
13     from SOAPpy.NS import NS
14     from SOAPpy.SOAPBuilder import buildSOAP
15 except ImportError:
16     SOAPpy = None
17
18 ####################
19 #from sfa.util.faults import SfaNotImplemented, SfaAPIError, SfaInvalidAPIMethod, SfaFault
20 from sfa.util.faults import SfaInvalidAPIMethod, SfaAPIError, SfaFault
21 from sfa.util.sfalogging import logger
22
23 ####################
24 # See "2.2 Characters" in the XML specification:
25 #
26 # #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD]
27 # avoiding
28 # [#x7F-#x84], [#x86-#x9F], [#xFDD0-#xFDDF]
29
30 invalid_xml_ascii = map(chr, range(0x0, 0x8) + [0xB, 0xC] + range(0xE, 0x1F))
31 xml_escape_table = string.maketrans("".join(invalid_xml_ascii), "?" * len(invalid_xml_ascii))
32
33 def xmlrpclib_escape(s, replace = string.replace):
34     """
35     xmlrpclib does not handle invalid 7-bit control characters. This
36     function augments xmlrpclib.escape, which by default only replaces
37     '&', '<', and '>' with entities.
38     """
39
40     # This is the standard xmlrpclib.escape function
41     s = replace(s, "&", "&amp;")
42     s = replace(s, "<", "&lt;")
43     s = replace(s, ">", "&gt;",)
44
45     # Replace invalid 7-bit control characters with '?'
46     return s.translate(xml_escape_table)
47
48 def xmlrpclib_dump(self, value, write):
49     """
50     xmlrpclib cannot marshal instances of subclasses of built-in
51     types. This function overrides xmlrpclib.Marshaller.__dump so that
52     any value that is an instance of one of its acceptable types is
53     marshalled as that type.
54
55     xmlrpclib also cannot handle invalid 7-bit control characters. See
56     above.
57     """
58
59     # Use our escape function
60     args = [self, value, write]
61     if isinstance(value, (str, unicode)):
62         args.append(xmlrpclib_escape)
63
64     try:
65         # Try for an exact match first
66         f = self.dispatch[type(value)]
67     except KeyError:
68         raise
69         # Try for an isinstance() match
70         for Type, f in self.dispatch.iteritems():
71             if isinstance(value, Type):
72                 f(*args)
73                 return
74         raise TypeError("cannot marshal %s objects" % type(value))
75     else:
76         f(*args)
77
78 # You can't hide from me!
79 xmlrpclib.Marshaller._Marshaller__dump = xmlrpclib_dump
80
81 class XmlrpcApi:
82     """
83     The XmlrpcApi class implements a basic xmlrpc (or soap) service 
84     """
85
86     protocol = None
87   
88     def __init__ (self, encoding="utf-8", methods='sfa.methods'):
89
90         self.encoding = encoding
91         self.source = None 
92         
93         # flat list of method names
94         self.methods_module = methods_module = __import__(methods, fromlist=[methods])
95         self.methods = methods_module.all
96
97         self.logger = logger
98  
99     def callable(self, method):
100         """
101         Return a new instance of the specified method.
102         """
103         # Look up method
104         if method not in self.methods:
105             raise SfaInvalidAPIMethod(method)
106         
107         # Get new instance of method
108         try:
109             classname = method.split(".")[-1]
110             module = __import__(self.methods_module.__name__ + "." + method, globals(), locals(), [classname])
111             callablemethod = getattr(module, classname)(self)
112             return getattr(module, classname)(self)
113         except (ImportError, AttributeError):
114             self.logger.log_exc("Error importing method: %s" % method)
115             raise SfaInvalidAPIMethod(method)
116
117     def call(self, source, method, *args):
118         """
119         Call the named method from the specified source with the
120         specified arguments.
121         """
122         function = self.callable(method)
123         function.source = source
124         self.source = source
125         return function(*args)
126
127     
128     def handle(self, source, data, method_map):
129         """
130         Handle an XML-RPC or SOAP request from the specified source.
131         """
132         # Parse request into method name and arguments
133         try:
134             interface = xmlrpclib
135             self.protocol = 'xmlrpclib'
136             (args, method) = xmlrpclib.loads(data)
137             if method_map.has_key(method):
138                 method = method_map[method]
139             methodresponse = True
140             
141         except Exception as e:
142             if SOAPpy is not None:
143                 self.protocol = 'soap'
144                 interface = SOAPpy
145                 (r, header, body, attrs) = parseSOAPRPC(data, header = 1, body = 1, attrs = 1)
146                 method = r._name
147                 args = r._aslist()
148                 # XXX Support named arguments
149             else:
150                 raise e
151
152         try:
153             result = self.call(source, method, *args)
154         except SfaFault as fault:
155             result = fault
156             self.logger.log_exc("XmlrpcApi.handle has caught Exception") 
157         except Exception as fault:
158             self.logger.log_exc("XmlrpcApi.handle has caught Exception")
159             result = SfaAPIError(fault)
160
161
162         # Return result
163         response = self.prepare_response(result, method)
164         return response
165     
166     def prepare_response(self, result, method=""):
167         """
168         convert result to a valid xmlrpc or soap response
169         """   
170  
171         if self.protocol == 'xmlrpclib':
172             if not isinstance(result, SfaFault):
173                 result = (result,)
174             response = xmlrpclib.dumps(result, methodresponse = True, encoding = self.encoding, allow_none = 1)
175         elif self.protocol == 'soap':
176             if isinstance(result, Exception):
177                 result = faultParameter(NS.ENV_T + ":Server", "Method Failed", method)
178                 result._setDetail("Fault %d: %s" % (result.faultCode, result.faultString))
179             else:
180                 response = buildSOAP(kw = {'%sResponse' % method: {'Result': result}}, encoding = self.encoding)
181         else:
182             if isinstance(result, Exception):
183                 raise result 
184             
185         return response
186