2 # SFA XML-RPC and SOAP interfaces
11 from sfa.util.sfalogging import sfa_logger
12 from sfa.trust.auth import Auth
13 from sfa.util.config import *
14 from sfa.util.faults import *
15 from sfa.trust.credential import *
16 from sfa.trust.certificate import *
18 # See "2.2 Characters" in the XML specification:
20 # #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD]
22 # [#x7F-#x84], [#x86-#x9F], [#xFDD0-#xFDDF]
24 invalid_xml_ascii = map(chr, range(0x0, 0x8) + [0xB, 0xC] + range(0xE, 0x1F))
25 xml_escape_table = string.maketrans("".join(invalid_xml_ascii), "?" * len(invalid_xml_ascii))
27 def xmlrpclib_escape(s, replace = string.replace):
29 xmlrpclib does not handle invalid 7-bit control characters. This
30 function augments xmlrpclib.escape, which by default only replaces
31 '&', '<', and '>' with entities.
34 # This is the standard xmlrpclib.escape function
35 s = replace(s, "&", "&")
36 s = replace(s, "<", "<")
37 s = replace(s, ">", ">",)
39 # Replace invalid 7-bit control characters with '?'
40 return s.translate(xml_escape_table)
42 def xmlrpclib_dump(self, value, write):
44 xmlrpclib cannot marshal instances of subclasses of built-in
45 types. This function overrides xmlrpclib.Marshaller.__dump so that
46 any value that is an instance of one of its acceptable types is
47 marshalled as that type.
49 xmlrpclib also cannot handle invalid 7-bit control characters. See
53 # Use our escape function
54 args = [self, value, write]
55 if isinstance(value, (str, unicode)):
56 args.append(xmlrpclib_escape)
59 # Try for an exact match first
60 f = self.dispatch[type(value)]
63 # Try for an isinstance() match
64 for Type, f in self.dispatch.iteritems():
65 if isinstance(value, Type):
68 raise TypeError, "cannot marshal %s objects" % type(value)
72 # You can't hide from me!
73 xmlrpclib.Marshaller._Marshaller__dump = xmlrpclib_dump
75 # SOAP support is optional
78 from SOAPpy.Parser import parseSOAPRPC
79 from SOAPpy.Types import faultType
80 from SOAPpy.NS import NS
81 from SOAPpy.SOAPBuilder import buildSOAP
86 def import_deep(name):
87 mod = __import__(name)
88 components = name.split('.')
89 for comp in components[1:]:
90 mod = getattr(mod, comp)
95 This class acts as a wrapper around an SFA interface manager module, but
96 can be used with any python module. The purpose of this class is raise a
97 SfaNotImplemented exception if the a someone attepmts to use an attribute
98 (could be a callable) thats not available in the library by checking the
99 library using hasattr. This helps to communicate better errors messages
100 to the users and developers in the event that a specifiec operation
101 is not implemented by a libarary and will generally be more helpful than
102 the standard AttributeError
104 def __init__(self, manager, interface):
105 self.manager = manager
106 self.interface = interface
108 def __getattr__(self, method):
110 if not hasattr(self.manager, method):
111 raise SfaNotImplemented(method, self.interface)
112 return getattr(self.manager, method)
119 def __init__(self, config = "/etc/sfa/sfa_config.py", encoding = "utf-8",
120 methods='sfa.methods', peer_cert = None, interface = None,
121 key_file = None, cert_file = None, cache = cache):
123 self.encoding = encoding
125 # flat list of method names
126 self.methods_module = methods_module = __import__(methods, fromlist=[methods])
127 self.methods = methods_module.all
129 # Better just be documenting the API
134 self.config = Config(config)
135 self.auth = Auth(peer_cert)
136 self.hrn = self.config.SFA_INTERFACE_HRN
137 self.interface = interface
138 self.key_file = key_file
139 self.key = Keypair(filename=self.key_file)
140 self.cert_file = cert_file
141 self.cert = Certificate(filename=self.cert_file)
143 self.credential = None
145 self.time_format = "%Y-%m-%d %H:%M:%S"
146 self.logger=sfa_logger
149 from sfa.server.registry import Registries
150 self.registries = Registries(self)
153 from sfa.server.aggregate import Aggregates
154 self.aggregates = Aggregates(self)
157 def get_interface_manager(self, manager_base = 'sfa.managers'):
159 Returns the appropriate manager module for this interface.
160 Modules are usually found in sfa/managers/
163 if self.interface in ['registry']:
164 mgr_type = self.config.SFA_REGISTRY_TYPE
165 manager_module = manager_base + ".registry_manager_%s" % mgr_type
166 elif self.interface in ['aggregate']:
167 mgr_type = self.config.SFA_AGGREGATE_TYPE
168 manager_module = manager_base + ".aggregate_manager_%s" % mgr_type
169 elif self.interface in ['slicemgr', 'sm']:
170 mgr_type = self.config.SFA_SM_TYPE
171 manager_module = manager_base + ".slice_manager_%s" % mgr_type
172 elif self.interface in ['component', 'cm']:
173 mgr_type = self.config.SFA_CM_TYPE
174 manager_module = manager_base + ".component_manager_%s" % mgr_type
176 raise SfaAPIError("No manager for interface: %s" % self.interface)
177 manager = __import__(manager_module, fromlist=[manager_base])
178 # this isnt necessary but will hlep to produce better error messages
179 # if someone tries to access an operation this manager doesn't implement
180 manager = ManagerWrapper(manager, self.interface)
184 def callable(self, method):
186 Return a new instance of the specified method.
189 if method not in self.methods:
190 raise SfaInvalidAPIMethod, method
192 # Get new instance of method
194 classname = method.split(".")[-1]
195 module = __import__(self.methods_module.__name__ + "." + method, globals(), locals(), [classname])
196 callablemethod = getattr(module, classname)(self)
197 return getattr(module, classname)(self)
198 except ImportError, AttributeError:
199 raise SfaInvalidAPIMethod, method
201 def call(self, source, method, *args):
203 Call the named method from the specified source with the
206 function = self.callable(method)
207 function.source = source
209 return function(*args)
212 def handle(self, source, data, method_map):
214 Handle an XML-RPC or SOAP request from the specified source.
216 # Parse request into method name and arguments
218 interface = xmlrpclib
219 self.protocol = 'xmlrpclib'
220 (args, method) = xmlrpclib.loads(data)
221 if method_map.has_key(method):
222 method = method_map[method]
223 methodresponse = True
226 if SOAPpy is not None:
227 self.protocol = 'soap'
229 (r, header, body, attrs) = parseSOAPRPC(data, header = 1, body = 1, attrs = 1)
232 # XXX Support named arguments
237 result = self.call(source, method, *args)
238 except SfaFault, fault:
240 except Exception, fault:
241 sfa_logger().log_exc("BaseAPI.handle has caught Exception")
242 result = SfaAPIError(fault)
246 response = self.prepare_response(result, method)
249 def prepare_response(self, result, method=""):
251 convert result to a valid xmlrpc or soap response
254 if self.protocol == 'xmlrpclib':
255 if not isinstance(result, SfaFault):
257 response = xmlrpclib.dumps(result, methodresponse = True, encoding = self.encoding, allow_none = 1)
258 elif self.protocol == 'soap':
259 if isinstance(result, Exception):
260 result = faultParameter(NS.ENV_T + ":Server", "Method Failed", method)
261 result._setDetail("Fault %d: %s" % (result.faultCode, result.faultString))
263 response = buildSOAP(kw = {'%sResponse' % method: {'Result': result}}, encoding = self.encoding)
265 if isinstance(result, Exception):