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