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