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