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 from geni.util.misc import *
19 # See "2.2 Characters" in the XML specification:
21 # #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD]
23 # [#x7F-#x84], [#x86-#x9F], [#xFDD0-#xFDDF]
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))
28 def xmlrpclib_escape(s, replace = string.replace):
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.
35 # This is the standard xmlrpclib.escape function
36 s = replace(s, "&", "&")
37 s = replace(s, "<", "<")
38 s = replace(s, ">", ">",)
40 # Replace invalid 7-bit control characters with '?'
41 return s.translate(xml_escape_table)
43 def xmlrpclib_dump(self, value, write):
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.
50 xmlrpclib also cannot handle invalid 7-bit control characters. See
54 # Use our escape function
55 args = [self, value, write]
56 if isinstance(value, (str, unicode)):
57 args.append(xmlrpclib_escape)
60 # Try for an exact match first
61 f = self.dispatch[type(value)]
64 # Try for an isinstance() match
65 for Type, f in self.dispatch.iteritems():
66 if isinstance(value, Type):
69 raise TypeError, "cannot marshal %s objects" % type(value)
73 # You can't hide from me!
74 xmlrpclib.Marshaller._Marshaller__dump = xmlrpclib_dump
76 # SOAP support is optional
79 from SOAPpy.Parser import parseSOAPRPC
80 from SOAPpy.Types import faultType
81 from SOAPpy.NS import NS
82 from SOAPpy.SOAPBuilder import buildSOAP
87 def import_deep(name):
88 mod = __import__(name)
89 components = name.split('.')
90 for comp in components[1:]:
91 mod = getattr(mod, comp)
96 # flat list of method names
98 methods = geni.methods.all
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
103 # Better just be documenting the API
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"
122 def getPLCShell(self):
123 self.plauth = {'Username': self.config.GENI_PLC_USER,
124 'AuthMethod': 'password',
125 'AuthString': self.config.GENI_PLC_PASSWORD}
128 shell = PLC.Shell.Shell(globals = globals())
129 shell.AuthCheck(self.plauth)
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/" % locals()
138 shell = xmlrpclib.Server(url, verbose = 0, allow_none = True)
139 shell.AuthCheck(self.plauth)
142 def getPLCShellVersion(self):
143 # We need to figure out what version of PLCAPI we are talking to.
144 # Some calls we need to make later will be different depending on
147 # This is probably a bad way to determine api versions
148 # but its easy and will work for now. Lets try to make
149 # a call that only exists is PLCAPI.4.3. If it fails, we
150 # can assume the api version is 4.2
151 self.plshell.GetTagTypes(self.plauth)
157 def getCredential(self):
158 if self.interface in ['registry']:
159 return self.getCredentialFromLocalRegistry()
161 return self.getCredentialFromRegistry()
164 def getCredentialFromRegistry(self):
166 Get our credential from a remote registry using a geniclient connection
169 path = self.config.basepath
170 filename = ".".join([self.interface, self.hrn, type, "cred"])
171 cred_filename = path + os.sep + filename
173 credential = Credential(filename = cred_filename)
176 from geni.registry import Registries
177 registries = Registries(self)
178 registry = registries[self.hrn]
179 self_cred = registry.get_credential(None, type, self.hrn)
180 cred = registry.get_credential(self_cred, type, self.hrn)
181 cred.save_to_file(cred_filename, save_parents=True)
184 def getCredentialFromLocalRegistry(self):
186 Get our current credential directly from the local registry.
190 auth_hrn = self.auth.get_authority(hrn)
193 auth_info = self.auth.get_auth_info(auth_hrn)
194 table = self.auth.get_auth_table(auth_hrn)
195 records = table.resolve('*', hrn)
199 type = record.get_type()
200 object_gid = record.get_gid_object()
201 new_cred = Credential(subject = object_gid.get_subject())
202 new_cred.set_gid_caller(object_gid)
203 new_cred.set_gid_object(object_gid)
204 new_cred.set_issuer(key=auth_info.get_pkey_object(), subject=auth_hrn)
205 new_cred.set_pubkey(object_gid.get_pubkey())
206 r1 = determine_rights(type, hrn)
207 new_cred.set_privileges(r1)
209 auth_kind = "authority,ma,sa"
211 new_cred.set_parent(self.auth.hierarchy.get_auth_cred(auth_hrn, kind=auth_kind))
219 def loadCredential(self):
221 Attempt to load credential from file if it exists. If it doesnt get
222 credential from registry.
225 # see if this file exists
226 # XX This is really the aggregate's credential. Using this is easier than getting
227 # the registry's credential from iteslf (ssl errors).
228 ma_cred_filename = self.server_basedir + os.sep + self.interface + self.hrn + ".ma.cred"
230 self.credential = Credential(filename = ma_cred_filename)
232 self.credential = self.getCredentialFromRegistry()
235 # Convert geni fields to PLC fields for use when registering up updating
236 # registry record in the PLC database
238 # @param type type of record (user, slice, ...)
239 # @param hrn human readable name
240 # @param geni_fields dictionary of geni fields
241 # @param pl_fields dictionary of PLC fields (output)
243 def geni_fields_to_pl_fields(self, type, hrn, geni_fields, pl_fields):
245 if not "email" in pl_fields:
246 if not "email" in geni_fields:
247 raise MissingGeniInfo("email")
248 pl_fields["email"] = geni_fields["email"]
250 if not "first_name" in pl_fields:
251 pl_fields["first_name"] = "geni"
253 if not "last_name" in pl_fields:
254 pl_fields["last_name"] = hrn
256 elif type == "slice":
257 if not "instantiation" in pl_fields:
258 pl_fields["instantiation"] = "delegated" # "plc-instantiated"
259 if not "name" in pl_fields:
260 pl_fields["name"] = hrn_to_pl_slicename(hrn)
261 if not "max_nodes" in pl_fields:
262 pl_fields["max_nodes"] = 10
265 if not "hostname" in pl_fields:
266 if not "dns" in geni_fields:
267 raise MissingGeniInfo("dns")
268 pl_fields["hostname"] = geni_fields["dns"]
269 if not "model" in pl_fields:
270 pl_fields["model"] = "geni"
272 elif type == "authority":
273 pl_fields["login_base"] = hrn_to_pl_login_base(hrn)
275 if not "name" in pl_fields:
276 pl_fields["name"] = hrn
278 if not "abbreviated_name" in pl_fields:
279 pl_fields["abbreviated_name"] = hrn
281 if not "enabled" in pl_fields:
282 pl_fields["enabled"] = True
284 if not "is_public" in pl_fields:
285 pl_fields["is_public"] = True
289 def fill_record_pl_info(self, record):
291 Fill in the planetlab specific fields of a Geni record. This
292 involves calling the appropriate PLC method to retrieve the
293 database record for the object.
295 PLC data is filled into the pl_info field of the record.
297 @param record: record to fill in field (in/out param)
299 type = record.get_type()
300 pointer = record.get_pointer()
303 # records with pointer==-1 do not have plc info associated with them.
304 # for example, the top level authority records which are
305 # authorities, but not PL "sites"
310 if (type in ["authority", "sa", "ma"]):
311 pl_res = self.plshell.GetSites(self.plauth, [pointer])
312 elif (type == "slice"):
313 pl_res = self.plshell.GetSlices(self.plauth, [pointer])
314 elif (type == "user"):
315 pl_res = self.plshell.GetPersons(self.plauth, [pointer])
316 elif (type == "node"):
317 pl_res = self.plshell.GetNodes(self.plauth, [pointer])
319 raise UnknownGeniType(type)
322 raise PlanetLabRecordDoesNotExist(record.get_name())
324 # convert ids to hrns
325 pl_record = pl_res[0]
326 if 'site_id' in pl_record:
327 sites = self.plshell.GetSites(self.plauth, pl_record['site_id'], ['login_base'])
329 login_base = site['login_base']
330 pl_record['site'] = ".".join([auth_hrn, login_base])
331 if 'person_ids' in pl_record:
332 persons = self.plshell.GetPersons(self.plauth, pl_record['person_ids'], ['email'])
333 emails = [person['email'] for person in persons]
334 usernames = [email.split('@')[0] for email in emails]
335 person_hrns = [".".join([auth_hrn, login_base, username]) for username in usernames]
336 pl_record['persons'] = person_hrns
337 if 'slice_ids' in pl_record:
338 slices = self.plshell.GetSlices(self.plauth, pl_record['slice_ids'], ['name'])
339 slicenames = [slice['name'] for slice in slices]
340 slice_hrns = [slicename_to_hrn(auth_hrn, slicename) for slicename in slicenames]
341 pl_record['slices'] = slice_hrns
342 if 'node_ids' in pl_record:
343 nodes = self.plshell.GetNodes(self.plauth, pl_record['node_ids'], ['hostname'])
344 hostnames = [node['hostname'] for node in nodes]
345 node_hrns = [hostname_to_hrn(auth_hrn, login_base, hostname) for hostname in hostnames]
346 pl_record['nodes'] = node_hrns
347 if 'site_ids' in pl_record:
348 sites = self.plshell.GetSites(self.plauth, pl_record['site_ids'], ['login_base'])
349 login_bases = [site['login_base'] for site in sites]
350 site_hrns = [".".join([auth_hrn, lbase]) for lbase in login_bases]
351 pl_record['sites'] = site_hrns
352 if 'key_ids' in pl_record:
353 keys = self.plshell.GetKeys(self.plauth, pl_record['key_ids'])
356 pubkeys = [key['key'] for key in keys]
357 pl_record['keys'] = pubkeys
359 record.update(pl_record)
362 def lookup_users(self, auth_table, user_id_list, role="*"):
364 for person_id in user_id_list:
365 user_records = auth_table.find("user", person_id, "pointer")
366 for user_record in user_records:
367 self.fill_record_info(user_record)
369 user_roles = user_record.get("roles")
370 if (role=="*") or (role in user_roles):
371 record_list.append(user_record.get_name())
374 def fill_record_geni_info(self, record):
376 type = record.get_type()
378 if (type == "slice"):
379 auth_table = self.auth.get_auth_table(self.auth.get_authority(record.get_name()))
380 person_ids = record.get("person_ids", [])
381 researchers = self.lookup_users(auth_table, person_ids)
382 geni_info['researcher'] = researchers
384 elif (type == "authority"):
385 auth_table = self.auth.get_auth_table(record.get_name())
386 person_ids = record.get("person_ids", [])
387 pis = self.lookup_users(auth_table, person_ids, "pi")
388 operators = self.lookup_users(auth_table, person_ids, "tech")
389 owners = self.lookup_users(auth_table, person_ids, "admin")
390 geni_info['pi'] = pis
391 geni_info['operator'] = operators
392 geni_info['owner'] = owners
393 # xxx TODO: OrganizationName
395 elif (type == "node"):
396 geni_info['dns'] = record.get("hostname", "")
397 # xxx TODO: URI, LatLong, IP, DNS
399 elif (type == "user"):
400 geni_info['email'] = record.get("email", "")
401 # xxx TODO: PostalAddress, Phone
403 record.update(geni_info)
405 def fill_record_info(self, record):
407 Given a geni record, fill in the PLC specific and Geni specific
408 fields in the record.
410 self.fill_record_pl_info(record)
411 self.fill_record_geni_info(record)
413 def update_membership_list(self, oldRecord, record, listName, addFunc, delFunc):
414 # get a list of the HRNs tht are members of the old and new records
415 oldList = oldRecord.get(listName, [])
416 newList = record.get(listName, [])
418 # if the lists are the same, then we don't have to update anything
419 if (oldList == newList):
422 # build a list of the new person ids, by looking up each person to get
426 auth_hrn = self.auth.get_authority(hrn)
429 auth_info = self.auth.get_auth_info(auth_hrn)
430 table = self.auth.get_auth_table(auth_hrn)
431 records = table.resolve('user', hrn)
433 userRecord = records[0]
434 newIdList.append(userRecord.get_pointer())
436 # build a list of the old person ids from the person_ids field
438 oldIdList = oldRecord.get("person_ids", [])
439 containerId = oldRecord.get_pointer()
441 # if oldRecord==None, then we are doing a Register, instead of an
444 containerId = record.get_pointer()
446 # add people who are in the new list, but not the oldList
447 for personId in newIdList:
448 if not (personId in oldIdList):
449 print "adding id", personId, "to", record.get_name()
450 addFunc(self.plauth, personId, containerId)
452 # remove people who are in the old list, but not the new list
453 for personId in oldIdList:
454 if not (personId in newIdList):
455 print "removing id", personId, "from", record.get_name()
456 delFunc(self.plauth, personId, containerId)
458 def update_membership(self, oldRecord, record):
459 if record.type == "slice":
460 self.update_membership_list(oldRecord, record, 'researcher',
461 self.plshell.AddPersonToSlice,
462 self.plshell.DeletePersonFromSlice)
463 elif record.type == "authority":
468 def callable(self, method):
470 Return a new instance of the specified method.
473 if method not in self.methods:
474 raise GeniInvalidAPIMethod, method
476 # Get new instance of method
478 classname = method.split(".")[-1]
479 module = __import__("geni.methods." + method, globals(), locals(), [classname])
480 callablemethod = getattr(module, classname)(self)
481 return getattr(module, classname)(self)
482 except ImportError, AttributeError:
484 raise GeniInvalidAPIMethod, method
486 def call(self, source, method, *args):
488 Call the named method from the specified source with the
491 function = self.callable(method)
492 function.source = source
493 return function(*args)
495 def handle(self, source, data):
497 Handle an XML-RPC or SOAP request from the specified source.
500 # Parse request into method name and arguments
502 interface = xmlrpclib
503 (args, method) = xmlrpclib.loads(data)
504 methodresponse = True
506 if SOAPpy is not None:
508 (r, header, body, attrs) = parseSOAPRPC(data, header = 1, body = 1, attrs = 1)
511 # XXX Support named arguments
516 result = self.call(source, method, *args)
517 except Exception, fault:
518 traceback.print_exc(file = log)
519 # Handle expected faults
520 if interface == xmlrpclib:
522 methodresponse = None
523 elif interface == SOAPpy:
524 result = faultParameter(NS.ENV_T + ":Server", "Method Failed", method)
525 result._setDetail("Fault %d: %s" % (fault.faultCode, fault.faultString))
528 if interface == xmlrpclib:
529 if not isinstance(result, GeniFault):
532 data = xmlrpclib.dumps(result, methodresponse = True, encoding = self.encoding, allow_none = 1)
533 elif interface == SOAPpy:
534 data = buildSOAP(kw = {'%sResponse' % method: {'Result': result}}, encoding = self.encoding)