reorganizing code. moving some things out of the server interface classes and into...
[sfa.git] / geni / util / api.py
1 #
2 # Geniwrapper XML-RPC and SOAP interfaces
3 #
4 #
5
6 import sys
7 import os
8 import traceback
9 import string
10 import xmlrpclib
11 from geni.util.auth import Auth
12 from geni.util.config import *
13 from geni.util.faults import *
14 from geni.util.debug import *
15
16 # See "2.2 Characters" in the XML specification:
17 #
18 # #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD]
19 # avoiding
20 # [#x7F-#x84], [#x86-#x9F], [#xFDD0-#xFDDF]
21
22 invalid_xml_ascii = map(chr, range(0x0, 0x8) + [0xB, 0xC] + range(0xE, 0x1F))
23 xml_escape_table = string.maketrans("".join(invalid_xml_ascii), "?" * len(invalid_xml_ascii))
24
25 def xmlrpclib_escape(s, replace = string.replace):
26     """
27     xmlrpclib does not handle invalid 7-bit control characters. This
28     function augments xmlrpclib.escape, which by default only replaces
29     '&', '<', and '>' with entities.
30     """
31
32     # This is the standard xmlrpclib.escape function
33     s = replace(s, "&", "&amp;")
34     s = replace(s, "<", "&lt;")
35     s = replace(s, ">", "&gt;",)
36
37     # Replace invalid 7-bit control characters with '?'
38     return s.translate(xml_escape_table)
39
40 def xmlrpclib_dump(self, value, write):
41     """
42     xmlrpclib cannot marshal instances of subclasses of built-in
43     types. This function overrides xmlrpclib.Marshaller.__dump so that
44     any value that is an instance of one of its acceptable types is
45     marshalled as that type.
46
47     xmlrpclib also cannot handle invalid 7-bit control characters. See
48     above.
49     """
50
51     # Use our escape function
52     args = [self, value, write]
53     if isinstance(value, (str, unicode)):
54         args.append(xmlrpclib_escape)
55
56     try:
57         # Try for an exact match first
58         f = self.dispatch[type(value)]
59     except KeyError:
60         raise
61         # Try for an isinstance() match
62         for Type, f in self.dispatch.iteritems():
63             if isinstance(value, Type):
64                 f(*args)
65                 return
66         raise TypeError, "cannot marshal %s objects" % type(value)
67     else:
68         f(*args)
69
70 # You can't hide from me!
71 xmlrpclib.Marshaller._Marshaller__dump = xmlrpclib_dump
72
73 # SOAP support is optional
74 try:
75     import SOAPpy
76     from SOAPpy.Parser import parseSOAPRPC
77     from SOAPpy.Types import faultType
78     from SOAPpy.NS import NS
79     from SOAPpy.SOAPBuilder import buildSOAP
80 except ImportError:
81     SOAPpy = None
82
83 import geni.methods
84
85 def import_deep(name):
86     mod = __import__(name)
87     components = name.split('.')
88     for comp in components[1:]:
89         mod = getattr(mod, comp)
90     return mod
91
92 class GeniAPI:
93
94     # flat list of method names
95     methods = geni.methods.methods
96     
97     def __init__(self, config = "/usr/share/geniwrapper/geni/util/geni_config", encoding = "utf-8", peer_cert = None, interface = None):
98         self.encoding = encoding
99
100         # Better just be documenting the API
101         if config is None:
102             return
103
104         # Load configuration
105         self.config = Config(config)
106         self.auth = Auth(peer_cert)
107         self.interface = interface
108         self.plshell = self.getPLCShell()
109         self.basedir = self.config.GENI_BASE_DIR + os.sep
110         self.server_basedir = self.basedir + os.sep + "geni" + os.sep
111         self.hrn = self.config.GENI_INTERFACE_HRN
112
113
114     def getPLCShell(self):
115         self.plauth = {'Username': self.config.GENI_PLC_USER,
116                          'AuthMethod': 'password',
117                          'AuthString': self.config.GENI_PLC_PASSWORD} 
118         try:
119             import PLC.Shell
120             shell = PLC.Shell.Shell(globals = globals())
121             shell.AuthCheck(self.plauth)
122             return shell
123         except ImportError:
124             # connect via xmlrpc
125             plc_host = self.config.GENI_PLC_HOST
126             plc_port = self.config.GENI_PLC_PORT
127             plc_api_path = self.config.GENI_PLC_API_PATH
128             url = "https://%(plc_host)s:%(plc_port)s/%(plc_api_path)s/" % \
129                    locals()
130              
131             shell = xmlrpclib.Server(url, verbose = 0, allow_none = True)
132             shell.AuthCheck(self.plauth)
133             return shell         
134    
135     def fill_record_pl_info(self, record):
136         """
137         Fill in the planetlab specific fields of a Geni record. This
138         involves calling the appropraite PLC method to retrie the 
139         dtabase record for the object.
140         
141         PLC data is filled into the pl_fino field of the record.
142     
143         @param record record to fill in field (in/out param)     
144         """
145         type = record.get_type()
146         pointer = record.get_pointer()
147
148         # records with pointer==-1 do not have plc info associated with them.
149         # for example, the top level authority records which are
150         # authorities, but not PL "sites"
151         if pointer == -1:
152             record.set_pl_info({})
153             return
154
155         if (type == "sa") or (type == "ma"):
156             pl_res = self.plshell.GetSites(self.plauth, [pointer])
157         elif (type == "slice"):
158             pl_res = self.plshell.GetSlices(self.plauth, [pointer])
159         elif (type == "user"):
160             pl_res = self.plshell.GetPersons(self.plauth, [pointer])
161             key_ids = pl_res[0]['key_ids']
162             keys = self.plshell.GetKeys(self.plauth, key_ids)
163             pubkeys = []
164             if keys:
165                 pubkeys = [key['key'] for key in keys]
166             pl_res[0]['keys'] = pubkeys
167         elif (type == "node"):
168             pl_res = self.plshell.GetNodes(self.plauth, [pointer])
169         else:
170             raise UnknownGeniType(type)
171
172         if not pl_res:
173             # the planetlab record no longer exists
174             # TODO: delete the geni record ?
175             raise PlanetLabRecordDoesNotExist(record.get_name())
176
177         record.set_pl_info(pl_res[0])
178
179
180     def lookup_users(self, auth_table, user_id_list, role="*"):
181         record_list = []
182         for person_id in user_id_list:
183             user_records = auth_table.find("user", person_id, "pointer")
184             for user_record in user_records:
185                 self.fill_record_info(user_record)
186
187                 user_roles = user_record.get_pl_info().get("roles")
188                 if (role=="*") or (role in user_roles):
189                     record_list.append(user_record.get_name())
190         return record_list
191
192     def fill_record_geni_info(self, record):
193         geni_info = {}
194         type = record.get_type()
195
196         if (type == "slice"):
197             auth_table = self.auth.get_auth_table(self.auth.get_authority(record.get_name()))
198             person_ids = record.pl_info.get("person_ids", [])
199             researchers = self.lookup_users(auth_table, person_ids)
200             geni_info['researcher'] = researchers
201
202         elif (type == "sa"):
203             auth_table = self.auth.get_auth_table(record.get_name())
204             person_ids = record.pl_info.get("person_ids", [])
205             pis = self.lookup_users(auth_table, person_ids, "pi")
206             geni_info['pi'] = pis
207             # TODO: OrganizationName
208
209         elif (type == "ma"):
210             auth_table = self.auth.get_auth_table(record.get_name())
211             person_ids = record.pl_info.get("person_ids", [])
212             operators = self.lookup_users(auth_table, person_ids, "tech")
213             geni_info['operator'] = operators
214             # TODO: OrganizationName
215
216             auth_table = self.auth.get_auth_table(record.get_name())
217             person_ids = record.pl_info.get("person_ids", [])
218             owners = self.lookup_users(auth_table, person_ids, "admin")
219             geni_info['owner'] = owners
220
221         elif (type == "node"):
222             geni_info['dns'] = record.pl_info.get("hostname", "")
223             # TODO: URI, LatLong, IP, DNS
224     
225         elif (type == "user"):
226             geni_info['email'] = record.pl_info.get("email", "")
227             # TODO: PostalAddress, Phone
228
229         record.set_geni_info(geni_info)
230
231     def fill_record_info(self, record):
232         """
233         Given a geni record, fill in the PLC specific and Geni specific
234         fields in the record. 
235         """
236         self.fill_record_pl_info(record)
237         self.fill_record_geni_info(record)
238
239     def update_membership_list(self, oldRecord, record, listName, addFunc, delFunc):
240         # get a list of the HRNs tht are members of the old and new records^M
241         if oldRecord:
242             if oldRecord.pl_info == None:
243                 oldRecord.pl_info = {}
244             oldList = oldRecord.get_geni_info().get(listName, [])
245         else:
246             oldList = []
247         newList = record.get_geni_info().get(listName, [])
248
249         # if the lists are the same, then we don't have to update anything
250         if (oldList == newList):
251             return
252
253         # build a list of the new person ids, by looking up each person to get
254         # their pointer
255         newIdList = []
256         for hrn in newList:
257             userRecord = self.resolve_raw("user", hrn)[0]
258             newIdList.append(userRecord.get_pointer())
259
260         # build a list of the old person ids from the person_ids field of the
261         # pl_info
262         if oldRecord:
263             oldIdList = oldRecord.plinfo.get("person_ids", [])
264             containerId = oldRecord.get_pointer()
265         else:
266             # if oldRecord==None, then we are doing a Register, instead of an
267             # update.
268             oldIdList = []
269             containerId = record.get_pointer()
270
271     # add people who are in the new list, but not the oldList
272         for personId in newIdList:
273             if not (personId in oldIdList):
274                 print "adding id", personId, "to", record.get_name()
275                 addFunc(self.plauth, personId, containerId)
276
277         # remove people who are in the old list, but not the new list
278         for personId in oldIdList:
279             if not (personId in newIdList):
280                 print "removing id", personId, "from", record.get_name()
281                 delFunc(self.plauth, personId, containerId)
282
283     def update_membership(self, oldRecord, record):
284         if record.type == "slice":
285             self.update_membership_list(oldRecord, record, 'researcher',
286                                         self.plshell.AddPersonToSlice,
287                                         self.plshell.DeletePersonFromSlice)
288         elif record.type == "sa":
289             # TODO
290             pass
291         elif record.type == "ma":
292             # TODO
293             pass
294  
295
296     def callable(self, method):
297         """
298         Return a new instance of the specified method.
299         """
300         # Look up method
301         if method not in self.methods:
302             raise GeniInvalidAPIMethod, method
303         
304         # Get new instance of method
305         try:
306             classname = method.split(".")[-1]
307             module = __import__("geni.methods." + method, globals(), locals(), [classname])
308             callablemethod = getattr(module, classname)(self)
309             return getattr(module, classname)(self)
310         except ImportError, AttributeError:
311             raise GeniInvalidAPIMethod, method
312
313     def call(self, source, method, *args):
314         """
315         Call the named method from the specified source with the
316         specified arguments.
317         """
318         function = self.callable(method)
319         function.source = source
320         return function(*args)
321
322     def handle(self, source, data):
323         """
324         Handle an XML-RPC or SOAP request from the specified source.
325         """
326
327         # Parse request into method name and arguments
328         try:
329             interface = xmlrpclib
330             (args, method) = xmlrpclib.loads(data)
331             methodresponse = True
332         except Exception, e:
333             if SOAPpy is not None:
334                 interface = SOAPpy
335                 (r, header, body, attrs) = parseSOAPRPC(data, header = 1, body = 1, attrs = 1)
336                 method = r._name
337                 args = r._aslist()
338                 # XXX Support named arguments
339             else:
340                 raise e
341
342         try:
343             result = self.call(source, method, *args)
344         except Exception, fault:
345             traceback.print_exc(file = log)
346             # Handle expected faults
347             if interface == xmlrpclib:
348                 result = fault
349                 methodresponse = None
350             elif interface == SOAPpy:
351                 result = faultParameter(NS.ENV_T + ":Server", "Method Failed", method)
352                 result._setDetail("Fault %d: %s" % (fault.faultCode, fault.faultString))
353
354         # Return result
355         if interface == xmlrpclib:
356             if not isinstance(result, GeniFault):
357                 result = (result,)
358
359             data = xmlrpclib.dumps(result, methodresponse = True, encoding = self.encoding, allow_none = 1)
360         elif interface == SOAPpy:
361             data = buildSOAP(kw = {'%sResponse' % method: {'Result': result}}, encoding = self.encoding)
362
363         return data