trim unneeded fun
[sfa.git] / sfa / util / api.py
1 #
2 # SFA XML-RPC and SOAP interfaces
3 #
4
5 import string
6 import xmlrpclib
7
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
14
15 # this is wrong all right, but temporary 
16 from sfa.managers.import_manager import import_manager
17
18 # See "2.2 Characters" in the XML specification:
19 #
20 # #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD]
21 # avoiding
22 # [#x7F-#x84], [#x86-#x9F], [#xFDD0-#xFDDF]
23
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))
26
27 def xmlrpclib_escape(s, replace = string.replace):
28     """
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.
32     """
33
34     # This is the standard xmlrpclib.escape function
35     s = replace(s, "&", "&amp;")
36     s = replace(s, "<", "&lt;")
37     s = replace(s, ">", "&gt;",)
38
39     # Replace invalid 7-bit control characters with '?'
40     return s.translate(xml_escape_table)
41
42 def xmlrpclib_dump(self, value, write):
43     """
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.
48
49     xmlrpclib also cannot handle invalid 7-bit control characters. See
50     above.
51     """
52
53     # Use our escape function
54     args = [self, value, write]
55     if isinstance(value, (str, unicode)):
56         args.append(xmlrpclib_escape)
57
58     try:
59         # Try for an exact match first
60         f = self.dispatch[type(value)]
61     except KeyError:
62         raise
63         # Try for an isinstance() match
64         for Type, f in self.dispatch.iteritems():
65             if isinstance(value, Type):
66                 f(*args)
67                 return
68         raise TypeError, "cannot marshal %s objects" % type(value)
69     else:
70         f(*args)
71
72 # You can't hide from me!
73 xmlrpclib.Marshaller._Marshaller__dump = xmlrpclib_dump
74
75 # SOAP support is optional
76 try:
77     import SOAPpy
78     from SOAPpy.Parser import parseSOAPRPC
79     from SOAPpy.Types import faultType
80     from SOAPpy.NS import NS
81     from SOAPpy.SOAPBuilder import buildSOAP
82 except ImportError:
83     SOAPpy = None
84
85
86 class ManagerWrapper:
87     """
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         
96     """
97     def __init__(self, manager, interface):
98         self.manager = manager
99         self.interface = interface
100         
101     def __getattr__(self, method):
102         if not hasattr(self.manager, method):
103             raise SfaNotImplemented(method, self.interface)
104         return getattr(self.manager, method)
105         
106 class BaseAPI:
107
108     protocol = None
109   
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):
113
114         self.encoding = encoding
115         
116         # flat list of method names
117         self.methods_module = methods_module = __import__(methods, fromlist=[methods])
118         self.methods = methods_module.all
119
120         # Better just be documenting the API
121         if config is None:
122             return
123         # Load configuration
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)
132         self.cache = cache
133         if self.cache is None:
134             self.cache = Cache()
135         self.credential = None
136         self.source = None 
137         self.time_format = "%Y-%m-%d %H:%M:%S"
138         self.logger = logger
139  
140         # load registries
141         from sfa.server.registry import Registries
142         self.registries = Registries() 
143
144         # load aggregates
145         from sfa.server.aggregate import Aggregates
146         self.aggregates = Aggregates()
147
148
149     def get_interface_manager(self, manager_base = 'sfa.managers'):
150         """
151         Returns the appropriate manager module for this interface.
152         Modules are usually found in sfa/managers/
153         """
154         manager=None
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)
163         if not manager:
164             raise SfaAPIError("No manager for interface: %s" % self.interface)  
165             
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)
169
170         return manager
171
172     def callable(self, method):
173         """
174         Return a new instance of the specified method.
175         """
176         # Look up method
177         if method not in self.methods:
178             raise SfaInvalidAPIMethod, method
179         
180         # Get new instance of method
181         try:
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
188
189     def call(self, source, method, *args):
190         """
191         Call the named method from the specified source with the
192         specified arguments.
193         """
194         function = self.callable(method)
195         function.source = source
196         self.source = source
197         return function(*args)
198
199     
200     def handle(self, source, data, method_map):
201         """
202         Handle an XML-RPC or SOAP request from the specified source.
203         """
204         # Parse request into method name and arguments
205         try:
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
212             
213         except Exception, e:
214             if SOAPpy is not None:
215                 self.protocol = 'soap'
216                 interface = SOAPpy
217                 (r, header, body, attrs) = parseSOAPRPC(data, header = 1, body = 1, attrs = 1)
218                 method = r._name
219                 args = r._aslist()
220                 # XXX Support named arguments
221             else:
222                 raise e
223
224         try:
225             result = self.call(source, method, *args)
226         except SfaFault, fault:
227             result = fault 
228         except Exception, fault:
229             logger.log_exc("BaseAPI.handle has caught Exception")
230             result = SfaAPIError(fault)
231
232
233         # Return result
234         response = self.prepare_response(result, method)
235         return response
236     
237     def prepare_response(self, result, method=""):
238         """
239         convert result to a valid xmlrpc or soap response
240         """   
241  
242         if self.protocol == 'xmlrpclib':
243             if not isinstance(result, SfaFault):
244                 result = (result,)
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))
250             else:
251                 response = buildSOAP(kw = {'%sResponse' % method: {'Result': result}}, encoding = self.encoding)
252         else:
253             if isinstance(result, Exception):
254                 raise result 
255             
256         return response
257
258     def get_cached_server_version(self, server):
259         cache_key = server.url + "-version"
260         server_version = None
261         if self.cache:
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