added get_manager() method
[sfa.git] / sfa / util / api.py
1 #
2 # SFA XML-RPC and SOAP interfaces
3 #
4 ### $Id$
5 ### $URL$
6 #
7
8 import sys
9 import os
10 import traceback
11 import string
12 import xmlrpclib
13
14 from sfa.trust.auth import Auth
15 from sfa.util.config import *
16 from sfa.util.faults import *
17 from sfa.util.debug import *
18 from sfa.trust.credential import *
19 from sfa.trust.certificate import *
20 from sfa.util.namespace import *
21 from sfa.util.sfalogging import *
22
23 # See "2.2 Characters" in the XML specification:
24 #
25 # #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD]
26 # avoiding
27 # [#x7F-#x84], [#x86-#x9F], [#xFDD0-#xFDDF]
28
29 invalid_xml_ascii = map(chr, range(0x0, 0x8) + [0xB, 0xC] + range(0xE, 0x1F))
30 xml_escape_table = string.maketrans("".join(invalid_xml_ascii), "?" * len(invalid_xml_ascii))
31
32 def xmlrpclib_escape(s, replace = string.replace):
33     """
34     xmlrpclib does not handle invalid 7-bit control characters. This
35     function augments xmlrpclib.escape, which by default only replaces
36     '&', '<', and '>' with entities.
37     """
38
39     # This is the standard xmlrpclib.escape function
40     s = replace(s, "&", "&amp;")
41     s = replace(s, "<", "&lt;")
42     s = replace(s, ">", "&gt;",)
43
44     # Replace invalid 7-bit control characters with '?'
45     return s.translate(xml_escape_table)
46
47 def xmlrpclib_dump(self, value, write):
48     """
49     xmlrpclib cannot marshal instances of subclasses of built-in
50     types. This function overrides xmlrpclib.Marshaller.__dump so that
51     any value that is an instance of one of its acceptable types is
52     marshalled as that type.
53
54     xmlrpclib also cannot handle invalid 7-bit control characters. See
55     above.
56     """
57
58     # Use our escape function
59     args = [self, value, write]
60     if isinstance(value, (str, unicode)):
61         args.append(xmlrpclib_escape)
62
63     try:
64         # Try for an exact match first
65         f = self.dispatch[type(value)]
66     except KeyError:
67         raise
68         # Try for an isinstance() match
69         for Type, f in self.dispatch.iteritems():
70             if isinstance(value, Type):
71                 f(*args)
72                 return
73         raise TypeError, "cannot marshal %s objects" % type(value)
74     else:
75         f(*args)
76
77 # You can't hide from me!
78 xmlrpclib.Marshaller._Marshaller__dump = xmlrpclib_dump
79
80 # SOAP support is optional
81 try:
82     import SOAPpy
83     from SOAPpy.Parser import parseSOAPRPC
84     from SOAPpy.Types import faultType
85     from SOAPpy.NS import NS
86     from SOAPpy.SOAPBuilder import buildSOAP
87 except ImportError:
88     SOAPpy = None
89
90
91 def import_deep(name):
92     mod = __import__(name)
93     components = name.split('.')
94     for comp in components[1:]:
95         mod = getattr(mod, comp)
96     return mod
97
98 class BaseAPI:
99
100     cache = None
101     protocol = None
102   
103     def __init__(self, config = "/etc/sfa/sfa_config.py", encoding = "utf-8", 
104                  methods='sfa.methods', peer_cert = None, interface = None, 
105                  key_file = None, cert_file = None, cache = cache):
106
107         self.encoding = encoding
108         
109         # flat list of method names
110         self.methods_module = methods_module = __import__(methods, fromlist=[methods])
111         self.methods = methods_module.all
112
113         # Better just be documenting the API
114         if config is None:
115             return
116         
117         # Load configuration
118         self.config = Config(config)
119         self.auth = Auth(peer_cert)
120         self.hrn = self.config.SFA_INTERFACE_HRN
121         self.interface = interface
122         self.key_file = key_file
123         self.key = Keypair(filename=self.key_file)
124         self.cert_file = cert_file
125         self.cert = Certificate(filename=self.cert_file)
126         self.cache = cache
127         self.credential = None
128         self.source = None 
129         self.time_format = "%Y-%m-%d %H:%M:%S"
130         self.logger=get_sfa_logger()
131         
132         # load registries
133         from sfa.server.registry import Registries
134         self.registries = Registries(self) 
135
136         # load aggregates
137         from sfa.server.aggregate import Aggregates
138         self.aggregates = Aggregates(self)
139
140
141     def get_manager(self, manager_base = 'sfa.managers'):
142         """
143         Returns the appropriate manager module for this interface.
144         Modules are usually found in sfa/managers/
145         """
146         
147         if self.interface in ['registry']:
148             mgr_type = self.api.config.SFA_REGISTRY_TYPE
149             manager_module = manager_base + ".registry_manager_%s" % mgr_type
150         elif self.interface in ['aggregate']:
151             mgr_type = self.api.config.SFA_AGGREGATE_TYPE
152             manager_module = manager_base + ".aggregate_manager_%s" % mgr_type 
153         elif self.interface in ['slicemgr', 'sm']:
154             mgr_type = self.api.config.SFA_SM_TYPE
155             manager_module = manager_base + ".slice_manager_%s" % mgr_type
156         elif self.interface in ['component', 'cm']:
157             mgr_type = self.api.config.SFA_CM_TYPE
158             manager_module = manager_base + ".component_manager_%s" % mgr_type
159         else:
160             raise SfaAPIError("No manager for interface: %s" % self.interface)  
161         manager = __import__(manager_module, fromlist=[manager_base])   
162  
163         return manager
164
165     def callable(self, method):
166         """
167         Return a new instance of the specified method.
168         """
169         # Look up method
170         if method not in self.methods:
171             raise SfaInvalidAPIMethod, method
172         
173         # Get new instance of method
174         try:
175             classname = method.split(".")[-1]
176             module = __import__(self.methods_module.__name__ + "." + method, globals(), locals(), [classname])
177             callablemethod = getattr(module, classname)(self)
178             return getattr(module, classname)(self)
179         except ImportError, AttributeError:
180             raise SfaInvalidAPIMethod, method
181
182     def call(self, source, method, *args):
183         """
184         Call the named method from the specified source with the
185         specified arguments.
186         """
187         function = self.callable(method)
188         function.source = source
189         self.source = source
190         return function(*args)
191
192     
193     def handle(self, source, data, method_map):
194         """
195         Handle an XML-RPC or SOAP request from the specified source.
196         """
197         # Parse request into method name and arguments
198         try:
199             interface = xmlrpclib
200             self.protocol = 'xmlrpclib'
201             (args, method) = xmlrpclib.loads(data)
202             if method_map.has_key(method):
203                 method = method_map[method]
204             methodresponse = True
205             
206         except Exception, e:
207             if SOAPpy is not None:
208                 self.protocol = 'soap'
209                 interface = SOAPpy
210                 (r, header, body, attrs) = parseSOAPRPC(data, header = 1, body = 1, attrs = 1)
211                 method = r._name
212                 args = r._aslist()
213                 # XXX Support named arguments
214             else:
215                 raise e
216
217         try:
218             result = self.call(source, method, *args)
219         except SfaFault, fault:
220             result = fault 
221         except Exception, fault:
222             traceback.print_exc(file = log)
223             result = SfaAPIError(fault)
224
225
226         # Return result
227         response = self.prepare_response(result, method)
228         return response
229     
230     def prepare_response(self, result, method=""):
231         """
232         convert result to a valid xmlrpc or soap response
233         """   
234  
235         if self.protocol == 'xmlrpclib':
236             if not isinstance(result, SfaFault):
237                 result = (result,)
238             response = xmlrpclib.dumps(result, methodresponse = True, encoding = self.encoding, allow_none = 1)
239         elif self.protocol == 'soap':
240             if isinstance(result, Exception):
241                 result = faultParameter(NS.ENV_T + ":Server", "Method Failed", method)
242                 result._setDetail("Fault %d: %s" % (result.faultCode, result.faultString))
243             else:
244                 response = buildSOAP(kw = {'%sResponse' % method: {'Result': result}}, encoding = self.encoding)
245         else:
246             if isinstance(result, Exception):
247                 raise result 
248             
249         return response