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