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 *
22 from sfa.util.genitable import *
24 # See "2.2 Characters" in the XML specification:
26 # #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD]
28 # [#x7F-#x84], [#x86-#x9F], [#xFDD0-#xFDDF]
30 invalid_xml_ascii = map(chr, range(0x0, 0x8) + [0xB, 0xC] + range(0xE, 0x1F))
31 xml_escape_table = string.maketrans("".join(invalid_xml_ascii), "?" * len(invalid_xml_ascii))
33 def xmlrpclib_escape(s, replace = string.replace):
35 xmlrpclib does not handle invalid 7-bit control characters. This
36 function augments xmlrpclib.escape, which by default only replaces
37 '&', '<', and '>' with entities.
40 # This is the standard xmlrpclib.escape function
41 s = replace(s, "&", "&")
42 s = replace(s, "<", "<")
43 s = replace(s, ">", ">",)
45 # Replace invalid 7-bit control characters with '?'
46 return s.translate(xml_escape_table)
48 def xmlrpclib_dump(self, value, write):
50 xmlrpclib cannot marshal instances of subclasses of built-in
51 types. This function overrides xmlrpclib.Marshaller.__dump so that
52 any value that is an instance of one of its acceptable types is
53 marshalled as that type.
55 xmlrpclib also cannot handle invalid 7-bit control characters. See
59 # Use our escape function
60 args = [self, value, write]
61 if isinstance(value, (str, unicode)):
62 args.append(xmlrpclib_escape)
65 # Try for an exact match first
66 f = self.dispatch[type(value)]
69 # Try for an isinstance() match
70 for Type, f in self.dispatch.iteritems():
71 if isinstance(value, Type):
74 raise TypeError, "cannot marshal %s objects" % type(value)
78 # You can't hide from me!
79 xmlrpclib.Marshaller._Marshaller__dump = xmlrpclib_dump
81 # SOAP support is optional
84 from SOAPpy.Parser import parseSOAPRPC
85 from SOAPpy.Types import faultType
86 from SOAPpy.NS import NS
87 from SOAPpy.SOAPBuilder import buildSOAP
92 def import_deep(name):
93 mod = __import__(name)
94 components = name.split('.')
95 for comp in components[1:]:
96 mod = getattr(mod, comp)
101 # flat list of method names
103 methods = sfa.methods.all
105 def __init__(self, config = "/etc/sfa/sfa_config", encoding = "utf-8",
106 peer_cert = None, interface = None, key_file = None, cert_file = None):
107 self.encoding = encoding
109 # Better just be documenting the API
114 self.config = Config(config)
115 self.auth = Auth(peer_cert)
116 self.interface = interface
117 self.key_file = key_file
118 self.cert_file = cert_file
119 self.credential = None
120 self.plshell = self.getPLCShell()
121 self.plshell_version = self.getPLCShellVersion()
122 self.hrn = self.config.SFA_INTERFACE_HRN
123 self.time_format = "%Y-%m-%d %H:%M:%S"
124 self.logger=get_sfa_logger()
126 def getPLCShell(self):
127 self.plauth = {'Username': self.config.SFA_PLC_USER,
128 'AuthMethod': 'password',
129 'AuthString': self.config.SFA_PLC_PASSWORD}
132 shell = PLC.Shell.Shell(globals = globals())
133 shell.AuthCheck(self.plauth)
137 url = self.config.SFA_PLC_URL
139 shell = xmlrpclib.Server(url, verbose = 0, allow_none = True)
140 shell.AuthCheck(self.plauth)
143 def getPLCShellVersion(self):
144 # We need to figure out what version of PLCAPI we are talking to.
145 # Some calls we need to make later will be different depending on
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)
158 def getCredential(self):
159 if self.interface in ['registry']:
160 return self.getCredentialFromLocalRegistry()
162 return self.getCredentialFromRegistry()
165 def getCredentialFromRegistry(self):
167 Get our credential from a remote registry using a geniclient connection
170 path = self.config.SFA_BASE_DIR
171 filename = ".".join([self.interface, self.hrn, type, "cred"])
172 cred_filename = path + os.sep + filename
174 credential = Credential(filename = cred_filename)
177 from sfa.server.registry import Registries
178 registries = Registries(self)
179 registry = registries[self.hrn]
180 self_cred = registry.get_credential(None, type, self.hrn)
181 cred = registry.get_credential(self_cred, type, self.hrn)
182 cred.save_to_file(cred_filename, save_parents=True)
185 def getCredentialFromLocalRegistry(self):
187 Get our current credential directly from the local registry.
191 auth_hrn = self.auth.get_authority(hrn)
193 # is this a root or sub authority
194 if not auth_hrn or hrn == self.config.SFA_INTERFACE_HRN:
196 auth_info = self.auth.get_auth_info(auth_hrn)
198 records = table.findObjects(hrn)
202 type = record['type']
203 object_gid = record.get_gid_object()
204 new_cred = Credential(subject = object_gid.get_subject())
205 new_cred.set_gid_caller(object_gid)
206 new_cred.set_gid_object(object_gid)
207 new_cred.set_issuer(key=auth_info.get_pkey_object(), subject=auth_hrn)
208 new_cred.set_pubkey(object_gid.get_pubkey())
209 r1 = determine_rights(type, hrn)
210 new_cred.set_privileges(r1)
212 auth_kind = "authority,ma,sa"
214 new_cred.set_parent(self.auth.hierarchy.get_auth_cred(auth_hrn, kind=auth_kind))
222 def loadCredential (self):
224 Attempt to load credential from file if it exists. If it doesnt get
225 credential from registry.
228 # see if this file exists
229 # XX This is really the aggregate's credential. Using this is easier than getting
230 # the registry's credential from iteslf (ssl errors).
231 ma_cred_filename = self.config.SFA_BASE_DIR + os.sep + self.interface + self.hrn + ".ma.cred"
233 self.credential = Credential(filename = ma_cred_filename)
235 self.credential = self.getCredentialFromRegistry()
238 # Convert geni fields to PLC fields for use when registering up updating
239 # registry record in the PLC database
241 # @param type type of record (user, slice, ...)
242 # @param hrn human readable name
243 # @param geni_fields dictionary of geni fields
244 # @param pl_fields dictionary of PLC fields (output)
246 def geni_fields_to_pl_fields(self, type, hrn, record):
248 def convert_ints(tmpdict, int_fields):
249 for field in int_fields:
251 tmpdict[field] = int(tmpdict[field])
254 #for field in record:
255 # pl_record[field] = record[field]
258 if not "instantiation" in pl_record:
259 pl_record["instantiation"] = "plc-instantiated"
260 pl_record["name"] = hrn_to_pl_slicename(hrn)
262 pl_record["url"] = record["url"]
263 if "description" in record:
264 pl_record["description"] = record["description"]
267 if not "hostname" in pl_record:
268 if not "hostname" in record:
269 raise MissingGeniInfo("hostname")
270 pl_record["hostname"] = record["hostname"]
271 if not "model" in pl_record:
272 pl_record["model"] = "geni"
274 elif type == "authority":
275 pl_record["login_base"] = hrn_to_pl_login_base(hrn)
277 if not "name" in pl_record:
278 pl_record["name"] = hrn
280 if not "abbreviated_name" in pl_record:
281 pl_record["abbreviated_name"] = hrn
283 if not "enabled" in pl_record:
284 pl_record["enabled"] = True
286 if not "is_public" in pl_record:
287 pl_record["is_public"] = True
291 def fill_record_pl_info(self, record):
293 Fill in the planetlab specific fields of a Geni record. This
294 involves calling the appropriate PLC method to retrieve the
295 database record for the object.
297 PLC data is filled into the pl_info field of the record.
299 @param record: record to fill in field (in/out param)
301 type = record['type']
302 pointer = record['pointer']
305 # records with pointer==-1 do not have plc info associated with them.
306 # for example, the top level authority records which are
307 # authorities, but not PL "sites"
312 if (type in ["authority", "sa", "ma"]):
313 pl_res = self.plshell.GetSites(self.plauth, [pointer])
314 elif (type == "slice"):
315 pl_res = self.plshell.GetSlices(self.plauth, [pointer])
316 elif (type == "user"):
317 pl_res = self.plshell.GetPersons(self.plauth, [pointer])
318 elif (type == "node"):
319 pl_res = self.plshell.GetNodes(self.plauth, [pointer])
321 raise UnknownGeniType(type)
324 raise PlanetLabRecordDoesNotExist(record['hrn'])
326 # convert ids to hrns
327 pl_record = pl_res[0]
328 if 'site_id' in pl_record:
329 sites = self.plshell.GetSites(self.plauth, pl_record['site_id'], ['login_base'])
331 login_base = site['login_base']
332 pl_record['site'] = ".".join([auth_hrn, login_base])
333 if 'person_ids' in pl_record:
334 persons = self.plshell.GetPersons(self.plauth, pl_record['person_ids'], ['email'])
335 emails = [person['email'] for person in persons]
336 usernames = [email.split('@')[0] for email in emails]
337 person_hrns = [".".join([auth_hrn, login_base, username]) for username in usernames]
338 pl_record['persons'] = person_hrns
339 if 'slice_ids' in pl_record:
340 slices = self.plshell.GetSlices(self.plauth, pl_record['slice_ids'], ['name'])
341 slicenames = [slice['name'] for slice in slices]
342 slice_hrns = [slicename_to_hrn(auth_hrn, slicename) for slicename in slicenames]
343 pl_record['slices'] = slice_hrns
344 if 'node_ids' in pl_record:
345 nodes = self.plshell.GetNodes(self.plauth, pl_record['node_ids'], ['hostname'])
346 hostnames = [node['hostname'] for node in nodes]
347 node_hrns = [hostname_to_hrn(auth_hrn, login_base, hostname) for hostname in hostnames]
348 pl_record['nodes'] = node_hrns
349 if 'site_ids' in pl_record:
350 sites = self.plshell.GetSites(self.plauth, pl_record['site_ids'], ['login_base'])
351 login_bases = [site['login_base'] for site in sites]
352 site_hrns = [".".join([auth_hrn, lbase]) for lbase in login_bases]
353 pl_record['sites'] = site_hrns
354 if 'key_ids' in pl_record:
355 keys = self.plshell.GetKeys(self.plauth, pl_record['key_ids'])
358 pubkeys = [key['key'] for key in keys]
359 pl_record['keys'] = pubkeys
361 record.update(pl_record)
364 def lookup_users(self, user_id_list, role="*"):
367 for person_id in user_id_list:
368 user_records = table.find({'type': 'user', 'pointer': person_id})
369 for user_record in user_records:
370 self.fill_record_info(user_record)
371 user_roles = user_record.get("roles")
372 if (role=="*") or (role in user_roles):
373 record_list.append(user_record['hrn'])
376 def fill_record_geni_info(self, record):
378 type = record['type']
379 if (type == "slice"):
380 person_ids = record.get("person_ids", [])
381 researchers = self.lookup_users(person_ids)
382 geni_info['researcher'] = researchers
384 elif (type == "authority"):
385 person_ids = record.get("person_ids", [])
386 pis = self.lookup_users(person_ids, "pi")
387 operators = self.lookup_users(person_ids, "tech")
388 owners = self.lookup_users(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 records = table.find({'type': 'user', 'hrn': newList})
430 newIdList.append(rec['pointer'])
432 # build a list of the old person ids from the person_ids field
434 oldIdList = oldRecord.get("person_ids", [])
435 containerId = oldRecord.get_pointer()
437 # if oldRecord==None, then we are doing a Register, instead of an
440 containerId = record.get_pointer()
442 # add people who are in the new list, but not the oldList
443 for personId in newIdList:
444 if not (personId in oldIdList):
445 print "adding id", personId, "to", record.get_name()
446 addFunc(self.plauth, personId, containerId)
448 # remove people who are in the old list, but not the new list
449 for personId in oldIdList:
450 if not (personId in newIdList):
451 print "removing id", personId, "from", record.get_name()
452 delFunc(self.plauth, personId, containerId)
454 def update_membership(self, oldRecord, record):
455 if record.type == "slice":
456 self.update_membership_list(oldRecord, record, 'researcher',
457 self.plshell.AddPersonToSlice,
458 self.plshell.DeletePersonFromSlice)
459 elif record.type == "authority":
464 def callable(self, method):
466 Return a new instance of the specified method.
469 if method not in self.methods:
470 raise GeniInvalidAPIMethod, method
472 # Get new instance of method
474 classname = method.split(".")[-1]
475 module = __import__("sfa.methods." + method, globals(), locals(), [classname])
476 callablemethod = getattr(module, classname)(self)
477 return getattr(module, classname)(self)
478 except ImportError, AttributeError:
480 raise GeniInvalidAPIMethod, method
482 def call(self, source, method, *args):
484 Call the named method from the specified source with the
487 function = self.callable(method)
488 function.source = source
489 return function(*args)
491 def handle(self, source, data):
493 Handle an XML-RPC or SOAP request from the specified source.
495 # Parse request into method name and arguments
497 interface = xmlrpclib
498 (args, method) = xmlrpclib.loads(data)
499 methodresponse = True
501 if SOAPpy is not None:
503 (r, header, body, attrs) = parseSOAPRPC(data, header = 1, body = 1, attrs = 1)
506 # XXX Support named arguments
511 result = self.call(source, method, *args)
512 except Exception, fault:
513 traceback.print_exc(file = log)
514 # Handle expected faults
515 if interface == xmlrpclib:
517 methodresponse = None
518 elif interface == SOAPpy:
519 result = faultParameter(NS.ENV_T + ":Server", "Method Failed", method)
520 result._setDetail("Fault %d: %s" % (fault.faultCode, fault.faultString))
525 if interface == xmlrpclib:
526 if not isinstance(result, GeniFault):
529 data = xmlrpclib.dumps(result, methodresponse = True, encoding = self.encoding, allow_none = 1)
530 elif interface == SOAPpy:
531 data = buildSOAP(kw = {'%sResponse' % method: {'Result': result}}, encoding = self.encoding)