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))
30 class SfaAPI(BaseAPI):
32 # flat list of method names
34 methods = sfa.methods.all
36 def __init__(self, config = "/etc/sfa/sfa_config.py", encoding = "utf-8", methods='sfa.methods', \
37 peer_cert = None, interface = None, key_file = None, cert_file = None):
38 BaseAPI.__init__(self, config=config, encoding=encoding, methods=methods, \
39 peer_cert=peer_cert, interface=interface, key_file=key_file, \
42 self.encoding = encoding
44 from sfa.util.table import SfaTable
45 self.SfaTable = SfaTable
46 # Better just be documenting the API
51 self.config = Config(config)
52 self.auth = Auth(peer_cert)
53 self.interface = interface
54 self.key_file = key_file
55 self.key = Keypair(filename=self.key_file)
56 self.cert_file = cert_file
57 self.cert = Certificate(filename=self.cert_file)
58 self.credential = None
59 # Initialize the PLC shell only if SFA wraps a myPLC
60 rspec_type = self.config.get_aggregate_type()
61 if (rspec_type == 'pl' or rspec_type == 'vini'):
62 self.plshell = self.getPLCShell()
63 self.plshell_version = self.getPLCShellVersion()
65 self.hrn = self.config.SFA_INTERFACE_HRN
66 self.time_format = "%Y-%m-%d %H:%M:%S"
67 self.logger=get_sfa_logger()
69 def getPLCShell(self):
70 self.plauth = {'Username': self.config.SFA_PLC_USER,
71 'AuthMethod': 'password',
72 '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())
78 shell.AuthCheck(self.plauth)
81 self.plshell_type = 'xmlrpc'
83 url = self.config.SFA_PLC_URL
84 shell = xmlrpclib.Server(url, verbose = 0, allow_none = True)
85 shell.AuthCheck(self.plauth)
88 def getPLCShellVersion(self):
89 # We need to figure out what version of PLCAPI we are talking to.
90 # Some calls we need to make later will be different depending on
93 # This is probably a bad way to determine api versions
94 # but its easy and will work for now. Lets try to make
95 # a call that only exists is PLCAPI.4.3. If it fails, we
96 # can assume the api version is 4.2
97 self.plshell.GetTagTypes(self.plauth)
103 def getCredential(self):
104 if self.interface in ['registry']:
105 return self.getCredentialFromLocalRegistry()
107 return self.getCredentialFromRegistry()
109 def getCredentialFromRegistry(self):
111 Get our credential from a remote registry
114 path = self.config.SFA_DATA_DIR
115 filename = ".".join([self.interface, self.hrn, type, "cred"])
116 cred_filename = path + os.sep + filename
118 credential = Credential(filename = cred_filename)
119 return credential.save_to_string(save_parents=True)
121 from sfa.server.registry import Registries
122 registries = Registries(self)
123 registry = registries[self.hrn]
124 cert_string=self.cert.save_to_string(save_parents=True)
125 # get self credential
126 self_cred = registry.get_self_credential(cert_string, type, self.hrn)
128 cred = registry.get_credential(self_cred, type, self.hrn)
131 Credential(string=cred).save_to_file(cred_filename, save_parents=True)
134 def getCredentialFromLocalRegistry(self):
136 Get our current credential directly from the local registry.
140 auth_hrn = self.auth.get_authority(hrn)
142 # is this a root or sub authority
143 if not auth_hrn or hrn == self.config.SFA_INTERFACE_HRN:
145 auth_info = self.auth.get_auth_info(auth_hrn)
146 table = self.SfaTable()
147 records = table.findObjects(hrn)
151 type = record['type']
152 object_gid = record.get_gid_object()
153 new_cred = Credential(subject = object_gid.get_subject())
154 new_cred.set_gid_caller(object_gid)
155 new_cred.set_gid_object(object_gid)
156 new_cred.set_issuer(key=auth_info.get_pkey_object(), subject=auth_hrn)
157 new_cred.set_pubkey(object_gid.get_pubkey())
158 r1 = determine_rights(type, hrn)
159 new_cred.set_privileges(r1)
161 auth_kind = "authority,ma,sa"
163 new_cred.set_parent(self.auth.hierarchy.get_auth_cred(auth_hrn, kind=auth_kind))
168 return new_cred.save_to_string(save_parents=True)
171 def loadCredential (self):
173 Attempt to load credential from file if it exists. If it doesnt get
174 credential from registry.
177 # see if this file exists
178 # XX This is really the aggregate's credential. Using this is easier than getting
179 # the registry's credential from iteslf (ssl errors).
180 ma_cred_filename = self.config.SFA_DATA_DIR + os.sep + self.interface + self.hrn + ".ma.cred"
182 self.credential = Credential(filename = ma_cred_filename)
184 self.credential = self.getCredentialFromRegistry()
187 # Convert SFA fields to PLC fields for use when registering up updating
188 # registry record in the PLC database
190 # @param type type of record (user, slice, ...)
191 # @param hrn human readable name
192 # @param sfa_fields dictionary of SFA fields
193 # @param pl_fields dictionary of PLC fields (output)
195 def sfa_fields_to_pl_fields(self, type, hrn, record):
197 def convert_ints(tmpdict, int_fields):
198 for field in int_fields:
200 tmpdict[field] = int(tmpdict[field])
203 #for field in record:
204 # pl_record[field] = record[field]
207 if not "instantiation" in pl_record:
208 pl_record["instantiation"] = "plc-instantiated"
209 pl_record["name"] = hrn_to_pl_slicename(hrn)
211 pl_record["url"] = record["url"]
212 if "description" in record:
213 pl_record["description"] = record["description"]
214 if "expires" in record:
215 pl_record["expires"] = int(record["expires"])
218 if not "hostname" in pl_record:
219 if not "hostname" in record:
220 raise MissingSfaInfo("hostname")
221 pl_record["hostname"] = record["hostname"]
222 if not "model" in pl_record:
223 pl_record["model"] = "geni"
225 elif type == "authority":
226 pl_record["login_base"] = hrn_to_pl_login_base(hrn)
228 if not "name" in pl_record:
229 pl_record["name"] = hrn
231 if not "abbreviated_name" in pl_record:
232 pl_record["abbreviated_name"] = hrn
234 if not "enabled" in pl_record:
235 pl_record["enabled"] = True
237 if not "is_public" in pl_record:
238 pl_record["is_public"] = True
242 def fill_record_pl_info(self, records):
244 Fill in the planetlab specific fields of a SFA record. This
245 involves calling the appropriate PLC method to retrieve the
246 database record for the object.
248 PLC data is filled into the pl_info field of the record.
250 @param record: record to fill in field (in/out param)
253 node_ids, site_ids, slice_ids = [], [], []
254 person_ids, key_ids = [], []
255 type_map = {'node': node_ids, 'authority': site_ids,
256 'slice': slice_ids, 'user': person_ids}
258 for record in records:
259 for type in type_map:
260 if type == record['type']:
261 type_map[type].append(record['pointer'])
264 nodes, sites, slices, persons, keys = {}, {}, {}, {}, {}
266 node_list = self.plshell.GetNodes(self.plauth, node_ids)
267 nodes = list_to_dict(node_list, 'node_id')
269 site_list = self.plshell.GetSites(self.plauth, site_ids)
270 sites = list_to_dict(site_list, 'site_id')
272 slice_list = self.plshell.GetSlices(self.plauth, slice_ids)
273 slices = list_to_dict(slice_list, 'slice_id')
275 person_list = self.plshell.GetPersons(self.plauth, person_ids)
276 persons = list_to_dict(person_list, 'person_id')
277 for person in persons:
278 key_ids.extend(persons[person]['key_ids'])
280 pl_records = {'node': nodes, 'authority': sites,
281 'slice': slices, 'user': persons}
284 key_list = self.plshell.GetKeys(self.plauth, key_ids)
285 keys = list_to_dict(key_list, 'key_id')
288 for record in records:
289 # records with pointer==-1 do not have plc info associated with them.
290 # for example, the top level authority records which are
291 # authorities, but not PL "sites"
292 if record['pointer'] == -1:
295 for type in pl_records:
296 if record['type'] == type:
297 if record['pointer'] in pl_records[type]:
298 record.update(pl_records[type][record['pointer']])
301 if record['type'] == 'user':
302 pubkeys = [keys[key_id]['key'] for key_id in record['key_ids'] if key_id in keys]
303 record['keys'] = pubkeys
305 # fill in record hrns
306 records = self.fill_record_hrns(records)
310 def fill_record_hrns(self, records):
312 convert pl ids to hrns
316 slice_ids, person_ids, site_ids, node_ids = [], [], [], []
317 for record in records:
318 if 'site_id' in record:
319 site_ids.append(record['site_id'])
320 if 'site_ids' in records:
321 site_ids.extend(record['site_ids'])
322 if 'person_ids' in record:
323 person_ids.extend(record['person_ids'])
324 if 'slice_ids' in record:
325 slice_ids.extend(record['slice_ids'])
326 if 'node_ids' in record:
327 node_ids.extend(record['node_ids'])
330 slices, persons, sites, nodes = {}, {}, {}, {}
332 site_list = self.plshell.GetSites(self.plauth, site_ids, ['site_id', 'login_base'])
333 sites = list_to_dict(site_list, 'site_id')
335 person_list = self.plshell.GetPersons(self.plauth, person_ids, ['person_id', 'email'])
336 persons = list_to_dict(person_list, 'person_id')
338 slice_list = self.plshell.GetSlices(self.plauth, slice_ids, ['slice_id', 'name'])
339 slices = list_to_dict(slice_list, 'slice_id')
341 node_list = self.plshell.GetNodes(self.plauth, node_ids, ['node_id', 'hostname'])
342 nodes = list_to_dict(node_list, 'node_id')
344 # convert ids to hrns
345 for record in records:
347 # get all relevant data
348 type = record['type']
349 pointer = record['pointer']
355 if 'site_id' in record:
356 site = sites[record['site_id']]
357 login_base = site['login_base']
358 record['site'] = ".".join([auth_hrn, login_base])
359 if 'person_ids' in record:
360 emails = [persons[person_id]['email'] for person_id in record['person_ids'] \
361 if person_id in persons]
362 usernames = [email.split('@')[0] for email in emails]
363 person_hrns = [".".join([auth_hrn, login_base, username]) for username in usernames]
364 record['persons'] = person_hrns
365 if 'slice_ids' in record:
366 slicenames = [slices[slice_id]['name'] for slice_id in record['slice_ids'] \
367 if slice_id in slices]
368 slice_hrns = [slicename_to_hrn(auth_hrn, slicename) for slicename in slicenames]
369 record['slices'] = slice_hrns
370 if 'node_ids' in record:
371 hostnames = [nodes[node_id]['hostname'] for node_id in record['node_ids'] \
373 node_hrns = [hostname_to_hrn(auth_hrn, login_base, hostname) for hostname in hostnames]
374 record['nodes'] = node_hrns
375 if 'site_ids' in record:
376 login_bases = [sites[site_id]['login_base'] for site_id in record['site_ids'] \
378 site_hrns = [".".join([auth_hrn, lbase]) for lbase in login_bases]
379 record['sites'] = site_hrns
383 def fill_record_sfa_info(self, records):
385 has_authority = False
388 for record in records:
389 if record['type'] == 'authority':
391 person_ids.extend(record.get("person_ids", []))
394 table = self.SfaTable()
395 person_list, persons = [], {}
396 pl_person_list, pl_persons = [], {}
397 person_list = table.find({'type': 'user', 'pointer': person_ids})
398 persons = list_to_dict(person_list, 'pointer')
400 pl_person_list = self.plshell.GetPersons(self.plauth, person_ids, ['person_id', 'roles'])
401 pl_persons = list_to_dict(pl_person_list, 'person_id')
405 for record in records:
407 type = record['type']
408 if (type == "slice"):
409 researchers = [persons[person_id]['hrn'] for person_id in record['person_ids'] \
410 if person_id in persons]
411 sfa_info['researcher'] = researchers
413 elif (type == "authority"):
414 pis, techs, admins = [], [], []
415 for pointer in record['person_ids']:
416 if pointer not in persons or pointer not in pl_persons:
417 # this means there is not sfa or pl record for this user
419 hrn = persons[pointer]['hrn']
420 roles = pl_persons[pointer]['roles']
429 sfa_info['operator'] = techs
430 sfa_info['owner'] = admins
431 # xxx TODO: OrganizationName
432 elif (type == "node"):
433 sfa_info['dns'] = record.get("hostname", "")
434 # xxx TODO: URI, LatLong, IP, DNS
436 elif (type == "user"):
437 sfa_info['email'] = record.get("email", "")
438 # xxx TODO: PostalAddress, Phone
439 record.update(sfa_info)
441 def fill_record_info(self, records):
443 Given a SFA record, fill in the PLC specific and SFA specific
444 fields in the record.
446 if not isinstance(records, list):
449 self.fill_record_pl_info(records)
450 self.fill_record_sfa_info(records)
452 def update_membership_list(self, oldRecord, record, listName, addFunc, delFunc):
453 # get a list of the HRNs tht are members of the old and new records
455 oldList = oldRecord.get(listName, [])
458 newList = record.get(listName, [])
460 # if the lists are the same, then we don't have to update anything
461 if (oldList == newList):
464 # build a list of the new person ids, by looking up each person to get
467 table = self.SfaTable()
468 records = table.find({'type': 'user', 'hrn': newList})
470 newIdList.append(rec['pointer'])
472 # build a list of the old person ids from the person_ids field
474 oldIdList = oldRecord.get("person_ids", [])
475 containerId = oldRecord.get_pointer()
477 # if oldRecord==None, then we are doing a Register, instead of an
480 containerId = record.get_pointer()
482 # add people who are in the new list, but not the oldList
483 for personId in newIdList:
484 if not (personId in oldIdList):
485 addFunc(self.plauth, personId, containerId)
487 # remove people who are in the old list, but not the new list
488 for personId in oldIdList:
489 if not (personId in newIdList):
490 delFunc(self.plauth, personId, containerId)
492 def update_membership(self, oldRecord, record):
493 if record.type == "slice":
494 self.update_membership_list(oldRecord, record, 'researcher',
495 self.plshell.AddPersonToSlice,
496 self.plshell.DeletePersonFromSlice)
497 elif record.type == "authority":
503 class ComponentAPI(BaseAPI):
505 def __init__(self, config = "/etc/sfa/sfa_config.py", encoding = "utf-8", methods='sfa.methods',
506 peer_cert = None, interface = None, key_file = None, cert_file = None):
508 BaseAPI.__init__(self, config=config, encoding=encoding, methods=methods, peer_cert=peer_cert,
509 interface=interface, key_file=key_file, cert_file=cert_file)
510 self.encoding = encoding
512 # Better just be documenting the API
516 self.nodemanager = NodeManager(self.config)
518 def sliver_exists(self):
519 sliver_dict = self.nodemanager.GetXIDs()
520 if slicename in sliver_dict.keys():