2 # SFA XML-RPC and SOAP interfaces
13 from sfa.trust.auth import Auth
14 from sfa.util.config import *
15 from sfa.util.faults import *
16 from sfa.util.debug import *
17 from sfa.trust.rights import *
18 from sfa.trust.credential import *
19 from sfa.trust.certificate import *
20 from sfa.util.namespace import *
21 from sfa.util.api import *
22 from sfa.util.nodemanager import NodeManager
23 from sfa.util.sfalogging import *
25 def list_to_dict(recs, key):
27 convert a list of dictionaries into a dictionary keyed on the
28 specified dictionary key
30 keys = [rec[key] for rec in recs]
31 return dict(zip(keys, recs))
33 class SfaAPI(BaseAPI):
35 # flat list of method names
37 methods = sfa.methods.all
39 def __init__(self, config = "/etc/sfa/sfa_config.py", encoding = "utf-8", methods='sfa.methods', \
40 peer_cert = None, interface = None, key_file = None, cert_file = None):
41 BaseAPI.__init__(self, config=config, encoding=encoding, methods=methods, \
42 peer_cert=peer_cert, interface=interface, key_file=key_file, \
45 self.encoding = encoding
47 from sfa.util.table import SfaTable
48 self.SfaTable = SfaTable
49 # Better just be documenting the API
54 self.config = Config(config)
55 self.auth = Auth(peer_cert)
56 self.interface = interface
57 self.key_file = key_file
58 self.key = Keypair(filename=self.key_file)
59 self.cert_file = cert_file
60 self.cert = Certificate(filename=self.cert_file)
61 self.credential = None
62 # Initialize the PLC shell only if SFA wraps a myPLC
63 rspec_type = self.config.get_aggregate_type()
64 if (rspec_type == 'pl' or rspec_type == 'vini'):
65 self.plshell = self.getPLCShell()
66 self.plshell_version = "4.3"
68 self.hrn = self.config.SFA_INTERFACE_HRN
69 self.time_format = "%Y-%m-%d %H:%M:%S"
70 self.logger=get_sfa_logger()
72 def getPLCShell(self):
73 self.plauth = {'Username': self.config.SFA_PLC_USER,
74 'AuthMethod': 'password',
75 'AuthString': self.config.SFA_PLC_PASSWORD}
77 self.plshell_type = 'xmlrpc'
79 url = self.config.SFA_PLC_URL
80 shell = xmlrpclib.Server(url, verbose = 0, allow_none = True)
83 def getCredential(self):
84 if self.interface in ['registry']:
85 return self.getCredentialFromLocalRegistry()
87 return self.getCredentialFromRegistry()
89 def getCredentialFromRegistry(self):
91 Get our credential from a remote registry
94 path = self.config.SFA_DATA_DIR
95 filename = ".".join([self.interface, self.hrn, type, "cred"])
96 cred_filename = path + os.sep + filename
98 credential = Credential(filename = cred_filename)
99 return credential.save_to_string(save_parents=True)
101 from sfa.server.registry import Registries
102 registries = Registries(self)
103 registry = registries[self.hrn]
104 cert_string=self.cert.save_to_string(save_parents=True)
105 # get self credential
106 self_cred = registry.get_self_credential(cert_string, type, self.hrn)
108 cred = registry.get_credential(self_cred, type, self.hrn)
111 Credential(string=cred).save_to_file(cred_filename, save_parents=True)
114 def getCredentialFromLocalRegistry(self):
116 Get our current credential directly from the local registry.
120 auth_hrn = self.auth.get_authority(hrn)
122 # is this a root or sub authority
123 if not auth_hrn or hrn == self.config.SFA_INTERFACE_HRN:
125 auth_info = self.auth.get_auth_info(auth_hrn)
126 table = self.SfaTable()
127 records = table.findObjects(hrn)
131 type = record['type']
132 object_gid = record.get_gid_object()
133 new_cred = Credential(subject = object_gid.get_subject())
134 new_cred.set_gid_caller(object_gid)
135 new_cred.set_gid_object(object_gid)
136 new_cred.set_issuer(key=auth_info.get_pkey_object(), subject=auth_hrn)
137 new_cred.set_pubkey(object_gid.get_pubkey())
138 r1 = determine_rights(type, hrn)
139 new_cred.set_privileges(r1)
141 auth_kind = "authority,ma,sa"
143 new_cred.set_parent(self.auth.hierarchy.get_auth_cred(auth_hrn, kind=auth_kind))
148 return new_cred.save_to_string(save_parents=True)
151 def loadCredential (self):
153 Attempt to load credential from file if it exists. If it doesnt get
154 credential from registry.
157 # see if this file exists
158 # XX This is really the aggregate's credential. Using this is easier than getting
159 # the registry's credential from iteslf (ssl errors).
160 ma_cred_filename = self.config.SFA_DATA_DIR + os.sep + self.interface + self.hrn + ".ma.cred"
162 self.credential = Credential(filename = ma_cred_filename)
164 self.credential = self.getCredentialFromRegistry()
167 # Convert SFA fields to PLC fields for use when registering up updating
168 # registry record in the PLC database
170 # @param type type of record (user, slice, ...)
171 # @param hrn human readable name
172 # @param sfa_fields dictionary of SFA fields
173 # @param pl_fields dictionary of PLC fields (output)
175 def sfa_fields_to_pl_fields(self, type, hrn, record):
177 def convert_ints(tmpdict, int_fields):
178 for field in int_fields:
180 tmpdict[field] = int(tmpdict[field])
183 #for field in record:
184 # pl_record[field] = record[field]
187 if not "instantiation" in pl_record:
188 pl_record["instantiation"] = "plc-instantiated"
189 pl_record["name"] = hrn_to_pl_slicename(hrn)
191 pl_record["url"] = record["url"]
192 if "description" in record:
193 pl_record["description"] = record["description"]
194 if "expires" in record:
195 pl_record["expires"] = int(record["expires"])
198 if not "hostname" in pl_record:
199 if not "hostname" in record:
200 raise MissingSfaInfo("hostname")
201 pl_record["hostname"] = record["hostname"]
202 if not "model" in pl_record:
203 pl_record["model"] = "geni"
205 elif type == "authority":
206 pl_record["login_base"] = hrn_to_pl_login_base(hrn)
208 if not "name" in pl_record:
209 pl_record["name"] = hrn
211 if not "abbreviated_name" in pl_record:
212 pl_record["abbreviated_name"] = hrn
214 if not "enabled" in pl_record:
215 pl_record["enabled"] = True
217 if not "is_public" in pl_record:
218 pl_record["is_public"] = True
222 def fill_record_pl_info(self, records):
224 Fill in the planetlab specific fields of a SFA record. This
225 involves calling the appropriate PLC method to retrieve the
226 database record for the object.
228 PLC data is filled into the pl_info field of the record.
230 @param record: record to fill in field (in/out param)
233 node_ids, site_ids, slice_ids = [], [], []
234 person_ids, key_ids = [], []
235 type_map = {'node': node_ids, 'authority': site_ids,
236 'slice': slice_ids, 'user': person_ids}
238 for record in records:
239 for type in type_map:
240 if type == record['type']:
241 type_map[type].append(record['pointer'])
244 nodes, sites, slices, persons, keys = {}, {}, {}, {}, {}
246 node_list = self.plshell.GetNodes(self.plauth, node_ids)
247 nodes = list_to_dict(node_list, 'node_id')
249 site_list = self.plshell.GetSites(self.plauth, site_ids)
250 sites = list_to_dict(site_list, 'site_id')
252 slice_list = self.plshell.GetSlices(self.plauth, slice_ids)
253 slices = list_to_dict(slice_list, 'slice_id')
255 person_list = self.plshell.GetPersons(self.plauth, person_ids)
256 persons = list_to_dict(person_list, 'person_id')
257 for person in persons:
258 key_ids.extend(persons[person]['key_ids'])
260 pl_records = {'node': nodes, 'authority': sites,
261 'slice': slices, 'user': persons}
264 key_list = self.plshell.GetKeys(self.plauth, key_ids)
265 keys = list_to_dict(key_list, 'key_id')
268 for record in records:
269 # records with pointer==-1 do not have plc info.
270 # for example, the top level authority records which are
271 # authorities, but not PL "sites"
272 if record['pointer'] == -1:
275 for type in pl_records:
276 if record['type'] == type:
277 if record['pointer'] in pl_records[type]:
278 record.update(pl_records[type][record['pointer']])
281 if record['type'] == 'user':
282 pubkeys = [keys[key_id]['key'] for key_id in record['key_ids'] if key_id in keys]
283 record['keys'] = pubkeys
285 # fill in record hrns
286 records = self.fill_record_hrns(records)
290 def fill_record_hrns(self, records):
292 convert pl ids to hrns
296 slice_ids, person_ids, site_ids, node_ids = [], [], [], []
297 for record in records:
298 if 'site_id' in record:
299 site_ids.append(record['site_id'])
300 if 'site_ids' in records:
301 site_ids.extend(record['site_ids'])
302 if 'person_ids' in record:
303 person_ids.extend(record['person_ids'])
304 if 'slice_ids' in record:
305 slice_ids.extend(record['slice_ids'])
306 if 'node_ids' in record:
307 node_ids.extend(record['node_ids'])
310 slices, persons, sites, nodes = {}, {}, {}, {}
312 site_list = self.plshell.GetSites(self.plauth, site_ids, ['site_id', 'login_base'])
313 sites = list_to_dict(site_list, 'site_id')
315 person_list = self.plshell.GetPersons(self.plauth, person_ids, ['person_id', 'email'])
316 persons = list_to_dict(person_list, 'person_id')
318 slice_list = self.plshell.GetSlices(self.plauth, slice_ids, ['slice_id', 'name'])
319 slices = list_to_dict(slice_list, 'slice_id')
321 node_list = self.plshell.GetNodes(self.plauth, node_ids, ['node_id', 'hostname'])
322 nodes = list_to_dict(node_list, 'node_id')
324 # convert ids to hrns
325 for record in records:
327 # get all relevant data
328 type = record['type']
329 pointer = record['pointer']
335 if 'site_id' in record:
336 site = sites[record['site_id']]
337 login_base = site['login_base']
338 record['site'] = ".".join([auth_hrn, login_base])
339 if 'person_ids' in record:
340 emails = [persons[person_id]['email'] for person_id in record['person_ids'] \
341 if person_id in persons]
342 usernames = [email.split('@')[0] for email in emails]
343 person_hrns = [".".join([auth_hrn, login_base, username]) for username in usernames]
344 record['persons'] = person_hrns
345 if 'slice_ids' in record:
346 slicenames = [slices[slice_id]['name'] for slice_id in record['slice_ids'] \
347 if slice_id in slices]
348 slice_hrns = [slicename_to_hrn(auth_hrn, slicename) for slicename in slicenames]
349 record['slices'] = slice_hrns
350 if 'node_ids' in record:
351 hostnames = [nodes[node_id]['hostname'] for node_id in record['node_ids'] \
353 node_hrns = [hostname_to_hrn(auth_hrn, login_base, hostname) for hostname in hostnames]
354 record['nodes'] = node_hrns
355 if 'site_ids' in record:
356 login_bases = [sites[site_id]['login_base'] for site_id in record['site_ids'] \
358 site_hrns = [".".join([auth_hrn, lbase]) for lbase in login_bases]
359 record['sites'] = site_hrns
363 def fill_record_sfa_info(self, records):
367 for record in records:
368 person_ids.extend(record.get("person_ids", []))
369 site_ids.extend(record.get("site_ids", []))
370 if 'site_id' in record:
371 site_ids.append(record['site_id'])
373 # get all pis from the sites we've encountered
374 # and store them in a dictionary keyed on site_id
377 pi_filter = {'|roles': ['pi'], '|site_ids': site_ids}
378 pi_list = self.plshell.GetPersons(self.plauth, pi_filter, ['person_id', 'site_ids'])
380 # we will need the pi's hrns also
381 person_ids.append(pi['person_id'])
383 # we also need to keep track of the sites these pis
385 for site_id in pi['site_ids']:
386 if site_id in site_pis:
387 site_pis[site_id].append(pi)
389 site_pis[site_id] = [pi]
391 # get sfa records for all records associated with these records.
392 # we'll replace pl ids (person_ids) with hrns from the sfa records
395 # get the sfa records
396 table = self.SfaTable()
397 person_list, persons = [], {}
398 person_list = table.find({'type': 'user', 'pointer': person_ids})
399 persons = list_to_dict(person_list, 'pointer')
402 pl_person_list, pl_persons = [], {}
403 pl_person_list = self.plshell.GetPersons(self.plauth, person_ids, ['person_id', 'roles'])
404 pl_persons = list_to_dict(pl_person_list, 'person_id')
407 for record in records:
408 # skip records with no pl info (top level authorities)
409 if record['pointer'] == -1:
412 type = record['type']
413 if (type == "slice"):
415 researchers = [persons[person_id]['hrn'] for person_id in record['person_ids'] \
416 if person_id in persons]
417 sfa_info['researcher'] = researchers
418 # pis at the slice's site
419 pl_pis = site_pis[record['site_id']]
420 pi_ids = [pi['person_id'] for pi in pl_pis]
421 sfa_info['PI'] = [persons[person_id]['hrn'] for person_id in pi_ids]
423 elif (type == "authority"):
424 pis, techs, admins = [], [], []
425 for pointer in record['person_ids']:
426 if pointer not in persons or pointer not in pl_persons:
427 # this means there is not sfa or pl record for this user
429 hrn = persons[pointer]['hrn']
430 roles = pl_persons[pointer]['roles']
438 sfa_info['operator'] = techs
439 sfa_info['owner'] = admins
440 # xxx TODO: OrganizationName
441 elif (type == "node"):
442 sfa_info['dns'] = record.get("hostname", "")
443 # xxx TODO: URI, LatLong, IP, DNS
445 elif (type == "user"):
446 sfa_info['email'] = record.get("email", "")
447 # xxx TODO: PostalAddress, Phone
448 record.update(sfa_info)
450 def fill_record_info(self, records):
452 Given a SFA record, fill in the PLC specific and SFA specific
453 fields in the record.
455 if not isinstance(records, list):
458 self.fill_record_pl_info(records)
459 self.fill_record_sfa_info(records)
461 def update_membership_list(self, oldRecord, record, listName, addFunc, delFunc):
462 # get a list of the HRNs tht are members of the old and new records
464 oldList = oldRecord.get(listName, [])
467 newList = record.get(listName, [])
469 # if the lists are the same, then we don't have to update anything
470 if (oldList == newList):
473 # build a list of the new person ids, by looking up each person to get
476 table = self.SfaTable()
477 records = table.find({'type': 'user', 'hrn': newList})
479 newIdList.append(rec['pointer'])
481 # build a list of the old person ids from the person_ids field
483 oldIdList = oldRecord.get("person_ids", [])
484 containerId = oldRecord.get_pointer()
486 # if oldRecord==None, then we are doing a Register, instead of an
489 containerId = record.get_pointer()
491 # add people who are in the new list, but not the oldList
492 for personId in newIdList:
493 if not (personId in oldIdList):
494 addFunc(self.plauth, personId, containerId)
496 # remove people who are in the old list, but not the new list
497 for personId in oldIdList:
498 if not (personId in newIdList):
499 delFunc(self.plauth, personId, containerId)
501 def update_membership(self, oldRecord, record):
502 if record.type == "slice":
503 self.update_membership_list(oldRecord, record, 'researcher',
504 self.plshell.AddPersonToSlice,
505 self.plshell.DeletePersonFromSlice)
506 elif record.type == "authority":
512 class ComponentAPI(BaseAPI):
514 def __init__(self, config = "/etc/sfa/sfa_config.py", encoding = "utf-8", methods='sfa.methods',
515 peer_cert = None, interface = None, key_file = None, cert_file = None):
517 BaseAPI.__init__(self, config=config, encoding=encoding, methods=methods, peer_cert=peer_cert,
518 interface=interface, key_file=key_file, cert_file=cert_file)
519 self.encoding = encoding
521 # Better just be documenting the API
525 self.nodemanager = NodeManager(self.config)
527 def sliver_exists(self):
528 sliver_dict = self.nodemanager.GetXIDs()
529 if slicename in sliver_dict.keys():