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