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