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 *
21 from sfa.util.sfalogging import *
23 # See "2.2 Characters" in the XML specification:
25 # #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD]
27 # [#x7F-#x84], [#x86-#x9F], [#xFDD0-#xFDDF]
29 invalid_xml_ascii = map(chr, range(0x0, 0x8) + [0xB, 0xC] + range(0xE, 0x1F))
30 xml_escape_table = string.maketrans("".join(invalid_xml_ascii), "?" * len(invalid_xml_ascii))
32 def xmlrpclib_escape(s, replace = string.replace):
34 xmlrpclib does not handle invalid 7-bit control characters. This
35 function augments xmlrpclib.escape, which by default only replaces
36 '&', '<', and '>' with entities.
39 # This is the standard xmlrpclib.escape function
40 s = replace(s, "&", "&")
41 s = replace(s, "<", "<")
42 s = replace(s, ">", ">",)
44 # Replace invalid 7-bit control characters with '?'
45 return s.translate(xml_escape_table)
47 def xmlrpclib_dump(self, value, write):
49 xmlrpclib cannot marshal instances of subclasses of built-in
50 types. This function overrides xmlrpclib.Marshaller.__dump so that
51 any value that is an instance of one of its acceptable types is
52 marshalled as that type.
54 xmlrpclib also cannot handle invalid 7-bit control characters. See
58 # Use our escape function
59 args = [self, value, write]
60 if isinstance(value, (str, unicode)):
61 args.append(xmlrpclib_escape)
64 # Try for an exact match first
65 f = self.dispatch[type(value)]
68 # Try for an isinstance() match
69 for Type, f in self.dispatch.iteritems():
70 if isinstance(value, Type):
73 raise TypeError, "cannot marshal %s objects" % type(value)
77 # You can't hide from me!
78 xmlrpclib.Marshaller._Marshaller__dump = xmlrpclib_dump
80 # SOAP support is optional
83 from SOAPpy.Parser import parseSOAPRPC
84 from SOAPpy.Types import faultType
85 from SOAPpy.NS import NS
86 from SOAPpy.SOAPBuilder import buildSOAP
91 def import_deep(name):
92 mod = __import__(name)
93 components = name.split('.')
94 for comp in components[1:]:
95 mod = getattr(mod, comp)
100 # flat list of method names
102 methods = sfa.methods.all
104 def __init__(self, config = "/etc/sfa/sfa_config", encoding = "utf-8",
105 peer_cert = None, interface = None, key_file = None, cert_file = None):
106 self.encoding = encoding
108 # Better just be documenting the API
113 self.config = Config(config)
114 self.auth = Auth(peer_cert)
115 self.interface = interface
116 self.key_file = key_file
117 self.cert_file = cert_file
118 self.credential = None
119 self.plshell = self.getPLCShell()
120 self.plshell_version = self.getPLCShellVersion()
121 self.hrn = self.config.SFA_INTERFACE_HRN
122 self.time_format = "%Y-%m-%d %H:%M:%S"
123 self.logger=get_sfa_logger()
125 def getPLCShell(self):
126 self.plauth = {'Username': self.config.SFA_PLC_USER,
127 'AuthMethod': 'password',
128 'AuthString': self.config.SFA_PLC_PASSWORD}
131 shell = PLC.Shell.Shell(globals = globals())
132 shell.AuthCheck(self.plauth)
136 url = self.config.SFA_PLC_URL
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.SFA_BASE_DIR
170 filename = ".".join([self.interface, self.hrn, type, "cred"])
171 cred_filename = path + os.sep + filename
173 credential = Credential(filename = cred_filename)
176 from sfa.server.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)
192 # is this a root or sub authority
193 if not auth_hrn or hrn == self.config.SFA_INTERFACE_HRN:
195 auth_info = self.auth.get_auth_info(auth_hrn)
196 table = self.auth.get_auth_table(auth_hrn)
197 records = table.resolve('*', hrn)
201 type = record.get_type()
202 object_gid = record.get_gid_object()
203 new_cred = Credential(subject = object_gid.get_subject())
204 new_cred.set_gid_caller(object_gid)
205 new_cred.set_gid_object(object_gid)
206 new_cred.set_issuer(key=auth_info.get_pkey_object(), subject=auth_hrn)
207 new_cred.set_pubkey(object_gid.get_pubkey())
208 r1 = determine_rights(type, hrn)
209 new_cred.set_privileges(r1)
211 auth_kind = "authority,ma,sa"
213 new_cred.set_parent(self.auth.hierarchy.get_auth_cred(auth_hrn, kind=auth_kind))
221 def loadCredential (self):
223 Attempt to load credential from file if it exists. If it doesnt get
224 credential from registry.
227 # see if this file exists
228 # XX This is really the aggregate's credential. Using this is easier than getting
229 # the registry's credential from iteslf (ssl errors).
230 ma_cred_filename = self.config.SFA_BASE_DIR + os.sep + self.interface + self.hrn + ".ma.cred"
232 self.credential = Credential(filename = ma_cred_filename)
234 self.credential = self.getCredentialFromRegistry()
237 # Convert geni fields to PLC fields for use when registering up updating
238 # registry record in the PLC database
240 # @param type type of record (user, slice, ...)
241 # @param hrn human readable name
242 # @param geni_fields dictionary of geni fields
243 # @param pl_fields dictionary of PLC fields (output)
245 def geni_fields_to_pl_fields(self, type, hrn, record):
247 def convert_ints(tmpdict, int_fields):
248 for field in int_fields:
250 tmpdict[field] = int(tmpdict[field])
253 #for field in record:
254 # pl_record[field] = record[field]
257 if not "instantiation" in pl_record:
258 pl_record["instantiation"] = "plc-instantiated"
259 pl_record["name"] = hrn_to_pl_slicename(hrn)
261 pl_record["url"] = record["url"]
262 if "description" in record:
263 pl_record["description"] = record["description"]
266 if not "hostname" in pl_record:
267 if not "hostname" in record:
268 raise MissingGeniInfo("hostname")
269 pl_record["hostname"] = record["hostname"]
270 if not "model" in pl_record:
271 pl_record["model"] = "geni"
273 elif type == "authority":
274 pl_record["login_base"] = hrn_to_pl_login_base(hrn)
276 if not "name" in pl_record:
277 pl_record["name"] = hrn
279 if not "abbreviated_name" in pl_record:
280 pl_record["abbreviated_name"] = hrn
282 if not "enabled" in pl_record:
283 pl_record["enabled"] = True
285 if not "is_public" in pl_record:
286 pl_record["is_public"] = True
290 def fill_record_pl_info(self, record):
292 Fill in the planetlab specific fields of a Geni record. This
293 involves calling the appropriate PLC method to retrieve the
294 database record for the object.
296 PLC data is filled into the pl_info field of the record.
298 @param record: record to fill in field (in/out param)
300 type = record.get_type()
301 pointer = record.get_pointer()
304 # records with pointer==-1 do not have plc info associated with them.
305 # for example, the top level authority records which are
306 # authorities, but not PL "sites"
311 if (type in ["authority", "sa", "ma"]):
312 pl_res = self.plshell.GetSites(self.plauth, [pointer])
313 elif (type == "slice"):
314 pl_res = self.plshell.GetSlices(self.plauth, [pointer])
315 elif (type == "user"):
316 pl_res = self.plshell.GetPersons(self.plauth, [pointer])
317 elif (type == "node"):
318 pl_res = self.plshell.GetNodes(self.plauth, [pointer])
320 raise UnknownGeniType(type)
323 raise PlanetLabRecordDoesNotExist(record.get_name())
325 # convert ids to hrns
326 pl_record = pl_res[0]
327 if 'site_id' in pl_record:
328 sites = self.plshell.GetSites(self.plauth, pl_record['site_id'], ['login_base'])
330 login_base = site['login_base']
331 pl_record['site'] = ".".join([auth_hrn, login_base])
332 if 'person_ids' in pl_record:
333 persons = self.plshell.GetPersons(self.plauth, pl_record['person_ids'], ['email'])
334 emails = [person['email'] for person in persons]
335 usernames = [email.split('@')[0] for email in emails]
336 person_hrns = [".".join([auth_hrn, login_base, username]) for username in usernames]
337 pl_record['persons'] = person_hrns
338 if 'slice_ids' in pl_record:
339 slices = self.plshell.GetSlices(self.plauth, pl_record['slice_ids'], ['name'])
340 slicenames = [slice['name'] for slice in slices]
341 slice_hrns = [slicename_to_hrn(auth_hrn, slicename) for slicename in slicenames]
342 pl_record['slices'] = slice_hrns
343 if 'node_ids' in pl_record:
344 nodes = self.plshell.GetNodes(self.plauth, pl_record['node_ids'], ['hostname'])
345 hostnames = [node['hostname'] for node in nodes]
346 node_hrns = [hostname_to_hrn(auth_hrn, login_base, hostname) for hostname in hostnames]
347 pl_record['nodes'] = node_hrns
348 if 'site_ids' in pl_record:
349 sites = self.plshell.GetSites(self.plauth, pl_record['site_ids'], ['login_base'])
350 login_bases = [site['login_base'] for site in sites]
351 site_hrns = [".".join([auth_hrn, lbase]) for lbase in login_bases]
352 pl_record['sites'] = site_hrns
353 if 'key_ids' in pl_record:
354 keys = self.plshell.GetKeys(self.plauth, pl_record['key_ids'])
357 pubkeys = [key['key'] for key in keys]
358 pl_record['keys'] = pubkeys
360 record.update(pl_record)
363 def lookup_users(self, auth_table, user_id_list, role="*"):
365 for person_id in user_id_list:
366 user_records = auth_table.find("user", person_id, "pointer")
367 for user_record in user_records:
368 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()
377 if (type == "slice"):
378 auth_table = self.auth.get_auth_table(self.auth.get_authority(record.get_name()))
379 person_ids = record.get("person_ids", [])
380 researchers = self.lookup_users(auth_table, person_ids)
381 geni_info['researcher'] = researchers
383 elif (type == "authority"):
384 auth_table = self.auth.get_auth_table(record.get_name())
385 person_ids = record.get("person_ids", [])
386 pis = self.lookup_users(auth_table, person_ids, "pi")
387 operators = self.lookup_users(auth_table, person_ids, "tech")
388 owners = self.lookup_users(auth_table, person_ids, "admin")
389 geni_info['pi'] = pis
390 geni_info['operator'] = operators
391 geni_info['owner'] = owners
392 # xxx TODO: OrganizationName
394 elif (type == "node"):
395 geni_info['dns'] = record.get("hostname", "")
396 # xxx TODO: URI, LatLong, IP, DNS
398 elif (type == "user"):
399 geni_info['email'] = record.get("email", "")
400 # xxx TODO: PostalAddress, Phone
402 record.update(geni_info)
404 def fill_record_info(self, record):
406 Given a geni record, fill in the PLC specific and Geni specific
407 fields in the record.
409 self.fill_record_pl_info(record)
410 self.fill_record_geni_info(record)
412 def update_membership_list(self, oldRecord, record, listName, addFunc, delFunc):
413 # get a list of the HRNs tht are members of the old and new records
415 oldList = oldRecord.get(listName, [])
418 newList = record.get(listName, [])
420 # if the lists are the same, then we don't have to update anything
421 if (oldList == newList):
424 # build a list of the new person ids, by looking up each person to get
428 auth_hrn = self.auth.get_authority(hrn)
431 auth_info = self.auth.get_auth_info(auth_hrn)
432 table = self.auth.get_auth_table(auth_hrn)
433 records = table.resolve('user', hrn)
435 userRecord = records[0]
436 newIdList.append(userRecord.get_pointer())
438 # build a list of the old person ids from the person_ids field
440 oldIdList = oldRecord.get("person_ids", [])
441 containerId = oldRecord.get_pointer()
443 # if oldRecord==None, then we are doing a Register, instead of an
446 containerId = record.get_pointer()
448 # add people who are in the new list, but not the oldList
449 for personId in newIdList:
450 if not (personId in oldIdList):
451 print "adding id", personId, "to", record.get_name()
452 addFunc(self.plauth, personId, containerId)
454 # remove people who are in the old list, but not the new list
455 for personId in oldIdList:
456 if not (personId in newIdList):
457 print "removing id", personId, "from", record.get_name()
458 delFunc(self.plauth, personId, containerId)
460 def update_membership(self, oldRecord, record):
461 if record.type == "slice":
462 self.update_membership_list(oldRecord, record, 'researcher',
463 self.plshell.AddPersonToSlice,
464 self.plshell.DeletePersonFromSlice)
465 elif record.type == "authority":
470 def callable(self, method):
472 Return a new instance of the specified method.
475 if method not in self.methods:
476 raise GeniInvalidAPIMethod, method
478 # Get new instance of method
480 classname = method.split(".")[-1]
481 module = __import__("sfa.methods." + method, globals(), locals(), [classname])
482 callablemethod = getattr(module, classname)(self)
483 return getattr(module, classname)(self)
484 except ImportError, AttributeError:
486 raise GeniInvalidAPIMethod, method
488 def call(self, source, method, *args):
490 Call the named method from the specified source with the
493 function = self.callable(method)
494 function.source = source
495 return function(*args)
497 def handle(self, source, data):
499 Handle an XML-RPC or SOAP request from the specified source.
501 # Parse request into method name and arguments
503 interface = xmlrpclib
504 (args, method) = xmlrpclib.loads(data)
505 methodresponse = True
507 if SOAPpy is not None:
509 (r, header, body, attrs) = parseSOAPRPC(data, header = 1, body = 1, attrs = 1)
512 # XXX Support named arguments
517 result = self.call(source, method, *args)
518 except Exception, fault:
519 traceback.print_exc(file = log)
520 # Handle expected faults
521 if interface == xmlrpclib:
523 methodresponse = None
524 elif interface == SOAPpy:
525 result = faultParameter(NS.ENV_T + ":Server", "Method Failed", method)
526 result._setDetail("Fault %d: %s" % (fault.faultCode, fault.faultString))
531 if interface == xmlrpclib:
532 if not isinstance(result, GeniFault):
535 data = xmlrpclib.dumps(result, methodresponse = True, encoding = self.encoding, allow_none = 1)
536 elif interface == SOAPpy:
537 data = buildSOAP(kw = {'%sResponse' % method: {'Result': result}}, encoding = self.encoding)