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