2 # Geniwrapper XML-RPC and SOAP interfaces
14 from sfa.trust.auth import Auth
15 from sfa.util.config import *
16 from sfa.util.faults import *
17 from sfa.util.debug import *
18 from sfa.trust.rights import *
19 from sfa.trust.credential import *
20 from sfa.util.misc import *
22 # See "2.2 Characters" in the XML specification:
24 # #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD]
26 # [#x7F-#x84], [#x86-#x9F], [#xFDD0-#xFDDF]
28 invalid_xml_ascii = map(chr, range(0x0, 0x8) + [0xB, 0xC] + range(0xE, 0x1F))
29 xml_escape_table = string.maketrans("".join(invalid_xml_ascii), "?" * len(invalid_xml_ascii))
31 def xmlrpclib_escape(s, replace = string.replace):
33 xmlrpclib does not handle invalid 7-bit control characters. This
34 function augments xmlrpclib.escape, which by default only replaces
35 '&', '<', and '>' with entities.
38 # This is the standard xmlrpclib.escape function
39 s = replace(s, "&", "&")
40 s = replace(s, "<", "<")
41 s = replace(s, ">", ">",)
43 # Replace invalid 7-bit control characters with '?'
44 return s.translate(xml_escape_table)
46 def xmlrpclib_dump(self, value, write):
48 xmlrpclib cannot marshal instances of subclasses of built-in
49 types. This function overrides xmlrpclib.Marshaller.__dump so that
50 any value that is an instance of one of its acceptable types is
51 marshalled as that type.
53 xmlrpclib also cannot handle invalid 7-bit control characters. See
57 # Use our escape function
58 args = [self, value, write]
59 if isinstance(value, (str, unicode)):
60 args.append(xmlrpclib_escape)
63 # Try for an exact match first
64 f = self.dispatch[type(value)]
67 # Try for an isinstance() match
68 for Type, f in self.dispatch.iteritems():
69 if isinstance(value, Type):
72 raise TypeError, "cannot marshal %s objects" % type(value)
76 # You can't hide from me!
77 xmlrpclib.Marshaller._Marshaller__dump = xmlrpclib_dump
79 # SOAP support is optional
82 from SOAPpy.Parser import parseSOAPRPC
83 from SOAPpy.Types import faultType
84 from SOAPpy.NS import NS
85 from SOAPpy.SOAPBuilder import buildSOAP
90 def import_deep(name):
91 mod = __import__(name)
92 components = name.split('.')
93 for comp in components[1:]:
94 mod = getattr(mod, comp)
99 # flat list of method names
101 methods = sfa.methods.all
103 def __init__(self, config = "/etc/sfa/sfa_config", encoding = "utf-8",
104 peer_cert = None, interface = None, key_file = None, cert_file = None):
105 self.encoding = encoding
107 # Better just be documenting the API
112 self.config = Config(config)
113 self.auth = Auth(peer_cert)
114 self.interface = interface
115 self.key_file = key_file
116 self.cert_file = cert_file
117 self.credential = None
118 self.plshell = self.getPLCShell()
119 self.plshell_version = self.getPLCShellVersion()
120 self.hrn = self.config.SFA_INTERFACE_HRN
121 self.time_format = "%Y-%m-%d %H:%M:%S"
124 def getPLCShell(self):
125 self.plauth = {'Username': self.config.SFA_PLC_USER,
126 'AuthMethod': 'password',
127 'AuthString': self.config.SFA_PLC_PASSWORD}
130 shell = PLC.Shell.Shell(globals = globals())
131 shell.AuthCheck(self.plauth)
135 url = self.config.SFA_PLC_URL
137 shell = xmlrpclib.Server(url, verbose = 0, allow_none = True)
138 shell.AuthCheck(self.plauth)
141 def getPLCShellVersion(self):
142 # We need to figure out what version of PLCAPI we are talking to.
143 # Some calls we need to make later will be different depending on
146 # This is probably a bad way to determine api versions
147 # but its easy and will work for now. Lets try to make
148 # a call that only exists is PLCAPI.4.3. If it fails, we
149 # can assume the api version is 4.2
150 self.plshell.GetTagTypes(self.plauth)
156 def getCredential(self):
157 if self.interface in ['registry']:
158 return self.getCredentialFromLocalRegistry()
160 return self.getCredentialFromRegistry()
163 def getCredentialFromRegistry(self):
165 Get our credential from a remote registry using a geniclient connection
168 path = self.config.SFA_BASE_DIR
169 filename = ".".join([self.interface, self.hrn, type, "cred"])
170 cred_filename = path + os.sep + filename
172 credential = Credential(filename = cred_filename)
175 from sfa.server.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)
183 def getCredentialFromLocalRegistry(self):
185 Get our current credential directly from the local registry.
189 auth_hrn = self.auth.get_authority(hrn)
192 auth_info = self.auth.get_auth_info(auth_hrn)
193 table = self.auth.get_auth_table(auth_hrn)
194 records = table.resolve('*', hrn)
198 type = record.get_type()
199 object_gid = record.get_gid_object()
200 new_cred = Credential(subject = object_gid.get_subject())
201 new_cred.set_gid_caller(object_gid)
202 new_cred.set_gid_object(object_gid)
203 new_cred.set_issuer(key=auth_info.get_pkey_object(), subject=auth_hrn)
204 new_cred.set_pubkey(object_gid.get_pubkey())
205 r1 = determine_rights(type, hrn)
206 new_cred.set_privileges(r1)
208 auth_kind = "authority,ma,sa"
210 new_cred.set_parent(self.auth.hierarchy.get_auth_cred(auth_hrn, kind=auth_kind))
218 def loadCredential (self):
220 Attempt to load credential from file if it exists. If it doesnt get
221 credential from registry.
224 # see if this file exists
225 # XX This is really the aggregate's credential. Using this is easier than getting
226 # the registry's credential from iteslf (ssl errors).
227 ma_cred_filename = self.config.SFA_BASE_DIR + os.sep + self.interface + self.hrn + ".ma.cred"
229 self.credential = Credential(filename = ma_cred_filename)
231 self.credential = self.getCredentialFromRegistry()
234 # Convert geni fields to PLC fields for use when registering up updating
235 # registry record in the PLC database
237 # @param type type of record (user, slice, ...)
238 # @param hrn human readable name
239 # @param geni_fields dictionary of geni fields
240 # @param pl_fields dictionary of PLC fields (output)
242 def geni_fields_to_pl_fields(self, type, hrn, record):
244 def convert_ints(tmpdict, int_fields):
245 for field in int_fields:
247 tmpdict[field] = int(tmpdict[field])
250 #for field in record:
251 # pl_record[field] = record[field]
254 if not "instantiation" in pl_record:
255 pl_record["instantiation"] = "plc-instantiated"
256 pl_record["name"] = hrn_to_pl_slicename(hrn)
258 pl_record["url"] = record["url"]
259 if "description" in record:
260 pl_record["description"] = record["description"]
263 if not "hostname" in pl_record:
264 if not "dns" in record:
265 raise MissingGeniInfo("dns")
266 pl_record["hostname"] = record["dns"]
267 if not "model" in pl_record:
268 pl_record["model"] = "geni"
270 elif type == "authority":
271 pl_record["login_base"] = hrn_to_pl_login_base(hrn)
273 if not "name" in pl_record:
274 pl_record["name"] = hrn
276 if not "abbreviated_name" in pl_record:
277 pl_record["abbreviated_name"] = hrn
279 if not "enabled" in pl_record:
280 pl_record["enabled"] = True
282 if not "is_public" in pl_record:
283 pl_record["is_public"] = True
287 def fill_record_pl_info(self, record):
289 Fill in the planetlab specific fields of a Geni record. This
290 involves calling the appropriate PLC method to retrieve the
291 database record for the object.
293 PLC data is filled into the pl_info field of the record.
295 @param record: record to fill in field (in/out param)
297 type = record.get_type()
298 pointer = record.get_pointer()
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"
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])
317 raise UnknownGeniType(type)
320 raise PlanetLabRecordDoesNotExist(record.get_name())
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'])
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'])
354 pubkeys = [key['key'] for key in keys]
355 pl_record['keys'] = pubkeys
357 record.update(pl_record)
360 def lookup_users(self, auth_table, user_id_list, role="*"):
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 user_roles = user_record.get("roles")
367 if (role=="*") or (role in user_roles):
368 record_list.append(user_record.get_name())
371 def fill_record_geni_info(self, record):
373 type = record.get_type()
374 if (type == "slice"):
375 auth_table = self.auth.get_auth_table(self.auth.get_authority(record.get_name()))
376 person_ids = record.get("person_ids", [])
377 researchers = self.lookup_users(auth_table, person_ids)
378 geni_info['researcher'] = researchers
380 elif (type == "authority"):
381 auth_table = self.auth.get_auth_table(record.get_name())
382 person_ids = record.get("person_ids", [])
383 pis = self.lookup_users(auth_table, person_ids, "pi")
384 operators = self.lookup_users(auth_table, person_ids, "tech")
385 owners = self.lookup_users(auth_table, person_ids, "admin")
386 geni_info['pi'] = pis
387 geni_info['operator'] = operators
388 geni_info['owner'] = owners
389 # xxx TODO: OrganizationName
391 elif (type == "node"):
392 geni_info['dns'] = record.get("hostname", "")
393 # xxx TODO: URI, LatLong, IP, DNS
395 elif (type == "user"):
396 geni_info['email'] = record.get("email", "")
397 # xxx TODO: PostalAddress, Phone
399 record.update(geni_info)
401 def fill_record_info(self, record):
403 Given a geni record, fill in the PLC specific and Geni specific
404 fields in the record.
406 self.fill_record_pl_info(record)
407 self.fill_record_geni_info(record)
409 def update_membership_list(self, oldRecord, record, listName, addFunc, delFunc):
410 # get a list of the HRNs tht are members of the old and new records
412 oldList = oldRecord.get(listName, [])
415 newList = record.get(listName, [])
417 # if the lists are the same, then we don't have to update anything
418 if (oldList == newList):
421 # build a list of the new person ids, by looking up each person to get
425 auth_hrn = self.auth.get_authority(hrn)
428 auth_info = self.auth.get_auth_info(auth_hrn)
429 table = self.auth.get_auth_table(auth_hrn)
430 records = table.resolve('user', hrn)
432 userRecord = records[0]
433 newIdList.append(userRecord.get_pointer())
435 # build a list of the old person ids from the person_ids field
437 oldIdList = oldRecord.get("person_ids", [])
438 containerId = oldRecord.get_pointer()
440 # if oldRecord==None, then we are doing a Register, instead of an
443 containerId = record.get_pointer()
445 # add people who are in the new list, but not the oldList
446 for personId in newIdList:
447 if not (personId in oldIdList):
448 print "adding id", personId, "to", record.get_name()
449 addFunc(self.plauth, personId, containerId)
451 # remove people who are in the old list, but not the new list
452 for personId in oldIdList:
453 if not (personId in newIdList):
454 print "removing id", personId, "from", record.get_name()
455 delFunc(self.plauth, personId, containerId)
457 def update_membership(self, oldRecord, record):
458 if record.type == "slice":
459 self.update_membership_list(oldRecord, record, 'researcher',
460 self.plshell.AddPersonToSlice,
461 self.plshell.DeletePersonFromSlice)
462 elif record.type == "authority":
467 def callable(self, method):
469 Return a new instance of the specified method.
472 if method not in self.methods:
473 raise GeniInvalidAPIMethod, method
475 # Get new instance of method
477 classname = method.split(".")[-1]
478 module = __import__("sfa.methods." + method, globals(), locals(), [classname])
479 callablemethod = getattr(module, classname)(self)
480 return getattr(module, classname)(self)
481 except ImportError, AttributeError:
483 raise GeniInvalidAPIMethod, method
485 def call(self, source, method, *args):
487 Call the named method from the specified source with the
490 function = self.callable(method)
491 function.source = source
492 return function(*args)
494 def handle(self, source, data):
496 Handle an XML-RPC or SOAP request from the specified source.
499 # Parse request into method name and arguments
501 interface = xmlrpclib
502 (args, method) = xmlrpclib.loads(data)
503 methodresponse = True
505 if SOAPpy is not None:
507 (r, header, body, attrs) = parseSOAPRPC(data, header = 1, body = 1, attrs = 1)
510 # XXX Support named arguments
515 result = self.call(source, method, *args)
516 except Exception, fault:
517 traceback.print_exc(file = log)
518 # Handle expected faults
519 if interface == xmlrpclib:
521 methodresponse = None
522 elif interface == SOAPpy:
523 result = faultParameter(NS.ENV_T + ":Server", "Method Failed", method)
524 result._setDetail("Fault %d: %s" % (fault.faultCode, fault.faultString))
529 if interface == xmlrpclib:
530 if not isinstance(result, GeniFault):
533 data = xmlrpclib.dumps(result, methodresponse = True, encoding = self.encoding, allow_none = 1)
534 elif interface == SOAPpy:
535 data = buildSOAP(kw = {'%sResponse' % method: {'Result': result}}, encoding = self.encoding)