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,
61 ## end of http://code.activestate.com/recipes/523034/ }}}
63 def list_to_dict(recs, key):
65 convert a list of dictionaries into a dictionary keyed on the
66 specified dictionary key
68 keys = [rec[key] for rec in recs]
69 return dict(zip(keys, recs))
71 class SfaAPI(BaseAPI):
73 # flat list of method names
75 methods = sfa.methods.all
77 def __init__(self, config = "/etc/sfa/sfa_config.py", encoding = "utf-8",
78 methods='sfa.methods', peer_cert = None, interface = None,
79 key_file = None, cert_file = None, cache = None):
80 BaseAPI.__init__(self, config=config, encoding=encoding, methods=methods, \
81 peer_cert=peer_cert, interface=interface, key_file=key_file, \
82 cert_file=cert_file, cache=cache)
84 self.encoding = encoding
85 from sfa.util.table import SfaTable
86 self.SfaTable = SfaTable
87 # Better just be documenting the API
92 self.config = Config(config)
93 self.auth = Auth(peer_cert)
94 self.interface = interface
95 self.key_file = key_file
96 self.key = Keypair(filename=self.key_file)
97 self.cert_file = cert_file
98 self.cert = Certificate(filename=self.cert_file)
99 self.credential = None
100 # Initialize the PLC shell only if SFA wraps a myPLC
101 rspec_type = self.config.get_aggregate_type()
102 if (rspec_type == 'pl' or rspec_type == 'vini' or rspec_type == 'eucalyptus'):
103 self.plshell = self.getPLCShell()
104 self.plshell_version = "4.3"
106 self.hrn = self.config.SFA_INTERFACE_HRN
107 self.time_format = "%Y-%m-%d %H:%M:%S"
108 self.logger=get_sfa_logger()
110 def getPLCShell(self):
111 self.plauth = {'Username': self.config.SFA_PLC_USER,
112 'AuthMethod': 'password',
113 'AuthString': self.config.SFA_PLC_PASSWORD}
115 sys.path.append(os.path.dirname(os.path.realpath("/usr/bin/plcsh")))
116 self.plshell_type = 'direct'
118 shell = PLC.Shell.Shell(globals = globals())
120 self.plshell_type = 'xmlrpc'
121 url = self.config.SFA_PLC_URL
122 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_keys(auth_info.get_privkey_filename(), auth_info.get_gid_filename())
181 r1 = determine_rights(type, hrn)
182 new_cred.set_privileges(r1)
184 auth_kind = "authority,ma,sa"
186 new_cred.set_parent(self.auth.hierarchy.get_auth_cred(auth_hrn, kind=auth_kind))
191 return new_cred.save_to_string(save_parents=True)
194 def loadCredential (self):
196 Attempt to load credential from file if it exists. If it doesnt get
197 credential from registry.
200 # see if this file exists
201 # XX This is really the aggregate's credential. Using this is easier than getting
202 # the registry's credential from iteslf (ssl errors).
203 ma_cred_filename = self.config.SFA_DATA_DIR + os.sep + self.interface + self.hrn + ".ma.cred"
205 self.credential = Credential(filename = ma_cred_filename)
207 self.credential = self.getCredentialFromRegistry()
210 # Convert SFA fields to PLC fields for use when registering up updating
211 # registry record in the PLC database
213 # @param type type of record (user, slice, ...)
214 # @param hrn human readable name
215 # @param sfa_fields dictionary of SFA fields
216 # @param pl_fields dictionary of PLC fields (output)
218 def sfa_fields_to_pl_fields(self, type, hrn, record):
220 def convert_ints(tmpdict, int_fields):
221 for field in int_fields:
223 tmpdict[field] = int(tmpdict[field])
226 #for field in record:
227 # pl_record[field] = record[field]
230 if not "instantiation" in pl_record:
231 pl_record["instantiation"] = "plc-instantiated"
232 pl_record["name"] = hrn_to_pl_slicename(hrn)
234 pl_record["url"] = record["url"]
235 if "description" in record:
236 pl_record["description"] = record["description"]
237 if "expires" in record:
238 pl_record["expires"] = int(record["expires"])
241 if not "hostname" in pl_record:
242 if not "hostname" in record:
243 raise MissingSfaInfo("hostname")
244 pl_record["hostname"] = record["hostname"]
245 if not "model" in pl_record:
246 pl_record["model"] = "geni"
248 elif type == "authority":
249 pl_record["login_base"] = hrn_to_pl_login_base(hrn)
251 if not "name" in pl_record:
252 pl_record["name"] = hrn
254 if not "abbreviated_name" in pl_record:
255 pl_record["abbreviated_name"] = hrn
257 if not "enabled" in pl_record:
258 pl_record["enabled"] = True
260 if not "is_public" in pl_record:
261 pl_record["is_public"] = True
265 def fill_record_pl_info(self, records):
267 Fill in the planetlab specific fields of a SFA record. This
268 involves calling the appropriate PLC method to retrieve the
269 database record for the object.
271 PLC data is filled into the pl_info field of the record.
273 @param record: record to fill in field (in/out param)
276 node_ids, site_ids, slice_ids = [], [], []
277 person_ids, key_ids = [], []
278 type_map = {'node': node_ids, 'authority': site_ids,
279 'slice': slice_ids, 'user': person_ids}
281 for record in records:
282 for type in type_map:
283 if type == record['type']:
284 type_map[type].append(record['pointer'])
287 nodes, sites, slices, persons, keys = {}, {}, {}, {}, {}
289 node_list = self.plshell.GetNodes(self.plauth, node_ids)
290 nodes = list_to_dict(node_list, 'node_id')
292 site_list = self.plshell.GetSites(self.plauth, site_ids)
293 sites = list_to_dict(site_list, 'site_id')
295 slice_list = self.plshell.GetSlices(self.plauth, slice_ids)
296 slices = list_to_dict(slice_list, 'slice_id')
298 person_list = self.plshell.GetPersons(self.plauth, person_ids)
299 persons = list_to_dict(person_list, 'person_id')
300 for person in persons:
301 key_ids.extend(persons[person]['key_ids'])
303 pl_records = {'node': nodes, 'authority': sites,
304 'slice': slices, 'user': persons}
307 key_list = self.plshell.GetKeys(self.plauth, key_ids)
308 keys = list_to_dict(key_list, 'key_id')
311 for record in records:
312 # records with pointer==-1 do not have plc info.
313 # for example, the top level authority records which are
314 # authorities, but not PL "sites"
315 if record['pointer'] == -1:
318 for type in pl_records:
319 if record['type'] == type:
320 if record['pointer'] in pl_records[type]:
321 record.update(pl_records[type][record['pointer']])
324 if record['type'] == 'user':
325 pubkeys = [keys[key_id]['key'] for key_id in record['key_ids'] if key_id in keys]
326 record['keys'] = pubkeys
328 # fill in record hrns
329 records = self.fill_record_hrns(records)
333 def fill_record_hrns(self, records):
335 convert pl ids to hrns
339 slice_ids, person_ids, site_ids, node_ids = [], [], [], []
340 for record in records:
341 if 'site_id' in record:
342 site_ids.append(record['site_id'])
343 if 'site_ids' in records:
344 site_ids.extend(record['site_ids'])
345 if 'person_ids' in record:
346 person_ids.extend(record['person_ids'])
347 if 'slice_ids' in record:
348 slice_ids.extend(record['slice_ids'])
349 if 'node_ids' in record:
350 node_ids.extend(record['node_ids'])
353 slices, persons, sites, nodes = {}, {}, {}, {}
355 site_list = self.plshell.GetSites(self.plauth, site_ids, ['site_id', 'login_base'])
356 sites = list_to_dict(site_list, 'site_id')
358 person_list = self.plshell.GetPersons(self.plauth, person_ids, ['person_id', 'email'])
359 persons = list_to_dict(person_list, 'person_id')
361 slice_list = self.plshell.GetSlices(self.plauth, slice_ids, ['slice_id', 'name'])
362 slices = list_to_dict(slice_list, 'slice_id')
364 node_list = self.plshell.GetNodes(self.plauth, node_ids, ['node_id', 'hostname'])
365 nodes = list_to_dict(node_list, 'node_id')
367 # convert ids to hrns
368 for record in records:
370 # get all relevant data
371 type = record['type']
372 pointer = record['pointer']
378 if 'site_id' in record:
379 site = sites[record['site_id']]
380 login_base = site['login_base']
381 record['site'] = ".".join([auth_hrn, login_base])
382 if 'person_ids' in record:
383 emails = [persons[person_id]['email'] for person_id in record['person_ids'] \
384 if person_id in persons]
385 usernames = [email.split('@')[0] for email in emails]
386 person_hrns = [".".join([auth_hrn, login_base, username]) for username in usernames]
387 record['persons'] = person_hrns
388 if 'slice_ids' in record:
389 slicenames = [slices[slice_id]['name'] for slice_id in record['slice_ids'] \
390 if slice_id in slices]
391 slice_hrns = [slicename_to_hrn(auth_hrn, slicename) for slicename in slicenames]
392 record['slices'] = slice_hrns
393 if 'node_ids' in record:
394 hostnames = [nodes[node_id]['hostname'] for node_id in record['node_ids'] \
396 node_hrns = [hostname_to_hrn(auth_hrn, login_base, hostname) for hostname in hostnames]
397 record['nodes'] = node_hrns
398 if 'site_ids' in record:
399 login_bases = [sites[site_id]['login_base'] for site_id in record['site_ids'] \
401 site_hrns = [".".join([auth_hrn, lbase]) for lbase in login_bases]
402 record['sites'] = site_hrns
406 def fill_record_sfa_info(self, records):
408 def startswith(prefix, values):
409 return [value for value in values if value.startswith(prefix)]
414 for record in records:
415 person_ids.extend(record.get("person_ids", []))
416 site_ids.extend(record.get("site_ids", []))
417 if 'site_id' in record:
418 site_ids.append(record['site_id'])
420 # get all pis from the sites we've encountered
421 # and store them in a dictionary keyed on site_id
424 pi_filter = {'|roles': ['pi'], '|site_ids': site_ids}
425 pi_list = self.plshell.GetPersons(self.plauth, pi_filter, ['person_id', 'site_ids'])
427 # we will need the pi's hrns also
428 person_ids.append(pi['person_id'])
430 # we also need to keep track of the sites these pis
432 for site_id in pi['site_ids']:
433 if site_id in site_pis:
434 site_pis[site_id].append(pi)
436 site_pis[site_id] = [pi]
438 # get sfa records for all records associated with these records.
439 # we'll replace pl ids (person_ids) with hrns from the sfa records
442 # get the sfa records
443 table = self.SfaTable()
444 person_list, persons = [], {}
445 person_list = table.find({'type': 'user', 'pointer': person_ids})
446 # create a hrns keyed on the sfa record's pointer.
447 # Its possible for multiple records to have the same pointer so
448 # the dict's value will be a list of hrns.
449 persons = defaultdict(list)
450 for person in person_list:
451 persons[person['pointer']].append(person)
454 pl_person_list, pl_persons = [], {}
455 pl_person_list = self.plshell.GetPersons(self.plauth, person_ids, ['person_id', 'roles'])
456 pl_persons = list_to_dict(pl_person_list, 'person_id')
459 for record in records:
460 # skip records with no pl info (top level authorities)
461 if record['pointer'] == -1:
464 type = record['type']
465 if (type == "slice"):
466 # all slice users are researchers
468 record['researcher'] = []
469 for person_id in record['person_ids']:
470 hrns = [person['hrn'] for person in persons[person_id]]
471 record['researcher'].extend(hrns)
473 # pis at the slice's site
474 pl_pis = site_pis[record['site_id']]
475 pi_ids = [pi['person_id'] for pi in pl_pis]
476 for person_id in pi_ids:
477 hrns = [person['hrn'] for person in persons[person_id]]
478 record['PI'].extend(hrns)
479 record['geni_urn'] = hrn_to_urn(record['hrn'], 'slice')
480 record['geni_creator'] = record['PI']
482 elif (type == "authority"):
484 record['operator'] = []
486 for pointer in record['person_ids']:
487 if pointer not in persons or pointer not in pl_persons:
488 # this means there is not sfa or pl record for this user
490 hrns = [person['hrn'] for person in persons[pointer]]
491 roles = pl_persons[pointer]['roles']
493 record['PI'].extend(hrns)
495 record['operator'].extend(hrns)
497 record['owner'].extend(hrns)
498 # xxx TODO: OrganizationName
499 elif (type == "node"):
500 sfa_info['dns'] = record.get("hostname", "")
501 # xxx TODO: URI, LatLong, IP, DNS
503 elif (type == "user"):
504 sfa_info['email'] = record.get("email", "")
505 sfa_info['geni_urn'] = hrn_to_urn(record['hrn'], 'user')
506 sfa_info['geni_certificate'] = record['gid']
507 # xxx TODO: PostalAddress, Phone
508 record.update(sfa_info)
510 def fill_record_info(self, records):
512 Given a SFA record, fill in the PLC specific and SFA specific
513 fields in the record.
515 if not isinstance(records, list):
518 self.fill_record_pl_info(records)
519 self.fill_record_sfa_info(records)
521 def update_membership_list(self, oldRecord, record, listName, addFunc, delFunc):
522 # get a list of the HRNs tht are members of the old and new records
524 oldList = oldRecord.get(listName, [])
527 newList = record.get(listName, [])
529 # if the lists are the same, then we don't have to update anything
530 if (oldList == newList):
533 # build a list of the new person ids, by looking up each person to get
536 table = self.SfaTable()
537 records = table.find({'type': 'user', 'hrn': newList})
539 newIdList.append(rec['pointer'])
541 # build a list of the old person ids from the person_ids field
543 oldIdList = oldRecord.get("person_ids", [])
544 containerId = oldRecord.get_pointer()
546 # if oldRecord==None, then we are doing a Register, instead of an
549 containerId = record.get_pointer()
551 # add people who are in the new list, but not the oldList
552 for personId in newIdList:
553 if not (personId in oldIdList):
554 addFunc(self.plauth, personId, containerId)
556 # remove people who are in the old list, but not the new list
557 for personId in oldIdList:
558 if not (personId in newIdList):
559 delFunc(self.plauth, personId, containerId)
561 def update_membership(self, oldRecord, record):
562 if record.type == "slice":
563 self.update_membership_list(oldRecord, record, 'researcher',
564 self.plshell.AddPersonToSlice,
565 self.plshell.DeletePersonFromSlice)
566 elif record.type == "authority":
572 class ComponentAPI(BaseAPI):
574 def __init__(self, config = "/etc/sfa/sfa_config.py", encoding = "utf-8", methods='sfa.methods',
575 peer_cert = None, interface = None, key_file = None, cert_file = None):
577 BaseAPI.__init__(self, config=config, encoding=encoding, methods=methods, peer_cert=peer_cert,
578 interface=interface, key_file=key_file, cert_file=cert_file)
579 self.encoding = encoding
581 # Better just be documenting the API
585 self.nodemanager = NodeManager(self.config)
587 def sliver_exists(self):
588 sliver_dict = self.nodemanager.GetXIDs()
589 if slicename in sliver_dict.keys():
594 def get_registry(self):
595 addr, port = self.config.SFA_REGISTRY_HOST, self.config.SFA_REGISTRY_PORT
596 url = "http://%(addr)s:%(port)s" % locals()
597 server = xmlrpcprotocol.get_server(url, self.key_file, self.cert_file)
600 def get_node_key(self):
601 # this call requires no authentication,
602 # so we can generate a random keypair here
604 (kfd, keyfile) = tempfile.mkstemp()
605 (cfd, certfile) = tempfile.mkstemp()
606 key = Keypair(create=True)
607 key.save_to_file(keyfile)
608 cert = Certificate(subject=subject)
609 cert.set_issuer(key=key, subject=subject)
612 cert.save_to_file(certfile)
613 registry = self.get_registry()
614 # the registry will scp the key onto the node
617 def getCredential(self):
619 Get our credential from a remote registry
621 path = self.config.SFA_DATA_DIR
622 config_dir = self.config.config_path
623 credfile = path + os.sep + 'node.cred'
625 credential = Credential(filename = cred_filename)
626 return credential.save_to_string(save_parents=True)
628 node_pkey_file = config_dir + os.sep + "node.key"
629 node_gid_file = config_dir + os.sep + "node.gid"
630 if not os.path.exists(node_pkey_file) or \
631 not os.path.exists(node_gid_file):
635 gid = GID(filename=node_gid_file)
637 # get credential from registry
638 registry = self.get_registry()
639 cred = registry.get_self_credential(cert_str, 'node', hrn)
640 Credential(string=cred).save_to_file(credfile, save_parents=True)
644 def clean_key_cred(self):
646 remove the existing keypair and cred and generate new ones
648 files = ["server.key", "server.cert", "node.cred"]
650 filepath = KEYDIR + os.sep + f
651 if os.path.isfile(filepath):
654 # install the new key pair
655 # get_credential will take care of generating the new keypair