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