2 # Geniwrapper XML-RPC and SOAP interfaces
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 # See "2.2 Characters" in the XML specification:
19 # #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD]
21 # [#x7F-#x84], [#x86-#x9F], [#xFDD0-#xFDDF]
23 invalid_xml_ascii = map(chr, range(0x0, 0x8) + [0xB, 0xC] + range(0xE, 0x1F))
24 xml_escape_table = string.maketrans("".join(invalid_xml_ascii), "?" * len(invalid_xml_ascii))
26 def xmlrpclib_escape(s, replace = string.replace):
28 xmlrpclib does not handle invalid 7-bit control characters. This
29 function augments xmlrpclib.escape, which by default only replaces
30 '&', '<', and '>' with entities.
33 # This is the standard xmlrpclib.escape function
34 s = replace(s, "&", "&")
35 s = replace(s, "<", "<")
36 s = replace(s, ">", ">",)
38 # Replace invalid 7-bit control characters with '?'
39 return s.translate(xml_escape_table)
41 def xmlrpclib_dump(self, value, write):
43 xmlrpclib cannot marshal instances of subclasses of built-in
44 types. This function overrides xmlrpclib.Marshaller.__dump so that
45 any value that is an instance of one of its acceptable types is
46 marshalled as that type.
48 xmlrpclib also cannot handle invalid 7-bit control characters. See
52 # Use our escape function
53 args = [self, value, write]
54 if isinstance(value, (str, unicode)):
55 args.append(xmlrpclib_escape)
58 # Try for an exact match first
59 f = self.dispatch[type(value)]
62 # Try for an isinstance() match
63 for Type, f in self.dispatch.iteritems():
64 if isinstance(value, Type):
67 raise TypeError, "cannot marshal %s objects" % type(value)
71 # You can't hide from me!
72 xmlrpclib.Marshaller._Marshaller__dump = xmlrpclib_dump
74 # SOAP support is optional
77 from SOAPpy.Parser import parseSOAPRPC
78 from SOAPpy.Types import faultType
79 from SOAPpy.NS import NS
80 from SOAPpy.SOAPBuilder import buildSOAP
86 def import_deep(name):
87 mod = __import__(name)
88 components = name.split('.')
89 for comp in components[1:]:
90 mod = getattr(mod, comp)
95 # flat list of method names
96 methods = geni.methods.methods
98 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):
99 self.encoding = encoding
101 # Better just be documenting the API
106 self.config = Config(config)
107 self.auth = Auth(peer_cert)
108 self.interface = interface
109 self.key_file = key_file
110 self.cert_file = cert_file
111 self.credential = None
112 self.plshell = self.getPLCShell()
113 self.basedir = self.config.GENI_BASE_DIR + os.sep
114 self.server_basedir = self.basedir + os.sep + "geni" + os.sep
115 self.hrn = self.config.GENI_INTERFACE_HRN
116 self.time_format = "%Y-%m-%d %H:%M:%S"
119 def getPLCShell(self):
120 self.plauth = {'Username': self.config.GENI_PLC_USER,
121 'AuthMethod': 'password',
122 'AuthString': self.config.GENI_PLC_PASSWORD}
125 shell = PLC.Shell.Shell(globals = globals())
126 shell.AuthCheck(self.plauth)
130 plc_host = self.config.GENI_PLC_HOST
131 plc_port = self.config.GENI_PLC_PORT
132 plc_api_path = self.config.GENI_PLC_API_PATH
133 url = "https://%(plc_host)s:%(plc_port)s/%(plc_api_path)s/" % \
136 shell = xmlrpclib.Server(url, verbose = 0, allow_none = True)
137 shell.AuthCheck(self.plauth)
140 def getCredential(self):
141 return self.getCredentialFromRegistry()
143 def getCredentialFromRegistry(self):
145 Get our current credential from the local registry.
149 auth_hrn = self.auth.get_authority(hrn)
152 auth_info = self.auth.get_auth_info(auth_hrn)
153 table = self.auth.get_auth_table(auth_hrn)
154 records = table.resolve('*', hrn)
158 type = record.get_type()
159 object_gid = record.get_gid_object()
160 new_cred = Credential(subject = object_gid.get_subject())
161 new_cred.set_gid_caller(object_gid)
162 new_cred.set_gid_object(object_gid)
163 new_cred.set_issuer(key=auth_info.get_pkey_object(), subject=auth_hrn)
164 new_cred.set_pubkey(object_gid.get_pubkey())
165 r1 = determine_rights(type, hrn)
166 new_cred.set_privileges(r1)
168 # determine the type of credential that we want to use as a parent for
171 if (type == "ma") or (type == "node"):
172 auth_kind = "authority,ma"
173 else: # user, slice, sa
174 auth_kind = "authority,sa"
176 new_cred.set_parent(self.auth.hierarchy.get_auth_cred(auth_hrn, kind=auth_kind))
184 def loadCredential(self):
186 Attempt to load credential from file if it exists. If it doesnt get
187 credential from registry.
190 # see if this file exists
191 # XX This is really the aggregate's credential. Using this is easier than getting
192 # the registry's credential from iteslf (ssl errors).
193 ma_cred_filename = self.server_basedir + os.sep + self.interface + self.hrn + ".ma.cred"
195 self.credential = Credential(filename = ma_cred_filename)
197 self.credential = self.getCredentialFromRegistry()
200 # Convert geni fields to PLC fields for use when registering up updating
201 # registry record in the PLC database
203 # @param type type of record (user, slice, ...)
204 # @param hrn human readable name
205 # @param geni_fields dictionary of geni fields
206 # @param pl_fields dictionary of PLC fields (output)
208 def geni_fields_to_pl_fields(self, type, hrn, geni_fields, pl_fields):
210 if not "email" in pl_fields:
211 if not "email" in geni_fields:
212 raise MissingGeniInfo("email")
213 pl_fields["email"] = geni_fields["email"]
215 if not "first_name" in pl_fields:
216 pl_fields["first_name"] = "geni"
218 if not "last_name" in pl_fields:
219 pl_fields["last_name"] = hrn
221 elif type == "slice":
222 if not "instantiation" in pl_fields:
223 pl_fields["instantiation"] = "delegated" # "plc-instantiated"
224 if not "name" in pl_fields:
225 pl_fields["name"] = hrn_to_pl_slicename(hrn)
226 if not "max_nodes" in pl_fields:
227 pl_fields["max_nodes"] = 10
230 if not "hostname" in pl_fields:
231 if not "dns" in geni_fields:
232 raise MissingGeniInfo("dns")
233 pl_fields["hostname"] = geni_fields["dns"]
234 if not "model" in pl_fields:
235 pl_fields["model"] = "geni"
238 pl_fields["login_base"] = hrn_to_pl_login_base(hrn)
240 if not "name" in pl_fields:
241 pl_fields["name"] = hrn
243 if not "abbreviated_name" in pl_fields:
244 pl_fields["abbreviated_name"] = hrn
246 if not "enabled" in pl_fields:
247 pl_fields["enabled"] = True
249 if not "is_public" in pl_fields:
250 pl_fields["is_public"] = True
254 def fill_record_pl_info(self, record):
256 Fill in the planetlab specific fields of a Geni record. This
257 involves calling the appropraite PLC method to retrie the
258 dtabase record for the object.
260 PLC data is filled into the pl_fino field of the record.
262 @param record record to fill in field (in/out param)
264 type = record.get_type()
265 pointer = record.get_pointer()
267 # records with pointer==-1 do not have plc info associated with them.
268 # for example, the top level authority records which are
269 # authorities, but not PL "sites"
271 record.set_pl_info({})
274 if (type == "sa") or (type == "ma"):
275 pl_res = self.plshell.GetSites(self.plauth, [pointer])
276 elif (type == "slice"):
277 pl_res = self.plshell.GetSlices(self.plauth, [pointer])
278 elif (type == "user"):
279 pl_res = self.plshell.GetPersons(self.plauth, [pointer])
280 key_ids = pl_res[0]['key_ids']
281 keys = self.plshell.GetKeys(self.plauth, key_ids)
284 pubkeys = [key['key'] for key in keys]
285 pl_res[0]['keys'] = pubkeys
286 elif (type == "node"):
287 pl_res = self.plshell.GetNodes(self.plauth, [pointer])
289 raise UnknownGeniType(type)
292 # the planetlab record no longer exists
293 # TODO: delete the geni record ?
294 raise PlanetLabRecordDoesNotExist(record.get_name())
296 record.set_pl_info(pl_res[0])
299 def lookup_users(self, auth_table, user_id_list, role="*"):
301 for person_id in user_id_list:
302 user_records = auth_table.find("user", person_id, "pointer")
303 for user_record in user_records:
304 self.fill_record_info(user_record)
306 user_roles = user_record.get_pl_info().get("roles")
307 if (role=="*") or (role in user_roles):
308 record_list.append(user_record.get_name())
311 def fill_record_geni_info(self, record):
313 type = record.get_type()
315 if (type == "slice"):
316 auth_table = self.auth.get_auth_table(self.auth.get_authority(record.get_name()))
317 person_ids = record.pl_info.get("person_ids", [])
318 researchers = self.lookup_users(auth_table, person_ids)
319 geni_info['researcher'] = researchers
322 auth_table = self.auth.get_auth_table(record.get_name())
323 person_ids = record.pl_info.get("person_ids", [])
324 pis = self.lookup_users(auth_table, person_ids, "pi")
325 geni_info['pi'] = pis
326 # TODO: OrganizationName
329 auth_table = self.auth.get_auth_table(record.get_name())
330 person_ids = record.pl_info.get("person_ids", [])
331 operators = self.lookup_users(auth_table, person_ids, "tech")
332 geni_info['operator'] = operators
333 # TODO: OrganizationName
335 auth_table = self.auth.get_auth_table(record.get_name())
336 person_ids = record.pl_info.get("person_ids", [])
337 owners = self.lookup_users(auth_table, person_ids, "admin")
338 geni_info['owner'] = owners
340 elif (type == "node"):
341 geni_info['dns'] = record.pl_info.get("hostname", "")
342 # TODO: URI, LatLong, IP, DNS
344 elif (type == "user"):
345 geni_info['email'] = record.pl_info.get("email", "")
346 # TODO: PostalAddress, Phone
348 record.set_geni_info(geni_info)
350 def fill_record_info(self, record):
352 Given a geni record, fill in the PLC specific and Geni specific
353 fields in the record.
355 self.fill_record_pl_info(record)
356 self.fill_record_geni_info(record)
358 def update_membership_list(self, oldRecord, record, listName, addFunc, delFunc):
359 # get a list of the HRNs tht are members of the old and new records^M
361 if oldRecord.pl_info == None:
362 oldRecord.pl_info = {}
363 oldList = oldRecord.get_geni_info().get(listName, [])
366 newList = record.get_geni_info().get(listName, [])
368 # if the lists are the same, then we don't have to update anything
369 if (oldList == newList):
372 # build a list of the new person ids, by looking up each person to get
376 userRecord = self.resolve_raw("user", hrn)[0]
377 newIdList.append(userRecord.get_pointer())
379 # build a list of the old person ids from the person_ids field of the
382 oldIdList = oldRecord.plinfo.get("person_ids", [])
383 containerId = oldRecord.get_pointer()
385 # if oldRecord==None, then we are doing a Register, instead of an
388 containerId = record.get_pointer()
390 # add people who are in the new list, but not the oldList
391 for personId in newIdList:
392 if not (personId in oldIdList):
393 print "adding id", personId, "to", record.get_name()
394 addFunc(self.plauth, personId, containerId)
396 # remove people who are in the old list, but not the new list
397 for personId in oldIdList:
398 if not (personId in newIdList):
399 print "removing id", personId, "from", record.get_name()
400 delFunc(self.plauth, personId, containerId)
402 def update_membership(self, oldRecord, record):
403 if record.type == "slice":
404 self.update_membership_list(oldRecord, record, 'researcher',
405 self.plshell.AddPersonToSlice,
406 self.plshell.DeletePersonFromSlice)
407 elif record.type == "sa":
410 elif record.type == "ma":
415 def callable(self, method):
417 Return a new instance of the specified method.
420 if method not in self.methods:
421 raise GeniInvalidAPIMethod, method
423 # Get new instance of method
425 classname = method.split(".")[-1]
426 module = __import__("geni.methods." + method, globals(), locals(), [classname])
427 callablemethod = getattr(module, classname)(self)
428 return getattr(module, classname)(self)
429 except ImportError, AttributeError:
430 raise GeniInvalidAPIMethod, method
432 def call(self, source, method, *args):
434 Call the named method from the specified source with the
437 function = self.callable(method)
438 function.source = source
439 return function(*args)
441 def handle(self, source, data):
443 Handle an XML-RPC or SOAP request from the specified source.
446 # Parse request into method name and arguments
448 interface = xmlrpclib
449 (args, method) = xmlrpclib.loads(data)
450 methodresponse = True
452 if SOAPpy is not None:
454 (r, header, body, attrs) = parseSOAPRPC(data, header = 1, body = 1, attrs = 1)
457 # XXX Support named arguments
462 result = self.call(source, method, *args)
463 except Exception, fault:
464 traceback.print_exc(file = log)
465 # Handle expected faults
466 if interface == xmlrpclib:
468 methodresponse = None
469 elif interface == SOAPpy:
470 result = faultParameter(NS.ENV_T + ":Server", "Method Failed", method)
471 result._setDetail("Fault %d: %s" % (fault.faultCode, fault.faultString))
474 if interface == xmlrpclib:
475 if not isinstance(result, GeniFault):
478 data = xmlrpclib.dumps(result, methodresponse = True, encoding = self.encoding, allow_none = 1)
479 elif interface == SOAPpy:
480 data = buildSOAP(kw = {'%sResponse' % method: {'Result': result}}, encoding = self.encoding)