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",
40 methods='sfa.methods', peer_cert = None, interface = None,
41 key_file = None, cert_file = None, cache = None):
42 BaseAPI.__init__(self, config=config, encoding=encoding, methods=methods, \
43 peer_cert=peer_cert, interface=interface, key_file=key_file, \
44 cert_file=cert_file, cache=cache)
46 self.encoding = encoding
48 from sfa.util.table import SfaTable
49 self.SfaTable = SfaTable
50 # Better just be documenting the API
55 self.config = Config(config)
56 self.auth = Auth(peer_cert)
57 self.interface = interface
58 self.key_file = key_file
59 self.key = Keypair(filename=self.key_file)
60 self.cert_file = cert_file
61 self.cert = Certificate(filename=self.cert_file)
62 self.credential = None
63 # Initialize the PLC shell only if SFA wraps a myPLC
64 rspec_type = self.config.get_aggregate_type()
65 if (rspec_type == 'pl' or rspec_type == 'vini'):
66 self.plshell = self.getPLCShell()
67 self.plshell_version = "4.3"
69 self.hrn = self.config.SFA_INTERFACE_HRN
70 self.time_format = "%Y-%m-%d %H:%M:%S"
71 self.logger=get_sfa_logger()
73 def getPLCShell(self):
74 self.plauth = {'Username': self.config.SFA_PLC_USER,
75 'AuthMethod': 'password',
76 'AuthString': self.config.SFA_PLC_PASSWORD}
78 self.plshell_type = 'xmlrpc'
80 url = self.config.SFA_PLC_URL
81 shell = xmlrpclib.Server(url, verbose = 0, allow_none = True)
84 def getCredential(self):
85 if self.interface in ['registry']:
86 return self.getCredentialFromLocalRegistry()
88 return self.getCredentialFromRegistry()
90 def getCredentialFromRegistry(self):
92 Get our credential from a remote registry
95 path = self.config.SFA_DATA_DIR
96 filename = ".".join([self.interface, self.hrn, type, "cred"])
97 cred_filename = path + os.sep + filename
99 credential = Credential(filename = cred_filename)
100 return credential.save_to_string(save_parents=True)
102 from sfa.server.registry import Registries
103 registries = Registries(self)
104 registry = registries[self.hrn]
105 cert_string=self.cert.save_to_string(save_parents=True)
106 # get self credential
107 self_cred = registry.get_self_credential(cert_string, type, self.hrn)
109 cred = registry.get_credential(self_cred, type, self.hrn)
112 Credential(string=cred).save_to_file(cred_filename, save_parents=True)
115 def getCredentialFromLocalRegistry(self):
117 Get our current credential directly from the local registry.
121 auth_hrn = self.auth.get_authority(hrn)
123 # is this a root or sub authority
124 if not auth_hrn or hrn == self.config.SFA_INTERFACE_HRN:
126 auth_info = self.auth.get_auth_info(auth_hrn)
127 table = self.SfaTable()
128 records = table.findObjects(hrn)
132 type = record['type']
133 object_gid = record.get_gid_object()
134 new_cred = Credential(subject = object_gid.get_subject())
135 new_cred.set_gid_caller(object_gid)
136 new_cred.set_gid_object(object_gid)
137 new_cred.set_issuer(key=auth_info.get_pkey_object(), subject=auth_hrn)
138 new_cred.set_pubkey(object_gid.get_pubkey())
139 r1 = determine_rights(type, hrn)
140 new_cred.set_privileges(r1)
142 auth_kind = "authority,ma,sa"
144 new_cred.set_parent(self.auth.hierarchy.get_auth_cred(auth_hrn, kind=auth_kind))
149 return new_cred.save_to_string(save_parents=True)
152 def loadCredential (self):
154 Attempt to load credential from file if it exists. If it doesnt get
155 credential from registry.
158 # see if this file exists
159 # XX This is really the aggregate's credential. Using this is easier than getting
160 # the registry's credential from iteslf (ssl errors).
161 ma_cred_filename = self.config.SFA_DATA_DIR + os.sep + self.interface + self.hrn + ".ma.cred"
163 self.credential = Credential(filename = ma_cred_filename)
165 self.credential = self.getCredentialFromRegistry()
168 # Convert SFA fields to PLC fields for use when registering up updating
169 # registry record in the PLC database
171 # @param type type of record (user, slice, ...)
172 # @param hrn human readable name
173 # @param sfa_fields dictionary of SFA fields
174 # @param pl_fields dictionary of PLC fields (output)
176 def sfa_fields_to_pl_fields(self, type, hrn, record):
178 def convert_ints(tmpdict, int_fields):
179 for field in int_fields:
181 tmpdict[field] = int(tmpdict[field])
184 #for field in record:
185 # pl_record[field] = record[field]
188 if not "instantiation" in pl_record:
189 pl_record["instantiation"] = "plc-instantiated"
190 pl_record["name"] = hrn_to_pl_slicename(hrn)
192 pl_record["url"] = record["url"]
193 if "description" in record:
194 pl_record["description"] = record["description"]
195 if "expires" in record:
196 pl_record["expires"] = int(record["expires"])
199 if not "hostname" in pl_record:
200 if not "hostname" in record:
201 raise MissingSfaInfo("hostname")
202 pl_record["hostname"] = record["hostname"]
203 if not "model" in pl_record:
204 pl_record["model"] = "geni"
206 elif type == "authority":
207 pl_record["login_base"] = hrn_to_pl_login_base(hrn)
209 if not "name" in pl_record:
210 pl_record["name"] = hrn
212 if not "abbreviated_name" in pl_record:
213 pl_record["abbreviated_name"] = hrn
215 if not "enabled" in pl_record:
216 pl_record["enabled"] = True
218 if not "is_public" in pl_record:
219 pl_record["is_public"] = True
223 def fill_record_pl_info(self, records):
225 Fill in the planetlab specific fields of a SFA record. This
226 involves calling the appropriate PLC method to retrieve the
227 database record for the object.
229 PLC data is filled into the pl_info field of the record.
231 @param record: record to fill in field (in/out param)
234 node_ids, site_ids, slice_ids = [], [], []
235 person_ids, key_ids = [], []
236 type_map = {'node': node_ids, 'authority': site_ids,
237 'slice': slice_ids, 'user': person_ids}
239 for record in records:
240 for type in type_map:
241 if type == record['type']:
242 type_map[type].append(record['pointer'])
245 nodes, sites, slices, persons, keys = {}, {}, {}, {}, {}
247 node_list = self.plshell.GetNodes(self.plauth, node_ids)
248 nodes = list_to_dict(node_list, 'node_id')
250 site_list = self.plshell.GetSites(self.plauth, site_ids)
251 sites = list_to_dict(site_list, 'site_id')
253 slice_list = self.plshell.GetSlices(self.plauth, slice_ids)
254 slices = list_to_dict(slice_list, 'slice_id')
256 person_list = self.plshell.GetPersons(self.plauth, person_ids)
257 persons = list_to_dict(person_list, 'person_id')
258 for person in persons:
259 key_ids.extend(persons[person]['key_ids'])
261 pl_records = {'node': nodes, 'authority': sites,
262 'slice': slices, 'user': persons}
265 key_list = self.plshell.GetKeys(self.plauth, key_ids)
266 keys = list_to_dict(key_list, 'key_id')
269 for record in records:
270 # records with pointer==-1 do not have plc info.
271 # for example, the top level authority records which are
272 # authorities, but not PL "sites"
273 if record['pointer'] == -1:
276 for type in pl_records:
277 if record['type'] == type:
278 if record['pointer'] in pl_records[type]:
279 record.update(pl_records[type][record['pointer']])
282 if record['type'] == 'user':
283 pubkeys = [keys[key_id]['key'] for key_id in record['key_ids'] if key_id in keys]
284 record['keys'] = pubkeys
286 # fill in record hrns
287 records = self.fill_record_hrns(records)
291 def fill_record_hrns(self, records):
293 convert pl ids to hrns
297 slice_ids, person_ids, site_ids, node_ids = [], [], [], []
298 for record in records:
299 if 'site_id' in record:
300 site_ids.append(record['site_id'])
301 if 'site_ids' in records:
302 site_ids.extend(record['site_ids'])
303 if 'person_ids' in record:
304 person_ids.extend(record['person_ids'])
305 if 'slice_ids' in record:
306 slice_ids.extend(record['slice_ids'])
307 if 'node_ids' in record:
308 node_ids.extend(record['node_ids'])
311 slices, persons, sites, nodes = {}, {}, {}, {}
313 site_list = self.plshell.GetSites(self.plauth, site_ids, ['site_id', 'login_base'])
314 sites = list_to_dict(site_list, 'site_id')
316 person_list = self.plshell.GetPersons(self.plauth, person_ids, ['person_id', 'email'])
317 persons = list_to_dict(person_list, 'person_id')
319 slice_list = self.plshell.GetSlices(self.plauth, slice_ids, ['slice_id', 'name'])
320 slices = list_to_dict(slice_list, 'slice_id')
322 node_list = self.plshell.GetNodes(self.plauth, node_ids, ['node_id', 'hostname'])
323 nodes = list_to_dict(node_list, 'node_id')
325 # convert ids to hrns
326 for record in records:
328 # get all relevant data
329 type = record['type']
330 pointer = record['pointer']
336 if 'site_id' in record:
337 site = sites[record['site_id']]
338 login_base = site['login_base']
339 record['site'] = ".".join([auth_hrn, login_base])
340 if 'person_ids' in record:
341 emails = [persons[person_id]['email'] for person_id in record['person_ids'] \
342 if person_id in persons]
343 usernames = [email.split('@')[0] for email in emails]
344 person_hrns = [".".join([auth_hrn, login_base, username]) for username in usernames]
345 record['persons'] = person_hrns
346 if 'slice_ids' in record:
347 slicenames = [slices[slice_id]['name'] for slice_id in record['slice_ids'] \
348 if slice_id in slices]
349 slice_hrns = [slicename_to_hrn(auth_hrn, slicename) for slicename in slicenames]
350 record['slices'] = slice_hrns
351 if 'node_ids' in record:
352 hostnames = [nodes[node_id]['hostname'] for node_id in record['node_ids'] \
354 node_hrns = [hostname_to_hrn(auth_hrn, login_base, hostname) for hostname in hostnames]
355 record['nodes'] = node_hrns
356 if 'site_ids' in record:
357 login_bases = [sites[site_id]['login_base'] for site_id in record['site_ids'] \
359 site_hrns = [".".join([auth_hrn, lbase]) for lbase in login_bases]
360 record['sites'] = site_hrns
364 def fill_record_sfa_info(self, records):
368 for record in records:
369 person_ids.extend(record.get("person_ids", []))
370 site_ids.extend(record.get("site_ids", []))
371 if 'site_id' in record:
372 site_ids.append(record['site_id'])
374 # get all pis from the sites we've encountered
375 # and store them in a dictionary keyed on site_id
378 pi_filter = {'|roles': ['pi'], '|site_ids': site_ids}
379 pi_list = self.plshell.GetPersons(self.plauth, pi_filter, ['person_id', 'site_ids'])
381 # we will need the pi's hrns also
382 person_ids.append(pi['person_id'])
384 # we also need to keep track of the sites these pis
386 for site_id in pi['site_ids']:
387 if site_id in site_pis:
388 site_pis[site_id].append(pi)
390 site_pis[site_id] = [pi]
392 # get sfa records for all records associated with these records.
393 # we'll replace pl ids (person_ids) with hrns from the sfa records
396 # get the sfa records
397 table = self.SfaTable()
398 person_list, persons = [], {}
399 person_list = table.find({'type': 'user', 'pointer': person_ids})
400 persons = list_to_dict(person_list, 'pointer')
403 pl_person_list, pl_persons = [], {}
404 pl_person_list = self.plshell.GetPersons(self.plauth, person_ids, ['person_id', 'roles'])
405 pl_persons = list_to_dict(pl_person_list, 'person_id')
408 for record in records:
409 # skip records with no pl info (top level authorities)
410 if record['pointer'] == -1:
413 type = record['type']
414 if (type == "slice"):
416 researchers = [persons[person_id]['hrn'] for person_id in record['person_ids'] \
417 if person_id in persons]
418 sfa_info['researcher'] = researchers
419 # pis at the slice's site
420 pl_pis = site_pis[record['site_id']]
421 pi_ids = [pi['person_id'] for pi in pl_pis]
422 sfa_info['PI'] = [persons[person_id]['hrn'] for person_id in pi_ids]
424 elif (type == "authority"):
425 pis, techs, admins = [], [], []
426 for pointer in record['person_ids']:
427 if pointer not in persons or pointer not in pl_persons:
428 # this means there is not sfa or pl record for this user
430 hrn = persons[pointer]['hrn']
431 roles = pl_persons[pointer]['roles']
439 sfa_info['operator'] = techs
440 sfa_info['owner'] = admins
441 # xxx TODO: OrganizationName
442 elif (type == "node"):
443 sfa_info['dns'] = record.get("hostname", "")
444 # xxx TODO: URI, LatLong, IP, DNS
446 elif (type == "user"):
447 sfa_info['email'] = record.get("email", "")
448 # xxx TODO: PostalAddress, Phone
449 record.update(sfa_info)
451 def fill_record_info(self, records):
453 Given a SFA record, fill in the PLC specific and SFA specific
454 fields in the record.
456 if not isinstance(records, list):
459 self.fill_record_pl_info(records)
460 self.fill_record_sfa_info(records)
462 def update_membership_list(self, oldRecord, record, listName, addFunc, delFunc):
463 # get a list of the HRNs tht are members of the old and new records
465 oldList = oldRecord.get(listName, [])
468 newList = record.get(listName, [])
470 # if the lists are the same, then we don't have to update anything
471 if (oldList == newList):
474 # build a list of the new person ids, by looking up each person to get
477 table = self.SfaTable()
478 records = table.find({'type': 'user', 'hrn': newList})
480 newIdList.append(rec['pointer'])
482 # build a list of the old person ids from the person_ids field
484 oldIdList = oldRecord.get("person_ids", [])
485 containerId = oldRecord.get_pointer()
487 # if oldRecord==None, then we are doing a Register, instead of an
490 containerId = record.get_pointer()
492 # add people who are in the new list, but not the oldList
493 for personId in newIdList:
494 if not (personId in oldIdList):
495 addFunc(self.plauth, personId, containerId)
497 # remove people who are in the old list, but not the new list
498 for personId in oldIdList:
499 if not (personId in newIdList):
500 delFunc(self.plauth, personId, containerId)
502 def update_membership(self, oldRecord, record):
503 if record.type == "slice":
504 self.update_membership_list(oldRecord, record, 'researcher',
505 self.plshell.AddPersonToSlice,
506 self.plshell.DeletePersonFromSlice)
507 elif record.type == "authority":
513 class ComponentAPI(BaseAPI):
515 def __init__(self, config = "/etc/sfa/sfa_config.py", encoding = "utf-8", methods='sfa.methods',
516 peer_cert = None, interface = None, key_file = None, cert_file = None):
518 BaseAPI.__init__(self, config=config, encoding=encoding, methods=methods, peer_cert=peer_cert,
519 interface=interface, key_file=key_file, cert_file=cert_file)
520 self.encoding = encoding
522 # Better just be documenting the API
526 self.nodemanager = NodeManager(self.config)
528 def sliver_exists(self):
529 sliver_dict = self.nodemanager.GetXIDs()
530 if slicename in sliver_dict.keys():