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}
80 self.plshell_type = 'xmlrpc'
82 url = self.config.SFA_PLC_URL
83 shell = xmlrpclib.Server(url, verbose = 0, allow_none = True)
86 def getCredential(self):
87 if self.interface in ['registry']:
88 return self.getCredentialFromLocalRegistry()
90 return self.getCredentialFromRegistry()
92 def getCredentialFromRegistry(self):
94 Get our credential from a remote registry
97 path = self.config.SFA_DATA_DIR
98 filename = ".".join([self.interface, self.hrn, type, "cred"])
99 cred_filename = path + os.sep + filename
101 credential = Credential(filename = cred_filename)
102 return credential.save_to_string(save_parents=True)
104 from sfa.server.registry import Registries
105 registries = Registries(self)
106 registry = registries[self.hrn]
107 cert_string=self.cert.save_to_string(save_parents=True)
108 # get self credential
109 self_cred = registry.get_self_credential(cert_string, type, self.hrn)
111 cred = registry.get_credential(self_cred, type, self.hrn)
114 Credential(string=cred).save_to_file(cred_filename, save_parents=True)
117 def getCredentialFromLocalRegistry(self):
119 Get our current credential directly from the local registry.
123 auth_hrn = self.auth.get_authority(hrn)
125 # is this a root or sub authority
126 if not auth_hrn or hrn == self.config.SFA_INTERFACE_HRN:
128 auth_info = self.auth.get_auth_info(auth_hrn)
129 table = self.SfaTable()
130 records = table.findObjects(hrn)
134 type = record['type']
135 object_gid = record.get_gid_object()
136 new_cred = Credential(subject = object_gid.get_subject())
137 new_cred.set_gid_caller(object_gid)
138 new_cred.set_gid_object(object_gid)
139 new_cred.set_issuer_keys(auth_info.get_privkey_filename(), auth_info.get_gid_filename())
141 r1 = determine_rights(type, hrn)
142 new_cred.set_privileges(r1)
144 auth_kind = "authority,ma,sa"
146 new_cred.set_parent(self.auth.hierarchy.get_auth_cred(auth_hrn, kind=auth_kind))
151 return new_cred.save_to_string(save_parents=True)
154 def loadCredential (self):
156 Attempt to load credential from file if it exists. If it doesnt get
157 credential from registry.
160 # see if this file exists
161 # XX This is really the aggregate's credential. Using this is easier than getting
162 # the registry's credential from iteslf (ssl errors).
163 ma_cred_filename = self.config.SFA_DATA_DIR + os.sep + self.interface + self.hrn + ".ma.cred"
165 self.credential = Credential(filename = ma_cred_filename)
167 self.credential = self.getCredentialFromRegistry()
170 # Convert SFA fields to PLC fields for use when registering up updating
171 # registry record in the PLC database
173 # @param type type of record (user, slice, ...)
174 # @param hrn human readable name
175 # @param sfa_fields dictionary of SFA fields
176 # @param pl_fields dictionary of PLC fields (output)
178 def sfa_fields_to_pl_fields(self, type, hrn, record):
180 def convert_ints(tmpdict, int_fields):
181 for field in int_fields:
183 tmpdict[field] = int(tmpdict[field])
186 #for field in record:
187 # pl_record[field] = record[field]
190 if not "instantiation" in pl_record:
191 pl_record["instantiation"] = "plc-instantiated"
192 pl_record["name"] = hrn_to_pl_slicename(hrn)
194 pl_record["url"] = record["url"]
195 if "description" in record:
196 pl_record["description"] = record["description"]
197 if "expires" in record:
198 pl_record["expires"] = int(record["expires"])
201 if not "hostname" in pl_record:
202 if not "hostname" in record:
203 raise MissingSfaInfo("hostname")
204 pl_record["hostname"] = record["hostname"]
205 if not "model" in pl_record:
206 pl_record["model"] = "geni"
208 elif type == "authority":
209 pl_record["login_base"] = hrn_to_pl_login_base(hrn)
211 if not "name" in pl_record:
212 pl_record["name"] = hrn
214 if not "abbreviated_name" in pl_record:
215 pl_record["abbreviated_name"] = hrn
217 if not "enabled" in pl_record:
218 pl_record["enabled"] = True
220 if not "is_public" in pl_record:
221 pl_record["is_public"] = True
225 def fill_record_pl_info(self, records):
227 Fill in the planetlab specific fields of a SFA record. This
228 involves calling the appropriate PLC method to retrieve the
229 database record for the object.
231 PLC data is filled into the pl_info field of the record.
233 @param record: record to fill in field (in/out param)
236 node_ids, site_ids, slice_ids = [], [], []
237 person_ids, key_ids = [], []
238 type_map = {'node': node_ids, 'authority': site_ids,
239 'slice': slice_ids, 'user': person_ids}
241 for record in records:
242 for type in type_map:
243 if type == record['type']:
244 type_map[type].append(record['pointer'])
247 nodes, sites, slices, persons, keys = {}, {}, {}, {}, {}
249 node_list = self.plshell.GetNodes(self.plauth, node_ids)
250 nodes = list_to_dict(node_list, 'node_id')
252 site_list = self.plshell.GetSites(self.plauth, site_ids)
253 sites = list_to_dict(site_list, 'site_id')
255 slice_list = self.plshell.GetSlices(self.plauth, slice_ids)
256 slices = list_to_dict(slice_list, 'slice_id')
258 person_list = self.plshell.GetPersons(self.plauth, person_ids)
259 persons = list_to_dict(person_list, 'person_id')
260 for person in persons:
261 key_ids.extend(persons[person]['key_ids'])
263 pl_records = {'node': nodes, 'authority': sites,
264 'slice': slices, 'user': persons}
267 key_list = self.plshell.GetKeys(self.plauth, key_ids)
268 keys = list_to_dict(key_list, 'key_id')
271 for record in records:
272 # records with pointer==-1 do not have plc info.
273 # for example, the top level authority records which are
274 # authorities, but not PL "sites"
275 if record['pointer'] == -1:
278 for type in pl_records:
279 if record['type'] == type:
280 if record['pointer'] in pl_records[type]:
281 record.update(pl_records[type][record['pointer']])
284 if record['type'] == 'user':
285 pubkeys = [keys[key_id]['key'] for key_id in record['key_ids'] if key_id in keys]
286 record['keys'] = pubkeys
288 # fill in record hrns
289 records = self.fill_record_hrns(records)
293 def fill_record_hrns(self, records):
295 convert pl ids to hrns
299 slice_ids, person_ids, site_ids, node_ids = [], [], [], []
300 for record in records:
301 if 'site_id' in record:
302 site_ids.append(record['site_id'])
303 if 'site_ids' in records:
304 site_ids.extend(record['site_ids'])
305 if 'person_ids' in record:
306 person_ids.extend(record['person_ids'])
307 if 'slice_ids' in record:
308 slice_ids.extend(record['slice_ids'])
309 if 'node_ids' in record:
310 node_ids.extend(record['node_ids'])
313 slices, persons, sites, nodes = {}, {}, {}, {}
315 site_list = self.plshell.GetSites(self.plauth, site_ids, ['site_id', 'login_base'])
316 sites = list_to_dict(site_list, 'site_id')
318 person_list = self.plshell.GetPersons(self.plauth, person_ids, ['person_id', 'email'])
319 persons = list_to_dict(person_list, 'person_id')
321 slice_list = self.plshell.GetSlices(self.plauth, slice_ids, ['slice_id', 'name'])
322 slices = list_to_dict(slice_list, 'slice_id')
324 node_list = self.plshell.GetNodes(self.plauth, node_ids, ['node_id', 'hostname'])
325 nodes = list_to_dict(node_list, 'node_id')
327 # convert ids to hrns
328 for record in records:
330 # get all relevant data
331 type = record['type']
332 pointer = record['pointer']
338 if 'site_id' in record:
339 site = sites[record['site_id']]
340 login_base = site['login_base']
341 record['site'] = ".".join([auth_hrn, login_base])
342 if 'person_ids' in record:
343 emails = [persons[person_id]['email'] for person_id in record['person_ids'] \
344 if person_id in persons]
345 usernames = [email.split('@')[0] for email in emails]
346 person_hrns = [".".join([auth_hrn, login_base, username]) for username in usernames]
347 record['persons'] = person_hrns
348 if 'slice_ids' in record:
349 slicenames = [slices[slice_id]['name'] for slice_id in record['slice_ids'] \
350 if slice_id in slices]
351 slice_hrns = [slicename_to_hrn(auth_hrn, slicename) for slicename in slicenames]
352 record['slices'] = slice_hrns
353 if 'node_ids' in record:
354 hostnames = [nodes[node_id]['hostname'] for node_id in record['node_ids'] \
356 node_hrns = [hostname_to_hrn(auth_hrn, login_base, hostname) for hostname in hostnames]
357 record['nodes'] = node_hrns
358 if 'site_ids' in record:
359 login_bases = [sites[site_id]['login_base'] for site_id in record['site_ids'] \
361 site_hrns = [".".join([auth_hrn, lbase]) for lbase in login_bases]
362 record['sites'] = site_hrns
366 def fill_record_sfa_info(self, records):
368 def startswith(prefix, values):
369 return [value for value in values if value.startswith(prefix)]
374 for record in records:
375 person_ids.extend(record.get("person_ids", []))
376 site_ids.extend(record.get("site_ids", []))
377 if 'site_id' in record:
378 site_ids.append(record['site_id'])
380 # get all pis from the sites we've encountered
381 # and store them in a dictionary keyed on site_id
384 pi_filter = {'|roles': ['pi'], '|site_ids': site_ids}
385 pi_list = self.plshell.GetPersons(self.plauth, pi_filter, ['person_id', 'site_ids'])
387 # we will need the pi's hrns also
388 person_ids.append(pi['person_id'])
390 # we also need to keep track of the sites these pis
392 for site_id in pi['site_ids']:
393 if site_id in site_pis:
394 site_pis[site_id].append(pi)
396 site_pis[site_id] = [pi]
398 # get sfa records for all records associated with these records.
399 # we'll replace pl ids (person_ids) with hrns from the sfa records
402 # get the sfa records
403 table = self.SfaTable()
404 person_list, persons = [], {}
405 person_list = table.find({'type': 'user', 'pointer': person_ids})
406 # create a hrns keyed on the sfa record's pointer.
407 # Its possible for multiple records to have the same pointer so
408 # the dict's value will be a list of hrns.
409 persons = defaultdict(list)
410 for person in person_list:
411 persons[person['pointer']].append(person)
414 pl_person_list, pl_persons = [], {}
415 pl_person_list = self.plshell.GetPersons(self.plauth, person_ids, ['person_id', 'roles'])
416 pl_persons = list_to_dict(pl_person_list, 'person_id')
419 for record in records:
420 # skip records with no pl info (top level authorities)
421 if record['pointer'] == -1:
424 type = record['type']
425 if (type == "slice"):
426 # all slice users are researchers
428 record['researchers'] = []
429 for person_id in record['person_ids']:
430 hrns = [person['hrn'] for person in persons[person_id]]
431 record['researchers'].extend(hrns)
433 # pis at the slice's site
434 pl_pis = site_pis[record['site_id']]
435 pi_ids = [pi['person_id'] for pi in pl_pis]
436 for person_id in pi_ids:
437 hrns = [person['hrn'] for person in persons[person_id]]
438 record['PI'].extend(hrns)
440 elif (type == "authority"):
442 record['operator'] = []
444 for pointer in record['person_ids']:
445 if pointer not in persons or pointer not in pl_persons:
446 # this means there is not sfa or pl record for this user
448 hrns = [person['hrn'] for person in persons[pointer]]
449 roles = pl_persons[pointer]['roles']
451 record['PI'].extend(hrns)
453 record['operator'].extend(hrns)
455 record['owner'].extend(hrns)
456 # xxx TODO: OrganizationName
457 elif (type == "node"):
458 sfa_info['dns'] = record.get("hostname", "")
459 # xxx TODO: URI, LatLong, IP, DNS
461 elif (type == "user"):
462 sfa_info['email'] = record.get("email", "")
463 # xxx TODO: PostalAddress, Phone
464 record.update(sfa_info)
466 def fill_record_info(self, records):
468 Given a SFA record, fill in the PLC specific and SFA specific
469 fields in the record.
471 if not isinstance(records, list):
474 self.fill_record_pl_info(records)
475 self.fill_record_sfa_info(records)
477 def update_membership_list(self, oldRecord, record, listName, addFunc, delFunc):
478 # get a list of the HRNs tht are members of the old and new records
480 oldList = oldRecord.get(listName, [])
483 newList = record.get(listName, [])
485 # if the lists are the same, then we don't have to update anything
486 if (oldList == newList):
489 # build a list of the new person ids, by looking up each person to get
492 table = self.SfaTable()
493 records = table.find({'type': 'user', 'hrn': newList})
495 newIdList.append(rec['pointer'])
497 # build a list of the old person ids from the person_ids field
499 oldIdList = oldRecord.get("person_ids", [])
500 containerId = oldRecord.get_pointer()
502 # if oldRecord==None, then we are doing a Register, instead of an
505 containerId = record.get_pointer()
507 # add people who are in the new list, but not the oldList
508 for personId in newIdList:
509 if not (personId in oldIdList):
510 addFunc(self.plauth, personId, containerId)
512 # remove people who are in the old list, but not the new list
513 for personId in oldIdList:
514 if not (personId in newIdList):
515 delFunc(self.plauth, personId, containerId)
517 def update_membership(self, oldRecord, record):
518 if record.type == "slice":
519 self.update_membership_list(oldRecord, record, 'researcher',
520 self.plshell.AddPersonToSlice,
521 self.plshell.DeletePersonFromSlice)
522 elif record.type == "authority":
528 class ComponentAPI(BaseAPI):
530 def __init__(self, config = "/etc/sfa/sfa_config.py", encoding = "utf-8", methods='sfa.methods',
531 peer_cert = None, interface = None, key_file = None, cert_file = None):
533 BaseAPI.__init__(self, config=config, encoding=encoding, methods=methods, peer_cert=peer_cert,
534 interface=interface, key_file=key_file, cert_file=cert_file)
535 self.encoding = encoding
537 # Better just be documenting the API
541 self.nodemanager = NodeManager(self.config)
543 def sliver_exists(self):
544 sliver_dict = self.nodemanager.GetXIDs()
545 if slicename in sliver_dict.keys():