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):
26 keys = [rec[key] for rec in recs]
27 return dict(zip(keys, recs))
29 class SfaAPI(BaseAPI):
31 # flat list of method names
33 methods = sfa.methods.all
35 def __init__(self, config = "/etc/sfa/sfa_config.py", encoding = "utf-8", methods='sfa.methods', \
36 peer_cert = None, interface = None, key_file = None, cert_file = None):
37 BaseAPI.__init__(self, config=config, encoding=encoding, methods=methods, \
38 peer_cert=peer_cert, interface=interface, key_file=key_file, \
41 self.encoding = encoding
43 from sfa.util.table import SfaTable
44 self.SfaTable = SfaTable
45 # Better just be documenting the API
50 self.config = Config(config)
51 self.auth = Auth(peer_cert)
52 self.interface = interface
53 self.key_file = key_file
54 self.key = Keypair(filename=self.key_file)
55 self.cert_file = cert_file
56 self.cert = Certificate(filename=self.cert_file)
57 self.credential = None
58 # Initialize the PLC shell only if SFA wraps a myPLC
59 rspec_type = self.config.get_aggregate_type()
60 if (rspec_type == 'pl' or rspec_type == 'vini'):
61 self.plshell = self.getPLCShell()
62 self.plshell_version = self.getPLCShellVersion()
64 self.hrn = self.config.SFA_INTERFACE_HRN
65 self.time_format = "%Y-%m-%d %H:%M:%S"
66 self.logger=get_sfa_logger()
68 def getPLCShell(self):
69 self.plauth = {'Username': self.config.SFA_PLC_USER,
70 'AuthMethod': 'password',
71 'AuthString': self.config.SFA_PLC_PASSWORD}
74 sys.path.append(os.path.dirname(os.path.realpath("/usr/bin/plcsh")))
75 self.plshell_type = 'direct'
77 shell = PLC.Shell.Shell(globals = globals())
80 self.plshell_type = 'xmlrpc'
82 url = self.config.SFA_PLC_URL
83 shell = xmlrpclib.Server(url, verbose = 0, allow_none = True)
86 def getPLCShellVersion(self):
87 # We need to figure out what version of PLCAPI we are talking to.
88 # Some calls we need to make later will be different depending on
91 # This is probably a bad way to determine api versions
92 # but its easy and will work for now. Lets try to make
93 # a call that only exists is PLCAPI.4.3. If it fails, we
94 # can assume the api version is 4.2
95 self.plshell.GetTagTypes(self.plauth)
101 def getCredential(self):
102 if self.interface in ['registry']:
103 return self.getCredentialFromLocalRegistry()
105 return self.getCredentialFromRegistry()
107 def getCredentialFromRegistry(self):
109 Get our credential from a remote registry
112 path = self.config.SFA_DATA_DIR
113 filename = ".".join([self.interface, self.hrn, type, "cred"])
114 cred_filename = path + os.sep + filename
116 credential = Credential(filename = cred_filename)
117 return credential.save_to_string(save_parents=True)
119 from sfa.server.registry import Registries
120 registries = Registries(self)
121 registry = registries[self.hrn]
122 cert_string=self.cert.save_to_string(save_parents=True)
123 # get self credential
124 self_cred = registry.get_self_credential(cert_string, type, self.hrn)
126 cred = registry.get_credential(self_cred, type, self.hrn)
129 Credential(string=cred).save_to_file(cred_filename, save_parents=True)
132 def getCredentialFromLocalRegistry(self):
134 Get our current credential directly from the local registry.
138 auth_hrn = self.auth.get_authority(hrn)
140 # is this a root or sub authority
141 if not auth_hrn or hrn == self.config.SFA_INTERFACE_HRN:
143 auth_info = self.auth.get_auth_info(auth_hrn)
144 table = self.SfaTable()
145 records = table.findObjects(hrn)
149 type = record['type']
150 object_gid = record.get_gid_object()
151 new_cred = Credential(subject = object_gid.get_subject())
152 new_cred.set_gid_caller(object_gid)
153 new_cred.set_gid_object(object_gid)
154 new_cred.set_issuer(key=auth_info.get_pkey_object(), subject=auth_hrn)
155 new_cred.set_pubkey(object_gid.get_pubkey())
156 r1 = determine_rights(type, hrn)
157 new_cred.set_privileges(r1)
159 auth_kind = "authority,ma,sa"
161 new_cred.set_parent(self.auth.hierarchy.get_auth_cred(auth_hrn, kind=auth_kind))
166 return new_cred.save_to_string(save_parents=True)
169 def loadCredential (self):
171 Attempt to load credential from file if it exists. If it doesnt get
172 credential from registry.
175 # see if this file exists
176 # XX This is really the aggregate's credential. Using this is easier than getting
177 # the registry's credential from iteslf (ssl errors).
178 ma_cred_filename = self.config.SFA_DATA_DIR + os.sep + self.interface + self.hrn + ".ma.cred"
180 self.credential = Credential(filename = ma_cred_filename)
182 self.credential = self.getCredentialFromRegistry()
185 # Convert SFA fields to PLC fields for use when registering up updating
186 # registry record in the PLC database
188 # @param type type of record (user, slice, ...)
189 # @param hrn human readable name
190 # @param sfa_fields dictionary of SFA fields
191 # @param pl_fields dictionary of PLC fields (output)
193 def sfa_fields_to_pl_fields(self, type, hrn, record):
195 def convert_ints(tmpdict, int_fields):
196 for field in int_fields:
198 tmpdict[field] = int(tmpdict[field])
201 #for field in record:
202 # pl_record[field] = record[field]
205 if not "instantiation" in pl_record:
206 pl_record["instantiation"] = "plc-instantiated"
207 pl_record["name"] = hrn_to_pl_slicename(hrn)
209 pl_record["url"] = record["url"]
210 if "description" in record:
211 pl_record["description"] = record["description"]
212 if "expires" in record:
213 pl_record["expires"] = int(record["expires"])
216 if not "hostname" in pl_record:
217 if not "hostname" in record:
218 raise MissingSfaInfo("hostname")
219 pl_record["hostname"] = record["hostname"]
220 if not "model" in pl_record:
221 pl_record["model"] = "geni"
223 elif type == "authority":
224 pl_record["login_base"] = hrn_to_pl_login_base(hrn)
226 if not "name" in pl_record:
227 pl_record["name"] = hrn
229 if not "abbreviated_name" in pl_record:
230 pl_record["abbreviated_name"] = hrn
232 if not "enabled" in pl_record:
233 pl_record["enabled"] = True
235 if not "is_public" in pl_record:
236 pl_record["is_public"] = True
240 def fill_record_pl_info(self, records):
242 Fill in the planetlab specific fields of a SFA record. This
243 involves calling the appropriate PLC method to retrieve the
244 database record for the object.
246 PLC data is filled into the pl_info field of the record.
248 @param record: record to fill in field (in/out param)
251 node_ids, site_ids, slice_ids = [], [], []
252 person_ids, key_ids = [], []
253 type_map = {'node': node_ids, 'authority': site_ids,
254 'slice': slice_ids, 'user': person_ids}
256 for record in records:
257 for type in type_map:
258 if type == record['type']:
259 type_map[type].append(record['pointer'])
262 nodes, sites, slices, persons, keys = {}, {}, {}, {}, {}
264 node_list = self.plshell.GetNodes(self.plauth, node_ids)
265 nodes = list_to_dict(node_list, 'node_id')
267 site_list = self.plshell.GetSites(self.plauth, site_ids)
268 sites = list_to_dict(site_list, 'site_id')
270 slice_list = self.plshell.GetSlices(self.plauth, slice_ids)
271 slices = list_to_dict(slice_list, 'slice_id')
273 person_list = self.plshell.GetPersons(self.plauth, person_ids)
274 persons = list_to_dict(person_list, 'person_id')
275 for person in persons:
276 key_ids.extend(persons[person]['key_ids'])
278 pl_records = {'node': nodes, 'authority': sites,
279 'slice': slices, 'user': persons}
282 key_list = self.plshell.GetKeys(self.plauth, key_ids)
283 keys = list_to_dict(key_list, 'key_id')
286 for record in records:
287 # records with pointer==-1 do not have plc info associated with them.
288 # for example, the top level authority records which are
289 # authorities, but not PL "sites"
290 if record['pointer'] == -1:
293 for type in pl_records:
294 if record['type'] == type:
295 if record['pointer'] in pl_records[type]:
296 record.update(pl_records[type][record['pointer']])
299 if record['type'] == 'user':
300 pubkeys = [keys[key_id]['key'] for key_id in record['key_ids'] if key_id in keys]
301 record['keys'] = pubkeys
303 # fill in record hrns
304 records = self.fill_record_hrns(records)
308 def fill_record_hrns(self, records):
310 convert pl ids to hrns
314 slice_ids, person_ids, site_ids, node_ids = [], [], [], []
315 for record in records:
316 if 'site_id' in record:
317 site_ids.append(record['site_id'])
318 if 'site_ids' in records:
319 site_ids.extend(record['site_ids'])
320 if 'person_ids' in record:
321 person_ids.extend(record['person_ids'])
322 if 'slice_ids' in record:
323 slice_ids.extend(record['slice_ids'])
324 if 'node_ids' in record:
325 node_ids.extend(record['node_ids'])
328 slices, persons, sites, nodes = {}, {}, {}, {}
330 site_list = self.plshell.GetSites(self.plauth, site_ids, ['site_id', 'login_base'])
331 sites = list_to_dict(site_list, 'site_id')
333 person_list = self.plshell.GetPersons(self.plauth, person_ids, ['person_id', 'email'])
334 persons = list_to_dict(person_list, 'person_id')
336 slice_list = self.plshell.GetSlices(self.plauth, slice_ids, ['slice_id', 'name'])
337 slices = list_to_dict(slice_list, 'slice_id')
339 node_list = self.plshell.GetNodes(self.plauth, node_ids, ['node_id', 'hostname'])
340 nodes = list_to_dict(node_list, 'node_id')
342 # convert ids to hrns
343 for record in records:
345 # get all relevant data
346 type = record['type']
347 pointer = record['pointer']
353 if 'site_id' in record:
354 site = sites[record['site_id']]
355 login_base = site['login_base']
356 record['site'] = ".".join([auth_hrn, login_base])
357 if 'person_ids' in record:
358 emails = [persons[person_id]['email'] for person_id in record['person_ids'] \
359 if person_id in persons]
360 usernames = [email.split('@')[0] for email in emails]
361 person_hrns = [".".join([auth_hrn, login_base, username]) for username in usernames]
362 record['persons'] = person_hrns
363 if 'slice_ids' in record:
364 slicenames = [slices[slice_id]['name'] for slice_id in record['slice_ids'] \
365 if slice_id in slices]
366 slice_hrns = [slicename_to_hrn(auth_hrn, slicename) for slicename in slicenames]
367 record['slices'] = slice_hrns
368 if 'node_ids' in record:
369 hostnames = [nodes[node_id]['hostname'] for node_id in record['node_ids'] \
371 node_hrns = [hostname_to_hrn(auth_hrn, login_base, hostname) for hostname in hostnames]
372 record['nodes'] = node_hrns
373 if 'site_ids' in record:
374 login_bases = [sites[site_id]['login_base'] for site_id in record['site_ids'] \
376 site_hrns = [".".join([auth_hrn, lbase]) for lbase in login_bases]
377 record['sites'] = site_hrns
381 def fill_record_sfa_info(self, records):
383 has_authority = False
386 for record in records:
387 if record['type'] == 'authority':
389 person_ids.extend(record.get("person_ids", []))
392 table = self.SfaTable()
393 person_list, persons = [], {}
394 pl_person_list, pl_persons = [], {}
395 person_list = table.find({'type': 'user', 'pointer': person_ids})
396 persons = list_to_dict(person_list, 'pointer')
398 pl_person_list = self.plshell.GetPersons(self.plauth, person_ids, ['person_id', 'roles'])
399 pl_persons = list_to_dict(pl_person_list, 'person_id')
403 for record in records:
404 # skip records with no pl info (top level authorities)
405 if record['pointer'] == -1:
408 type = record['type']
409 if (type == "slice"):
410 researchers = [persons[person_id]['hrn'] for person_id in record['person_ids'] \
411 if person_id in persons]
412 sfa_info['researcher'] = researchers
414 elif (type == "authority"):
415 pis, techs, admins = [], [], []
416 for pointer in record['person_ids']:
417 if pointer not in persons or pointer not in pl_persons:
418 # this means there is not sfa or pl record for this user
420 hrn = persons[pointer]['hrn']
421 roles = pl_persons[pointer]['roles']
430 sfa_info['operator'] = techs
431 sfa_info['owner'] = admins
432 # xxx TODO: OrganizationName
433 elif (type == "node"):
434 sfa_info['dns'] = record.get("hostname", "")
435 # xxx TODO: URI, LatLong, IP, DNS
437 elif (type == "user"):
438 sfa_info['email'] = record.get("email", "")
439 # xxx TODO: PostalAddress, Phone
440 record.update(sfa_info)
442 def fill_record_info(self, records):
444 Given a SFA record, fill in the PLC specific and SFA specific
445 fields in the record.
447 if not isinstance(records, list):
450 self.fill_record_pl_info(records)
451 self.fill_record_sfa_info(records)
453 def update_membership_list(self, oldRecord, record, listName, addFunc, delFunc):
454 # get a list of the HRNs tht are members of the old and new records
456 oldList = oldRecord.get(listName, [])
459 newList = record.get(listName, [])
461 # if the lists are the same, then we don't have to update anything
462 if (oldList == newList):
465 # build a list of the new person ids, by looking up each person to get
468 table = self.SfaTable()
469 records = table.find({'type': 'user', 'hrn': newList})
471 newIdList.append(rec['pointer'])
473 # build a list of the old person ids from the person_ids field
475 oldIdList = oldRecord.get("person_ids", [])
476 containerId = oldRecord.get_pointer()
478 # if oldRecord==None, then we are doing a Register, instead of an
481 containerId = record.get_pointer()
483 # add people who are in the new list, but not the oldList
484 for personId in newIdList:
485 if not (personId in oldIdList):
486 addFunc(self.plauth, personId, containerId)
488 # remove people who are in the old list, but not the new list
489 for personId in oldIdList:
490 if not (personId in newIdList):
491 delFunc(self.plauth, personId, containerId)
493 def update_membership(self, oldRecord, record):
494 if record.type == "slice":
495 self.update_membership_list(oldRecord, record, 'researcher',
496 self.plshell.AddPersonToSlice,
497 self.plshell.DeletePersonFromSlice)
498 elif record.type == "authority":
504 class ComponentAPI(BaseAPI):
506 def __init__(self, config = "/etc/sfa/sfa_config.py", encoding = "utf-8", methods='sfa.methods',
507 peer_cert = None, interface = None, key_file = None, cert_file = None):
509 BaseAPI.__init__(self, config=config, encoding=encoding, methods=methods, peer_cert=peer_cert,
510 interface=interface, key_file=key_file, cert_file=cert_file)
511 self.encoding = encoding
513 # Better just be documenting the API
517 self.nodemanager = NodeManager(self.config)
519 def sliver_exists(self):
520 sliver_dict = self.nodemanager.GetXIDs()
521 if slicename in sliver_dict.keys():