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
48 print "CONFIG IS NONE"
52 self.config = Config(config)
53 self.auth = Auth(peer_cert)
54 self.interface = interface
55 self.key_file = key_file
56 self.key = Keypair(filename=self.key_file)
57 self.cert_file = cert_file
58 self.cert = Certificate(filename=self.cert_file)
59 self.credential = None
60 # Initialize the PLC shell only if SFA wraps a myPLC
61 rspec_type = self.config.get_aggregate_type()
62 if (rspec_type == 'pl' or rspec_type == 'vini'):
63 self.plshell = self.getPLCShell()
64 self.plshell_version = self.getPLCShellVersion()
66 self.hrn = self.config.SFA_INTERFACE_HRN
67 self.time_format = "%Y-%m-%d %H:%M:%S"
68 self.logger=get_sfa_logger()
70 def getPLCShell(self):
71 self.plauth = {'Username': self.config.SFA_PLC_USER,
72 'AuthMethod': 'password',
73 'AuthString': self.config.SFA_PLC_PASSWORD}
75 sys.path.append(os.path.dirname(os.path.realpath("/usr/bin/plcsh")))
76 self.plshell_type = 'direct'
78 shell = PLC.Shell.Shell(globals = globals())
79 shell.AuthCheck(self.plauth)
82 self.plshell_type = 'xmlrpc'
84 url = self.config.SFA_PLC_URL
85 shell = xmlrpclib.Server(url, verbose = 0, allow_none = True)
86 shell.AuthCheck(self.plauth)
89 def getPLCShellVersion(self):
90 # We need to figure out what version of PLCAPI we are talking to.
91 # Some calls we need to make later will be different depending on
94 # This is probably a bad way to determine api versions
95 # but its easy and will work for now. Lets try to make
96 # a call that only exists is PLCAPI.4.3. If it fails, we
97 # can assume the api version is 4.2
98 self.plshell.GetTagTypes(self.plauth)
104 def getCredential(self):
105 if self.interface in ['registry']:
106 return self.getCredentialFromLocalRegistry()
108 return self.getCredentialFromRegistry()
110 def getCredentialFromRegistry(self):
112 Get our credential from a remote registry
115 path = self.config.SFA_DATA_DIR
116 filename = ".".join([self.interface, self.hrn, type, "cred"])
117 cred_filename = path + os.sep + filename
119 credential = Credential(filename = cred_filename)
120 return credential.save_to_string(save_parents=True)
122 from sfa.server.registry import Registries
123 registries = Registries(self)
124 registry = registries[self.hrn]
125 cert_string=self.cert.save_to_string(save_parents=True)
126 # get self credential
127 self_cred = registry.get_self_credential(cert_string, type, self.hrn)
129 cred = registry.get_credential(self_cred, type, self.hrn)
132 Credential(string=cred).save_to_file(cred_filename, save_parents=True)
135 def getCredentialFromLocalRegistry(self):
137 Get our current credential directly from the local registry.
141 auth_hrn = self.auth.get_authority(hrn)
143 # is this a root or sub authority
144 if not auth_hrn or hrn == self.config.SFA_INTERFACE_HRN:
146 auth_info = self.auth.get_auth_info(auth_hrn)
147 table = self.SfaTable()
148 records = table.findObjects(hrn)
152 type = record['type']
153 object_gid = record.get_gid_object()
154 new_cred = Credential(subject = object_gid.get_subject())
155 new_cred.set_gid_caller(object_gid)
156 new_cred.set_gid_object(object_gid)
157 new_cred.set_issuer(key=auth_info.get_pkey_object(), subject=auth_hrn)
158 new_cred.set_pubkey(object_gid.get_pubkey())
159 r1 = determine_rights(type, hrn)
160 new_cred.set_privileges(r1)
162 auth_kind = "authority,ma,sa"
164 new_cred.set_parent(self.auth.hierarchy.get_auth_cred(auth_hrn, kind=auth_kind))
169 return new_cred.save_to_string(save_parents=True)
172 def loadCredential (self):
174 Attempt to load credential from file if it exists. If it doesnt get
175 credential from registry.
178 # see if this file exists
179 # XX This is really the aggregate's credential. Using this is easier than getting
180 # the registry's credential from iteslf (ssl errors).
181 ma_cred_filename = self.config.SFA_DATA_DIR + os.sep + self.interface + self.hrn + ".ma.cred"
183 self.credential = Credential(filename = ma_cred_filename)
185 self.credential = self.getCredentialFromRegistry()
188 # Convert SFA fields to PLC fields for use when registering up updating
189 # registry record in the PLC database
191 # @param type type of record (user, slice, ...)
192 # @param hrn human readable name
193 # @param sfa_fields dictionary of SFA fields
194 # @param pl_fields dictionary of PLC fields (output)
196 def sfa_fields_to_pl_fields(self, type, hrn, record):
198 def convert_ints(tmpdict, int_fields):
199 for field in int_fields:
201 tmpdict[field] = int(tmpdict[field])
204 #for field in record:
205 # pl_record[field] = record[field]
208 if not "instantiation" in pl_record:
209 pl_record["instantiation"] = "plc-instantiated"
210 pl_record["name"] = hrn_to_pl_slicename(hrn)
212 pl_record["url"] = record["url"]
213 if "description" in record:
214 pl_record["description"] = record["description"]
215 if "expires" in record:
216 pl_record["expires"] = int(record["expires"])
219 if not "hostname" in pl_record:
220 if not "hostname" in record:
221 raise MissingSfaInfo("hostname")
222 pl_record["hostname"] = record["hostname"]
223 if not "model" in pl_record:
224 pl_record["model"] = "geni"
226 elif type == "authority":
227 pl_record["login_base"] = hrn_to_pl_login_base(hrn)
229 if not "name" in pl_record:
230 pl_record["name"] = hrn
232 if not "abbreviated_name" in pl_record:
233 pl_record["abbreviated_name"] = hrn
235 if not "enabled" in pl_record:
236 pl_record["enabled"] = True
238 if not "is_public" in pl_record:
239 pl_record["is_public"] = True
243 def fill_record_pl_info(self, records):
245 Fill in the planetlab specific fields of a SFA record. This
246 involves calling the appropriate PLC method to retrieve the
247 database record for the object.
249 PLC data is filled into the pl_info field of the record.
251 @param record: record to fill in field (in/out param)
254 node_ids, site_ids, slice_ids = [], [], []
255 person_ids, key_ids = [], []
256 type_map = {'node': node_ids, 'authority': site_ids,
257 'slice': slice_ids, 'user': person_ids}
259 for record in records:
260 for type in type_map:
261 if type == record['type']:
262 type_map[type].append(record['pointer'])
265 nodes, sites, slices, persons, keys = {}, {}, {}, {}, {}
267 node_list = self.plshell.GetNodes(self.plauth, node_ids)
268 nodes = list_to_dict(node_list, 'node_id')
270 site_lists = self.plshell.GetSites(self.plauth, site_ids)
271 sites = list_to_dict(site_list, 'site_id')
273 slice_list = self.plshell.GetSlices(self.plauth, slice_ids)
274 slices = list_to_dict(slice_list, 'slice_id')
276 person_list = self.plshell.GetPersons(self.plauth, person_ids)
277 persons = list_to_dict(person_list, 'person_id')
278 for person in persons:
279 key_ids.extend(persons[person]['key_ids'])
281 pl_records = {'node': nodes, 'authority': sites,
282 'slice': slices, 'user': persons}
285 key_list = self.plshell.GetKeys(self.plauth, key_ids)
286 keys = list_to_dict(key_list, 'key_id')
289 for record in records:
290 # records with pointer==-1 do not have plc info associated with them.
291 # for example, the top level authority records which are
292 # authorities, but not PL "sites"
293 if record['pointer'] == -1:
296 for type in pl_records:
297 if record['type'] == type:
298 if record['pointer'] in pl_records[type]:
299 record.update(pl_records[type][record['pointer']])
302 if record['type'] == 'user':
303 pubkeys = [keys[key_id]['key'] for key_id in record['key_ids'] if key_id in keys]
304 record['keys'] = pubkeys
306 # fill in record hrns
307 records = self.fill_record_hrns(records)
311 def fill_record_hrns(self, records):
313 convert pl ids to hrns
317 slice_ids, person_ids, site_ids, node_ids = [], [], [], []
318 for record in records:
319 if 'site_id' in record:
320 site_ids.append(record['site_id'])
321 if 'site_ids' in records:
322 site_ids.extend(record['site_ids'])
323 if 'person_ids' in record:
324 person_ids.extend(record['person_ids'])
325 if 'slice_ids' in record:
326 slice_ids.extend(record['slice_ids'])
327 if 'node_ids' in record:
328 node_ids.extend(record['node_ids'])
331 slices, persons, sites, nodes = {}, {}, {}, {}
333 site_list = self.plshell.GetSites(self.plauth, site_ids, ['site_id', 'login_base'])
334 sites = list_to_dict(site_list, 'site_id')
336 person_list = self.plshell.GetPersons(self.plauth, person_ids, ['person_id', 'email'])
337 persons = list_to_dict(person_list, 'person_id')
339 slice_list = self.plshell.GetSlices(self.plauth, slice_ids, ['slice_id', 'name'])
340 slices = list_to_dict(slice_list, 'slice_id')
342 node_list = self.plshell.GetNodes(self.plauth, node_ids, ['node_id', 'hostname'])
343 nodes = list_to_dict(node_list, 'node_id')
345 # convert ids to hrns
346 for record in records:
348 # get all relevant data
349 type = record['type']
350 pointer = record['pointer']
356 if 'site_id' in record:
357 site = sites[record['site_id']]
358 login_base = site['login_base']
359 record['site'] = ".".join([auth_hrn, login_base])
360 if 'person_ids' in record:
361 emails = [persons[person_id]['email'] for person_id in record['person_ids'] \
362 if person_id in persons]
363 usernames = [email.split('@')[0] for email in emails]
364 person_hrns = [".".join([auth_hrn, login_base, username]) for username in usernames]
365 record['persons'] = person_hrns
366 if 'slice_ids' in record:
367 slicenames = [slices[slice_id]['name'] for slice_id in record['slice_ids'] \
368 if slice_id in slices]
369 slice_hrns = [slicename_to_hrn(auth_hrn, slicename) for slicename in slicenames]
370 record['slices'] = slice_hrns
371 if 'node_ids' in record:
372 hostnames = [nodes[node_id]['hostname'] for node_id in record['node_ids'] \
374 node_hrns = [hostname_to_hrn(auth_hrn, login_base, hostname) for hostname in hostnames]
375 record['nodes'] = node_hrns
376 if 'site_ids' in record:
377 login_bases = [sites[site_id]['login_base'] for site_id in record['site_ids'] \
379 site_hrns = [".".join([auth_hrn, lbase]) for lbase in login_bases]
380 record['sites'] = site_hrns
384 def fill_record_sfa_info(self, record):
386 type = record['type']
387 table = self.SfaTable()
388 if (type == "slice"):
389 person_ids = record.get("person_ids", [])
390 persons = table.find({'type': 'user', 'pointer': person_ids})
391 researchers = [person['hrn'] for person in persons]
392 sfa_info['researcher'] = researchers
394 elif (type == "authority"):
395 person_ids = record.get("person_ids", [])
396 persons = table.find({'type': 'user', 'pointer': person_ids})
398 for person in persons:
399 persons_dict[person['pointer']] = person
400 pl_persons = self.plshell.GetPersons(self.plauth, person_ids, ['person_id', 'roles'])
401 pis, techs, admins = [], [], []
402 for person in pl_persons:
403 pointer = person['person_id']
405 if pointer not in persons_dict:
406 # this means there is not sfa record for this user
408 hrn = persons_dict[pointer]['hrn']
409 if 'pi' in person['roles']:
411 if 'tech' in person['roles']:
413 if 'admin' in person['roles']:
417 sfa_info['operator'] = techs
418 sfa_info['owner'] = admins
419 # xxx TODO: OrganizationName
421 elif (type == "node"):
422 sfa_info['dns'] = record.get("hostname", "")
423 # xxx TODO: URI, LatLong, IP, DNS
425 elif (type == "user"):
426 sfa_info['email'] = record.get("email", "")
427 # xxx TODO: PostalAddress, Phone
429 record.update(sfa_info)
431 def fill_record_info(self, records):
433 Given a SFA record, fill in the PLC specific and SFA specific
434 fields in the record.
436 if not isinstance(records, list):
439 self.fill_record_pl_info(records)
440 for record in records:
441 self.fill_record_sfa_info(record)
442 #self.fill_record_sfa_info(records)
444 def update_membership_list(self, oldRecord, record, listName, addFunc, delFunc):
445 # get a list of the HRNs tht are members of the old and new records
447 oldList = oldRecord.get(listName, [])
450 newList = record.get(listName, [])
452 # if the lists are the same, then we don't have to update anything
453 if (oldList == newList):
456 # build a list of the new person ids, by looking up each person to get
459 table = self.SfaTable()
460 records = table.find({'type': 'user', 'hrn': newList})
462 newIdList.append(rec['pointer'])
464 # build a list of the old person ids from the person_ids field
466 oldIdList = oldRecord.get("person_ids", [])
467 containerId = oldRecord.get_pointer()
469 # if oldRecord==None, then we are doing a Register, instead of an
472 containerId = record.get_pointer()
474 # add people who are in the new list, but not the oldList
475 for personId in newIdList:
476 if not (personId in oldIdList):
477 addFunc(self.plauth, personId, containerId)
479 # remove people who are in the old list, but not the new list
480 for personId in oldIdList:
481 if not (personId in newIdList):
482 delFunc(self.plauth, personId, containerId)
484 def update_membership(self, oldRecord, record):
485 if record.type == "slice":
486 self.update_membership_list(oldRecord, record, 'researcher',
487 self.plshell.AddPersonToSlice,
488 self.plshell.DeletePersonFromSlice)
489 elif record.type == "authority":
495 class ComponentAPI(BaseAPI):
497 def __init__(self, config = "/etc/sfa/sfa_config.py", encoding = "utf-8", methods='sfa.methods',
498 peer_cert = None, interface = None, key_file = None, cert_file = None):
500 BaseAPI.__init__(self, config=config, encoding=encoding, methods=methods, peer_cert=peer_cert,
501 interface=interface, key_file=key_file, cert_file=cert_file)
502 self.encoding = encoding
504 # Better just be documenting the API
508 self.nodemanager = NodeManager(self.config)
510 def sliver_exists(self):
511 sliver_dict = self.nodemanager.GetXIDs()
512 if slicename in sliver_dict.keys():