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 from collections import defaultdict
27 class defaultdict(dict):
28 def __init__(self, default_factory=None, *a, **kw):
29 if (default_factory is not None and
30 not hasattr(default_factory, '__call__')):
31 raise TypeError('first argument must be callable')
32 dict.__init__(self, *a, **kw)
33 self.default_factory = default_factory
34 def __getitem__(self, key):
36 return dict.__getitem__(self, key)
38 return self.__missing__(key)
39 def __missing__(self, key):
40 if self.default_factory is None:
42 self[key] = value = self.default_factory()
45 if self.default_factory is None:
48 args = self.default_factory,
49 return type(self), args, None, None, self.items()
51 return self.__copy__()
53 return type(self)(self.default_factory, self)
54 def __deepcopy__(self, memo):
56 return type(self)(self.default_factory,
57 copy.deepcopy(self.items()))
59 return 'defaultdict(%s, %s)' % (self.default_factory,
63 ## end of http://code.activestate.com/recipes/523034/ }}}
66 def list_to_dict(recs, key):
68 convert a list of dictionaries into a dictionary keyed on the
69 specified dictionary key
71 keys = [rec[key] for rec in recs]
72 return dict(zip(keys, recs))
74 class SfaAPI(BaseAPI):
76 # flat list of method names
78 methods = sfa.methods.all
80 def __init__(self, config = "/etc/sfa/sfa_config.py", encoding = "utf-8",
81 methods='sfa.methods', peer_cert = None, interface = None,
82 key_file = None, cert_file = None, cache = None):
83 BaseAPI.__init__(self, config=config, encoding=encoding, methods=methods, \
84 peer_cert=peer_cert, interface=interface, key_file=key_file, \
85 cert_file=cert_file, cache=cache)
87 self.encoding = encoding
89 from sfa.util.table import SfaTable
90 self.SfaTable = SfaTable
91 # Better just be documenting the API
96 self.config = Config(config)
97 self.auth = Auth(peer_cert)
98 self.interface = interface
99 self.key_file = key_file
100 self.key = Keypair(filename=self.key_file)
101 self.cert_file = cert_file
102 self.cert = Certificate(filename=self.cert_file)
103 self.credential = None
104 # Initialize the PLC shell only if SFA wraps a myPLC
105 rspec_type = self.config.get_aggregate_type()
106 if (rspec_type == 'pl' or rspec_type == 'vini'):
107 self.plshell = self.getPLCShell()
108 self.plshell_version = "4.3"
110 self.hrn = self.config.SFA_INTERFACE_HRN
111 self.time_format = "%Y-%m-%d %H:%M:%S"
112 self.logger=get_sfa_logger()
114 def getPLCShell(self):
115 self.plauth = {'Username': self.config.SFA_PLC_USER,
116 'AuthMethod': 'password',
117 'AuthString': self.config.SFA_PLC_PASSWORD}
120 self.plshell_type = 'xmlrpc'
122 url = self.config.SFA_PLC_URL
123 shell = xmlrpclib.Server(url, verbose = 0, allow_none = True)
126 def getCredential(self):
127 if self.interface in ['registry']:
128 return self.getCredentialFromLocalRegistry()
130 return self.getCredentialFromRegistry()
132 def getCredentialFromRegistry(self):
134 Get our credential from a remote registry
137 path = self.config.SFA_DATA_DIR
138 filename = ".".join([self.interface, self.hrn, type, "cred"])
139 cred_filename = path + os.sep + filename
141 credential = Credential(filename = cred_filename)
142 return credential.save_to_string(save_parents=True)
144 from sfa.server.registry import Registries
145 registries = Registries(self)
146 registry = registries[self.hrn]
147 cert_string=self.cert.save_to_string(save_parents=True)
148 # get self credential
149 self_cred = registry.get_self_credential(cert_string, type, self.hrn)
151 cred = registry.get_credential(self_cred, type, self.hrn)
154 Credential(string=cred).save_to_file(cred_filename, save_parents=True)
157 def getCredentialFromLocalRegistry(self):
159 Get our current credential directly from the local registry.
163 auth_hrn = self.auth.get_authority(hrn)
165 # is this a root or sub authority
166 if not auth_hrn or hrn == self.config.SFA_INTERFACE_HRN:
168 auth_info = self.auth.get_auth_info(auth_hrn)
169 table = self.SfaTable()
170 records = table.findObjects(hrn)
174 type = record['type']
175 object_gid = record.get_gid_object()
176 new_cred = Credential(subject = object_gid.get_subject())
177 new_cred.set_gid_caller(object_gid)
178 new_cred.set_gid_object(object_gid)
179 new_cred.set_issuer(key=auth_info.get_pkey_object(), subject=auth_hrn)
180 new_cred.set_pubkey(object_gid.get_pubkey())
182 r1 = determine_rights(type, hrn)
183 new_cred.set_privileges(r1)
185 auth_kind = "authority,ma,sa"
187 new_cred.set_parent(self.auth.hierarchy.get_auth_cred(auth_hrn, kind=auth_kind))
192 return new_cred.save_to_string(save_parents=True)
195 def loadCredential (self):
197 Attempt to load credential from file if it exists. If it doesnt get
198 credential from registry.
201 # see if this file exists
202 # XX This is really the aggregate's credential. Using this is easier than getting
203 # the registry's credential from iteslf (ssl errors).
204 ma_cred_filename = self.config.SFA_DATA_DIR + os.sep + self.interface + self.hrn + ".ma.cred"
206 self.credential = Credential(filename = ma_cred_filename)
208 self.credential = self.getCredentialFromRegistry()
211 # Convert SFA fields to PLC fields for use when registering up updating
212 # registry record in the PLC database
214 # @param type type of record (user, slice, ...)
215 # @param hrn human readable name
216 # @param sfa_fields dictionary of SFA fields
217 # @param pl_fields dictionary of PLC fields (output)
219 def sfa_fields_to_pl_fields(self, type, hrn, record):
221 def convert_ints(tmpdict, int_fields):
222 for field in int_fields:
224 tmpdict[field] = int(tmpdict[field])
227 #for field in record:
228 # pl_record[field] = record[field]
231 if not "instantiation" in pl_record:
232 pl_record["instantiation"] = "plc-instantiated"
233 pl_record["name"] = hrn_to_pl_slicename(hrn)
235 pl_record["url"] = record["url"]
236 if "description" in record:
237 pl_record["description"] = record["description"]
238 if "expires" in record:
239 pl_record["expires"] = int(record["expires"])
242 if not "hostname" in pl_record:
243 if not "hostname" in record:
244 raise MissingSfaInfo("hostname")
245 pl_record["hostname"] = record["hostname"]
246 if not "model" in pl_record:
247 pl_record["model"] = "geni"
249 elif type == "authority":
250 pl_record["login_base"] = hrn_to_pl_login_base(hrn)
252 if not "name" in pl_record:
253 pl_record["name"] = hrn
255 if not "abbreviated_name" in pl_record:
256 pl_record["abbreviated_name"] = hrn
258 if not "enabled" in pl_record:
259 pl_record["enabled"] = True
261 if not "is_public" in pl_record:
262 pl_record["is_public"] = True
266 def fill_record_pl_info(self, records):
268 Fill in the planetlab specific fields of a SFA record. This
269 involves calling the appropriate PLC method to retrieve the
270 database record for the object.
272 PLC data is filled into the pl_info field of the record.
274 @param record: record to fill in field (in/out param)
277 node_ids, site_ids, slice_ids = [], [], []
278 person_ids, key_ids = [], []
279 type_map = {'node': node_ids, 'authority': site_ids,
280 'slice': slice_ids, 'user': person_ids}
282 for record in records:
283 for type in type_map:
284 if type == record['type']:
285 type_map[type].append(record['pointer'])
288 nodes, sites, slices, persons, keys = {}, {}, {}, {}, {}
290 node_list = self.plshell.GetNodes(self.plauth, node_ids)
291 nodes = list_to_dict(node_list, 'node_id')
293 site_list = self.plshell.GetSites(self.plauth, site_ids)
294 sites = list_to_dict(site_list, 'site_id')
296 slice_list = self.plshell.GetSlices(self.plauth, slice_ids)
297 slices = list_to_dict(slice_list, 'slice_id')
299 person_list = self.plshell.GetPersons(self.plauth, person_ids)
300 persons = list_to_dict(person_list, 'person_id')
301 for person in persons:
302 key_ids.extend(persons[person]['key_ids'])
304 pl_records = {'node': nodes, 'authority': sites,
305 'slice': slices, 'user': persons}
308 key_list = self.plshell.GetKeys(self.plauth, key_ids)
309 keys = list_to_dict(key_list, 'key_id')
312 for record in records:
313 # records with pointer==-1 do not have plc info.
314 # for example, the top level authority records which are
315 # authorities, but not PL "sites"
316 if record['pointer'] == -1:
319 for type in pl_records:
320 if record['type'] == type:
321 if record['pointer'] in pl_records[type]:
322 record.update(pl_records[type][record['pointer']])
325 if record['type'] == 'user':
326 pubkeys = [keys[key_id]['key'] for key_id in record['key_ids'] if key_id in keys]
327 record['keys'] = pubkeys
329 # fill in record hrns
330 records = self.fill_record_hrns(records)
334 def fill_record_hrns(self, records):
336 convert pl ids to hrns
340 slice_ids, person_ids, site_ids, node_ids = [], [], [], []
341 for record in records:
342 if 'site_id' in record:
343 site_ids.append(record['site_id'])
344 if 'site_ids' in records:
345 site_ids.extend(record['site_ids'])
346 if 'person_ids' in record:
347 person_ids.extend(record['person_ids'])
348 if 'slice_ids' in record:
349 slice_ids.extend(record['slice_ids'])
350 if 'node_ids' in record:
351 node_ids.extend(record['node_ids'])
354 slices, persons, sites, nodes = {}, {}, {}, {}
356 site_list = self.plshell.GetSites(self.plauth, site_ids, ['site_id', 'login_base'])
357 sites = list_to_dict(site_list, 'site_id')
359 person_list = self.plshell.GetPersons(self.plauth, person_ids, ['person_id', 'email'])
360 persons = list_to_dict(person_list, 'person_id')
362 slice_list = self.plshell.GetSlices(self.plauth, slice_ids, ['slice_id', 'name'])
363 slices = list_to_dict(slice_list, 'slice_id')
365 node_list = self.plshell.GetNodes(self.plauth, node_ids, ['node_id', 'hostname'])
366 nodes = list_to_dict(node_list, 'node_id')
368 # convert ids to hrns
369 for record in records:
371 # get all relevant data
372 type = record['type']
373 pointer = record['pointer']
379 if 'site_id' in record:
380 site = sites[record['site_id']]
381 login_base = site['login_base']
382 record['site'] = ".".join([auth_hrn, login_base])
383 if 'person_ids' in record:
384 emails = [persons[person_id]['email'] for person_id in record['person_ids'] \
385 if person_id in persons]
386 usernames = [email.split('@')[0] for email in emails]
387 person_hrns = [".".join([auth_hrn, login_base, username]) for username in usernames]
388 record['persons'] = person_hrns
389 if 'slice_ids' in record:
390 slicenames = [slices[slice_id]['name'] for slice_id in record['slice_ids'] \
391 if slice_id in slices]
392 slice_hrns = [slicename_to_hrn(auth_hrn, slicename) for slicename in slicenames]
393 record['slices'] = slice_hrns
394 if 'node_ids' in record:
395 hostnames = [nodes[node_id]['hostname'] for node_id in record['node_ids'] \
397 node_hrns = [hostname_to_hrn(auth_hrn, login_base, hostname) for hostname in hostnames]
398 record['nodes'] = node_hrns
399 if 'site_ids' in record:
400 login_bases = [sites[site_id]['login_base'] for site_id in record['site_ids'] \
402 site_hrns = [".".join([auth_hrn, lbase]) for lbase in login_bases]
403 record['sites'] = site_hrns
407 def fill_record_sfa_info(self, records):
409 def startswith(prefix, values):
410 return [value for value in values if value.startswith(prefix)]
415 for record in records:
416 person_ids.extend(record.get("person_ids", []))
417 site_ids.extend(record.get("site_ids", []))
418 if 'site_id' in record:
419 site_ids.append(record['site_id'])
421 # get all pis from the sites we've encountered
422 # and store them in a dictionary keyed on site_id
425 pi_filter = {'|roles': ['pi'], '|site_ids': site_ids}
426 pi_list = self.plshell.GetPersons(self.plauth, pi_filter, ['person_id', 'site_ids'])
428 # we will need the pi's hrns also
429 person_ids.append(pi['person_id'])
431 # we also need to keep track of the sites these pis
433 for site_id in pi['site_ids']:
434 if site_id in site_pis:
435 site_pis[site_id].append(pi)
437 site_pis[site_id] = [pi]
439 # get sfa records for all records associated with these records.
440 # we'll replace pl ids (person_ids) with hrns from the sfa records
443 # get the sfa records
444 table = self.SfaTable()
445 person_list, persons = [], {}
446 person_list = table.find({'type': 'user', 'pointer': person_ids})
447 # create a hrns keyed on the sfa record's pointer.
448 # Its possible for multiple records to have the same pointer so
449 # the dict's value will be a list of hrns.
450 persons = defaultdict(list)
451 for person in person_list:
452 persons[person['pointer']].append(person)
455 pl_person_list, pl_persons = [], {}
456 pl_person_list = self.plshell.GetPersons(self.plauth, person_ids, ['person_id', 'roles'])
457 pl_persons = list_to_dict(pl_person_list, 'person_id')
460 for record in records:
461 # skip records with no pl info (top level authorities)
462 if record['pointer'] == -1:
465 type = record['type']
466 if (type == "slice"):
467 # all slice users are researchers
469 record['researcher'] = []
470 for person_id in record['person_ids']:
471 hrns = [person['hrn'] for person in persons[person_id]]
472 record['researcher'].extend(hrns)
474 # pis at the slice's site
475 pl_pis = site_pis[record['site_id']]
476 pi_ids = [pi['person_id'] for pi in pl_pis]
477 for person_id in pi_ids:
478 hrns = [person['hrn'] for person in persons[person_id]]
479 record['PI'].extend(hrns)
481 elif (type == "authority"):
483 record['operator'] = []
485 for pointer in record['person_ids']:
486 if pointer not in persons or pointer not in pl_persons:
487 # this means there is not sfa or pl record for this user
489 hrns = [person['hrn'] for person in persons[pointer]]
490 roles = pl_persons[pointer]['roles']
492 record['PI'].extend(hrns)
494 record['operator'].extend(hrns)
496 record['owner'].extend(hrns)
497 # xxx TODO: OrganizationName
498 elif (type == "node"):
499 sfa_info['dns'] = record.get("hostname", "")
500 # xxx TODO: URI, LatLong, IP, DNS
502 elif (type == "user"):
503 sfa_info['email'] = record.get("email", "")
504 # xxx TODO: PostalAddress, Phone
505 record.update(sfa_info)
507 def fill_record_info(self, records):
509 Given a SFA record, fill in the PLC specific and SFA specific
510 fields in the record.
512 if not isinstance(records, list):
515 self.fill_record_pl_info(records)
516 self.fill_record_sfa_info(records)
518 def update_membership_list(self, oldRecord, record, listName, addFunc, delFunc):
519 # get a list of the HRNs tht are members of the old and new records
521 oldList = oldRecord.get(listName, [])
524 newList = record.get(listName, [])
526 # if the lists are the same, then we don't have to update anything
527 if (oldList == newList):
530 # build a list of the new person ids, by looking up each person to get
533 table = self.SfaTable()
534 records = table.find({'type': 'user', 'hrn': newList})
536 newIdList.append(rec['pointer'])
538 # build a list of the old person ids from the person_ids field
540 oldIdList = oldRecord.get("person_ids", [])
541 containerId = oldRecord.get_pointer()
543 # if oldRecord==None, then we are doing a Register, instead of an
546 containerId = record.get_pointer()
548 # add people who are in the new list, but not the oldList
549 for personId in newIdList:
550 if not (personId in oldIdList):
551 addFunc(self.plauth, personId, containerId)
553 # remove people who are in the old list, but not the new list
554 for personId in oldIdList:
555 if not (personId in newIdList):
556 delFunc(self.plauth, personId, containerId)
558 def update_membership(self, oldRecord, record):
559 if record.type == "slice":
560 self.update_membership_list(oldRecord, record, 'researcher',
561 self.plshell.AddPersonToSlice,
562 self.plshell.DeletePersonFromSlice)
563 elif record.type == "authority":
569 class ComponentAPI(BaseAPI):
571 def __init__(self, config = "/etc/sfa/sfa_config.py", encoding = "utf-8", methods='sfa.methods',
572 peer_cert = None, interface = None, key_file = None, cert_file = None):
574 BaseAPI.__init__(self, config=config, encoding=encoding, methods=methods, peer_cert=peer_cert,
575 interface=interface, key_file=key_file, cert_file=cert_file)
576 self.encoding = encoding
578 # Better just be documenting the API
582 self.nodemanager = NodeManager(self.config)
584 def sliver_exists(self):
585 sliver_dict = self.nodemanager.GetXIDs()
586 if slicename in sliver_dict.keys():