6244fbe5e1ed6d6628bcc9cb301b6c4f4aa2f907
[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 from geni.util.rights import *
16 from geni.util.credential import *
17 # See "2.2 Characters" in the XML specification:
18 #
19 # #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD]
20 # avoiding
21 # [#x7F-#x84], [#x86-#x9F], [#xFDD0-#xFDDF]
22
23 invalid_xml_ascii = map(chr, range(0x0, 0x8) + [0xB, 0xC] + range(0xE, 0x1F))
24 xml_escape_table = string.maketrans("".join(invalid_xml_ascii), "?" * len(invalid_xml_ascii))
25
26 def xmlrpclib_escape(s, replace = string.replace):
27     """
28     xmlrpclib does not handle invalid 7-bit control characters. This
29     function augments xmlrpclib.escape, which by default only replaces
30     '&', '<', and '>' with entities.
31     """
32
33     # This is the standard xmlrpclib.escape function
34     s = replace(s, "&", "&amp;")
35     s = replace(s, "<", "&lt;")
36     s = replace(s, ">", "&gt;",)
37
38     # Replace invalid 7-bit control characters with '?'
39     return s.translate(xml_escape_table)
40
41 def xmlrpclib_dump(self, value, write):
42     """
43     xmlrpclib cannot marshal instances of subclasses of built-in
44     types. This function overrides xmlrpclib.Marshaller.__dump so that
45     any value that is an instance of one of its acceptable types is
46     marshalled as that type.
47
48     xmlrpclib also cannot handle invalid 7-bit control characters. See
49     above.
50     """
51
52     # Use our escape function
53     args = [self, value, write]
54     if isinstance(value, (str, unicode)):
55         args.append(xmlrpclib_escape)
56
57     try:
58         # Try for an exact match first
59         f = self.dispatch[type(value)]
60     except KeyError:
61         raise
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 import geni.methods
85
86 def import_deep(name):
87     mod = __import__(name)
88     components = name.split('.')
89     for comp in components[1:]:
90         mod = getattr(mod, comp)
91     return mod
92
93 class GeniAPI:
94
95     # flat list of method names
96     methods = geni.methods.methods
97     
98     def __init__(self, config = "/usr/share/geniwrapper/geni/util/geni_config", encoding = "utf-8", peer_cert = None, interface = None, key_file = None, cert_file = None):
99         self.encoding = encoding
100
101         # Better just be documenting the API
102         if config is None:
103             return
104
105         # Load configuration
106         self.config = Config(config)
107         self.auth = Auth(peer_cert)
108         self.interface = interface
109         self.key_file = key_file
110         self.cert_file = cert_file
111         self.credential = None
112         self.plshell = self.getPLCShell()
113         self.basedir = self.config.GENI_BASE_DIR + os.sep
114         self.server_basedir = self.basedir + os.sep + "geni" + os.sep
115         self.hrn = self.config.GENI_INTERFACE_HRN
116         self.time_format = "%Y-%m-%d %H:%M:%S"
117
118
119     def getPLCShell(self):
120         self.plauth = {'Username': self.config.GENI_PLC_USER,
121                          'AuthMethod': 'password',
122                          'AuthString': self.config.GENI_PLC_PASSWORD} 
123         try:
124             import PLC.Shell
125             shell = PLC.Shell.Shell(globals = globals())
126             shell.AuthCheck(self.plauth)
127             return shell
128         except ImportError:
129             # connect via xmlrpc
130             plc_host = self.config.GENI_PLC_HOST
131             plc_port = self.config.GENI_PLC_PORT
132             plc_api_path = self.config.GENI_PLC_API_PATH
133             url = "https://%(plc_host)s:%(plc_port)s/%(plc_api_path)s/" % \
134                    locals()
135              
136             shell = xmlrpclib.Server(url, verbose = 0, allow_none = True)
137             shell.AuthCheck(self.plauth)
138             return shell
139
140     def getCredential(self):
141         return self.getCredentialFromRegistry()
142
143     def getCredentialFromRegistry(self):
144         """
145         Get our current credential from the local registry.
146         """
147     
148         hrn = self.hrn
149         auth_hrn = self.auth.get_authority(hrn)
150         if not auth_hrn:
151             auth_hrn = hrn
152         auth_info = self.auth.get_auth_info(auth_hrn)
153         table = self.auth.get_auth_table(auth_hrn)
154         records = table.resolve('*', hrn)
155         if not records:
156             raise RecordnotFound
157         record = records[0]
158         type = record.get_type()
159         object_gid = record.get_gid_object()
160         new_cred = Credential(subject = object_gid.get_subject())
161         new_cred.set_gid_caller(object_gid)
162         new_cred.set_gid_object(object_gid)
163         new_cred.set_issuer(key=auth_info.get_pkey_object(), subject=auth_hrn)
164         new_cred.set_pubkey(object_gid.get_pubkey())
165         r1 = determine_rights(type, hrn)
166         new_cred.set_privileges(r1)
167     
168         # determine the type of credential that we want to use as a parent for
169         # this credential.
170
171         if (type == "ma") or (type == "node"):
172             auth_kind = "authority,ma"
173         else: # user, slice, sa
174             auth_kind = "authority,sa"
175
176         new_cred.set_parent(self.auth.hierarchy.get_auth_cred(auth_hrn, kind=auth_kind))
177
178         new_cred.encode()
179         new_cred.sign()
180
181         return new_cred
182    
183
184     def loadCredential(self):
185         """
186         Attempt to load credential from file if it exists. If it doesnt get
187         credential from registry.
188         """
189
190         # see if this file exists
191         # XX This is really the aggregate's credential. Using this is easier than getting
192         # the registry's credential from iteslf (ssl errors).   
193         ma_cred_filename = self.server_basedir + os.sep + self.interface + self.hrn + ".ma.cred"
194         try:
195             self.credential = Credential(filename = ma_cred_filename)
196         except IOError:
197             self.credential = self.getCredentialFromRegistry()
198       
199     ##
200     # Convert geni fields to PLC fields for use when registering up updating
201     # registry record in the PLC database
202     #
203     # @param type type of record (user, slice, ...)
204     # @param hrn human readable name
205     # @param geni_fields dictionary of geni fields
206     # @param pl_fields dictionary of PLC fields (output)
207
208     def geni_fields_to_pl_fields(self, type, hrn, geni_fields, pl_fields):
209         if type == "user":
210             if not "email" in pl_fields:
211                 if not "email" in geni_fields:
212                     raise MissingGeniInfo("email")
213                 pl_fields["email"] = geni_fields["email"]
214
215             if not "first_name" in pl_fields:
216                 pl_fields["first_name"] = "geni"
217
218             if not "last_name" in pl_fields:
219                 pl_fields["last_name"] = hrn
220
221         elif type == "slice":
222             if not "instantiation" in pl_fields:
223                 pl_fields["instantiation"] = "delegated"  # "plc-instantiated"
224             if not "name" in pl_fields:
225                 pl_fields["name"] = hrn_to_pl_slicename(hrn)
226             if not "max_nodes" in pl_fields:
227                 pl_fields["max_nodes"] = 10
228
229         elif type == "node":
230             if not "hostname" in pl_fields:
231                 if not "dns" in geni_fields:
232                     raise MissingGeniInfo("dns")
233                 pl_fields["hostname"] = geni_fields["dns"]
234             if not "model" in pl_fields:
235                 pl_fields["model"] = "geni"
236
237         elif type == "sa":
238             pl_fields["login_base"] = hrn_to_pl_login_base(hrn)
239
240             if not "name" in pl_fields:
241                 pl_fields["name"] = hrn
242
243             if not "abbreviated_name" in pl_fields:
244                 pl_fields["abbreviated_name"] = hrn
245
246             if not "enabled" in pl_fields:
247                 pl_fields["enabled"] = True
248
249             if not "is_public" in pl_fields:
250                 pl_fields["is_public"] = True
251
252
253  
254     def fill_record_pl_info(self, record):
255         """
256         Fill in the planetlab specific fields of a Geni record. This
257         involves calling the appropraite PLC method to retrie the 
258         dtabase record for the object.
259         
260         PLC data is filled into the pl_fino field of the record.
261     
262         @param record record to fill in field (in/out param)     
263         """
264         type = record.get_type()
265         pointer = record.get_pointer()
266
267         # records with pointer==-1 do not have plc info associated with them.
268         # for example, the top level authority records which are
269         # authorities, but not PL "sites"
270         if pointer == -1:
271             record.set_pl_info({})
272             return
273
274         if (type == "sa") or (type == "ma"):
275             pl_res = self.plshell.GetSites(self.plauth, [pointer])
276         elif (type == "slice"):
277             pl_res = self.plshell.GetSlices(self.plauth, [pointer])
278         elif (type == "user"):
279             pl_res = self.plshell.GetPersons(self.plauth, [pointer])
280             key_ids = pl_res[0]['key_ids']
281             keys = self.plshell.GetKeys(self.plauth, key_ids)
282             pubkeys = []
283             if keys:
284                 pubkeys = [key['key'] for key in keys]
285             pl_res[0]['keys'] = pubkeys
286         elif (type == "node"):
287             pl_res = self.plshell.GetNodes(self.plauth, [pointer])
288         else:
289             raise UnknownGeniType(type)
290
291         if not pl_res:
292             # the planetlab record no longer exists
293             # TODO: delete the geni record ?
294             raise PlanetLabRecordDoesNotExist(record.get_name())
295
296         record.set_pl_info(pl_res[0])
297
298
299     def lookup_users(self, auth_table, user_id_list, role="*"):
300         record_list = []
301         for person_id in user_id_list:
302             user_records = auth_table.find("user", person_id, "pointer")
303             for user_record in user_records:
304                 self.fill_record_info(user_record)
305
306                 user_roles = user_record.get_pl_info().get("roles")
307                 if (role=="*") or (role in user_roles):
308                     record_list.append(user_record.get_name())
309         return record_list
310
311     def fill_record_geni_info(self, record):
312         geni_info = {}
313         type = record.get_type()
314
315         if (type == "slice"):
316             auth_table = self.auth.get_auth_table(self.auth.get_authority(record.get_name()))
317             person_ids = record.pl_info.get("person_ids", [])
318             researchers = self.lookup_users(auth_table, person_ids)
319             geni_info['researcher'] = researchers
320
321         elif (type == "sa"):
322             auth_table = self.auth.get_auth_table(record.get_name())
323             person_ids = record.pl_info.get("person_ids", [])
324             pis = self.lookup_users(auth_table, person_ids, "pi")
325             geni_info['pi'] = pis
326             # TODO: OrganizationName
327
328         elif (type == "ma"):
329             auth_table = self.auth.get_auth_table(record.get_name())
330             person_ids = record.pl_info.get("person_ids", [])
331             operators = self.lookup_users(auth_table, person_ids, "tech")
332             geni_info['operator'] = operators
333             # TODO: OrganizationName
334
335             auth_table = self.auth.get_auth_table(record.get_name())
336             person_ids = record.pl_info.get("person_ids", [])
337             owners = self.lookup_users(auth_table, person_ids, "admin")
338             geni_info['owner'] = owners
339
340         elif (type == "node"):
341             geni_info['dns'] = record.pl_info.get("hostname", "")
342             # TODO: URI, LatLong, IP, DNS
343     
344         elif (type == "user"):
345             geni_info['email'] = record.pl_info.get("email", "")
346             # TODO: PostalAddress, Phone
347
348         record.set_geni_info(geni_info)
349
350     def fill_record_info(self, record):
351         """
352         Given a geni record, fill in the PLC specific and Geni specific
353         fields in the record. 
354         """
355         self.fill_record_pl_info(record)
356         self.fill_record_geni_info(record)
357
358     def update_membership_list(self, oldRecord, record, listName, addFunc, delFunc):
359         # get a list of the HRNs tht are members of the old and new records^M
360         if oldRecord:
361             if oldRecord.pl_info == None:
362                 oldRecord.pl_info = {}
363             oldList = oldRecord.get_geni_info().get(listName, [])
364         else:
365             oldList = []
366         newList = record.get_geni_info().get(listName, [])
367
368         # if the lists are the same, then we don't have to update anything
369         if (oldList == newList):
370             return
371
372         # build a list of the new person ids, by looking up each person to get
373         # their pointer
374         newIdList = []
375         for hrn in newList:
376             userRecord = self.resolve_raw("user", hrn)[0]
377             newIdList.append(userRecord.get_pointer())
378
379         # build a list of the old person ids from the person_ids field of the
380         # pl_info
381         if oldRecord:
382             oldIdList = oldRecord.plinfo.get("person_ids", [])
383             containerId = oldRecord.get_pointer()
384         else:
385             # if oldRecord==None, then we are doing a Register, instead of an
386             # update.
387             oldIdList = []
388             containerId = record.get_pointer()
389
390     # add people who are in the new list, but not the oldList
391         for personId in newIdList:
392             if not (personId in oldIdList):
393                 print "adding id", personId, "to", record.get_name()
394                 addFunc(self.plauth, personId, containerId)
395
396         # remove people who are in the old list, but not the new list
397         for personId in oldIdList:
398             if not (personId in newIdList):
399                 print "removing id", personId, "from", record.get_name()
400                 delFunc(self.plauth, personId, containerId)
401
402     def update_membership(self, oldRecord, record):
403         if record.type == "slice":
404             self.update_membership_list(oldRecord, record, 'researcher',
405                                         self.plshell.AddPersonToSlice,
406                                         self.plshell.DeletePersonFromSlice)
407         elif record.type == "sa":
408             # TODO
409             pass
410         elif record.type == "ma":
411             # TODO
412             pass
413  
414
415     def callable(self, method):
416         """
417         Return a new instance of the specified method.
418         """
419         # Look up method
420         if method not in self.methods:
421             raise GeniInvalidAPIMethod, method
422         
423         # Get new instance of method
424         try:
425             classname = method.split(".")[-1]
426             module = __import__("geni.methods." + method, globals(), locals(), [classname])
427             callablemethod = getattr(module, classname)(self)
428             return getattr(module, classname)(self)
429         except ImportError, AttributeError:
430             raise GeniInvalidAPIMethod, method
431
432     def call(self, source, method, *args):
433         """
434         Call the named method from the specified source with the
435         specified arguments.
436         """
437         function = self.callable(method)
438         function.source = source
439         return function(*args)
440
441     def handle(self, source, data):
442         """
443         Handle an XML-RPC or SOAP request from the specified source.
444         """
445
446         # Parse request into method name and arguments
447         try:
448             interface = xmlrpclib
449             (args, method) = xmlrpclib.loads(data)
450             methodresponse = True
451         except Exception, e:
452             if SOAPpy is not None:
453                 interface = SOAPpy
454                 (r, header, body, attrs) = parseSOAPRPC(data, header = 1, body = 1, attrs = 1)
455                 method = r._name
456                 args = r._aslist()
457                 # XXX Support named arguments
458             else:
459                 raise e
460
461         try:
462             result = self.call(source, method, *args)
463         except Exception, fault:
464             traceback.print_exc(file = log)
465             # Handle expected faults
466             if interface == xmlrpclib:
467                 result = fault
468                 methodresponse = None
469             elif interface == SOAPpy:
470                 result = faultParameter(NS.ENV_T + ":Server", "Method Failed", method)
471                 result._setDetail("Fault %d: %s" % (fault.faultCode, fault.faultString))
472
473         # Return result
474         if interface == xmlrpclib:
475             if not isinstance(result, GeniFault):
476                 result = (result,)
477
478             data = xmlrpclib.dumps(result, methodresponse = True, encoding = self.encoding, allow_none = 1)
479         elif interface == SOAPpy:
480             data = buildSOAP(kw = {'%sResponse' % method: {'Result': result}}, encoding = self.encoding)
481
482         return data