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 = "4.3"
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 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(key=auth_info.get_pkey_object(), subject=auth_hrn)
140 new_cred.set_pubkey(object_gid.get_pubkey())
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 associated with them.
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 has_authority = False
371 for record in records:
372 if record['type'] == 'authority':
374 person_ids.extend(record.get("person_ids", []))
377 table = self.SfaTable()
378 person_list, persons = [], {}
379 pl_person_list, pl_persons = [], {}
380 person_list = table.find({'type': 'user', 'pointer': person_ids})
381 persons = list_to_dict(person_list, 'pointer')
383 pl_person_list = self.plshell.GetPersons(self.plauth, person_ids, ['person_id', 'roles'])
384 pl_persons = list_to_dict(pl_person_list, 'person_id')
388 for record in records:
389 # skip records with no pl info (top level authorities)
390 if record['pointer'] == -1:
393 type = record['type']
394 if (type == "slice"):
395 researchers = [persons[person_id]['hrn'] for person_id in record['person_ids'] \
396 if person_id in persons]
397 sfa_info['researcher'] = researchers
399 elif (type == "authority"):
400 pis, techs, admins = [], [], []
401 for pointer in record['person_ids']:
402 if pointer not in persons or pointer not in pl_persons:
403 # this means there is not sfa or pl record for this user
405 hrn = persons[pointer]['hrn']
406 roles = pl_persons[pointer]['roles']
415 sfa_info['operator'] = techs
416 sfa_info['owner'] = admins
417 # xxx TODO: OrganizationName
418 elif (type == "node"):
419 sfa_info['dns'] = record.get("hostname", "")
420 # xxx TODO: URI, LatLong, IP, DNS
422 elif (type == "user"):
423 sfa_info['email'] = record.get("email", "")
424 # xxx TODO: PostalAddress, Phone
425 record.update(sfa_info)
427 def fill_record_info(self, records):
429 Given a SFA record, fill in the PLC specific and SFA specific
430 fields in the record.
432 if not isinstance(records, list):
435 self.fill_record_pl_info(records)
436 self.fill_record_sfa_info(records)
438 def update_membership_list(self, oldRecord, record, listName, addFunc, delFunc):
439 # get a list of the HRNs tht are members of the old and new records
441 oldList = oldRecord.get(listName, [])
444 newList = record.get(listName, [])
446 # if the lists are the same, then we don't have to update anything
447 if (oldList == newList):
450 # build a list of the new person ids, by looking up each person to get
453 table = self.SfaTable()
454 records = table.find({'type': 'user', 'hrn': newList})
456 newIdList.append(rec['pointer'])
458 # build a list of the old person ids from the person_ids field
460 oldIdList = oldRecord.get("person_ids", [])
461 containerId = oldRecord.get_pointer()
463 # if oldRecord==None, then we are doing a Register, instead of an
466 containerId = record.get_pointer()
468 # add people who are in the new list, but not the oldList
469 for personId in newIdList:
470 if not (personId in oldIdList):
471 addFunc(self.plauth, personId, containerId)
473 # remove people who are in the old list, but not the new list
474 for personId in oldIdList:
475 if not (personId in newIdList):
476 delFunc(self.plauth, personId, containerId)
478 def update_membership(self, oldRecord, record):
479 if record.type == "slice":
480 self.update_membership_list(oldRecord, record, 'researcher',
481 self.plshell.AddPersonToSlice,
482 self.plshell.DeletePersonFromSlice)
483 elif record.type == "authority":
489 class ComponentAPI(BaseAPI):
491 def __init__(self, config = "/etc/sfa/sfa_config.py", encoding = "utf-8", methods='sfa.methods',
492 peer_cert = None, interface = None, key_file = None, cert_file = None):
494 BaseAPI.__init__(self, config=config, encoding=encoding, methods=methods, peer_cert=peer_cert,
495 interface=interface, key_file=key_file, cert_file=cert_file)
496 self.encoding = encoding
498 # Better just be documenting the API
502 self.nodemanager = NodeManager(self.config)
504 def sliver_exists(self):
505 sliver_dict = self.nodemanager.GetXIDs()
506 if slicename in sliver_dict.keys():