9d61ed9b9dfadad340a44a8530da36930cdd20d7
[plcapi.git] / PLC / API.py
1 #
2 # PLCAPI XML-RPC and SOAP interfaces
3 #
4 # Aaron Klingaman <alk@absarokasoft.com>
5 # Mark Huang <mlhuang@cs.princeton.edu>
6 #
7 # Copyright (C) 2004-2006 The Trustees of Princeton University
8 # $Id$
9 # $URL$
10 #
11
12 import sys
13 import traceback
14 import string
15
16 import xmlrpclib
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         # Try for an isinstance() match
63         for Type, f in self.dispatch.iteritems():
64             if isinstance(value, Type):
65                 f(*args)
66                 return
67         raise TypeError, "cannot marshal %s objects" % type(value)
68     else:
69         f(*args)
70
71 # You can't hide from me!
72 xmlrpclib.Marshaller._Marshaller__dump = xmlrpclib_dump
73
74 # SOAP support is optional
75 try:
76     import SOAPpy
77     from SOAPpy.Parser import parseSOAPRPC
78     from SOAPpy.Types import faultType
79     from SOAPpy.NS import NS
80     from SOAPpy.SOAPBuilder import buildSOAP
81 except ImportError:
82     SOAPpy = None
83
84 from PLC.Config import Config
85 from PLC.Faults import *
86 import PLC.Methods
87 import PLC.Accessors
88
89 def import_deep(name):
90     mod = __import__(name)
91     components = name.split('.')
92     for comp in components[1:]:
93         mod = getattr(mod, comp)
94     return mod
95
96 class PLCAPI:
97
98     # flat list of method names
99     native_methods = PLC.Methods.native_methods
100
101     # other_methods_map : dict {methodname: fullpath}
102     # e.g. 'Accessors' -> 'PLC.Accessors.Accessors'
103     other_methods_map={}
104     for subdir in [ 'Accessors' ]:
105         path="PLC."+subdir
106         # scan e.g. PLC.Accessors.__all__
107         pkg = __import__(path).__dict__[subdir]
108         for modulename in getattr(pkg,"__all__"):
109             fullpath=path+"."+modulename
110             for method in getattr(import_deep(fullpath),"methods"):
111                 other_methods_map[method] = fullpath
112
113     all_methods = native_methods + other_methods_map.keys()
114     
115     def __init__(self, config = "/etc/planetlab/plc_config", encoding = "utf-8"):
116         self.encoding = encoding
117
118         # Better just be documenting the API
119         if config is None:
120             return
121
122         # Load configuration
123         self.config = Config(config)
124         
125         # Initialize database connection
126         if self.config.PLC_DB_TYPE == "postgresql":
127             from PLC.PostgreSQL import PostgreSQL
128             self.db = PostgreSQL(self)
129
130         else:
131             raise PLCAPIError, "Unsupported database type " + self.config.PLC_DB_TYPE
132
133     def callable(self, method):
134         """
135         Return a new instance of the specified method.
136         """
137
138         # Look up method
139         if method not in self.all_methods:
140             raise PLCInvalidAPIMethod, method
141         
142         # Get new instance of method
143         try:
144             classname = method.split(".")[-1]
145             if method in self.native_methods:
146                 fullpath="PLC.Methods." + method
147             else:
148                 fullpath=self.other_methods_map[method]
149             module = __import__(fullpath, globals(), locals(), [classname])
150             return getattr(module, classname)(self)
151         except ImportError, AttributeError:
152             raise PLCInvalidAPIMethod, "import error %s for %s" % (AttributeError,fullpath)
153
154     def call(self, source, method, *args):
155         """
156         Call the named method from the specified source with the
157         specified arguments.
158         """
159
160         function = self.callable(method)
161         function.source = source
162         return function(*args)
163
164     def handle(self, source, data):
165         """
166         Handle an XML-RPC or SOAP request from the specified source.
167         """
168
169         # Parse request into method name and arguments
170         try:
171             interface = xmlrpclib
172             (args, method) = xmlrpclib.loads(data)
173             methodresponse = True
174         except Exception, e:
175             if SOAPpy is not None:
176                 interface = SOAPpy
177                 (r, header, body, attrs) = parseSOAPRPC(data, header = 1, body = 1, attrs = 1)
178                 method = r._name
179                 args = r._aslist()
180                 # XXX Support named arguments
181             else:
182                 raise e
183
184         try:
185             result = self.call(source, method, *args)
186         except PLCFault, fault:
187             # Handle expected faults
188             if interface == xmlrpclib:
189                 result = fault
190                 methodresponse = None
191             elif interface == SOAPpy:
192                 result = faultParameter(NS.ENV_T + ":Server", "Method Failed", method)
193                 result._setDetail("Fault %d: %s" % (fault.faultCode, fault.faultString))
194
195         # Return result
196         if interface == xmlrpclib:
197             if not isinstance(result, PLCFault):
198                 result = (result,)
199             data = xmlrpclib.dumps(result, methodresponse = True, encoding = self.encoding, allow_none = 1)
200         elif interface == SOAPpy:
201             data = buildSOAP(kw = {'%sResponse' % method: {'Result': result}}, encoding = self.encoding)
202
203         return data