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