b501fd723c954bd3eaf59a1d557c48c031bf6a71
[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 import geni.methods
87
88 def import_deep(name):
89     mod = __import__(name)
90     components = name.split('.')
91     for comp in components[1:]:
92         mod = getattr(mod, comp)
93     return mod
94
95 class GeniAPI:
96
97     # flat list of method names
98     methods = geni.methods.methods
99     
100     def __init__(self, config = "/usr/share/geniwrapper/geni/util/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 = 'sa'
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         # determine the type of credential that we want to use as a parent for
192         # this credential.
193
194         if (type == "ma") or (type == "node"):
195             auth_kind = "authority,ma"
196         else: # user, slice, sa
197             auth_kind = "authority,sa"
198
199         new_cred.set_parent(self.auth.hierarchy.get_auth_cred(auth_hrn, kind=auth_kind))
200
201         new_cred.encode()
202         new_cred.sign()
203
204         return new_cred
205    
206
207     def loadCredential(self):
208         """
209         Attempt to load credential from file if it exists. If it doesnt get
210         credential from registry.
211         """
212
213         # see if this file exists
214         # XX This is really the aggregate's credential. Using this is easier than getting
215         # the registry's credential from iteslf (ssl errors).   
216         ma_cred_filename = self.server_basedir + os.sep + self.interface + self.hrn + ".ma.cred"
217         try:
218             self.credential = Credential(filename = ma_cred_filename)
219         except IOError:
220             self.credential = self.getCredentialFromRegistry()
221       
222     ##
223     # Convert geni fields to PLC fields for use when registering up updating
224     # registry record in the PLC database
225     #
226     # @param type type of record (user, slice, ...)
227     # @param hrn human readable name
228     # @param geni_fields dictionary of geni fields
229     # @param pl_fields dictionary of PLC fields (output)
230
231     def geni_fields_to_pl_fields(self, type, hrn, geni_fields, pl_fields):
232         if type == "user":
233             if not "email" in pl_fields:
234                 if not "email" in geni_fields:
235                     raise MissingGeniInfo("email")
236                 pl_fields["email"] = geni_fields["email"]
237
238             if not "first_name" in pl_fields:
239                 pl_fields["first_name"] = "geni"
240
241             if not "last_name" in pl_fields:
242                 pl_fields["last_name"] = hrn
243
244         elif type == "slice":
245             if not "instantiation" in pl_fields:
246                 pl_fields["instantiation"] = "delegated"  # "plc-instantiated"
247             if not "name" in pl_fields:
248                 pl_fields["name"] = hrn_to_pl_slicename(hrn)
249             if not "max_nodes" in pl_fields:
250                 pl_fields["max_nodes"] = 10
251
252         elif type == "node":
253             if not "hostname" in pl_fields:
254                 if not "dns" in geni_fields:
255                     raise MissingGeniInfo("dns")
256                 pl_fields["hostname"] = geni_fields["dns"]
257             if not "model" in pl_fields:
258                 pl_fields["model"] = "geni"
259
260         elif type == "sa":
261             pl_fields["login_base"] = hrn_to_pl_login_base(hrn)
262
263             if not "name" in pl_fields:
264                 pl_fields["name"] = hrn
265
266             if not "abbreviated_name" in pl_fields:
267                 pl_fields["abbreviated_name"] = hrn
268
269             if not "enabled" in pl_fields:
270                 pl_fields["enabled"] = True
271
272             if not "is_public" in pl_fields:
273                 pl_fields["is_public"] = True
274
275
276  
277     def fill_record_pl_info(self, record):
278         """
279         Fill in the planetlab specific fields of a Geni record. This
280         involves calling the appropraite PLC method to retrie the 
281         dtabase record for the object.
282         
283         PLC data is filled into the pl_fino field of the record.
284     
285         @param record record to fill in field (in/out param)     
286         """
287         type = record.get_type()
288         pointer = record.get_pointer()
289
290         # records with pointer==-1 do not have plc info associated with them.
291         # for example, the top level authority records which are
292         # authorities, but not PL "sites"
293         if pointer == -1:
294             record.set_pl_info({})
295             return
296
297         if (type == "sa") or (type == "ma"):
298             pl_res = self.plshell.GetSites(self.plauth, [pointer])
299         elif (type == "slice"):
300             pl_res = self.plshell.GetSlices(self.plauth, [pointer])
301         elif (type == "user"):
302             pl_res = self.plshell.GetPersons(self.plauth, [pointer])
303             key_ids = pl_res[0]['key_ids']
304             keys = self.plshell.GetKeys(self.plauth, key_ids)
305             pubkeys = []
306             if keys:
307                 pubkeys = [key['key'] for key in keys]
308             pl_res[0]['keys'] = pubkeys
309         elif (type == "node"):
310             pl_res = self.plshell.GetNodes(self.plauth, [pointer])
311         else:
312             raise UnknownGeniType(type)
313
314         if not pl_res:
315             # the planetlab record no longer exists
316             # TODO: delete the geni record ?
317             raise PlanetLabRecordDoesNotExist(record.get_name())
318
319         record.set_pl_info(pl_res[0])
320
321
322     def lookup_users(self, auth_table, user_id_list, role="*"):
323         record_list = []
324         for person_id in user_id_list:
325             user_records = auth_table.find("user", person_id, "pointer")
326             for user_record in user_records:
327                 self.fill_record_info(user_record)
328
329                 user_roles = user_record.get_pl_info().get("roles")
330                 if (role=="*") or (role in user_roles):
331                     record_list.append(user_record.get_name())
332         return record_list
333
334     def fill_record_geni_info(self, record):
335         geni_info = {}
336         type = record.get_type()
337
338         if (type == "slice"):
339             auth_table = self.auth.get_auth_table(self.auth.get_authority(record.get_name()))
340             person_ids = record.pl_info.get("person_ids", [])
341             researchers = self.lookup_users(auth_table, person_ids)
342             geni_info['researcher'] = researchers
343
344         elif (type == "sa"):
345             auth_table = self.auth.get_auth_table(record.get_name())
346             person_ids = record.pl_info.get("person_ids", [])
347             pis = self.lookup_users(auth_table, person_ids, "pi")
348             geni_info['pi'] = pis
349             # TODO: OrganizationName
350
351         elif (type == "ma"):
352             auth_table = self.auth.get_auth_table(record.get_name())
353             person_ids = record.pl_info.get("person_ids", [])
354             operators = self.lookup_users(auth_table, person_ids, "tech")
355             geni_info['operator'] = operators
356             # TODO: OrganizationName
357
358             auth_table = self.auth.get_auth_table(record.get_name())
359             person_ids = record.pl_info.get("person_ids", [])
360             owners = self.lookup_users(auth_table, person_ids, "admin")
361             geni_info['owner'] = owners
362
363         elif (type == "node"):
364             geni_info['dns'] = record.pl_info.get("hostname", "")
365             # TODO: URI, LatLong, IP, DNS
366     
367         elif (type == "user"):
368             geni_info['email'] = record.pl_info.get("email", "")
369             # TODO: PostalAddress, Phone
370
371         record.set_geni_info(geni_info)
372
373     def fill_record_info(self, record):
374         """
375         Given a geni record, fill in the PLC specific and Geni specific
376         fields in the record. 
377         """
378         self.fill_record_pl_info(record)
379         self.fill_record_geni_info(record)
380
381     def update_membership_list(self, oldRecord, record, listName, addFunc, delFunc):
382         # get a list of the HRNs tht are members of the old and new records^M
383         if oldRecord:
384             if oldRecord.pl_info == None:
385                 oldRecord.pl_info = {}
386             oldList = oldRecord.get_geni_info().get(listName, [])
387         else:
388             oldList = []
389         newList = record.get_geni_info().get(listName, [])
390
391         # if the lists are the same, then we don't have to update anything
392         if (oldList == newList):
393             return
394
395         # build a list of the new person ids, by looking up each person to get
396         # their pointer
397         newIdList = []
398         for hrn in newList:
399             auth_hrn = self.auth.get_authority(hrn)
400             if not auth_hrn:
401                 auth_hrn = hrn
402             auth_info = self.auth.get_auth_info(auth_hrn)
403             table = self.auth.get_auth_table(auth_hrn)
404             records = table.resolve('user', hrn)
405             if records:
406                 userRecord = records[0]    
407                 newIdList.append(userRecord.get_pointer())
408
409         # build a list of the old person ids from the person_ids field of the
410         # pl_info
411         if oldRecord:
412             oldIdList = oldRecord.plinfo.get("person_ids", [])
413             containerId = oldRecord.get_pointer()
414         else:
415             # if oldRecord==None, then we are doing a Register, instead of an
416             # update.
417             oldIdList = []
418             containerId = record.get_pointer()
419
420     # add people who are in the new list, but not the oldList
421         for personId in newIdList:
422             if not (personId in oldIdList):
423                 print "adding id", personId, "to", record.get_name()
424                 addFunc(self.plauth, personId, containerId)
425
426         # remove people who are in the old list, but not the new list
427         for personId in oldIdList:
428             if not (personId in newIdList):
429                 print "removing id", personId, "from", record.get_name()
430                 delFunc(self.plauth, personId, containerId)
431
432     def update_membership(self, oldRecord, record):
433         if record.type == "slice":
434             self.update_membership_list(oldRecord, record, 'researcher',
435                                         self.plshell.AddPersonToSlice,
436                                         self.plshell.DeletePersonFromSlice)
437         elif record.type == "sa":
438             # TODO
439             pass
440         elif record.type == "ma":
441             # TODO
442             pass
443  
444
445     def callable(self, method):
446         """
447         Return a new instance of the specified method.
448         """
449         # Look up method
450         if method not in self.methods:
451             raise GeniInvalidAPIMethod, method
452         
453         # Get new instance of method
454         try:
455             classname = method.split(".")[-1]
456             module = __import__("geni.methods." + method, globals(), locals(), [classname])
457             callablemethod = getattr(module, classname)(self)
458             return getattr(module, classname)(self)
459         except ImportError, AttributeError:
460             raise
461             raise GeniInvalidAPIMethod, method
462
463     def call(self, source, method, *args):
464         """
465         Call the named method from the specified source with the
466         specified arguments.
467         """
468         function = self.callable(method)
469         function.source = source
470         return function(*args)
471
472     def handle(self, source, data):
473         """
474         Handle an XML-RPC or SOAP request from the specified source.
475         """
476
477         # Parse request into method name and arguments
478         try:
479             interface = xmlrpclib
480             (args, method) = xmlrpclib.loads(data)
481             methodresponse = True
482         except Exception, e:
483             if SOAPpy is not None:
484                 interface = SOAPpy
485                 (r, header, body, attrs) = parseSOAPRPC(data, header = 1, body = 1, attrs = 1)
486                 method = r._name
487                 args = r._aslist()
488                 # XXX Support named arguments
489             else:
490                 raise e
491
492         try:
493             result = self.call(source, method, *args)
494         except Exception, fault:
495             traceback.print_exc(file = log)
496             # Handle expected faults
497             if interface == xmlrpclib:
498                 result = fault
499                 methodresponse = None
500             elif interface == SOAPpy:
501                 result = faultParameter(NS.ENV_T + ":Server", "Method Failed", method)
502                 result._setDetail("Fault %d: %s" % (fault.faultCode, fault.faultString))
503
504         # Return result
505         if interface == xmlrpclib:
506             if not isinstance(result, GeniFault):
507                 result = (result,)
508
509             data = xmlrpclib.dumps(result, methodresponse = True, encoding = self.encoding, allow_none = 1)
510         elif interface == SOAPpy:
511             data = buildSOAP(kw = {'%sResponse' % method: {'Result': result}}, encoding = self.encoding)
512
513         return data