2 # SFA XML-RPC and SOAP interfaces
8 from sfa.util.faults import SfaNotImplemented, SfaAPIError, SfaInvalidAPIMethod, SfaFault
9 from sfa.util.config import Config
10 from sfa.util.sfalogging import logger
11 from sfa.trust.auth import Auth
12 from sfa.util.cache import Cache
13 from sfa.trust.certificate import Keypair, Certificate
15 # this is wrong all right, but temporary
16 from sfa.managers.import_manager import import_manager
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
88 This class acts as a wrapper around an SFA interface manager module, but
89 can be used with any python module. The purpose of this class is raise a
90 SfaNotImplemented exception if someone attempts to use an attribute
91 (could be a callable) thats not available in the library by checking the
92 library using hasattr. This helps to communicate better errors messages
93 to the users and developers in the event that a specifiec operation
94 is not implemented by a libarary and will generally be more helpful than
95 the standard AttributeError
97 def __init__(self, manager, interface):
98 self.manager = manager
99 self.interface = interface
101 def __getattr__(self, method):
102 if not hasattr(self.manager, method):
103 raise SfaNotImplemented(method, self.interface)
104 return getattr(self.manager, method)
110 def __init__(self, config = "/etc/sfa/sfa_config.py", encoding = "utf-8",
111 methods='sfa.methods', peer_cert = None, interface = None,
112 key_file = None, cert_file = None, cache = None):
114 self.encoding = encoding
116 # flat list of method names
117 self.methods_module = methods_module = __import__(methods, fromlist=[methods])
118 self.methods = methods_module.all
120 # Better just be documenting the API
124 self.config = Config(config)
125 self.auth = Auth(peer_cert)
126 self.hrn = self.config.SFA_INTERFACE_HRN
127 self.interface = interface
128 self.key_file = key_file
129 self.key = Keypair(filename=self.key_file)
130 self.cert_file = cert_file
131 self.cert = Certificate(filename=self.cert_file)
133 if self.cache is None:
135 self.credential = None
137 self.time_format = "%Y-%m-%d %H:%M:%S"
141 from sfa.server.registry import Registries
142 self.registries = Registries()
145 from sfa.server.aggregate import Aggregates
146 self.aggregates = Aggregates()
149 def get_interface_manager(self, manager_base = 'sfa.managers'):
151 Returns the appropriate manager module for this interface.
152 Modules are usually found in sfa/managers/
155 if self.interface in ['registry']:
156 manager=import_manager ("registry", self.config.SFA_REGISTRY_TYPE)
157 elif self.interface in ['aggregate']:
158 manager=import_manager ("aggregate", self.config.SFA_AGGREGATE_TYPE)
159 elif self.interface in ['slicemgr', 'sm']:
160 manager=import_manager ("slice", self.config.SFA_SM_TYPE)
161 elif self.interface in ['component', 'cm']:
162 manager=import_manager ("component", self.config.SFA_CM_TYPE)
164 raise SfaAPIError("No manager for interface: %s" % self.interface)
166 # this isnt necessary but will help to produce better error messages
167 # if someone tries to access an operation this manager doesn't implement
168 manager = ManagerWrapper(manager, self.interface)
172 def callable(self, method):
174 Return a new instance of the specified method.
177 if method not in self.methods:
178 raise SfaInvalidAPIMethod, method
180 # Get new instance of method
182 classname = method.split(".")[-1]
183 module = __import__(self.methods_module.__name__ + "." + method, globals(), locals(), [classname])
184 callablemethod = getattr(module, classname)(self)
185 return getattr(module, classname)(self)
186 except ImportError, AttributeError:
187 raise SfaInvalidAPIMethod, method
189 def call(self, source, method, *args):
191 Call the named method from the specified source with the
194 function = self.callable(method)
195 function.source = source
197 return function(*args)
200 def handle(self, source, data, method_map):
202 Handle an XML-RPC or SOAP request from the specified source.
204 # Parse request into method name and arguments
206 interface = xmlrpclib
207 self.protocol = 'xmlrpclib'
208 (args, method) = xmlrpclib.loads(data)
209 if method_map.has_key(method):
210 method = method_map[method]
211 methodresponse = True
214 if SOAPpy is not None:
215 self.protocol = 'soap'
217 (r, header, body, attrs) = parseSOAPRPC(data, header = 1, body = 1, attrs = 1)
220 # XXX Support named arguments
225 result = self.call(source, method, *args)
226 except SfaFault, fault:
228 except Exception, fault:
229 logger.log_exc("BaseAPI.handle has caught Exception")
230 result = SfaAPIError(fault)
234 response = self.prepare_response(result, method)
237 def prepare_response(self, result, method=""):
239 convert result to a valid xmlrpc or soap response
242 if self.protocol == 'xmlrpclib':
243 if not isinstance(result, SfaFault):
245 response = xmlrpclib.dumps(result, methodresponse = True, encoding = self.encoding, allow_none = 1)
246 elif self.protocol == 'soap':
247 if isinstance(result, Exception):
248 result = faultParameter(NS.ENV_T + ":Server", "Method Failed", method)
249 result._setDetail("Fault %d: %s" % (result.faultCode, result.faultString))
251 response = buildSOAP(kw = {'%sResponse' % method: {'Result': result}}, encoding = self.encoding)
253 if isinstance(result, Exception):
258 def get_cached_server_version(self, server):
259 cache_key = server.url + "-version"
260 server_version = None
262 server_version = self.cache.get(cache_key)
263 if not server_version:
264 server_version = server.GetVersion()
265 # cache version for 24 hours
266 self.cache.add(cache_key, server_version, ttl= 60*60*24)
267 return server_version