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}
73 self.plshell_type = 'xmlrpc'
74 url = self.config.SFA_PLC_URL
75 shell = xmlrpclib.Server(url, verbose = 0, allow_none = True)
76 shell.AuthCheck(self.plauth)
79 def getPLCShellVersion(self):
80 # We need to figure out what version of PLCAPI we are talking to.
81 # Some calls we need to make later will be different depending on
84 # This is probably a bad way to determine api versions
85 # but its easy and will work for now. Lets try to make
86 # a call that only exists is PLCAPI.4.3. If it fails, we
87 # can assume the api version is 4.2
88 self.plshell.GetTagTypes(self.plauth)
94 def getCredential(self):
95 if self.interface in ['registry']:
96 return self.getCredentialFromLocalRegistry()
98 return self.getCredentialFromRegistry()
100 def getCredentialFromRegistry(self):
102 Get our credential from a remote registry
105 path = self.config.SFA_DATA_DIR
106 filename = ".".join([self.interface, self.hrn, type, "cred"])
107 cred_filename = path + os.sep + filename
109 credential = Credential(filename = cred_filename)
110 return credential.save_to_string(save_parents=True)
112 from sfa.server.registry import Registries
113 registries = Registries(self)
114 registry = registries[self.hrn]
115 cert_string=self.cert.save_to_string(save_parents=True)
116 # get self credential
117 self_cred = registry.get_self_credential(cert_string, type, self.hrn)
119 cred = registry.get_credential(self_cred, type, self.hrn)
122 Credential(string=cred).save_to_file(cred_filename, save_parents=True)
125 def getCredentialFromLocalRegistry(self):
127 Get our current credential directly from the local registry.
131 auth_hrn = self.auth.get_authority(hrn)
133 # is this a root or sub authority
134 if not auth_hrn or hrn == self.config.SFA_INTERFACE_HRN:
136 auth_info = self.auth.get_auth_info(auth_hrn)
137 table = self.SfaTable()
138 records = table.findObjects(hrn)
142 type = record['type']
143 object_gid = record.get_gid_object()
144 new_cred = Credential(subject = object_gid.get_subject())
145 new_cred.set_gid_caller(object_gid)
146 new_cred.set_gid_object(object_gid)
147 new_cred.set_issuer(key=auth_info.get_pkey_object(), subject=auth_hrn)
148 new_cred.set_pubkey(object_gid.get_pubkey())
149 r1 = determine_rights(type, hrn)
150 new_cred.set_privileges(r1)
152 auth_kind = "authority,ma,sa"
154 new_cred.set_parent(self.auth.hierarchy.get_auth_cred(auth_hrn, kind=auth_kind))
159 return new_cred.save_to_string(save_parents=True)
162 def loadCredential (self):
164 Attempt to load credential from file if it exists. If it doesnt get
165 credential from registry.
168 # see if this file exists
169 # XX This is really the aggregate's credential. Using this is easier than getting
170 # the registry's credential from iteslf (ssl errors).
171 ma_cred_filename = self.config.SFA_DATA_DIR + os.sep + self.interface + self.hrn + ".ma.cred"
173 self.credential = Credential(filename = ma_cred_filename)
175 self.credential = self.getCredentialFromRegistry()
178 # Convert SFA fields to PLC fields for use when registering up updating
179 # registry record in the PLC database
181 # @param type type of record (user, slice, ...)
182 # @param hrn human readable name
183 # @param sfa_fields dictionary of SFA fields
184 # @param pl_fields dictionary of PLC fields (output)
186 def sfa_fields_to_pl_fields(self, type, hrn, record):
188 def convert_ints(tmpdict, int_fields):
189 for field in int_fields:
191 tmpdict[field] = int(tmpdict[field])
194 #for field in record:
195 # pl_record[field] = record[field]
198 if not "instantiation" in pl_record:
199 pl_record["instantiation"] = "plc-instantiated"
200 pl_record["name"] = hrn_to_pl_slicename(hrn)
202 pl_record["url"] = record["url"]
203 if "description" in record:
204 pl_record["description"] = record["description"]
205 if "expires" in record:
206 pl_record["expires"] = int(record["expires"])
209 if not "hostname" in pl_record:
210 if not "hostname" in record:
211 raise MissingSfaInfo("hostname")
212 pl_record["hostname"] = record["hostname"]
213 if not "model" in pl_record:
214 pl_record["model"] = "geni"
216 elif type == "authority":
217 pl_record["login_base"] = hrn_to_pl_login_base(hrn)
219 if not "name" in pl_record:
220 pl_record["name"] = hrn
222 if not "abbreviated_name" in pl_record:
223 pl_record["abbreviated_name"] = hrn
225 if not "enabled" in pl_record:
226 pl_record["enabled"] = True
228 if not "is_public" in pl_record:
229 pl_record["is_public"] = True
233 def fill_record_pl_info(self, records):
235 Fill in the planetlab specific fields of a SFA record. This
236 involves calling the appropriate PLC method to retrieve the
237 database record for the object.
239 PLC data is filled into the pl_info field of the record.
241 @param record: record to fill in field (in/out param)
244 node_ids, site_ids, slice_ids = [], [], []
245 person_ids, key_ids = [], []
246 type_map = {'node': node_ids, 'authority': site_ids,
247 'slice': slice_ids, 'user': person_ids}
249 for record in records:
250 for type in type_map:
251 if type == record['type']:
252 type_map[type].append(record['pointer'])
255 nodes, sites, slices, persons, keys = {}, {}, {}, {}, {}
257 node_list = self.plshell.GetNodes(self.plauth, node_ids)
258 nodes = list_to_dict(node_list, 'node_id')
260 site_list = self.plshell.GetSites(self.plauth, site_ids)
261 sites = list_to_dict(site_list, 'site_id')
263 slice_list = self.plshell.GetSlices(self.plauth, slice_ids)
264 slices = list_to_dict(slice_list, 'slice_id')
266 person_list = self.plshell.GetPersons(self.plauth, person_ids)
267 persons = list_to_dict(person_list, 'person_id')
268 for person in persons:
269 key_ids.extend(persons[person]['key_ids'])
271 pl_records = {'node': nodes, 'authority': sites,
272 'slice': slices, 'user': persons}
275 key_list = self.plshell.GetKeys(self.plauth, key_ids)
276 keys = list_to_dict(key_list, 'key_id')
279 for record in records:
280 # records with pointer==-1 do not have plc info associated with them.
281 # for example, the top level authority records which are
282 # authorities, but not PL "sites"
283 if record['pointer'] == -1:
286 for type in pl_records:
287 if record['type'] == type:
288 if record['pointer'] in pl_records[type]:
289 record.update(pl_records[type][record['pointer']])
292 if record['type'] == 'user':
293 pubkeys = [keys[key_id]['key'] for key_id in record['key_ids'] if key_id in keys]
294 record['keys'] = pubkeys
296 # fill in record hrns
297 records = self.fill_record_hrns(records)
301 def fill_record_hrns(self, records):
303 convert pl ids to hrns
307 slice_ids, person_ids, site_ids, node_ids = [], [], [], []
308 for record in records:
309 if 'site_id' in record:
310 site_ids.append(record['site_id'])
311 if 'site_ids' in records:
312 site_ids.extend(record['site_ids'])
313 if 'person_ids' in record:
314 person_ids.extend(record['person_ids'])
315 if 'slice_ids' in record:
316 slice_ids.extend(record['slice_ids'])
317 if 'node_ids' in record:
318 node_ids.extend(record['node_ids'])
321 slices, persons, sites, nodes = {}, {}, {}, {}
323 site_list = self.plshell.GetSites(self.plauth, site_ids, ['site_id', 'login_base'])
324 sites = list_to_dict(site_list, 'site_id')
326 person_list = self.plshell.GetPersons(self.plauth, person_ids, ['person_id', 'email'])
327 persons = list_to_dict(person_list, 'person_id')
329 slice_list = self.plshell.GetSlices(self.plauth, slice_ids, ['slice_id', 'name'])
330 slices = list_to_dict(slice_list, 'slice_id')
332 node_list = self.plshell.GetNodes(self.plauth, node_ids, ['node_id', 'hostname'])
333 nodes = list_to_dict(node_list, 'node_id')
335 # convert ids to hrns
336 for record in records:
338 # get all relevant data
339 type = record['type']
340 pointer = record['pointer']
346 if 'site_id' in record:
347 site = sites[record['site_id']]
348 login_base = site['login_base']
349 record['site'] = ".".join([auth_hrn, login_base])
350 if 'person_ids' in record:
351 emails = [persons[person_id]['email'] for person_id in record['person_ids'] \
352 if person_id in persons]
353 usernames = [email.split('@')[0] for email in emails]
354 person_hrns = [".".join([auth_hrn, login_base, username]) for username in usernames]
355 record['persons'] = person_hrns
356 if 'slice_ids' in record:
357 slicenames = [slices[slice_id]['name'] for slice_id in record['slice_ids'] \
358 if slice_id in slices]
359 slice_hrns = [slicename_to_hrn(auth_hrn, slicename) for slicename in slicenames]
360 record['slices'] = slice_hrns
361 if 'node_ids' in record:
362 hostnames = [nodes[node_id]['hostname'] for node_id in record['node_ids'] \
364 node_hrns = [hostname_to_hrn(auth_hrn, login_base, hostname) for hostname in hostnames]
365 record['nodes'] = node_hrns
366 if 'site_ids' in record:
367 login_bases = [sites[site_id]['login_base'] for site_id in record['site_ids'] \
369 site_hrns = [".".join([auth_hrn, lbase]) for lbase in login_bases]
370 record['sites'] = site_hrns
374 def fill_record_sfa_info(self, records):
376 has_authority = False
379 for record in records:
380 if record['type'] == 'authority':
382 person_ids.extend(record.get("person_ids", []))
385 table = self.SfaTable()
386 person_list, persons = [], {}
387 pl_person_list, pl_persons = [], {}
388 person_list = table.find({'type': 'user', 'pointer': person_ids})
389 persons = list_to_dict(person_list, 'pointer')
391 pl_person_list = self.plshell.GetPersons(self.plauth, person_ids, ['person_id', 'roles'])
392 pl_persons = list_to_dict(pl_person_list, 'person_id')
396 for record in records:
397 # skip records with no pl info (top level authorities)
398 if record['pointer'] == -1:
401 type = record['type']
402 if (type == "slice"):
403 researchers = [persons[person_id]['hrn'] for person_id in record['person_ids'] \
404 if person_id in persons]
405 sfa_info['researcher'] = researchers
407 elif (type == "authority"):
408 pis, techs, admins = [], [], []
409 for pointer in record['person_ids']:
410 if pointer not in persons or pointer not in pl_persons:
411 # this means there is not sfa or pl record for this user
413 hrn = persons[pointer]['hrn']
414 roles = pl_persons[pointer]['roles']
423 sfa_info['operator'] = techs
424 sfa_info['owner'] = admins
425 # xxx TODO: OrganizationName
426 elif (type == "node"):
427 sfa_info['dns'] = record.get("hostname", "")
428 # xxx TODO: URI, LatLong, IP, DNS
430 elif (type == "user"):
431 sfa_info['email'] = record.get("email", "")
432 # xxx TODO: PostalAddress, Phone
433 record.update(sfa_info)
435 def fill_record_info(self, records):
437 Given a SFA record, fill in the PLC specific and SFA specific
438 fields in the record.
440 if not isinstance(records, list):
443 self.fill_record_pl_info(records)
444 self.fill_record_sfa_info(records)
446 def update_membership_list(self, oldRecord, record, listName, addFunc, delFunc):
447 # get a list of the HRNs tht are members of the old and new records
449 oldList = oldRecord.get(listName, [])
452 newList = record.get(listName, [])
454 # if the lists are the same, then we don't have to update anything
455 if (oldList == newList):
458 # build a list of the new person ids, by looking up each person to get
461 table = self.SfaTable()
462 records = table.find({'type': 'user', 'hrn': newList})
464 newIdList.append(rec['pointer'])
466 # build a list of the old person ids from the person_ids field
468 oldIdList = oldRecord.get("person_ids", [])
469 containerId = oldRecord.get_pointer()
471 # if oldRecord==None, then we are doing a Register, instead of an
474 containerId = record.get_pointer()
476 # add people who are in the new list, but not the oldList
477 for personId in newIdList:
478 if not (personId in oldIdList):
479 addFunc(self.plauth, personId, containerId)
481 # remove people who are in the old list, but not the new list
482 for personId in oldIdList:
483 if not (personId in newIdList):
484 delFunc(self.plauth, personId, containerId)
486 def update_membership(self, oldRecord, record):
487 if record.type == "slice":
488 self.update_membership_list(oldRecord, record, 'researcher',
489 self.plshell.AddPersonToSlice,
490 self.plshell.DeletePersonFromSlice)
491 elif record.type == "authority":
497 class ComponentAPI(BaseAPI):
499 def __init__(self, config = "/etc/sfa/sfa_config.py", encoding = "utf-8", methods='sfa.methods',
500 peer_cert = None, interface = None, key_file = None, cert_file = None):
502 BaseAPI.__init__(self, config=config, encoding=encoding, methods=methods, peer_cert=peer_cert,
503 interface=interface, key_file=key_file, cert_file=cert_file)
504 self.encoding = encoding
506 # Better just be documenting the API
510 self.nodemanager = NodeManager(self.config)
512 def sliver_exists(self):
513 sliver_dict = self.nodemanager.GetXIDs()
514 if slicename in sliver_dict.keys():