2 # SFA XML-RPC and SOAP interfaces
11 from sfa.util.faults import *
12 from sfa.util.api import *
13 from sfa.util.config import *
14 from sfa.util.sfalogging import sfa_logger
15 import sfa.util.xmlrpcprotocol as xmlrpcprotocol
16 from sfa.trust.auth import Auth
17 from sfa.trust.rights import Right, Rights, determine_rights
18 from sfa.trust.credential import Credential,Keypair
19 from sfa.trust.certificate import Certificate
20 from sfa.util.xrn import get_authority, hrn_to_urn
21 from sfa.util.plxrn import hostname_to_hrn, hrn_to_pl_slicename, hrn_to_pl_slicename, slicename_to_hrn
22 from sfa.util.nodemanager import NodeManager
24 from collections import defaultdict
26 class defaultdict(dict):
27 def __init__(self, default_factory=None, *a, **kw):
28 if (default_factory is not None and
29 not hasattr(default_factory, '__call__')):
30 raise TypeError('first argument must be callable')
31 dict.__init__(self, *a, **kw)
32 self.default_factory = default_factory
33 def __getitem__(self, key):
35 return dict.__getitem__(self, key)
37 return self.__missing__(key)
38 def __missing__(self, key):
39 if self.default_factory is None:
41 self[key] = value = self.default_factory()
44 if self.default_factory is None:
47 args = self.default_factory,
48 return type(self), args, None, None, self.items()
50 return self.__copy__()
52 return type(self)(self.default_factory, self)
53 def __deepcopy__(self, memo):
55 return type(self)(self.default_factory,
56 copy.deepcopy(self.items()))
58 return 'defaultdict(%s, %s)' % (self.default_factory,
60 ## end of http://code.activestate.com/recipes/523034/ }}}
62 def list_to_dict(recs, key):
64 convert a list of dictionaries into a dictionary keyed on the
65 specified dictionary key
67 keys = [rec[key] for rec in recs]
68 return dict(zip(keys, recs))
70 class SfaAPI(BaseAPI):
72 # flat list of method names
74 methods = sfa.methods.all
76 def __init__(self, config = "/etc/sfa/sfa_config.py", encoding = "utf-8",
77 methods='sfa.methods', peer_cert = None, interface = None,
78 key_file = None, cert_file = None, cache = None):
79 BaseAPI.__init__(self, config=config, encoding=encoding, methods=methods, \
80 peer_cert=peer_cert, interface=interface, key_file=key_file, \
81 cert_file=cert_file, cache=cache)
83 self.encoding = encoding
84 from sfa.util.table import SfaTable
85 self.SfaTable = SfaTable
86 # Better just be documenting the API
91 self.config = Config(config)
92 self.auth = Auth(peer_cert)
93 self.interface = interface
94 self.key_file = key_file
95 self.key = Keypair(filename=self.key_file)
96 self.cert_file = cert_file
97 self.cert = Certificate(filename=self.cert_file)
98 self.credential = None
99 # Initialize the PLC shell only if SFA wraps a myPLC
100 rspec_type = self.config.get_aggregate_type()
101 if (rspec_type == 'pl' or rspec_type == 'vini' or rspec_type == 'eucalyptus'):
102 self.plshell = self.getPLCShell()
103 self.plshell_version = "4.3"
105 self.hrn = self.config.SFA_INTERFACE_HRN
106 self.time_format = "%Y-%m-%d %H:%M:%S"
107 self.logger=sfa_logger()
109 def getPLCShell(self):
110 self.plauth = {'Username': self.config.SFA_PLC_USER,
111 'AuthMethod': 'password',
112 'AuthString': self.config.SFA_PLC_PASSWORD}
114 sys.path.append(os.path.dirname(os.path.realpath("/usr/bin/plcsh")))
115 self.plshell_type = 'direct'
117 shell = PLC.Shell.Shell(globals = globals())
119 self.plshell_type = 'xmlrpc'
120 url = self.config.SFA_PLC_URL
121 shell = xmlrpclib.Server(url, verbose = 0, allow_none = True)
125 def getCredential(self):
127 Return a valid credential for this interface.
129 if self.interface in ['registry']:
130 return self.getCredentialFromLocalRegistry()
132 return self.getCredentialFromRegistry()
134 def getDelegatedCredential(self, creds):
136 Attempt to find a credential delegated to us in
137 the specified list of creds.
139 if creds and not isinstance(creds, list):
141 delegated_creds = filter_creds_by_caller(creds,self.hrn)
142 if not delegated_creds:
144 return delegated_creds[0]
146 def getCredentialFromRegistry(self):
148 Get our credential from a remote registry
151 path = self.config.SFA_DATA_DIR
152 filename = ".".join([self.interface, self.hrn, type, "cred"])
153 cred_filename = path + os.sep + filename
155 credential = Credential(filename = cred_filename)
156 return credential.save_to_string(save_parents=True)
158 from sfa.server.registry import Registries
159 registries = Registries(self)
160 registry = registries[self.hrn]
161 cert_string=self.cert.save_to_string(save_parents=True)
162 # get self credential
163 self_cred = registry.GetSelfCredential(cert_string, self.hrn, type)
165 cred = registry.GetCredential(self_cred, self.hrn, type)
168 Credential(string=cred).save_to_file(cred_filename, save_parents=True)
171 def getCredentialFromLocalRegistry(self):
173 Get our current credential directly from the local registry.
177 auth_hrn = self.auth.get_authority(hrn)
179 # is this a root or sub authority
180 if not auth_hrn or hrn == self.config.SFA_INTERFACE_HRN:
182 auth_info = self.auth.get_auth_info(auth_hrn)
183 table = self.SfaTable()
184 records = table.findObjects(hrn)
188 type = record['type']
189 object_gid = record.get_gid_object()
190 new_cred = Credential(subject = object_gid.get_subject())
191 new_cred.set_gid_caller(object_gid)
192 new_cred.set_gid_object(object_gid)
193 new_cred.set_issuer_keys(auth_info.get_privkey_filename(), auth_info.get_gid_filename())
195 r1 = determine_rights(type, hrn)
196 new_cred.set_privileges(r1)
198 auth_kind = "authority,ma,sa"
200 new_cred.set_parent(self.auth.hierarchy.get_auth_cred(auth_hrn, kind=auth_kind))
205 return new_cred.save_to_string(save_parents=True)
208 def loadCredential (self):
210 Attempt to load credential from file if it exists. If it doesnt get
211 credential from registry.
214 # see if this file exists
215 # XX This is really the aggregate's credential. Using this is easier than getting
216 # the registry's credential from iteslf (ssl errors).
217 ma_cred_filename = self.config.SFA_DATA_DIR + os.sep + self.interface + self.hrn + ".ma.cred"
219 self.credential = Credential(filename = ma_cred_filename)
221 self.credential = self.getCredentialFromRegistry()
224 # Convert SFA fields to PLC fields for use when registering up updating
225 # registry record in the PLC database
227 # @param type type of record (user, slice, ...)
228 # @param hrn human readable name
229 # @param sfa_fields dictionary of SFA fields
230 # @param pl_fields dictionary of PLC fields (output)
232 def sfa_fields_to_pl_fields(self, type, hrn, record):
234 def convert_ints(tmpdict, int_fields):
235 for field in int_fields:
237 tmpdict[field] = int(tmpdict[field])
240 #for field in record:
241 # pl_record[field] = record[field]
244 if not "instantiation" in pl_record:
245 pl_record["instantiation"] = "plc-instantiated"
246 pl_record["name"] = hrn_to_pl_slicename(hrn)
248 pl_record["url"] = record["url"]
249 if "description" in record:
250 pl_record["description"] = record["description"]
251 if "expires" in record:
252 pl_record["expires"] = int(record["expires"])
255 if not "hostname" in pl_record:
256 if not "hostname" in record:
257 raise MissingSfaInfo("hostname")
258 pl_record["hostname"] = record["hostname"]
259 if not "model" in pl_record:
260 pl_record["model"] = "geni"
262 elif type == "authority":
263 pl_record["login_base"] = hrn_to_pl_login_base(hrn)
265 if not "name" in pl_record:
266 pl_record["name"] = hrn
268 if not "abbreviated_name" in pl_record:
269 pl_record["abbreviated_name"] = hrn
271 if not "enabled" in pl_record:
272 pl_record["enabled"] = True
274 if not "is_public" in pl_record:
275 pl_record["is_public"] = True
279 def fill_record_pl_info(self, records):
281 Fill in the planetlab specific fields of a SFA record. This
282 involves calling the appropriate PLC method to retrieve the
283 database record for the object.
285 PLC data is filled into the pl_info field of the record.
287 @param record: record to fill in field (in/out param)
290 node_ids, site_ids, slice_ids = [], [], []
291 person_ids, key_ids = [], []
292 type_map = {'node': node_ids, 'authority': site_ids,
293 'slice': slice_ids, 'user': person_ids}
295 for record in records:
296 for type in type_map:
297 if type == record['type']:
298 type_map[type].append(record['pointer'])
301 nodes, sites, slices, persons, keys = {}, {}, {}, {}, {}
303 node_list = self.plshell.GetNodes(self.plauth, node_ids)
304 nodes = list_to_dict(node_list, 'node_id')
306 site_list = self.plshell.GetSites(self.plauth, site_ids)
307 sites = list_to_dict(site_list, 'site_id')
309 slice_list = self.plshell.GetSlices(self.plauth, slice_ids)
310 slices = list_to_dict(slice_list, 'slice_id')
312 person_list = self.plshell.GetPersons(self.plauth, person_ids)
313 persons = list_to_dict(person_list, 'person_id')
314 for person in persons:
315 key_ids.extend(persons[person]['key_ids'])
317 pl_records = {'node': nodes, 'authority': sites,
318 'slice': slices, 'user': persons}
321 key_list = self.plshell.GetKeys(self.plauth, key_ids)
322 keys = list_to_dict(key_list, 'key_id')
325 for record in records:
326 # records with pointer==-1 do not have plc info.
327 # for example, the top level authority records which are
328 # authorities, but not PL "sites"
329 if record['pointer'] == -1:
332 for type in pl_records:
333 if record['type'] == type:
334 if record['pointer'] in pl_records[type]:
335 record.update(pl_records[type][record['pointer']])
338 if record['type'] == 'user':
339 pubkeys = [keys[key_id]['key'] for key_id in record['key_ids'] if key_id in keys]
340 record['keys'] = pubkeys
342 # fill in record hrns
343 records = self.fill_record_hrns(records)
347 def fill_record_hrns(self, records):
349 convert pl ids to hrns
353 slice_ids, person_ids, site_ids, node_ids = [], [], [], []
354 for record in records:
355 if 'site_id' in record:
356 site_ids.append(record['site_id'])
357 if 'site_ids' in records:
358 site_ids.extend(record['site_ids'])
359 if 'person_ids' in record:
360 person_ids.extend(record['person_ids'])
361 if 'slice_ids' in record:
362 slice_ids.extend(record['slice_ids'])
363 if 'node_ids' in record:
364 node_ids.extend(record['node_ids'])
367 slices, persons, sites, nodes = {}, {}, {}, {}
369 site_list = self.plshell.GetSites(self.plauth, site_ids, ['site_id', 'login_base'])
370 sites = list_to_dict(site_list, 'site_id')
372 person_list = self.plshell.GetPersons(self.plauth, person_ids, ['person_id', 'email'])
373 persons = list_to_dict(person_list, 'person_id')
375 slice_list = self.plshell.GetSlices(self.plauth, slice_ids, ['slice_id', 'name'])
376 slices = list_to_dict(slice_list, 'slice_id')
378 node_list = self.plshell.GetNodes(self.plauth, node_ids, ['node_id', 'hostname'])
379 nodes = list_to_dict(node_list, 'node_id')
381 # convert ids to hrns
382 for record in records:
384 # get all relevant data
385 type = record['type']
386 pointer = record['pointer']
392 if 'site_id' in record:
393 site = sites[record['site_id']]
394 login_base = site['login_base']
395 record['site'] = ".".join([auth_hrn, login_base])
396 if 'person_ids' in record:
397 emails = [persons[person_id]['email'] for person_id in record['person_ids'] \
398 if person_id in persons]
399 usernames = [email.split('@')[0] for email in emails]
400 person_hrns = [".".join([auth_hrn, login_base, username]) for username in usernames]
401 record['persons'] = person_hrns
402 if 'slice_ids' in record:
403 slicenames = [slices[slice_id]['name'] for slice_id in record['slice_ids'] \
404 if slice_id in slices]
405 slice_hrns = [slicename_to_hrn(auth_hrn, slicename) for slicename in slicenames]
406 record['slices'] = slice_hrns
407 if 'node_ids' in record:
408 hostnames = [nodes[node_id]['hostname'] for node_id in record['node_ids'] \
410 node_hrns = [hostname_to_hrn(auth_hrn, login_base, hostname) for hostname in hostnames]
411 record['nodes'] = node_hrns
412 if 'site_ids' in record:
413 login_bases = [sites[site_id]['login_base'] for site_id in record['site_ids'] \
415 site_hrns = [".".join([auth_hrn, lbase]) for lbase in login_bases]
416 record['sites'] = site_hrns
420 def fill_record_sfa_info(self, records):
422 def startswith(prefix, values):
423 return [value for value in values if value.startswith(prefix)]
428 for record in records:
429 person_ids.extend(record.get("person_ids", []))
430 site_ids.extend(record.get("site_ids", []))
431 if 'site_id' in record:
432 site_ids.append(record['site_id'])
434 # get all pis from the sites we've encountered
435 # and store them in a dictionary keyed on site_id
438 pi_filter = {'|roles': ['pi'], '|site_ids': site_ids}
439 pi_list = self.plshell.GetPersons(self.plauth, pi_filter, ['person_id', 'site_ids'])
441 # we will need the pi's hrns also
442 person_ids.append(pi['person_id'])
444 # we also need to keep track of the sites these pis
446 for site_id in pi['site_ids']:
447 if site_id in site_pis:
448 site_pis[site_id].append(pi)
450 site_pis[site_id] = [pi]
452 # get sfa records for all records associated with these records.
453 # we'll replace pl ids (person_ids) with hrns from the sfa records
456 # get the sfa records
457 table = self.SfaTable()
458 person_list, persons = [], {}
459 person_list = table.find({'type': 'user', 'pointer': person_ids})
460 # create a hrns keyed on the sfa record's pointer.
461 # Its possible for multiple records to have the same pointer so
462 # the dict's value will be a list of hrns.
463 persons = defaultdict(list)
464 for person in person_list:
465 persons[person['pointer']].append(person)
468 pl_person_list, pl_persons = [], {}
469 pl_person_list = self.plshell.GetPersons(self.plauth, person_ids, ['person_id', 'roles'])
470 pl_persons = list_to_dict(pl_person_list, 'person_id')
473 for record in records:
474 # skip records with no pl info (top level authorities)
475 if record['pointer'] == -1:
478 type = record['type']
479 if (type == "slice"):
480 # all slice users are researchers
482 record['researcher'] = []
483 for person_id in record['person_ids']:
484 hrns = [person['hrn'] for person in persons[person_id]]
485 record['researcher'].extend(hrns)
487 # pis at the slice's site
488 pl_pis = site_pis[record['site_id']]
489 pi_ids = [pi['person_id'] for pi in pl_pis]
490 for person_id in pi_ids:
491 hrns = [person['hrn'] for person in persons[person_id]]
492 record['PI'].extend(hrns)
493 record['geni_urn'] = hrn_to_urn(record['hrn'], 'slice')
494 record['geni_creator'] = record['PI']
496 elif (type == "authority"):
498 record['operator'] = []
500 for pointer in record['person_ids']:
501 if pointer not in persons or pointer not in pl_persons:
502 # this means there is not sfa or pl record for this user
504 hrns = [person['hrn'] for person in persons[pointer]]
505 roles = pl_persons[pointer]['roles']
507 record['PI'].extend(hrns)
509 record['operator'].extend(hrns)
511 record['owner'].extend(hrns)
512 # xxx TODO: OrganizationName
513 elif (type == "node"):
514 sfa_info['dns'] = record.get("hostname", "")
515 # xxx TODO: URI, LatLong, IP, DNS
517 elif (type == "user"):
518 sfa_info['email'] = record.get("email", "")
519 sfa_info['geni_urn'] = hrn_to_urn(record['hrn'], 'user')
520 sfa_info['geni_certificate'] = record['gid']
521 # xxx TODO: PostalAddress, Phone
522 record.update(sfa_info)
524 def fill_record_info(self, records):
526 Given a SFA record, fill in the PLC specific and SFA specific
527 fields in the record.
529 if not isinstance(records, list):
532 self.fill_record_pl_info(records)
533 self.fill_record_sfa_info(records)
535 def update_membership_list(self, oldRecord, record, listName, addFunc, delFunc):
536 # get a list of the HRNs tht are members of the old and new records
538 oldList = oldRecord.get(listName, [])
541 newList = record.get(listName, [])
543 # if the lists are the same, then we don't have to update anything
544 if (oldList == newList):
547 # build a list of the new person ids, by looking up each person to get
550 table = self.SfaTable()
551 records = table.find({'type': 'user', 'hrn': newList})
553 newIdList.append(rec['pointer'])
555 # build a list of the old person ids from the person_ids field
557 oldIdList = oldRecord.get("person_ids", [])
558 containerId = oldRecord.get_pointer()
560 # if oldRecord==None, then we are doing a Register, instead of an
563 containerId = record.get_pointer()
565 # add people who are in the new list, but not the oldList
566 for personId in newIdList:
567 if not (personId in oldIdList):
568 addFunc(self.plauth, personId, containerId)
570 # remove people who are in the old list, but not the new list
571 for personId in oldIdList:
572 if not (personId in newIdList):
573 delFunc(self.plauth, personId, containerId)
575 def update_membership(self, oldRecord, record):
576 if record.type == "slice":
577 self.update_membership_list(oldRecord, record, 'researcher',
578 self.plshell.AddPersonToSlice,
579 self.plshell.DeletePersonFromSlice)
580 elif record.type == "authority":
586 class ComponentAPI(BaseAPI):
588 def __init__(self, config = "/etc/sfa/sfa_config.py", encoding = "utf-8", methods='sfa.methods',
589 peer_cert = None, interface = None, key_file = None, cert_file = None):
591 BaseAPI.__init__(self, config=config, encoding=encoding, methods=methods, peer_cert=peer_cert,
592 interface=interface, key_file=key_file, cert_file=cert_file)
593 self.encoding = encoding
595 # Better just be documenting the API
599 self.nodemanager = NodeManager(self.config)
601 def sliver_exists(self):
602 sliver_dict = self.nodemanager.GetXIDs()
603 if slicename in sliver_dict.keys():
608 def get_registry(self):
609 addr, port = self.config.SFA_REGISTRY_HOST, self.config.SFA_REGISTRY_PORT
610 url = "http://%(addr)s:%(port)s" % locals()
611 server = xmlrpcprotocol.get_server(url, self.key_file, self.cert_file)
614 def get_node_key(self):
615 # this call requires no authentication,
616 # so we can generate a random keypair here
618 (kfd, keyfile) = tempfile.mkstemp()
619 (cfd, certfile) = tempfile.mkstemp()
620 key = Keypair(create=True)
621 key.save_to_file(keyfile)
622 cert = Certificate(subject=subject)
623 cert.set_issuer(key=key, subject=subject)
626 cert.save_to_file(certfile)
627 registry = self.get_registry()
628 # the registry will scp the key onto the node
631 def getCredential(self):
633 Get our credential from a remote registry
635 path = self.config.SFA_DATA_DIR
636 config_dir = self.config.config_path
637 cred_filename = path + os.sep + 'node.cred'
639 credential = Credential(filename = cred_filename)
640 return credential.save_to_string(save_parents=True)
642 node_pkey_file = config_dir + os.sep + "node.key"
643 node_gid_file = config_dir + os.sep + "node.gid"
644 cert_filename = path + os.sep + 'server.cert'
645 if not os.path.exists(node_pkey_file) or \
646 not os.path.exists(node_gid_file):
650 gid = GID(filename=node_gid_file)
652 # get credential from registry
653 cert_str = Certificate(filename=cert_filename).save_to_string(save_parents=True)
654 registry = self.get_registry()
655 cred = registry.GetSelfCredential(cert_str, hrn, 'node')
656 Credential(string=cred).save_to_file(credfile, save_parents=True)
660 def clean_key_cred(self):
662 remove the existing keypair and cred and generate new ones
664 files = ["server.key", "server.cert", "node.cred"]
666 filepath = KEYDIR + os.sep + f
667 if os.path.isfile(filepath):
670 # install the new key pair
671 # GetCredential will take care of generating the new keypair