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