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 *
24 from collections import defaultdict
26 def list_to_dict(recs, key):
28 convert a list of dictionaries into a dictionary keyed on the
29 specified dictionary key
31 keys = [rec[key] for rec in recs]
32 return dict(zip(keys, recs))
34 class SfaAPI(BaseAPI):
36 # flat list of method names
38 methods = sfa.methods.all
40 def __init__(self, config = "/etc/sfa/sfa_config.py", encoding = "utf-8",
41 methods='sfa.methods', peer_cert = None, interface = None,
42 key_file = None, cert_file = None, cache = None):
43 BaseAPI.__init__(self, config=config, encoding=encoding, methods=methods, \
44 peer_cert=peer_cert, interface=interface, key_file=key_file, \
45 cert_file=cert_file, cache=cache)
47 self.encoding = encoding
49 from sfa.util.table import SfaTable
50 self.SfaTable = SfaTable
51 # Better just be documenting the API
56 self.config = Config(config)
57 self.auth = Auth(peer_cert)
58 self.interface = interface
59 self.key_file = key_file
60 self.key = Keypair(filename=self.key_file)
61 self.cert_file = cert_file
62 self.cert = Certificate(filename=self.cert_file)
63 self.credential = None
64 # Initialize the PLC shell only if SFA wraps a myPLC
65 rspec_type = self.config.get_aggregate_type()
66 if (rspec_type == 'pl' or rspec_type == 'vini'):
67 self.plshell = self.getPLCShell()
68 self.plshell_version = "4.3"
70 self.hrn = self.config.SFA_INTERFACE_HRN
71 self.time_format = "%Y-%m-%d %H:%M:%S"
72 self.logger=get_sfa_logger()
74 def getPLCShell(self):
75 self.plauth = {'Username': self.config.SFA_PLC_USER,
76 'AuthMethod': 'password',
77 'AuthString': self.config.SFA_PLC_PASSWORD}
79 self.plshell_type = 'xmlrpc'
81 url = self.config.SFA_PLC_URL
82 shell = xmlrpclib.Server(url, verbose = 0, allow_none = True)
85 def getCredential(self):
86 if self.interface in ['registry']:
87 return self.getCredentialFromLocalRegistry()
89 return self.getCredentialFromRegistry()
91 def getCredentialFromRegistry(self):
93 Get our credential from a remote registry
96 path = self.config.SFA_DATA_DIR
97 filename = ".".join([self.interface, self.hrn, type, "cred"])
98 cred_filename = path + os.sep + filename
100 credential = Credential(filename = cred_filename)
101 return credential.save_to_string(save_parents=True)
103 from sfa.server.registry import Registries
104 registries = Registries(self)
105 registry = registries[self.hrn]
106 cert_string=self.cert.save_to_string(save_parents=True)
107 # get self credential
108 self_cred = registry.get_self_credential(cert_string, type, self.hrn)
110 cred = registry.get_credential(self_cred, type, self.hrn)
113 Credential(string=cred).save_to_file(cred_filename, save_parents=True)
116 def getCredentialFromLocalRegistry(self):
118 Get our current credential directly from the local registry.
122 auth_hrn = self.auth.get_authority(hrn)
124 # is this a root or sub authority
125 if not auth_hrn or hrn == self.config.SFA_INTERFACE_HRN:
127 auth_info = self.auth.get_auth_info(auth_hrn)
128 table = self.SfaTable()
129 records = table.findObjects(hrn)
133 type = record['type']
134 object_gid = record.get_gid_object()
135 new_cred = Credential(subject = object_gid.get_subject())
136 new_cred.set_gid_caller(object_gid)
137 new_cred.set_gid_object(object_gid)
138 new_cred.set_issuer(key=auth_info.get_pkey_object(), subject=auth_hrn)
139 new_cred.set_pubkey(object_gid.get_pubkey())
140 r1 = determine_rights(type, hrn)
141 new_cred.set_privileges(r1)
143 auth_kind = "authority,ma,sa"
145 new_cred.set_parent(self.auth.hierarchy.get_auth_cred(auth_hrn, kind=auth_kind))
150 return new_cred.save_to_string(save_parents=True)
153 def loadCredential (self):
155 Attempt to load credential from file if it exists. If it doesnt get
156 credential from registry.
159 # see if this file exists
160 # XX This is really the aggregate's credential. Using this is easier than getting
161 # the registry's credential from iteslf (ssl errors).
162 ma_cred_filename = self.config.SFA_DATA_DIR + os.sep + self.interface + self.hrn + ".ma.cred"
164 self.credential = Credential(filename = ma_cred_filename)
166 self.credential = self.getCredentialFromRegistry()
169 # Convert SFA fields to PLC fields for use when registering up updating
170 # registry record in the PLC database
172 # @param type type of record (user, slice, ...)
173 # @param hrn human readable name
174 # @param sfa_fields dictionary of SFA fields
175 # @param pl_fields dictionary of PLC fields (output)
177 def sfa_fields_to_pl_fields(self, type, hrn, record):
179 def convert_ints(tmpdict, int_fields):
180 for field in int_fields:
182 tmpdict[field] = int(tmpdict[field])
185 #for field in record:
186 # pl_record[field] = record[field]
189 if not "instantiation" in pl_record:
190 pl_record["instantiation"] = "plc-instantiated"
191 pl_record["name"] = hrn_to_pl_slicename(hrn)
193 pl_record["url"] = record["url"]
194 if "description" in record:
195 pl_record["description"] = record["description"]
196 if "expires" in record:
197 pl_record["expires"] = int(record["expires"])
200 if not "hostname" in pl_record:
201 if not "hostname" in record:
202 raise MissingSfaInfo("hostname")
203 pl_record["hostname"] = record["hostname"]
204 if not "model" in pl_record:
205 pl_record["model"] = "geni"
207 elif type == "authority":
208 pl_record["login_base"] = hrn_to_pl_login_base(hrn)
210 if not "name" in pl_record:
211 pl_record["name"] = hrn
213 if not "abbreviated_name" in pl_record:
214 pl_record["abbreviated_name"] = hrn
216 if not "enabled" in pl_record:
217 pl_record["enabled"] = True
219 if not "is_public" in pl_record:
220 pl_record["is_public"] = True
224 def fill_record_pl_info(self, records):
226 Fill in the planetlab specific fields of a SFA record. This
227 involves calling the appropriate PLC method to retrieve the
228 database record for the object.
230 PLC data is filled into the pl_info field of the record.
232 @param record: record to fill in field (in/out param)
235 node_ids, site_ids, slice_ids = [], [], []
236 person_ids, key_ids = [], []
237 type_map = {'node': node_ids, 'authority': site_ids,
238 'slice': slice_ids, 'user': person_ids}
240 for record in records:
241 for type in type_map:
242 if type == record['type']:
243 type_map[type].append(record['pointer'])
246 nodes, sites, slices, persons, keys = {}, {}, {}, {}, {}
248 node_list = self.plshell.GetNodes(self.plauth, node_ids)
249 nodes = list_to_dict(node_list, 'node_id')
251 site_list = self.plshell.GetSites(self.plauth, site_ids)
252 sites = list_to_dict(site_list, 'site_id')
254 slice_list = self.plshell.GetSlices(self.plauth, slice_ids)
255 slices = list_to_dict(slice_list, 'slice_id')
257 person_list = self.plshell.GetPersons(self.plauth, person_ids)
258 persons = list_to_dict(person_list, 'person_id')
259 for person in persons:
260 key_ids.extend(persons[person]['key_ids'])
262 pl_records = {'node': nodes, 'authority': sites,
263 'slice': slices, 'user': persons}
266 key_list = self.plshell.GetKeys(self.plauth, key_ids)
267 keys = list_to_dict(key_list, 'key_id')
270 for record in records:
271 # records with pointer==-1 do not have plc info.
272 # for example, the top level authority records which are
273 # authorities, but not PL "sites"
274 if record['pointer'] == -1:
277 for type in pl_records:
278 if record['type'] == type:
279 if record['pointer'] in pl_records[type]:
280 record.update(pl_records[type][record['pointer']])
283 if record['type'] == 'user':
284 pubkeys = [keys[key_id]['key'] for key_id in record['key_ids'] if key_id in keys]
285 record['keys'] = pubkeys
287 # fill in record hrns
288 records = self.fill_record_hrns(records)
292 def fill_record_hrns(self, records):
294 convert pl ids to hrns
298 slice_ids, person_ids, site_ids, node_ids = [], [], [], []
299 for record in records:
300 if 'site_id' in record:
301 site_ids.append(record['site_id'])
302 if 'site_ids' in records:
303 site_ids.extend(record['site_ids'])
304 if 'person_ids' in record:
305 person_ids.extend(record['person_ids'])
306 if 'slice_ids' in record:
307 slice_ids.extend(record['slice_ids'])
308 if 'node_ids' in record:
309 node_ids.extend(record['node_ids'])
312 slices, persons, sites, nodes = {}, {}, {}, {}
314 site_list = self.plshell.GetSites(self.plauth, site_ids, ['site_id', 'login_base'])
315 sites = list_to_dict(site_list, 'site_id')
317 person_list = self.plshell.GetPersons(self.plauth, person_ids, ['person_id', 'email'])
318 persons = list_to_dict(person_list, 'person_id')
320 slice_list = self.plshell.GetSlices(self.plauth, slice_ids, ['slice_id', 'name'])
321 slices = list_to_dict(slice_list, 'slice_id')
323 node_list = self.plshell.GetNodes(self.plauth, node_ids, ['node_id', 'hostname'])
324 nodes = list_to_dict(node_list, 'node_id')
326 # convert ids to hrns
327 for record in records:
329 # get all relevant data
330 type = record['type']
331 pointer = record['pointer']
337 if 'site_id' in record:
338 site = sites[record['site_id']]
339 login_base = site['login_base']
340 record['site'] = ".".join([auth_hrn, login_base])
341 if 'person_ids' in record:
342 emails = [persons[person_id]['email'] for person_id in record['person_ids'] \
343 if person_id in persons]
344 usernames = [email.split('@')[0] for email in emails]
345 person_hrns = [".".join([auth_hrn, login_base, username]) for username in usernames]
346 record['persons'] = person_hrns
347 if 'slice_ids' in record:
348 slicenames = [slices[slice_id]['name'] for slice_id in record['slice_ids'] \
349 if slice_id in slices]
350 slice_hrns = [slicename_to_hrn(auth_hrn, slicename) for slicename in slicenames]
351 record['slices'] = slice_hrns
352 if 'node_ids' in record:
353 hostnames = [nodes[node_id]['hostname'] for node_id in record['node_ids'] \
355 node_hrns = [hostname_to_hrn(auth_hrn, login_base, hostname) for hostname in hostnames]
356 record['nodes'] = node_hrns
357 if 'site_ids' in record:
358 login_bases = [sites[site_id]['login_base'] for site_id in record['site_ids'] \
360 site_hrns = [".".join([auth_hrn, lbase]) for lbase in login_bases]
361 record['sites'] = site_hrns
365 def fill_record_sfa_info(self, records):
367 def startswith(prefix, values):
368 return [value for value in values if value.startswith(prefix)]
373 for record in records:
374 person_ids.extend(record.get("person_ids", []))
375 site_ids.extend(record.get("site_ids", []))
376 if 'site_id' in record:
377 site_ids.append(record['site_id'])
379 # get all pis from the sites we've encountered
380 # and store them in a dictionary keyed on site_id
383 pi_filter = {'|roles': ['pi'], '|site_ids': site_ids}
384 pi_list = self.plshell.GetPersons(self.plauth, pi_filter, ['person_id', 'site_ids'])
386 # we will need the pi's hrns also
387 person_ids.append(pi['person_id'])
389 # we also need to keep track of the sites these pis
391 for site_id in pi['site_ids']:
392 if site_id in site_pis:
393 site_pis[site_id].append(pi)
395 site_pis[site_id] = [pi]
397 # get sfa records for all records associated with these records.
398 # we'll replace pl ids (person_ids) with hrns from the sfa records
401 # get the sfa records
402 table = self.SfaTable()
403 person_list, persons = [], {}
404 person_list = table.find({'type': 'user', 'pointer': person_ids})
405 # create a hrns keyed on the sfa record's pointer.
406 # Its possible for multiple records to have the same pointer so
407 # the dict's value will be a list of hrns.
408 persons = defaultdict(list)
409 for person in person_list:
410 persons[person['pointer']].append(person)
413 pl_person_list, pl_persons = [], {}
414 pl_person_list = self.plshell.GetPersons(self.plauth, person_ids, ['person_id', 'roles'])
415 pl_persons = list_to_dict(pl_person_list, 'person_id')
418 for record in records:
419 # skip records with no pl info (top level authorities)
420 if record['pointer'] == -1:
423 type = record['type']
424 if (type == "slice"):
425 # all slice users are researchers
427 record['researchers'] = []
428 for person_id in record['person_ids']:
429 hrns = [person['hrn'] for person in persons[person_id]]
430 record['researchers'].extend(hrns)
432 # pis at the slice's site
433 pl_pis = site_pis[record['site_id']]
434 pi_ids = [pi['person_id'] for pi in pl_pis]
435 for person_id in pi_ids:
436 hrns = [person['hrn'] for person in persons[person_id]]
437 record['PI'].extend(hrns)
439 elif (type == "authority"):
441 record['operator'] = []
443 for pointer in record['person_ids']:
444 if pointer not in persons or pointer not in pl_persons:
445 # this means there is not sfa or pl record for this user
447 hrns = [person['hrn'] for person in persons[pointer]]
448 roles = pl_persons[pointer]['roles']
450 record['PI'].extend(hrns)
452 record['operator'].extend(hrns)
454 record['owner'].extend(hrns)
455 # xxx TODO: OrganizationName
456 elif (type == "node"):
457 sfa_info['dns'] = record.get("hostname", "")
458 # xxx TODO: URI, LatLong, IP, DNS
460 elif (type == "user"):
461 sfa_info['email'] = record.get("email", "")
462 # xxx TODO: PostalAddress, Phone
463 record.update(sfa_info)
465 def fill_record_info(self, records):
467 Given a SFA record, fill in the PLC specific and SFA specific
468 fields in the record.
470 if not isinstance(records, list):
473 self.fill_record_pl_info(records)
474 self.fill_record_sfa_info(records)
476 def update_membership_list(self, oldRecord, record, listName, addFunc, delFunc):
477 # get a list of the HRNs tht are members of the old and new records
479 oldList = oldRecord.get(listName, [])
482 newList = record.get(listName, [])
484 # if the lists are the same, then we don't have to update anything
485 if (oldList == newList):
488 # build a list of the new person ids, by looking up each person to get
491 table = self.SfaTable()
492 records = table.find({'type': 'user', 'hrn': newList})
494 newIdList.append(rec['pointer'])
496 # build a list of the old person ids from the person_ids field
498 oldIdList = oldRecord.get("person_ids", [])
499 containerId = oldRecord.get_pointer()
501 # if oldRecord==None, then we are doing a Register, instead of an
504 containerId = record.get_pointer()
506 # add people who are in the new list, but not the oldList
507 for personId in newIdList:
508 if not (personId in oldIdList):
509 addFunc(self.plauth, personId, containerId)
511 # remove people who are in the old list, but not the new list
512 for personId in oldIdList:
513 if not (personId in newIdList):
514 delFunc(self.plauth, personId, containerId)
516 def update_membership(self, oldRecord, record):
517 if record.type == "slice":
518 self.update_membership_list(oldRecord, record, 'researcher',
519 self.plshell.AddPersonToSlice,
520 self.plshell.DeletePersonFromSlice)
521 elif record.type == "authority":
527 class ComponentAPI(BaseAPI):
529 def __init__(self, config = "/etc/sfa/sfa_config.py", encoding = "utf-8", methods='sfa.methods',
530 peer_cert = None, interface = None, key_file = None, cert_file = None):
532 BaseAPI.__init__(self, config=config, encoding=encoding, methods=methods, peer_cert=peer_cert,
533 interface=interface, key_file=key_file, cert_file=cert_file)
534 self.encoding = encoding
536 # Better just be documenting the API
540 self.nodemanager = NodeManager(self.config)
542 def sliver_exists(self):
543 sliver_dict = self.nodemanager.GetXIDs()
544 if slicename in sliver_dict.keys():