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