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